-
Notifications
You must be signed in to change notification settings - Fork 47
/
lib.rs
1030 lines (900 loc) · 32.1 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! ## `humility qspi`
//!
//! `humility qspi` manipulates (and importantly, writes to) QSPI-attached
//! flash in Hubris. To read the device identifier, use the `--id` (`-i`)
//! option:
//!
//! ```console
//! % humility qspi -i
//! humility: attached via ST-Link V3
//! DeviceIdData {
//! manufacturer_id: Micron(0x20)
//! memory_type: 3V(186)
//! memory_capacity: 33554432
//! uid_n: 16
//! # If a Micron device:
//! ext_device_id: 0b1000100
//! 2nd device generation,
//! Standard BP scheme,
//! HOLD#/RESET#=HOLD
//! Additional HW RESET# is available,
//! Sector size is Uniform 64KB,
//! device_configuration_info: 0
//! uid: [9a, ec, 0b, 00, 19, f9, ff$, 39, 00, be, 69, 97, f4, a2]
//! }
//! [Ok([20, ba, 19, 10, 44, 0, 9a, ec, b, 0, 19, f9, ff, 39, 0, be, 69, 97, f4, a2])]
//! ```
//!
//! To write an image from a file, use the `--writefile` (`-W`) option:
//!
//! ```console
//! % humility -W ./milan-spew-115k2-2dpc-0.4.1-dataeye.bin
//! humility: attached via ST-Link V3
//! humility: erasing 16777216 bytes...
//! humility: ... done
//! humility: flashed 16.00MB in 5 minutes
//! ```
//!
//! If writing similar images, it is much faster to write only those blocks
//! that differ. To perform a differential write, use the `--diffwrite` (`-D`)
//! option:
//!
//! ```console
//! % humility qspi -D ./milan-spew-115k2-2dpc-0.4.1.bin
//! humility: attached via ST-Link V3
//! humility: erasing 65536 bytes...
//! humility: ... done
//! humility: hashed 16.00MB, wrote 64.00KB in 16 seconds
//! ```
//!
//! To read, write or hash a particular region, use the `--read` (`-r`),
//! `--write` (`-w`), or `--hash` (`-H`) respectively -- giving the address
//! via `--address` (`-a`) and the number of bytes via `--nbytes` (`-n`).
//! For example, to read 128 bytes from address 0x120000:
//!
//! ```console
//! % humility qspi -r -a 0x120000 -n 128
//! \/ 1 2 3 4 5 6 7 8 9 a b c d e f
//! 0x00120000 | 24 50 53 50 ee 7a 31 28 10 00 00 00 20 cd 48 20 | $PSP.z1(.... .H
//! 0x00120010 | 00 00 00 00 40 04 00 00 00 30 12 00 00 00 00 00 | ....@....0......
//! 0x00120020 | 01 00 00 00 00 54 01 00 00 40 12 00 00 00 00 00 | .....T...@......
//! 0x00120030 | 03 00 00 00 00 54 01 00 00 a0 13 00 00 00 00 00 | .....T..........
//! 0x00120040 | 08 00 00 00 40 ea 01 00 00 00 15 00 00 00 00 00 | ....@...........
//! 0x00120050 | 09 00 00 00 40 06 00 00 00 f0 16 00 00 00 00 00 | ....@...........
//! 0x00120060 | 0a 00 00 00 40 06 00 00 00 00 17 00 00 00 00 00 | ....@...........
//! 0x00120070 | 0b 00 00 00 ff ff ff ff 01 00 00 00 00 00 00 00 | ................
//! ```
//!
//! To get the SHA256 hash for that same region:
//!
//! ```console
//! % humility qspi -H -a 0x120000 -n 128
//! humility: attached via ST-Link V3
//! 120000..000080: 4d07112733efe240f990fad785726c52de4335d6c5c30a33e60096d4c2576742
//! ```
//!
use humility::core::Core;
use humility::hubris::*;
use humility_cmd::hiffy::*;
use humility_cmd::{Archive, Args, Attach, Command, Dumper, Validate};
use sha2::{Digest, Sha256};
use std::fmt;
use std::fs;
use std::fs::File;
use std::io::{BufWriter, Read, Write};
use std::mem;
use std::time::Instant;
use anyhow::{anyhow, bail, Result};
use clap::Command as ClapCommand;
use clap::{ArgGroup, CommandFactory, Parser};
use hif::*;
use indicatif::{HumanBytes, HumanDuration};
use indicatif::{ProgressBar, ProgressStyle};
#[derive(Parser, Debug)]
#[clap(
name = "qspi", about = env!("CARGO_PKG_DESCRIPTION"),
group = ArgGroup::new("command").multiple(false)
)]
struct QspiArgs {
/// sets timeout
#[clap(
long, short = 'T', default_value = "5000", value_name = "timeout_ms",
value_parser=parse_int::parse::<u32>,
)]
timeout: u32,
/// pull status string
#[clap(long, short, group = "command")]
status: bool,
/// pull identifier
#[clap(long, short, group = "command")]
id: bool,
/// Return the hash of a region of the flash
/// -a and -n are optional. Default is the entire contents.
#[clap(long, short = 'H', group = "command")]
hash: bool,
/// perform a sector erase
#[clap(
long, short,
group = "command",
requires_all = &["addr"]
)]
erase: bool,
/// perform a bulk erase
#[clap(long, short = 'E', group = "command")]
bulkerase: bool,
/// perform a read
#[clap(
long, short, group = "command", requires_all = &["addr", "nbytes"]
)]
read: bool,
/// specify flash address in bytes
#[clap(long, short, value_name = "address",
value_parser=parse_int::parse::<usize>,
)]
addr: Option<usize>,
/// specify size in bytes
#[clap(long, short, value_name = "nbytes",
value_parser=parse_int::parse::<usize>,
)]
nbytes: Option<usize>,
/// comma-separated bytes to write
#[clap(
long,
short,
value_name = "bytes",
group = "command",
requires = "addr"
)]
write: Option<String>,
/// file to write or verify
#[clap(long, short = 'W', value_name = "filename", group = "command")]
writefile: Option<String>,
/// verify instead of writing
#[clap(long, short = 'V', requires = "writefile")]
verify: bool,
/// file to read
#[clap(long, short = 'R', value_name = "filename", group = "command")]
readfile: Option<String>,
/// file to differentially write
#[clap(long, short = 'D', value_name = "filename", group = "command")]
diffwrite: Option<String>,
}
struct QspiDevice {
block_size: u32,
sector_size: u32,
}
fn optional_nbytes<'a>(
core: &'a mut dyn Core,
context: &'a mut HiffyContext,
qspi_read_id: &HiffyFunction,
nbytes: Option<usize>,
) -> Result<u32> {
// Nbytes (-n) is optional and defaults to
// the entire flash contents.
// Read the flash size from the flash part itself if nbytes
// is not specified.
match nbytes {
Some(nbytes) => Ok(nbytes as u32),
None => {
let ops = vec![Op::Call(qspi_read_id.id), Op::Done];
// Result<
// Vec<
// Result<Vec<u8>, u32>
// >, anyhow::Error>
match context.run(core, ops.as_slice(), None) {
Ok(results) => match &results[0] {
Ok(buf) => {
if mem::size_of::<DeviceIdData>() == buf.len() {
let did: DeviceIdData = unsafe {
std::ptr::read(buf.as_ptr() as *const _)
};
Ok(did.size()? as u32)
} else {
Err(anyhow!(
"Unexpected result length: {} != {}",
mem::size_of::<DeviceIdData>(),
buf.len()
))
}
}
Err(e) => Err(anyhow!("{}", e)),
},
Err(e) => Err(e),
}
}
}
}
///
/// Determine the deltas between the on-disk file and the specified vector
/// of sha256 sums
///
fn deltas(
device: &QspiDevice,
filename: &str,
compare: &[(u32, Vec<u8>)],
mut diff: impl FnMut(u32, &[u8]) -> Result<()>,
) -> Result<()> {
let filelen = fs::metadata(filename.to_string())?.len() as u32;
let mut file = File::open(filename)?;
let mut offset = 0;
for (c, result) in compare {
let mut buf = vec![0u8; device.sector_size as usize];
if offset != *c {
bail!("mismatched offset; expected {}, found {}", offset, c);
}
let len = if offset + device.sector_size > filelen {
filelen - offset
} else {
device.sector_size
};
file.read_exact(&mut buf[..len as usize])?;
let mut hasher = Sha256::new();
hasher.update(&buf);
let sum = hasher.finalize();
if !sum.iter().eq(result.iter()) {
diff(offset, &buf[..len as usize])?;
}
offset += device.sector_size;
}
Ok(())
}
///
/// Erase specified sectors
///
fn erase(
device: &QspiDevice,
core: &mut dyn Core,
context: &mut HiffyContext,
funcs: &HiffyFunctions,
sectors: &[u32],
) -> Result<()> {
let f = funcs.get("QspiSectorErase", 1)?;
let mut ops = vec![];
humility::msg!(
"erasing {} bytes...",
sectors.len() as u32 * device.sector_size
);
for addr in sectors {
if addr % device.sector_size != 0 {
bail!("illegal erase address 0x{:x}", addr);
}
ops.push(Op::Push32(*addr));
ops.push(Op::Call(f.id));
}
ops.push(Op::Done);
let results = context.run(core, ops.as_slice(), None)?;
for (i, block_result) in results.iter().enumerate() {
if let Err(err) = *block_result {
bail!("failed to erase 0x{:x}: {}", sectors[i], f.strerror(err));
}
}
humility::msg!("... done");
Ok(())
}
///
/// Write in units of blocksize.
///
fn write(
device: &QspiDevice,
core: &mut dyn Core,
context: &mut HiffyContext,
funcs: &HiffyFunctions,
addr: u32,
writelen: u32,
mut getbytes: impl FnMut(&mut [u8]) -> Result<()>,
) -> Result<()> {
let qspi_page_program = funcs.get("QspiPageProgram", 3)?;
let data_size = context.data_size() as u32;
let chunk = data_size - (data_size % device.block_size);
let mut offset = 0;
let mut buf = vec![0u8; chunk as usize];
loop {
let len = if offset + chunk > writelen {
//
// Zero the end of the buffer so we don't have to deal with
// sub-block size writes inside of HIF
//
for i in writelen - offset..chunk {
buf[i as usize] = 0;
}
writelen - offset
} else {
chunk
};
getbytes(&mut buf[..len as usize])?;
//
// We have our chunk; now a HIF loop to write our chunk
// in block_size nibbles.
//
let ops = vec![
Op::Push32(addr + offset), // Push flash address.
Op::Push32(0), // Buffer offset = 0.
Op::PushNone, // Placeholder to be dropped.
Op::Label(Target(0)), // Start of loop
Op::Drop, // Drop placeholder/limit.
Op::Push32(device.block_size), // Push length of this xfer.
Op::Call(qspi_page_program.id), // Call (&flash, &buf, len)
Op::Add, // Add len of xfer to buf offset
Op::Swap, // Address now at top
Op::Push32(device.block_size), // Push length
Op::Add, // Add to address
Op::Swap, // Buf offset back to top
Op::Push32(len), // Push limit.
Op::BranchGreaterThan(Target(0)), // Continue if not at limit.
Op::Done,
];
let results = context.run(core, ops.as_slice(), Some(&buf))?;
for (i, block_result) in results.iter().enumerate() {
if let Err(err) = block_result {
bail!(
"failed on block {} at offset {}: {}",
i,
offset,
qspi_page_program.strerror(*err),
);
}
}
offset += chunk;
if offset >= writelen {
return Ok(());
}
}
}
fn qspi(
hubris: &HubrisArchive,
core: &mut dyn Core,
_args: &Args,
subargs: &[String],
) -> Result<()> {
let subargs = QspiArgs::try_parse_from(subargs)?;
let mut context = HiffyContext::new(hubris, core, subargs.timeout)?;
let funcs = context.functions()?;
let sector_size = 64 * 1024;
let block_size = 256; // Conflating flash block size with hubris scratch buffer.
let device = QspiDevice { block_size, sector_size };
let mut ops = vec![];
let mut hash_name = "".to_string();
let (data, func) = if subargs.status {
let qspi_read_status = funcs.get("QspiReadStatus", 0)?;
ops.push(Op::Call(qspi_read_status.id));
(None, qspi_read_status)
} else if subargs.id {
let qspi_read_id = funcs.get("QspiReadId", 0)?;
ops.push(Op::Call(qspi_read_id.id));
(None, qspi_read_id)
} else if subargs.hash {
let qspi_hash = funcs.get("QspiHash", 2)?;
let qspi_read_id = funcs.get("QspiReadId", 0)?;
// Address is optional and defaults to zero.
let addr = subargs.addr.or(Some(0)).unwrap() as u32;
// nbytes is optional and defaults to the size of the entire flash.
let nbytes =
optional_nbytes(core, &mut context, qspi_read_id, subargs.nbytes)?;
ops.push(Op::Push32(addr));
ops.push(Op::Push32(nbytes));
ops.push(Op::Call(qspi_hash.id));
hash_name = format!("{:06x}..{:06x}", addr, nbytes);
(None, qspi_hash)
} else if subargs.erase {
let qspi_sector_erase = funcs.get("QspiSectorErase", 1)?;
ops.push(Op::Push32(subargs.addr.unwrap() as u32));
ops.push(Op::Call(qspi_sector_erase.id));
(None, qspi_sector_erase)
} else if subargs.bulkerase {
let qspi_bulk_erase = funcs.get("QspiBulkErase", 0)?;
ops.push(Op::Call(qspi_bulk_erase.id));
(None, qspi_bulk_erase)
} else if subargs.read {
let qspi_read = funcs.get("QspiRead", 2)?;
ops.push(Op::Push32(subargs.addr.unwrap() as u32));
ops.push(Op::Push32(subargs.nbytes.unwrap() as u32));
ops.push(Op::Call(qspi_read.id));
(None, qspi_read)
} else if let Some(ref write) = subargs.write {
let qspi_page_program = funcs.get("QspiPageProgram", 3)?;
let bytes: Vec<&str> = write.split(',').collect();
let mut arr = vec![];
for byte in &bytes {
if let Ok(val) = parse_int::parse::<u8>(byte) {
arr.push(val);
} else {
bail!("invalid byte {}", byte)
}
}
ops.push(Op::Push32(subargs.addr.unwrap() as u32));
ops.push(Op::Push(0));
ops.push(Op::Push32(arr.len() as u32));
ops.push(Op::Call(qspi_page_program.id));
(Some(arr), qspi_page_program)
} else if let Some(filename) = subargs.writefile {
let qspi_sector_erase = funcs.get("QspiSectorErase", 1)?;
let qspi_page_program = if subargs.verify {
funcs.get("QspiVerify", 3)
} else {
funcs.get("QspiPageProgram", 3)
}?;
let filelen = fs::metadata(filename.clone())?.len() as u32;
if !subargs.verify {
//
// First, we need to erase the sectors
//
ops.push(Op::Push32(filelen));
ops.push(Op::Push32(0));
ops.push(Op::Label(Target(0)));
ops.push(Op::Call(qspi_sector_erase.id));
ops.push(Op::Push32(sector_size));
ops.push(Op::Add);
ops.push(Op::BranchLessThan(Target(0)));
ops.push(Op::Done);
humility::msg!("erasing {} bytes...", filelen);
let results = context.run(core, ops.as_slice(), None)?;
let f = qspi_sector_erase;
for (i, block_result) in results.iter().enumerate() {
if let Err(err) = *block_result {
bail!("failed to erase sector {}: {}", i, f.strerror(err));
}
}
humility::msg!("... done");
} else {
humility::msg!("will verify {} bytes...", filelen);
}
//
// Now we're ready to write/verify in units of blocksize.
//
let data_size = context.data_size() as u32;
let chunk = data_size - (data_size % block_size);
let mut offset = 0;
let mut buf = vec![0u8; chunk as usize];
let mut file = File::open(filename)?;
let started = Instant::now();
let bar = ProgressBar::new(filelen as u64);
if !subargs.verify {
bar.set_style(ProgressStyle::default_bar().template(
"humility: flashing [{bar:30}] {bytes}/{total_bytes}",
));
} else {
bar.set_style(ProgressStyle::default_bar().template(
"humility: verifying [{bar:30}] {bytes}/{total_bytes}",
));
}
loop {
let len = if offset + chunk > filelen {
//
// Zero the end of the buffer so we don't have to deal with
// sub-block size writes inside of HIF
//
for i in filelen - offset..chunk {
buf[i as usize] = 0;
}
filelen - offset
} else {
chunk
};
file.read_exact(&mut buf[..len as usize])?;
//
// We have our chunk; now a HIF loop to write/verify our chunk
// in block_size nibbles.
//
let ops = vec![
Op::Push32(offset), // Push flash address.
Op::Push32(0), // Buffer offset = 0.
Op::PushNone, // Placeholder to be dropped.
Op::Label(Target(0)), // Start of loop
Op::Drop, // Drop placeholder/limit.
Op::Push32(block_size), // Push length of this xfer.
Op::Call(qspi_page_program.id), // Call (&flash, &buf, len)
Op::Add, // Add len of that xfer to both values on stack.
Op::Swap, //
Op::Push32(block_size), //
Op::Add, //
Op::Swap, // Now pointing to next xfer.
Op::Push32(len), // Push limit.
Op::BranchGreaterThan(Target(0)), // Continue if not at limit.
Op::Done,
];
let results = context.run(core, ops.as_slice(), Some(&buf))?;
bar.set_position((offset + len).into());
for (i, block_result) in results.iter().enumerate() {
match block_result {
Err(err) => {
bail!(
"failed on block {} at offset {}: {}",
i,
offset,
qspi_page_program.strerror(*err),
);
}
Ok(r) if subargs.verify => {
if r.len() != 1 {
bail!("expected single byte return value");
}
if r[0] != 0 {
let a = offset + (i as u32 * block_size);
humility::msg!(
"block at 0x{:x} failed to verify",
a
);
}
}
_ => {}
}
}
offset += chunk;
if offset >= filelen {
break;
}
}
bar.finish_and_clear();
if subargs.verify {
humility::msg!(
"verified {} in {}",
HumanBytes(filelen as u64),
HumanDuration(started.elapsed())
);
} else {
humility::msg!(
"flashed {} in {}",
HumanBytes(filelen as u64),
HumanDuration(started.elapsed())
);
}
return Ok(());
} else if let Some(filename) = subargs.readfile {
// Address(default=0) and n-bytes(default=size of part-address) are
// optional.
let qspi_read_id = funcs.get("QspiReadId", 0)?;
let qspi_read = funcs.get("QspiRead", 2)?;
// Address is optional and defaults to zero.
// The default can/should be done in `#[clap(...` for "address"
// if that works for the other users of the -a flag.
let mut address = subargs.addr.or(Some(0)).unwrap() as u32;
println!("addr={:?}", address);
let nbytes =
optional_nbytes(core, &mut context, qspi_read_id, subargs.nbytes)?;
println!("nbytes={:?}", nbytes);
//
// Low-level reads are in units less than or equal to
// context.scratch_size().
// Those can be batched, depending on serialization overhead, into
// context.rstack_size().
//
// TODO: check alignment of start and end.
// Things are broken if they aren't, so an assert would be ok.
//
let rstack_size = context.rstack_size() as u32;
let scratch_size = context.scratch_size() as u32;
// TODO: Don't guess at the overhead. Make sure that data and
// serialization meta data are both in rstack.
let overhead = 1; // XXX Assume each item in rstack has 1-byte overhead.
let chunk = scratch_size;
let max_chunks = rstack_size / (chunk + overhead);
let buf = vec![0u8; rstack_size as usize];
let output_file =
File::create(filename).expect("Cannot create output file");
let mut writer = BufWriter::with_capacity(nbytes as usize, output_file);
let started = Instant::now();
let bar = ProgressBar::new(nbytes as u64);
bar.set_style(
ProgressStyle::default_bar()
.template("humility: reading [{bar:30}] {bytes}/{total_bytes}"),
);
let update_cycle = 64;
let mut updates = 0;
let end_address = address + nbytes;
// let mut out_address = address;
println!(
"address={}, chunk={}, end_address={}",
address, chunk, end_address
);
println!("max_chunks={}", max_chunks);
assert!(max_chunks > 0);
loop {
let mut ops = vec![];
for _ in 0..max_chunks {
let len = if address + chunk > end_address {
end_address - address
} else {
chunk
};
if len == 0 {
break;
}
ops.push(Op::Push32(address));
ops.push(Op::Push32(len));
ops.push(Op::Call(qspi_read.id));
address += len;
}
ops.push(Op::Done);
let results = context.run(core, ops.as_slice(), Some(&buf))?;
if updates % update_cycle == 0 {
bar.set_position((address).into());
}
updates += 1;
for (i, block_result) in results.iter().enumerate() {
match &*block_result {
Err(err) => bail!(
"failed to read block {} at offset {}: {}",
i,
address,
qspi_read.strerror(*err)
),
Ok(buf) => {
writer.write_all(buf).expect("write error");
// _out_address += buf.len() as u32;
}
}
}
if address >= end_address {
// redundant with check at top of loop
break;
}
}
writer.flush().unwrap();
bar.finish_and_clear();
humility::msg!(
"read {} in {}",
HumanBytes(nbytes as u64),
HumanDuration(started.elapsed())
);
return Ok(());
} else if let Some(filename) = subargs.diffwrite {
let filelen = fs::metadata(filename.clone())?.len() as u32;
let qspi_hash = funcs.get("QspiHash", 2)?;
let started = Instant::now();
//
// We are going to hash the contents to find the differences, and
// then erase/flash the different sectors.
//
let mut address = 0u32;
let mut sums = vec![];
let bar = ProgressBar::new(filelen as u64);
bar.set_style(
ProgressStyle::default_bar()
.template("humility: hashing [{bar:30}] {bytes}/{total_bytes}"),
);
loop {
let mut ops = vec![];
let max = 8;
let mut laps = 0;
let base = address;
bar.set_position(address.into());
loop {
let len = if address + sector_size > filelen {
filelen - address
} else {
sector_size
};
ops.push(Op::Push32(address));
ops.push(Op::Push32(len));
ops.push(Op::Call(qspi_hash.id));
laps += 1;
address += len;
if address >= filelen || laps >= max {
break;
}
}
ops.push(Op::Done);
let results = context.run(core, ops.as_slice(), None)?;
for (sector, result) in results.iter().enumerate() {
match result {
Err(err) => {
bail!(
"failed on address 0x{:x}: {}",
base + sector as u32 * sector_size,
qspi_hash.strerror(*err),
);
}
Ok(hash) => {
sums.push((
base + sector as u32 * sector_size,
hash.clone(),
));
}
}
}
if address + sector_size >= filelen {
break;
}
}
bar.finish_and_clear();
let mut sectors = vec![];
let mut bufs: Vec<Vec<u8>> = vec![];
let mut nbytes = 0;
deltas(&device, &filename, &sums, |offset, buf| {
sectors.push(offset);
bufs.push(buf.to_vec());
nbytes += buf.len();
Ok(())
})?;
if sectors.is_empty() {
humility::msg!(
"no delta; hashed {} in {}",
HumanBytes(filelen as u64),
HumanDuration(started.elapsed())
);
return Ok(());
}
erase(&device, core, &mut context, &funcs, §ors)?;
let bar = ProgressBar::new(nbytes as u64);
bar.set_style(
ProgressStyle::default_bar()
.template("humility: writing [{bar:30}] {bytes}/{total_bytes}"),
);
let mut total = 0;
//
// Now write each sector.
//
for (addr, buf) in sectors.iter().zip(bufs.iter()) {
let mut offs = 0;
let writelen = buf.len() as u32;
let w = |dest: &mut [u8]| {
bar.set_position(total);
dest.clone_from_slice(&buf[offs..offs + dest.len()]);
offs += dest.len();
total += dest.len() as u64;
Ok(())
};
write(&device, core, &mut context, &funcs, *addr, writelen, w)?;
}
bar.finish_and_clear();
humility::msg!(
"hashed {}, wrote {} in {}",
HumanBytes(filelen as u64),
HumanBytes(total),
HumanDuration(started.elapsed())
);
return Ok(());
} else {
bail!("expected an operation");
};
ops.push(Op::Done);
let results = context.run(
core,
ops.as_slice(),
match data {
Some(ref data) => Some(data.as_slice()),
_ => None,
},
)?;
if subargs.read {
if let Ok(results) = &results[0] {
Dumper::new().dump(results, subargs.addr.unwrap_or(0) as u32);
return Ok(());
}
} else if subargs.id {
// If the response is well formatted, print it out in addition to raw hex.
if let Ok(results) = &results[0] {
if mem::size_of::<DeviceIdData>() == results.len() {
let did: DeviceIdData =
unsafe { std::ptr::read(results.as_ptr() as *const _) };
println!("{}", did);
} else {
println!(
"Unexpected result length: {} != {}",
mem::size_of::<DeviceIdData>(),
results.len()
);
}
}
} else if subargs.hash {
match &results[0] {
Ok(buf) => {
print!("{}: ", hash_name);
for byte in buf {
print!("{:02x}", byte);
}
println!();
}
Err(e) => {
bail!("hash failed: {}", func.strerror(*e));
}
}
return Ok(());
}
println!("{:x?}", results);
Ok(())
}
/// Micron's Device ID Data
// Responses to the Read ID family of instructions can be more flexible than
// the struct below, but until we need support beyond Micron MT25Q, this will do.
#[derive(Debug, Copy, Clone)]
#[repr(C, packed)]
struct DeviceIdData {
manufacturer_id: u8,
memory_type: u8,
memory_capacity: u8,
uid_n: u8,
ext_device_id: u8,
device_configuration_info: u8,
uid: [u8; 14],
}
impl DeviceIdData {
/// Return flash part size in bytes
pub fn size(&self) -> Result<usize> {
match self.memory_capacity {
// This is currently limited to the codes returned from Micron MT25Q parts.
0 => {
return Err(anyhow!(
"unknown size code=0x{:02x?}",
self.memory_capacity
))
}
_ => Ok(1usize << (self.memory_capacity)),
}
}
}
impl fmt::Display for DeviceIdData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mfg = match self.manufacturer_id {
0x20 => "Micron".to_string(),
0xEF => "Winbond".to_string(),
_ => format!("unknown({:x?}", self.manufacturer_id),
};
let memtype: String = match self.memory_type {
0xBA => "3V".to_string(),
0xBB => "1.8V".to_string(),
_ => format!("unknown(0x{:02x?})", self.memory_type),
};
write!(
f,
"DeviceIdData {{\n\
\tmanufacturer_id: {}(0x{:02x})\n\
\tmemory_type: {}({})\n\
\tmemory_capacity: {}\n\
\tuid_n: {}\n\
\t# If a Micron device:\n\
\text_device_id: 0b{:b}\n\
\t\t{} device generation,\n\
\t\t{} BP scheme,\n\
\t\tHOLD#/RESET#={}\n\
\t\tAdditional HW RESET# is {}available,\n\
\t\tSector size is {},\n\
\tdevice_configuration_info: {}\n\
\tuid: {:02x?}\n}}",
mfg,
self.manufacturer_id,
memtype,
self.memory_type,
match self.size() {
Ok(capacity) => capacity.to_string(),
Err(e) => e.to_string(),
},
self.uid_n,
self.ext_device_id,
if (self.ext_device_id & 0b01000000) != 0 { "2nd" } else { "1st" },
if (self.ext_device_id & 0b00100000) != 0 {
"Athernate"
} else {
"Standard"