-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathnvme_drive.py
More file actions
1536 lines (1397 loc) · 56.3 KB
/
Copy pathnvme_drive.py
File metadata and controls
1536 lines (1397 loc) · 56.3 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
#!/usr/bin/env python3
# pyre-unsafe
"""library to manage nvme drive"""
import json
import os
import re
import time
from enum import Enum
from time import sleep
from typing import Dict, List
from autoval.lib.host.component.component import COMPONENT
from autoval.lib.utils.autoval_errors import ErrorType
from autoval.lib.utils.autoval_exceptions import AutovalFileNotFound, TestError
from autoval.lib.utils.autoval_log import AutovalLog
from autoval.lib.utils.autoval_utils import AutovalUtils
from autoval.lib.utils.decorators import retry
from autoval.lib.utils.file_actions import FileActions
from autoval.lib.utils.generic_utils import GenericUtils
from autoval.lib.utils.result_handler import ResultHandler
from autoval.lib.utils.site_utils import SiteUtils
from autoval_ssd.lib.utils.disk_utils import DiskUtils
from autoval_ssd.lib.utils.pci_utils import PciUtils
from autoval_ssd.lib.utils.storage.drive import Drive, DriveInterface
from autoval_ssd.lib.utils.storage.nvme.nvme_utils import NVMeUtils
DEFAULT_VALIDATE_CONFIG = "nvme_validate.json"
def _strip_white_spaces_from_keys(mapping: dict) -> None:
"""
Recursively remove white spaces from key names of a dictionary in place
Args:
mapping: Dictionary to be modified
"""
for k, v in list(mapping.items()):
_k = k.strip()
if _k != k:
mapping[_k] = v
del mapping[k]
if isinstance(v, dict):
_strip_white_spaces_from_keys(v)
class OwnershipStatus(Enum):
"""Class for drive ownership"""
SET = "Set"
NOT_SET = "Not Set"
BLOCKED_AND_SET = "Blocked and set"
BLOCKED_AND_NOT_SET = "Blocked and not set"
BLOCKED = "Blocked"
class NVMeDrive(Drive):
"""Main class for nvme drive"""
FEATURE_IDS = [
"0x1",
"0x2",
"0x4",
"0x5",
"0x7",
"0x8",
"0x9",
"0xA",
"0xB",
"0xE",
]
NVMECLI_MANUFACTURER = None
def __init__(self, host, block_name, config=None) -> None:
"""
Class for storing data and interacting with NVME drives
@param Host host: host object
@param String block_name: drive name in /dev/ path
@param String config: name of json file that control how drive data is
validated. NVMe configs are in directory
NVME validate config are placed in two directories in
/autoval_ssd/cfg
- cfg/nvme_smart
- cfg/nvme_smart_fdi
"""
super().__init__(host, block_name, config=config)
if config is None:
config = DEFAULT_VALIDATE_CONFIG
self.interface = DriveInterface.NVME
self.serial_number = self.get_serial_number()
self.model = self._get_model()
self.manufacturer = self.get_manufacturer()
self.vid = NVMeUtils.get_vendor_id(host, block_name)
self.reboot_models = self.get_reboot_models()
self.subsystem_reset_models = self.get_susbsystem_reset_models()
self.tooling_owned_models = self.get_tooling_owned_models()
self.id_ctrl = self.get_id_ctrl()
self.vendor_entry = None
self.smart_log_keys = None
self.validate_config = self.load_config(config)
self.fw_ns_action_model_map = {}
self.fw_update_reset_req_models = []
self.fw_commit_timer_before = None
self.fw_commit_timer_after = None
self.command_timer_before = None
self.admin_command_timer_after = None
self.io_command_timer_after = None
self.admin_command = None
self.io_command = None
self.fw_ver = None
self.current_fw_ver = None
self.fw_ns_slots_models_map = {}
self.ocp_2_6_drives: List = []
self.workload_target_drives: List = []
self.lmparser_ocp_2_0_drives = {}
self.cfg_dir = ""
def get_smart_log_keys(self) -> None:
"""
Method to get list of applicable smart log keys for a drive
"""
if not self.smart_log_keys:
smart_log = self.get_smart_log()
self.smart_log_keys = self._flatten_validate_config_dict(smart_log).keys()
def load_config(self, config_file: str) -> Dict:
"""
@param config_file
@return config for smart validation
"""
config = {}
self.cfg_dir = self._get_config_dir(config_file)
relative_cfg_file_path = os.path.join(self.cfg_dir, config_file)
relative_cfg_file_path = "/cfg/" + relative_cfg_file_path
abs_path = self.get_target_path()
nvme_cfg_path = abs_path + relative_cfg_file_path
content = FileActions.read_data(nvme_cfg_path, json_file=True)
config.update(content["nvme"])
self.get_smart_log_keys()
config = self._flatten_validate_config_dict(config)
validate_config = {
key: config[key] for key in self.smart_log_keys if key in config
}
return validate_config
@staticmethod
def get_target_path() -> str:
"""
Returns the path of the target path which is used to get the cfg path in the autoval-oss
"""
# Get the absolute path of the current file
target_path = ""
current_file_path = os.path.abspath(__file__)
try:
pattern = r"^(/.*?)/autoval_ssd/"
match = re.search(pattern, current_file_path)
if match:
target_path = match.group(0)[:-1]
except Exception:
raise AutovalFileNotFound("The required file path is not found")
return target_path
def _get_config_dir(self, ext_file) -> str:
"""
JSON files specific for Flash Data Integirty tests are placed in
nvme_smart_fdi. Other files go in nvme_smart.
@param string ext_file: NVME json file name
@return string: directory with config file
"""
if "fdi" in ext_file:
return "nvme_smart_fdi"
return "nvme_smart"
def _filter_vendor_config(self, config):
"""
Only get validate instructions for specific for this drive vendor
@param {} config: dictionary contains validate instructions
for a specified vendor
@return {}: filtered dictionary
"""
return config.get(self.manufacturer, {})
def _flatten_validate_config_dict(self, config):
"""
Reduce config with nested comparing instructions, like this
{
"smart-log": {"item_1": "==", ... },
"<vendor_name>": {
"vs-smart-add-log": {"item_a": "<", ... }
}
}
to
{ "item_1": "==", "item_a": "<", ... }
"""
flat = {}
for each in config:
if isinstance(config[each], dict):
flat.update(self._flatten_validate_config_dict(config[each]))
else:
flat[each] = config[each]
return flat
def get_arbitration_mechanism_status(self):
"""
Method to get the controller properties
"""
nvme_drive = "/dev/%s" % self.block_name
cmd = "nvme show-regs %s -H" % nvme_drive
out = AutovalUtils.validate_no_exception(
self.host.run,
[cmd],
"Run '%s'" % cmd,
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.NVME_ERR,
)
return out
def get_nvme_read(self):
"""
Method to run nvme read command
"""
nvme_drive = f"/dev/{self.block_name}"
cmd = f"nvme read {nvme_drive} --data-size=520 --prinfo=1"
out = AutovalUtils.validate_no_exception(
self.host.run,
[cmd],
f"Run '{cmd}'",
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.NVME_ERR,
)
return out
def get_nvme_id_ctrl(self, human_readable=None, grep: str = "-v fguid") -> str:
"""
Method to get nvme_id_ctrl command output
"""
nvme_drive = f"/dev/{self.block_name}"
cmd = f"nvme id-ctrl {nvme_drive} "
if human_readable:
cmd += "-H "
if grep:
cmd += f"| grep {grep}"
out = AutovalUtils.validate_no_exception(
self.host.run,
[cmd],
f"Run '{cmd}'",
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.NVME_ERR,
)
return out
def get_nvme_id_ctrl_apsta(self) -> str:
"""
Method to get apsta from nvme id-ctrl command
"""
return self.get_nvme_id_ctrl(self, grep="apsta")
def get_nvme_id_ctrl_fw_revision(self) -> str:
"""
Method to get firmware revision from id-ctrl command
"""
out = self.get_nvme_id_ctrl(grep="fr")
match = re.search(r"fr\s+:\s+(.*)", out)
if match:
fw_version = match.group(1)
return str(fw_version)
else:
raise TestError(
"Fw revision not found for %s" % self.block_name,
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.FIRMWARE_ERR,
)
def get_nvme_id_ctrl_mtfa(self) -> int:
"""
Mathod to get the Maximum Time For Activation value from id-ctrl command
"""
out = self.get_nvme_id_ctrl(grep="mtfa")
match = re.search(r"mtfa\s+:\s+(.*)", out)
if match:
mtfa = match.group(1)
return int(mtfa)
else:
raise TestError(
f"mtfa not found for {self.block_name}",
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.DRIVE_ERR,
)
def get_nvme_controllers(self):
"""
Method to get the nvme controllers
"""
cmd = "lspci | grep 'Non-Volatile memory controller:'"
out = AutovalUtils.validate_no_exception(
self.host.run,
[cmd],
"Run '%s'" % cmd,
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.PCIE_ERR,
)
return out
def get_fw_log(self):
"""
Method to retrieve the firmware log for the specified device
"""
nvme_drive = "/dev/%s" % self.block_name
cmd = "nvme fw-log %s -o json" % nvme_drive
out = AutovalUtils.validate_no_exception(
self.host.run,
[cmd],
"Run '%s'" % cmd,
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.NVME_ERR,
)
return out
def get_crypto_erase_support_status(self) -> bool:
"""
Method to validate if the drive has crypto erase support
"""
out = self.get_nvme_id_ctrl(human_readable=True)
if re.search(r"Crypto Erase Supported", out) is not None:
return True
AutovalLog.log_info(
"%s drive on the DUT does not support crypto erase " % self.block_name
)
return False
def get_error_log(self):
"""
Method to retrieve specified number of error log entries from a given device
"""
nvme_drive = "/dev/%s" % self.block_name
cmd = "nvme error-log %s -o json" % nvme_drive
out = AutovalUtils.validate_no_exception(
self.host.run,
[cmd],
"Run '%s'" % cmd,
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.NVME_ERR,
)
return out
def get_id_ns(self):
"""
Method to log the properties of the specified namespace
"""
nvme_drive = "/dev/%s" % self.block_name
cmd = "nvme id-ns %s -o json" % nvme_drive
out = self.host.run(cmd=cmd)
return out
def get_size(self, param) -> int:
"""
Get Size.
This method is used to fetch the nuse or nsze value from the
nvme id-ns /dev/xxxx command
Parameters
----------
param: str : String value to get the nuse or nsze
Returns
-------
size: nvme id-ns output result: Integer
"""
out = self.get_id_ns()
out_json = json.loads(out)
size = out_json[param]
return size
def get_bs_size(self) -> int:
"""
Get current formatted block size
"""
nvme_drive = "/dev/%s" % self.block_name
cmd = "nvme id-ns %s -H" % nvme_drive
out = AutovalUtils.validate_no_exception(
self.host.run,
[cmd],
"Run '%s'" % cmd,
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.NVME_ERR,
)
match = re.search(r".*\s+(\d+)\s+bytes.*(in\s+use)", out)
if match:
current = match.group(1)
return int(current)
raise TestError(
"Block size not found for %s" % self.block_name,
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.DRIVE_ERR,
)
def get_bs_size_list(self):
"""
Get list of supported block sizes
"""
nvme_drive = "/dev/%s" % self.block_name
cmd = "nvme id-ns %s -H" % nvme_drive
out = AutovalUtils.validate_no_exception(
self.host.run,
[cmd],
"Run '%s'" % cmd,
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.NVME_ERR,
)
if out:
bs_list = re.findall(r".*\s+(\d+)\s+bytes\s+", out)
if bs_list:
bs_list = [int(i) for i in bs_list]
return bs_list
raise TestError(
"List of block size not found for %s" % self.block_name,
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.DRIVE_ERR,
)
def get_feature(self, feature_id=None, queue_id=None):
"""
Method to get the operating parameters of the specified controller
identified by the Feature Identifier.
"""
# according to the nvme specs
if feature_id is not None:
feature_ids = feature_id
else:
feature_ids = NVMeDrive.FEATURE_IDS
nvme_drive = "/dev/%s" % self.block_name
features_info = []
for _id in feature_ids:
if queue_id:
cmd = f"nvme get-feature {nvme_drive} -f {_id} -H {queue_id}"
else:
cmd = f"nvme get-feature {nvme_drive} -f {_id} -H"
out = self.host.run_get_result(cmd=cmd).stdout # noqa
feature_info = ",".join([s.strip() for s in out.splitlines()])
features_info.append(feature_info)
return features_info
def get_capacity(self, unit: str = "byte"):
"""Return drive capacity"""
_byte = NVMeUtils.get_from_nvme_list(self.host, self.block_name, "PhysicalSize")
return DiskUtils.convert_from_bytes(_byte, unit)
def get_serial_number(self):
"""Return drive serial_number"""
return NVMeUtils.get_from_nvme_list(self.host, self.block_name, "SerialNumber")
def _get_model(self):
return NVMeUtils.get_from_nvme_list(self.host, self.block_name, "ModelNumber")
def get_firmware_version(self):
"""Return drive FW version"""
return NVMeUtils.get_from_nvme_list(self.host, self.block_name, "Firmware")
def get_manufacturer(self) -> str:
"""Return drive manufacturer"""
return "GenericNVMe"
@retry(tries=3, sleep_seconds=30)
def get_smart_log(self):
"""Return drive smart log"""
cmd = "nvme smart-log /dev/%s -o json" % self.block_name
output = self.host.run(cmd=cmd)
try:
log = json.loads(output)
except json.decoder.JSONDecodeError:
raise TestError(
f"Failed to convert to JSON: {output}",
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.TOOL_ERR,
)
smart_log = {"smart-log": log}
smart_log.update(self.get_ocp_smart_log())
return smart_log
def get_ocp_smart_log(self) -> Dict:
"""
Collect OCP smart log and return it.
"""
cmd = "nvme ocp smart-add-log /dev/%s -o json" % self.block_name
try:
out = self.host.run(cmd)
log = json.loads(out)
result = GenericUtils.flatten_dict(log)
except json.decoder.JSONDecodeError:
raise TestError(
f"Failed to convert to JSON: {out}", # pyre-fixme
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.TOOL_ERR,
)
except Exception:
AutovalLog.log_info(
f"ocp-smart-add-log is not supported on the drive {self.block_name} ({self.model})."
)
return {}
for k, v in result.items():
if isinstance(v, int):
result[k] = float(v)
elif isinstance(v, str):
try:
result[k] = float(int(v, 16))
except Exception:
result[k] = v
return {"ocp-smart-add-log": result}
def get_ocp_telemetry_string_log(self) -> None:
"""
Retrieves and stores the OCP telemetry log from a specified NVMe drive.
Args:
None
Returns:
None
"""
dut_logdir = SiteUtils.get_dut_logdir(self.host.hostname)
cmd = f"nvme ocp telemetry-string-log /dev/{self.block_name}"
self.host.run(cmd=cmd, ignore_status=True, working_directory=dut_logdir)
def get_internal_log(self) -> bool:
"""
Return drive telemetry log.
Args:
None
Returns:
The completion status of internal log file generation.
"""
dut_logdir = SiteUtils.get_dut_logdir(self.host.hostname)
cmd = f"nvme telemetry-log --output-file=bin /dev/{self.block_name}"
ret = self.host.run_get_result(
cmd=cmd, ignore_status=True, working_directory=dut_logdir
)
if ret.return_code != 0:
AutovalLog.log_info(f"WARNING: command '{cmd}' failed with error code")
return False
return True
def get_effects_log(self):
"""Gets Effects Log.
This method retrieves the command effects log for the specified drive.
Returns
-------
out : Dictionary
Value of Admin Command Sets and I/O Command Sets.
Raises
------
TestStepError
When fails to retrieve the command effects log.
"""
cmd = "nvme effects-log /dev/%s -o json" % self.block_name
out = self.host.run(cmd=cmd)
return json.loads(out)
def get_id_ctrl(self):
"""Return id_ctrl"""
return NVMeUtils.get_id_ctrl(self.host, self.block_name)
def get_reboot_models(self) -> None:
"""Return drive model for reboot after fw update"""
# can be provided in the vendor subclass
return
def get_susbsystem_reset_models(self) -> None:
"""Return drive model for reboot after fw update"""
# can be provided in the vendor subclass
return
def get_tooling_owned_models(self) -> None:
"""Return models owned by tooling to bypass sed ownership test"""
# can be provided in the vendor subclass
return
def supports_flash_temp_check(self) -> bool:
"""Return whether the drive supports flash temp check"""
# can be provided in the vendor subclass
return True
def get_nand_write_param(self) -> Dict[str, str]:
"""Return nand_write params"""
# Can be provided in vendor subclass
return {}
def get_bit_error_ratio_param(self):
"""Get BER params"""
# TODO: implement when moving bit_error_ratio_test to Autoval
return {}
def get_vs_nand_stat_log(self) -> None:
"""Return vs_nand_stat log"""
# Can be provided in vendor subclass
return
def get_write_amplification(
self, smart_before: Dict[str, Dict], smart_after: Dict[str, Dict]
) -> bool:
"""
Method to calculate the Flash Write Amplification
HOST and NAND write bytes are captured before and after test
to determine total logical and physical write bytes.
@params: smart_before | Smart data before the test
@type: dict
@params: smart_after | Smart data after the test
@type: dict
"""
host_write_before = smart_before["smart-log"]["data_units_written"]
host_write_after = smart_after["smart-log"]["data_units_written"]
host_delta = host_write_after - host_write_before
write_amplification = {}
nand_write_formula = {}
if (
"ocp-smart-add-log" not in smart_before
and "ocp-smart-add-log" not in smart_after
):
return False
nand_write_formula = {
"field": "Physical media units written_lo",
"formula": f"NAND_WRITE/{pow(1024, 3)}",
}
nand_write_before = smart_before["ocp-smart-add-log"][
nand_write_formula["field"]
]
nand_write_after = smart_after["ocp-smart-add-log"][nand_write_formula["field"]]
nand_delta = nand_write_after - nand_write_before
# Calculate lifetime Write amp
write_amplification["lifetime_write_amplification"] = 0
if host_write_after and nand_write_after:
waf, error = self.calculate_waf(
host_write_after, nand_write_after, nand_write_formula
)
if waf:
AutovalLog.log_info(
"Lifetime WAF for drive %s is %s" % (self.block_name, waf)
)
write_amplification["lifetime_write_amplification"] = waf
waf = {
"name": self.block_name,
"write_amplification": waf,
"serial_number": self.serial_number,
"model": self.manufacturer,
}
result_handler = ResultHandler()
result_handler.update_test_results({self.block_name: waf})
if error:
AutovalLog.log_info(
"Cannot calculate WAF for drive %s due to %s"
% (self.block_name, error)
)
AutovalUtils.validate_range(
write_amplification["lifetime_write_amplification"],
1.0,
20.0,
"WAF expected range",
warning=True,
)
# Calculate Write amp for the currently running test
write_amplification["test_write_amplification"] = 0
waf, error = self.calculate_waf(host_delta, nand_delta, nand_write_formula)
AutovalLog.log_info(
"WAF during this test for drive %s: %s" % (self.block_name, waf)
)
write_amplification["test_write_amplification"] = waf
if error:
AutovalLog.log_info(
"Cannot calculate WAF for drive %s due to %s" % (self.block_name, error)
)
AutovalLog.log_info("Drive %s: %s" % (self.block_name, write_amplification))
return True
def calculate_waf(self, h_write, n_write, nand_write_formula):
"""
Method to calculate the Write Amplification factor from the
Host write and Nand Write
@params: h_write | host_delta
(difference of data units written before and after the test)
@params: n_write | nand_delta
(difference of nand units written before and after the test)
@params: nand_write_formula | vendor specific nand write field
@Returns: Write Amplication Factor
"""
try:
host_write = int(h_write) * 512 * 1000 / pow(1024, 3)
value = (
nand_write_formula["formula"]
.replace("NAND_WRITE", str(n_write))
.replace("value", str(n_write))
.split("/")
)
nand_writes = self._str_to_float(value[0]) / self._str_to_float(value[1])
waf = nand_writes / host_write
except ZeroDivisionError as exc:
return None, exc
return waf, None
def _str_to_float(self, value) -> float:
"""Helper function for complex formula"""
match = re.search(r"(\d+)\s*\**\s*(\d*)", value)
# pyre-fixme[16]: Optional type has no attribute `group`.
if match.group(2):
total = float(match.group(2)) * float(match.group(1))
else:
total = float(match.group(1))
return total
def convert_nand_write(self, nand_write) -> float:
"""Convert nand write to float"""
if isinstance(nand_write, str):
if "," in nand_write:
nand_write = nand_write.replace(",", "")
try:
nand_write = float(nand_write)
except Exception as exc:
raise TestError(
"Failed convert %s to float: %s" % (nand_write, exc),
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.TOOL_ERR,
)
return nand_write
def get_drive_name(self):
"""
Get NVMe drive name without the namespace part
e.g. "nvme1n1" -> "nvme1"
@return string
"""
match = re.search(r"(nvme\d+)", self.block_name)
if not match:
_msg = "Failed to get NVMe drive name from block name %s" % self.block_name
raise TestError(
_msg,
error_type=ErrorType.NVME_ERR,
)
return match.group(1)
def collect_data(self):
data = {
"SMART": self.get_smart_log(),
"firmware": self.get_firmware_version(),
"serial_number": self.serial_number,
"type": self.type.value,
"interface": self.interface.value,
"model": self.model,
"manufacturer": self.manufacturer,
"id_ctrl": self.id_ctrl,
"capacity": self.get_capacity(),
"id_ns": self.get_id_ns(),
}
_strip_white_spaces_from_keys(data)
return data
def update_firmware(self, *args, **kwargs) -> None:
"""Update Firmware for NVMe Drives.
This method updates the drive firmware using below parameters.
Parameters
----------
*args: :obj: `List` of :obj: `str`
fw_version - Firmware version to upgrade
fw_bin_loc - Binary path
**kwargs:
``fw_slots``:
Slots to install firmware (`List` of `int`)
``actions``:
Provide param for nvme fw-activate --action option
(`int`)
``force``:
Provide boolean for force install (`bool`)
"""
if len(args) == 0 and len(kwargs) == 0:
raise TestError(
"No parameters found for firmware update",
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.INPUT_ERR,
)
# positional arg[0] will have firmware version and
# arg[1] will have firmware binary location.
expected_fw_version = args[0]
fw_bin_loc = args[1]
fw_slots = kwargs.get("fw_slots", [])
action = kwargs.get("action", 1)
force = kwargs.get("force", False)
nvme_admin_io = kwargs.get("nvme_admin_io", False)
drive_name = self.get_drive_name()
AutovalLog.log_info(f"+++Nvme firmware update with action {action}")
# not supported actions
ns_action_list = self.get_fw_update_ns_actions()
if action in ns_action_list:
AutovalLog.log_info(
f"+++ Skipping the Firmware update because update with "
f"action {action} is not supported in the drive "
f"{self.serial_number} of model {self.model}."
)
return
fw_ver = self.get_firmware_version()
if not force and expected_fw_version == fw_ver:
AutovalLog.log_info(
"Device already updated with latest version: %s" % fw_ver
)
return
fw_bin_loc = FileActions.get_local_path(self.host, fw_bin_loc)
if not isinstance(fw_slots, list) or len(fw_slots) == 0:
fw_slots = self.get_fw_slots()
ns_fw_slots = self.fw_ns_slots_models_map.get(self.model, [])
if ns_fw_slots:
AutovalLog.log_info(
f"Removing the Not Supported Slots : {ns_fw_slots} from firmware slots : {fw_slots}"
)
fw_slots = [i for i in fw_slots if i not in ns_fw_slots]
if action == 2:
AutovalLog.log_info(
f"Skipping update on slot0. Firmware update action {action} "
"does not support the update on slot 0 as this will pick any random"
" slot and will activate the firmware downloaded on that slot which"
" might not be the expected version."
)
fw_slots.remove(0)
AutovalUtils.validate_non_empty_list(
fw_slots,
f"Validate the supported slots for the firmware action {action} "
"are not none",
warning=True,
component=COMPONENT.STORAGE_DRIVE,
error_type=ErrorType.FIRMWARE_ERR,
)
for fw_slot in fw_slots:
AutovalLog.log_info(
f"Performing update on drive {drive_name} slot: {fw_slot}"
)
self._fw_download(drive_name, fw_bin_loc)
if nvme_admin_io:
"""
for nvme_admin_io, we have commit, admin and IO timers to check the how long
commit action, admin and IO commands take and validate them. We do not require timers for
general flash_firmware_update test. Hence, including an if else condition here.
"""
fw_ver = self.get_nvme_id_ctrl_fw_revision() # noqa
self.fw_commit_timer_before = time.perf_counter() # noqa
if action == 2:
# As per the nvme spec action 2 will only avtivates the
# firmware which is already present on the slot. So
# downloading the firmware on the slot using action 0.
# Action 0: Downloaded image replaces the existing image,
# if any, in the specified Firmware Slot. The
# newly placed image is not activated.
self.fw_activate(
drive_name,
fw_bin_loc,
fw_slot,
action=0,
nvme_admin_io=nvme_admin_io,
)
self.fw_activate(drive_name, fw_bin_loc, fw_slot, action, nvme_admin_io)
if self.reboot_models and self.model in self.reboot_models:
AutovalLog.log_info(
f"Rebooting as the {self.serial_number} {self.model} "
"requires reboot after firmware update."
)
self.host.oob.cycle()
elif action != 2:
# All the actions except action 3 requires reset of the drive
# for the updated firmware version to reflect.
if action != 3:
AutovalLog.log_info(
f"Resetting as the {self.serial_number} {self.model} "
f"requires reset for action {action}"
)
self.reset()
self.fw_commit_timer_after = time.perf_counter() # noqa
self.command_timer_before = time.perf_counter() # noqa
self.admin_command = self.get_nvme_id_ctrl() # noqa
self.admin_command_timer_after = time.perf_counter() # noqa
self.io_command = self.get_nvme_read() # noqa
self.io_command_timer_after = time.perf_counter() # noqa
elif nvme_admin_io is False:
if action == 2:
# As per the nvme spec action 2 will only avtivates the
# firmware which is already present on the slot. So
# downloading the firmware on the slot using action 0.
# Action 0: Downloaded image replaces the existing image,
# if any, in the specified Firmware Slot. The
# newly placed image is not activated.
self.fw_activate(
drive_name,
fw_bin_loc,
fw_slot,
action=0,
nvme_admin_io=True,
)
self.fw_activate(
drive_name,
fw_bin_loc,
fw_slot,
action,
nvme_admin_io,
)
# Checking if the drive model requires reboot after update.
if self.reboot_models and self.model in self.reboot_models:
AutovalLog.log_info(
f"Rebooting as the {self.serial_number} {self.model} "
"requires reboot after firmware update."
)
self.host.oob.cycle()
elif action != 2:
# All the actions except action 3 requires reset of the drive
# for the updated firmware version to reflect.
if action != 3:
AutovalLog.log_info(
f"Resetting as the {self.serial_number} {self.model} "
f"requires reset for action {action}"
)
self.reset()
self.validate_firmware_update(expected_fw_version)
def _fw_download(self, drive_name, file_name) -> None:
"""
This method downloads the firmware binary file that is
to be updated for the drive.
Parameters
----------
drive_name : String
The drive name on which the firmware to be updated.
file_name : String
Firmware binary path.
"""
cmd = f"nvme fw-download /dev/{drive_name} -f '{file_name}'"
AutovalLog.log_info(self.host.run(cmd=cmd)) # noqa
def fw_activate(
self,
drive_name: str,
file_name: str,
fw_slot: List[int],
action: int,
nvme_admin_io=True,
) -> None:
"""
This method activates the downloaded firmware binary file on
the drive.
Parameters
----------
drive_name : String
The drive name on which the firmware to be updated.
file_name : String
Firmware binary path.
fw_slot : :obj: 'List' of :obj: 'Integer'
Firmware slots to update.
action : Integer
Provides param for nvme fw-activate --action option.
nvme_admin_io: Boolean
Flag to indicate whether to wait or not.
"""
cmd = "nvme fw-activate /dev/%s --slot=%d --action=%d" % (
drive_name,
fw_slot,
action,
)
AutovalLog.log_info(
f"Flashing device {drive_name}, serial {self.serial_number} "
f"with {file_name} on slot: {fw_slot}"
)
try:
AutovalLog.log_info(self.host.run(cmd=cmd)) # noqa
except Exception as exc: # thrift.py run() throws base Exception
if (
"firmware requires subsystem reset"
or "firmware requires any controller reset" in str(exc)
):
AutovalLog.log_info(
"Activation firmware is successful, but required reset"
)
else:
AutovalLog.log_info("Unknown exception occured: %s" % exc)
if not nvme_admin_io:
self.post_fw_activate()
def post_fw_activate(self) -> None:
"""
This method decides the time to wait to complete the fw activation
"""
sleep_time = 10
AutovalLog.log_info(f"Waiting for {sleep_time} seconds")
sleep(sleep_time)