-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmod.rs
More file actions
1873 lines (1643 loc) · 64 KB
/
mod.rs
File metadata and controls
1873 lines (1643 loc) · 64 KB
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
//! Interact with the Chrome EC controller firmware.
//!
//! It's used on Chromebooks as well as non-Chromebook Framework laptops.
//!
//! Currently three drivers are supported:
//!
//! - `cros_ec` - It uses the `cros_ec` kernel module in Linux
//! - `portio` - It uses raw port I/O. This works on UEFI and on Linux if the system isn't in lockdown mode (SecureBoot disabled).
//! - `windows` - It uses [DHowett's Windows driver](https://github.com/DHowett/FrameworkWindowsUtils)
use crate::ec_binary;
use crate::os_specific;
use crate::power;
use crate::smbios;
#[cfg(feature = "uefi")]
use crate::uefi::shell_get_execution_break_flag;
use crate::util::{self, Platform};
use no_std_compat::time::Duration;
use log::Level;
use num_derive::FromPrimitive;
pub mod command;
pub mod commands;
#[cfg(target_os = "linux")]
mod cros_ec;
pub mod i2c_passthrough;
pub mod input_deck;
#[cfg(not(windows))]
mod portio;
#[cfg(not(windows))]
mod portio_mec;
#[allow(dead_code)]
mod protocol;
#[cfg(windows)]
mod windows;
use alloc::format;
use alloc::string::String;
use alloc::string::ToString;
use alloc::vec;
use alloc::vec::Vec;
#[cfg(feature = "uefi")]
use core::prelude::rust_2021::derive;
use num_traits::FromPrimitive;
pub use command::EcRequestRaw;
use commands::*;
use self::command::EcCommands;
use self::input_deck::InputDeckStatus;
// 512K
pub const EC_FLASH_SIZE: usize = 512 * 1024;
/// Total size of EC memory mapped region
const EC_MEMMAP_SIZE: u16 = 0xFF;
/// Offset in mapped memory where there are two magic bytes
/// representing 'EC' in ASCII (0x20 == 'E', 0x21 == 'C')
const EC_MEMMAP_ID: u16 = 0x20;
const FLASH_BASE: u32 = 0x0; // 0x80000
const FLASH_RO_BASE: u32 = 0x0;
const FLASH_RO_SIZE: u32 = 0x3C000;
const FLASH_RW_BASE: u32 = 0x40000;
const FLASH_RW_SIZE: u32 = 0x39000;
const MEC_FLASH_FLAGS: u32 = 0x80000;
const NPC_FLASH_FLAGS: u32 = 0x7F000;
const FLASH_PROGRAM_OFFSET: u32 = 0x1000;
#[derive(Clone, Debug, PartialEq)]
pub enum EcFlashType {
Full,
Ro,
Rw,
}
#[derive(PartialEq)]
pub enum MecFlashNotify {
AccessSpi = 0x00,
FirmwareStart = 0x01,
FirmwareDone = 0x02,
AccessSpiDone = 0x03,
FlashPd = 0x16,
}
pub type EcResult<T> = Result<T, EcError>;
#[derive(Debug, PartialEq)]
pub enum EcError {
Response(EcResponseStatus),
UnknownResponseCode(u32),
// Failed to communicate with the EC
DeviceError(String),
}
/// Response codes returned by commands
#[derive(Debug, PartialEq, FromPrimitive, Clone, Copy)]
pub enum EcResponseStatus {
Success = 0,
InvalidCommand = 1,
Error = 2,
InvalidParameter = 3,
AccessDenied = 4,
InvalidResponse = 5,
InvalidVersion = 6,
InvalidChecksum = 7,
/// Accepted, command in progress
InProgress = 8,
/// No response available
Unavailable = 9,
/// We got a timeout
Timeout = 10,
/// Table / data overflow
Overflow = 11,
/// Header contains invalid data
InvalidHeader = 12,
/// Didn't get the entire request
RequestTruncated = 13,
/// Response was too big to handle
ResponseTooBig = 14,
/// Communications bus error
BusError = 15,
/// Up but too busy. Should retry
Busy = 16,
}
#[repr(u8)]
#[derive(Copy, Clone, Debug)]
pub enum Framework12Adc {
MainboardBoardId,
PowerButtonBoardId,
Psys,
AdapterCurrent,
TouchpadBoardId,
AudioBoardId,
}
#[repr(u8)]
#[derive(Copy, Clone, Debug)]
pub enum FrameworkHx20Hx30Adc {
AdapterCurrent,
Psys,
BattTemp,
TouchpadBoardId,
MainboardBoardId,
AudioBoardId,
}
/// So far on all Nuvoton/Zephyr EC based platforms
/// Until at least Framework 13 AMD Ryzen AI 300
#[repr(u8)]
#[derive(Copy, Clone, Debug)]
pub enum Framework13Adc {
MainboardBoardId,
Psys,
AdapterCurrent,
TouchpadBoardId,
AudioBoardId,
BattTemp,
}
#[repr(u8)]
#[derive(Copy, Clone, Debug)]
pub enum Framework16Adc {
MainboardBoardId,
HubBoardId,
GpuBoardId0,
GpuBoardId1,
AdapterCurrent,
Psys,
}
/*
* PLATFORM_EC_ADC_RESOLUTION default 10 bit
*
* +------------------+-----------+----------+-------------+---------+----------------------+
* | BOARD VERSION | voltage | NPC DB V | main board | GPU | Input module |
* +------------------+-----------+----------|-------------+---------+----------------------+
* | BOARD_VERSION_0 | 0 mV | 100 mV | Unused | | Reserved |
* | BOARD_VERSION_1 | 173 mV | 310 mV | Unused | | Reserved |
* | BOARD_VERSION_2 | 300 mV | 520 mV | Unused | | Reserved |
* | BOARD_VERSION_3 | 430 mV | 720 mV | Unused | | Reserved |
* | BOARD_VERSION_4 | 588 mV | 930 mV | EVT1 | | Reserved |
* | BOARD_VERSION_5 | 783 mV | 1130 mV | Unused | | Reserved |
* | BOARD_VERSION_6 | 905 mV | 1340 mV | Unused | | Reserved |
* | BOARD_VERSION_7 | 1033 mV | 1550 mV | DVT1 | | Reserved |
* | BOARD_VERSION_8 | 1320 mV | 1750 mV | DVT2 | | Generic A size |
* | BOARD_VERSION_9 | 1500 mV | 1960 mV | PVT | | Generic B size |
* | BOARD_VERSION_10 | 1650 mV | 2170 mV | MP | | Generic C size |
* | BOARD_VERSION_11 | 1980 mV | 2370 mV | Unused | RID_0 | 10 Key B size |
* | BOARD_VERSION_12 | 2135 mV | 2580 mV | Unused | RID_0,1 | Keyboard |
* | BOARD_VERSION_13 | 2500 mV | 2780 mV | Unused | RID_0 | Touchpad |
* | BOARD_VERSION_14 | 2706 mV | 2990 mV | Unused | | Reserved |
* | BOARD_VERSION_15 | 2813 mV | 3200 mV | Unused | | Not installed |
* +------------------+-----------+----------+-------------+---------+----------------------+
*/
const BOARD_VERSION_COUNT: usize = 16;
const BOARD_VERSION: [i32; BOARD_VERSION_COUNT] = [
203, 409, 615, 821, 1028, 1234, 1440, 1646, 1853, 2059, 2265, 2471, 2678, 2884, 3090, 3300,
];
const BOARD_VERSION_NPC_DB: [i32; BOARD_VERSION_COUNT] = [
85, 233, 360, 492, 649, 844, 965, 1094, 1380, 1562, 1710, 2040, 2197, 2557, 2766, 2814,
];
pub trait CrosEcDriver {
fn read_memory(&self, offset: u16, length: u16) -> Option<Vec<u8>>;
fn send_command(&self, command: u16, command_version: u8, data: &[u8]) -> EcResult<Vec<u8>>;
}
#[derive(Clone)]
pub struct CrosEc {
driver: CrosEcDriverType,
}
impl Default for CrosEc {
fn default() -> Self {
Self::new()
}
}
/// Find out which drivers are available
///
/// Depending on the availability we choose the first one as default
#[allow(clippy::vec_init_then_push)]
fn available_drivers() -> Vec<CrosEcDriverType> {
let mut drivers = vec![];
#[cfg(windows)]
drivers.push(CrosEcDriverType::Windows);
#[cfg(target_os = "linux")]
if std::path::Path::new(cros_ec::DEV_PATH).exists() {
drivers.push(CrosEcDriverType::CrosEc);
}
#[cfg(not(windows))]
drivers.push(CrosEcDriverType::Portio);
drivers
}
impl CrosEc {
pub fn new() -> CrosEc {
debug!("Chromium EC Driver: {:?}", available_drivers()[0]);
CrosEc {
driver: available_drivers()[0],
}
}
pub fn with(driver: CrosEcDriverType) -> Option<CrosEc> {
if !available_drivers().contains(&driver) {
return None;
}
debug!("Chromium EC Driver: {:?}", driver);
Some(CrosEc { driver })
}
/// Lock bus to PD controller in the beginning of flashing
/// TODO: Perhaps I could return a struct that will lock the bus again in its destructor
pub fn lock_pd_bus(&self, lock: bool) -> EcResult<()> {
let lock = if lock {
MecFlashNotify::FlashPd
} else {
MecFlashNotify::FirmwareDone
} as u8;
match self.send_command(EcCommands::FlashNotified as u16, 0, &[lock]) {
Ok(vec) if !vec.is_empty() => Err(EcError::DeviceError(
"Didn't expect a response!".to_string(),
)),
Ok(_) => Ok(()),
Err(err) => Err(err),
}
}
pub fn check_mem_magic(&self) -> EcResult<()> {
match self.read_memory(EC_MEMMAP_ID, 2) {
Some(ec_id) => {
if ec_id.len() != 2 {
Err(EcError::DeviceError(format!(
" Unexpected length returned: {:?}",
ec_id.len()
)))
} else if ec_id[0] != b'E' || ec_id[1] != b'C' {
Err(EcError::DeviceError(
"This machine doesn't look like it has a Framework EC".to_string(),
))
} else {
Ok(())
}
}
None => Err(EcError::DeviceError(
"Failed to read EC ID from memory map".to_string(),
)),
}
}
pub fn cmd_version_supported(&self, cmd: u16, version: u8) -> EcResult<bool> {
let res = EcRequestGetCmdVersionsV1 { cmd: cmd.into() }.send_command(self);
let mask = if let Ok(res) = res {
res.version_mask
} else {
let res = EcRequestGetCmdVersionsV0 { cmd: cmd as u8 }.send_command(self)?;
res.version_mask
};
Ok(mask & (1 << version) > 0)
}
pub fn dump_mem_region(&self) -> Option<Vec<u8>> {
// Crashes on Linux cros_ec driver if we read the last byte
self.read_memory(0x00, EC_MEMMAP_SIZE - 1)
}
/// Get EC firmware build information
pub fn version_info(&self) -> EcResult<String> {
// Response is null-terminated string.
let data = self.send_command(EcCommands::GetBuildInfo as u16, 0, &[])?;
Ok(std::str::from_utf8(&data)
.map_err(|utf8_err| {
EcError::DeviceError(format!("Failed to decode version: {:?}", utf8_err))
})?
.trim_end_matches(char::from(0))
.to_string())
}
pub fn flash_version(&self) -> Option<(String, String, EcCurrentImage)> {
// Unlock SPI
// TODO: Lock flash again again
let _data = EcRequestFlashNotify { flags: 0 }.send_command(self).ok()?;
let v = EcRequestGetVersion {}.send_command(self).ok()?;
let curr = match v.current_image {
1 => EcCurrentImage::RO,
2 => EcCurrentImage::RW,
_ => EcCurrentImage::Unknown,
};
Some((
std::str::from_utf8(&v.version_string_ro)
.ok()?
.trim_end_matches(char::from(0))
.to_string(),
std::str::from_utf8(&v.version_string_rw)
.ok()?
.trim_end_matches(char::from(0))
.to_string(),
curr,
))
}
pub fn motionsense_sensor_count(&self) -> EcResult<u8> {
EcRequestMotionSenseDump {
cmd: MotionSenseCmd::Dump as u8,
max_sensor_count: 0,
}
.send_command(self)
.map(|res| res.sensor_count)
}
pub fn motionsense_sensor_info(&self) -> EcResult<Vec<MotionSenseInfo>> {
let count = self.motionsense_sensor_count()?;
let mut sensors = vec![];
for sensor_num in 0..count {
let info = EcRequestMotionSenseInfo {
cmd: MotionSenseCmd::Info as u8,
sensor_num,
}
.send_command(self)?;
sensors.push(MotionSenseInfo {
sensor_type: FromPrimitive::from_u8(info.sensor_type).unwrap(),
location: FromPrimitive::from_u8(info.location).unwrap(),
chip: FromPrimitive::from_u8(info.chip).unwrap(),
});
}
Ok(sensors)
}
pub fn motionsense_sensor_list(&self) -> EcResult<u8> {
EcRequestMotionSenseDump {
cmd: MotionSenseCmd::Dump as u8,
max_sensor_count: 0,
}
.send_command(self)
.map(|res| res.sensor_count)
}
pub fn remap_caps_to_ctrl(&self) -> EcResult<()> {
self.remap_key(6, 15, 0x0014)
}
pub fn remap_key(&self, row: u8, col: u8, scanset: u16) -> EcResult<()> {
let _current_matrix = EcRequestUpdateKeyboardMatrix {
num_items: 1,
write: 1,
scan_update: [KeyboardMatrixMap { row, col, scanset }],
}
.send_command(self)?;
Ok(())
}
/// Get current status of Framework Laptop's microphone and camera privacy switches
/// [true = device enabled/connected, false = device disabled]
pub fn get_privacy_info(&self) -> EcResult<(bool, bool)> {
let status = EcRequestPrivacySwitches {}.send_command(self)?;
Ok((status.microphone == 1, status.camera == 1))
}
pub fn set_charge_limit(&self, min: u8, max: u8) -> EcResult<()> {
// Sending bytes manually because the Set command, as opposed to the Get command,
// does not return any data
let limits = &[ChargeLimitControlModes::Set as u8, max, min];
let data = self.send_command(EcCommands::ChargeLimitControl as u16, 0, limits)?;
util::assert_win_len(data.len(), 0);
Ok(())
}
/// Get charge limit in percent (min, max)
pub fn get_charge_limit(&self) -> EcResult<(u8, u8)> {
let limits = EcRequestChargeLimitControl {
modes: ChargeLimitControlModes::Get as u8,
max_percentage: 0xFF,
min_percentage: 0xFF,
}
.send_command(self)?;
debug!(
"Min Raw: {}, Max Raw: {}",
limits.min_percentage, limits.max_percentage
);
Ok((limits.min_percentage, limits.max_percentage))
}
pub fn set_charge_current_limit(&self, current: u32, battery_soc: Option<u32>) -> EcResult<()> {
if let Some(battery_soc) = battery_soc {
let battery_soc = battery_soc as u8;
EcRequestCurrentLimitV1 {
current,
battery_soc,
}
.send_command(self)
} else {
EcRequestCurrentLimitV0 { current }.send_command(self)
}
}
pub fn set_charge_rate_limit(&self, rate: f32, battery_soc: Option<f32>) -> EcResult<()> {
let power_info = power::power_info(self).ok_or(EcError::DeviceError(
"Failed to get battery info".to_string(),
))?;
let battery = power_info
.battery
.ok_or(EcError::DeviceError("No battery present".to_string()))?;
println!("Requested Rate: {}C", rate);
println!("Design Current: {}mA", battery.design_capacity);
let current = (rate * (battery.design_capacity as f32)) as u32;
println!("Limiting Current to: {}mA", current);
if let Some(battery_soc) = battery_soc {
let battery_soc = battery_soc as u8;
EcRequestCurrentLimitV1 {
current,
battery_soc,
}
.send_command(self)
} else {
EcRequestCurrentLimitV0 { current }.send_command(self)
}
}
pub fn set_fp_led_percentage(&self, percentage: u8) -> EcResult<()> {
// Sending bytes manually because the Set command, as opposed to the Get command,
// does not return any data
let limits = &[percentage, 0x00];
let data = self.send_command(EcCommands::FpLedLevelControl as u16, 1, limits)?;
util::assert_win_len(data.len(), 0);
Ok(())
}
pub fn set_fp_led_level(&self, level: FpLedBrightnessLevel) -> EcResult<()> {
// Sending bytes manually because the Set command, as opposed to the Get command,
// does not return any data
let limits = &[level as u8, 0x00];
let data = self.send_command(EcCommands::FpLedLevelControl as u16, 0, limits)?;
util::assert_win_len(data.len(), 0);
Ok(())
}
/// Get fingerprint led brightness level
pub fn get_fp_led_level(&self) -> EcResult<(u8, Option<FpLedBrightnessLevel>)> {
let res = EcRequestFpLedLevelControlV1 {
set_percentage: 0xFF,
get_level: 0xFF,
}
.send_command(self);
// If V1 does not exist, fall back
if let Err(EcError::Response(EcResponseStatus::InvalidVersion)) = res {
let res = EcRequestFpLedLevelControlV0 {
set_level: 0xFF,
get_level: 0xFF,
}
.send_command(self)?;
debug!("Current Brightness: {}%", res.percentage);
return Ok((res.percentage, None));
}
let res = res?;
debug!("Current Brightness: {}%", res.percentage);
debug!("Level Raw: {}", res.level);
// TODO: can turn this into None and log
let level = FromPrimitive::from_u8(res.level)
.ok_or(EcError::DeviceError(format!("Invalid level {}", res.level)))?;
Ok((res.percentage, Some(level)))
}
/// Get the intrusion switch status (whether the chassis is open or not)
pub fn get_intrusion_status(&self) -> EcResult<IntrusionStatus> {
let status = EcRequestChassisOpenCheck {}.send_command(self)?;
let intrusion = EcRequestChassisIntrusionControl {
clear_magic: 0,
clear_chassis_status: 0,
}
.send_command(self)?;
Ok(IntrusionStatus {
currently_open: status.status == 1,
coin_cell_ever_removed: intrusion.coin_batt_ever_remove == 1,
ever_opened: intrusion.chassis_ever_opened == 1,
total_opened: intrusion.total_open_count,
vtr_open_count: intrusion.vtr_open_count,
})
}
/// Check if the retimer is in firmware update mode
///
/// This is normally false. Update mode is used to enable the retimer power even when no device
/// is attached.
pub fn retimer_in_fwupd_mode(&self, retimer: u8) -> EcResult<bool> {
let status = EcRequestRetimerControl {
controller: retimer,
mode: RetimerControlMode::CheckStatus as u8,
}
.send_command(self)?;
Ok(status.status == 0x01)
}
/// Enable or disable retimer update mode
///
/// Check for success and returns Err if not successful
pub fn retimer_enable_fwupd(&self, retimer: u8, enable: bool) -> EcResult<()> {
if self.retimer_in_fwupd_mode(retimer)? == enable {
info!("Retimer update mode already: {:?}", enable);
return Ok(());
}
EcRequestRetimerControl {
controller: retimer,
mode: if enable {
RetimerControlMode::EntryFwUpdateMode as u8
} else {
RetimerControlMode::ExitFwUpdateMode as u8
},
}
.send_command(self)?;
// Wait half a second to let it enter the new mode
os_specific::sleep(500_000);
if self.retimer_in_fwupd_mode(retimer).unwrap() != enable {
error!("Failed to set retimer update mode to: {}", enable);
return Err(EcError::DeviceError(format!(
"Failed to set retimer update mode to: {}",
enable
)));
}
Ok(())
}
/// Enable or disable retimer Thunderbolt compliance mode (Intel only)
///
/// Cannot check for success
pub fn retimer_enable_compliance(&self, retimer: u8, enable: bool) -> EcResult<()> {
EcRequestRetimerControl {
controller: retimer,
mode: if enable {
RetimerControlMode::EnableComplianceMode as u8
} else {
RetimerControlMode::DisableComplianceMode as u8
},
}
.send_command(self)?;
Ok(())
}
pub fn get_input_deck_status(&self) -> EcResult<InputDeckStatus> {
let status = EcRequestDeckState {
mode: DeckStateMode::ReadOnly,
}
.send_command(self)?;
Ok(InputDeckStatus::from(status))
}
pub fn print_fw12_inputdeck_status(&self) -> EcResult<()> {
let intrusion = self.get_intrusion_status()?;
let pwrbtn = self.read_board_id(Framework12Adc::PowerButtonBoardId as u8)?;
let audio = self.read_board_id(Framework12Adc::AudioBoardId as u8)?;
let tp = self.read_board_id(Framework12Adc::TouchpadBoardId as u8)?;
let is_present = |p| if p { "Present" } else { "Missing" };
println!("Input Deck");
println!(" Chassis Closed: {}", !intrusion.currently_open);
println!(" Power Button Board: {}", is_present(pwrbtn.is_some()));
println!(" Audio Daughterboard: {}", is_present(audio.is_some()));
println!(" Touchpad: {}", is_present(tp.is_some()));
Ok(())
}
pub fn print_fw13_inputdeck_status(&self) -> EcResult<()> {
let intrusion = self.get_intrusion_status()?;
let (audio, tp) = match smbios::get_platform() {
Some(Platform::IntelGen11)
| Some(Platform::IntelGen12)
| Some(Platform::IntelGen13) => (
self.read_board_id(FrameworkHx20Hx30Adc::AudioBoardId as u8)?,
self.read_board_id(FrameworkHx20Hx30Adc::TouchpadBoardId as u8)?,
),
_ => (
self.read_board_id_npc_db(Framework13Adc::AudioBoardId as u8)?,
self.read_board_id_npc_db(Framework13Adc::TouchpadBoardId as u8)?,
),
};
let is_present = |p| if p { "Present" } else { "Missing" };
println!("Input Deck");
println!(" Chassis Closed: {}", !intrusion.currently_open);
println!(
" Audio Daughterboard: {}",
if let Some(audio) = audio {
format!("{} ({})", is_present(true), audio)
} else {
is_present(false).to_string()
}
);
println!(
" ADC Value (mV) {:?}",
self.adc_read(Framework13Adc::AudioBoardId as u8)
);
println!(
" Touchpad: {}",
if let Some(tp) = tp {
format!("{} ({})", is_present(true), tp)
} else {
is_present(false).to_string()
}
);
println!(
" ADC Value (mV) {:?}",
self.adc_read(Framework13Adc::TouchpadBoardId as u8)
);
Ok(())
}
pub fn print_fw16_inputdeck_status(&self) -> EcResult<()> {
let intrusion = self.get_intrusion_status()?;
let status = self.get_input_deck_status()?;
let sleep_l = self.get_gpio("sleep_l")?;
println!("Chassis Closed: {}", !intrusion.currently_open);
println!("Input Deck State: {:?}", status.state);
println!("Touchpad present: {}", status.touchpad_present);
println!("SLEEP# GPIO high: {}", sleep_l);
println!("Positions:");
println!(" Pos 0: {:?}", status.top_row.pos0);
println!(" Pos 1: {:?}", status.top_row.pos1);
println!(" Pos 2: {:?}", status.top_row.pos2);
println!(" Pos 3: {:?}", status.top_row.pos3);
println!(" Pos 4: {:?}", status.top_row.pos4);
Ok(())
}
pub fn set_input_deck_mode(&self, mode: DeckStateMode) -> EcResult<InputDeckStatus> {
let status = EcRequestDeckState { mode }.send_command(self)?;
Ok(InputDeckStatus::from(status))
}
/// Change the keyboard baclight brightness
///
/// # Arguments
/// * `percent` - An integer from 0 to 100. 0 being off, 100 being full brightness
pub fn set_keyboard_backlight(&self, percent: u8) {
debug_assert!(percent <= 100);
let res = EcRequestPwmSetDuty {
duty: percent as u16 * (PWM_MAX_DUTY / 100),
pwm_type: PwmType::KbLight as u8,
index: 0,
}
.send_command(self);
debug_assert!(res.is_ok());
}
/// Check the current brightness of the keyboard backlight
pub fn get_keyboard_backlight(&self) -> EcResult<u8> {
let kblight = EcRequestPwmGetDuty {
pwm_type: PwmType::KbLight as u8,
index: 0,
}
.send_command(self)?;
Ok((kblight.duty / (PWM_MAX_DUTY / 100)) as u8)
}
pub fn ps2_emulation_enable(&self, enable: bool) -> EcResult<()> {
EcRequestDisablePs2Emulation {
disable: !enable as u8,
}
.send_command(self)
}
pub fn fan_set_rpm(&self, fan: Option<u32>, rpm: u32) -> EcResult<()> {
if let Some(fan_idx) = fan {
EcRequestPwmSetFanTargetRpmV1 { rpm, fan_idx }.send_command(self)
} else {
EcRequestPwmSetFanTargetRpmV0 { rpm }.send_command(self)
}
}
pub fn fan_set_duty(&self, fan: Option<u32>, percent: u32) -> EcResult<()> {
if percent > 100 {
return Err(EcError::DeviceError("Fan duty must be <= 100".to_string()));
}
if let Some(fan_idx) = fan {
EcRequestPwmSetFanDutyV1 { fan_idx, percent }.send_command(self)
} else {
EcRequestPwmSetFanDutyV0 { percent }.send_command(self)
}
}
pub fn autofanctrl(&self, fan: Option<u8>) -> EcResult<()> {
if let Some(fan_idx) = fan {
EcRequestAutoFanCtrlV1 { fan_idx }.send_command(self)
} else {
EcRequestAutoFanCtrlV0 {}.send_command(self)
}
}
/// Set tablet mode
pub fn set_tablet_mode(&self, mode: TabletModeOverride) {
let mode = mode as u8;
let res = EcRequestSetTabletMode { mode }.send_command(self);
print_err(res);
}
/// Overwrite RO and RW regions of EC flash
/// MEC/Legacy EC
/// | Start | End | Size | Region |
/// | 00000 | 3BFFF | 3C000 | RO Region |
/// | 3C000 | 3FFFF | 04000 | Preserved |
/// | 40000 | 3C000 | 39000 | RO Region |
/// | 79000 | 79FFF | 01000 | Preserved |
/// | 80000 | 80FFF | 01000 | Flash Flags |
///
/// NPC/Zephyr
/// | Start | End | Size | Region |
/// | 00000 | 3BFFF | 3C000 | RO Region |
/// | 3C000 | 3FFFF | 04000 | Preserved |
/// | 40000 | 3C000 | 39000 | RO Region |
/// | 79000 | 79FFF | 01000 | Flash Flags |
pub fn reflash(&self, data: &[u8], ft: EcFlashType, dry_run: bool) -> EcResult<()> {
let mut res = Ok(());
let cur_ver = self.version_info()?;
let platform = if let Some(ver) = ec_binary::parse_ec_version_str(&cur_ver) {
ver.platform
} else {
return Err(EcError::DeviceError(
"Cannot determine currently running platform.".to_string(),
));
};
if ft == EcFlashType::Full || ft == EcFlashType::Ro {
if let Some(version) = ec_binary::read_ec_version(data, true) {
println!("EC RO Version in File: {:?}", version.version);
if version.details.platform != platform {
return Err(EcError::DeviceError(format!(
"RO Firmware file is for platform {}. Currently running {}",
version.details.platform, platform
)));
}
} else {
return Err(EcError::DeviceError(
"File does not contain valid EC RO firmware".to_string(),
));
}
}
if ft == EcFlashType::Full || ft == EcFlashType::Rw {
if let Some(version) = ec_binary::read_ec_version(data, false) {
println!("EC RW Version in File: {:?}", version.version);
if version.details.platform != platform {
return Err(EcError::DeviceError(format!(
"RW Firmware file is for platform {}. Currently running {}",
version.details.platform, platform
)));
}
} else {
return Err(EcError::DeviceError(
"File does not contain valid EW RW firmware".to_string(),
));
}
}
// Determine recommended flash parameters
let info = EcRequestFlashInfo {}.send_command(self)?;
// Check that our hardcoded offsets are valid for the available flash
if FLASH_RO_SIZE + FLASH_RW_SIZE > info.flash_size {
return Err(EcError::DeviceError(format!(
"RO+RW larger than flash 0x{:X}",
{ info.flash_size }
)));
}
if FLASH_RW_BASE + FLASH_RW_SIZE > info.flash_size {
return Err(EcError::DeviceError(format!(
"RW overruns end of flash 0x{:X}",
{ info.flash_size }
)));
}
println!("Unlocking flash");
self.flash_notify(MecFlashNotify::AccessSpi)?;
self.flash_notify(MecFlashNotify::FirmwareStart)?;
// TODO: Check if erase was successful
// 1. First erase 0x10000 bytes
// 2. Read back two rows and make sure it's all 0xFF
// 3. Write each row (128B) individually
if ft == EcFlashType::Full || ft == EcFlashType::Rw {
let rw_data = &data[FLASH_RW_BASE as usize..(FLASH_RW_BASE + FLASH_RW_SIZE) as usize];
println!(
"Erasing RW region{}",
if dry_run { " (DRY RUN)" } else { "" }
);
self.erase_ec_flash(
FLASH_BASE + FLASH_RW_BASE,
FLASH_RW_SIZE,
dry_run,
info.erase_block_size,
)?;
println!(" Done");
println!(
"Writing RW region{}",
if dry_run { " (DRY RUN)" } else { "" }
);
self.write_ec_flash(FLASH_BASE + FLASH_RW_BASE, rw_data, dry_run)?;
println!(" Done");
println!("Verifying RW region");
let flash_rw_data = self.read_ec_flash(FLASH_BASE + FLASH_RW_BASE, FLASH_RW_SIZE)?;
if rw_data == flash_rw_data {
println!(" RW verify success");
} else {
error!("RW verify fail!");
res = Err(EcError::DeviceError("RW verify fail!".to_string()));
}
}
if ft == EcFlashType::Full || ft == EcFlashType::Ro {
let ro_data = &data[FLASH_RO_BASE as usize..(FLASH_RO_BASE + FLASH_RO_SIZE) as usize];
println!("Erasing RO region");
self.erase_ec_flash(
FLASH_BASE + FLASH_RO_BASE,
FLASH_RO_SIZE,
dry_run,
info.erase_block_size,
)?;
println!(" Done");
println!("Writing RO region");
self.write_ec_flash(FLASH_BASE + FLASH_RO_BASE, ro_data, dry_run)?;
println!(" Done");
println!("Verifying RO region");
let flash_ro_data = self.read_ec_flash(FLASH_BASE + FLASH_RO_BASE, FLASH_RO_SIZE)?;
if ro_data == flash_ro_data {
println!(" RO verify success");
} else {
error!("RO verify fail!");
res = Err(EcError::DeviceError("RW verify fail!".to_string()));
}
}
println!("Locking flash");
self.flash_notify(MecFlashNotify::AccessSpiDone)?;
self.flash_notify(MecFlashNotify::FirmwareDone)?;
if res.is_ok() {
println!("Flashing EC done. You can reboot the EC now");
}
res
}
/// Write a big section of EC flash. Must be unlocked already
fn write_ec_flash(&self, addr: u32, data: &[u8], dry_run: bool) -> EcResult<()> {
// TODO: Use flash info to help guide ideal chunk size
// let info = EcRequestFlashInfo {}.send_command(self)?;
//let chunk_size = ((0x80 / info.write_ideal_size) * info.write_ideal_size) as usize;
let chunk_size = 0x80;
let chunks = data.len() / chunk_size;
println!(
" Will write flash from 0x{:X} to 0x{:X} in {}*{}B chunks",
addr,
data.len(),
chunks,
chunk_size
);
for chunk_no in 0..chunks {
let offset = chunk_no * chunk_size;
// Current chunk might be smaller if it's the last
let cur_chunk_size = std::cmp::min(chunk_size, data.len() - chunk_no * chunk_size);
if chunk_no % 100 == 0 {
if chunk_no != 0 {
println!();
}
print!(" Chunk {:>4}: X", chunk_no);
} else {
print!("X");
}
let chunk = &data[offset..offset + cur_chunk_size];
if !dry_run {
let res = self.write_ec_flash_chunk(addr + offset as u32, chunk);
if let Err(err) = res {
println!(" Failed to write chunk: {:?}", err);
return Err(err);
}
}
}
println!();
Ok(())
}
fn write_ec_flash_chunk(&self, offset: u32, data: &[u8]) -> EcResult<()> {
assert!(data.len() <= 0x80); // TODO: I think this is EC_LPC_HOST_PACKET_SIZE - size_of::<EcHostResponse>()
EcRequestFlashWrite {
offset,
size: data.len() as u32,
data: [],
}
.send_command_extra(self, data)
}
fn erase_ec_flash(
&self,
offset: u32,
size: u32,
dry_run: bool,
chunk_size: u32,
) -> EcResult<()> {
// Erasing a big section takes too long sometimes and the linux kernel driver times out, so
// split it up into chunks.
let mut cur_offset = offset;
while cur_offset < offset + size {
let rem_size = offset + size - cur_offset;
let cur_size = if rem_size < chunk_size {
rem_size