Debian Codegraph @

test/flash_test.py

raw symbols SCIP
1 # pyOCD debugger
2 # Copyright (c) 2015-2020,2025-2026 Arm Limited
3 # SPDX-License-Identifier: Apache-2.0
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 import argparse
17 import os
18 import sys
19 from time import (sleep, time)
20 from random import randrange
21 import math
22 import struct
23 import traceback
24 import argparse
25
26 from pyocd.core.helpers import ConnectHelper
27 from pyocd.probe.pydapaccess import DAPAccess
28 from pyocd.utility.conversion import float32_to_u32
29 from pyocd.utility.mask import (invert32, same)
30 from pyocd.core.memory_map import MemoryType
31 from pyocd.flash.flash import Flash
32 from pyocd.flash.builder import FlashBuilder
33 from pyocd.utility.progress import print_progress
34
35 from test_util import (
36 Test,
37 TestResult,
38 get_session_options,
39 get_target_test_params,
40 get_test_binary_path,
41 )
42
43 addr = 0
44 size = 0
45
46 board = None
47
48 import logging
49
50 class FlashTestResult(TestResult):
51 def __init__(self):
52 super(FlashTestResult, self).__init__(None, None, None)
53 self.name = "flash"
54 self.chip_erase_rate_erased = None
55 self.page_erase_rate_same = None
56 self.page_erase_rate = None
57 self.analyze = None
58 self.analyze_rate = None
59 self.chip_erase_rate = None
60
61 class FlashTest(Test):
62 def __init__(self):
63 super(FlashTest, self).__init__("Flash Test", flash_test)
64
65 def print_perf_info(self, result_list, output_file=None):
66 result_list = list(filter(lambda x: isinstance(x, FlashTestResult), result_list))
67
68 print("\n\n------ Analyzer Performance ------", file=output_file)
69 perf_format_str = "{:<10}{:<12}{:<18}{:<18}"
70 print(perf_format_str.format("Target", "Analyzer", "Rate", "Time"),
71 file=output_file)
72 print("", file=output_file)
73 for result in result_list:
74 if result.board is None or result.analyze is None:
75 continue
76 if result.passed:
77 analyze_rate = "%.3f KB/s" % (result.analyze_rate / float(1000))
78 analyze_time = "%.3f s" % result.analyze_time
79 else:
80 analyze_rate = "Fail"
81 analyze_time = "Fail"
82 print(perf_format_str.format(result.board,
83 result.analyze, analyze_rate,
84 analyze_time),
85 file=output_file)
86 print("", file=output_file)
87
88 print("\n\n------ Test Rate ------", file=output_file)
89 rate_format_str = "{:<10}{:<20}{:<20}{:<20}"
90 print(rate_format_str.format("Target", "Chip Erase", "Page Erase",
91 "Page Erase (Same data)"),
92 file=output_file)
93 print("", file=output_file)
94 for result in result_list:
95 if result.board is None:
96 continue
97 if result.passed:
98 chip_erase_rate = "%.3f KB/s" % (result.chip_erase_rate / float(1000))
99 page_erase_rate = "%.3f KB/s" % (result.page_erase_rate / float(1000))
100 page_erase_rate_same = "%.3f KB/s" % (result.page_erase_rate_same / float(1000))
101 else:
102 chip_erase_rate = "Fail"
103 page_erase_rate = "Fail"
104 page_erase_rate_same = "Fail"
105 print(rate_format_str.format(result.board,
106 chip_erase_rate, page_erase_rate,
107 page_erase_rate_same),
108 file=output_file)
109 print("", file=output_file)
110
111 def run(self, board):
112 try:
113 result = self.test_function(board.unique_id)
114 except Exception as e:
115 result = FlashTestResult()
116 result.passed = False
117 print("Exception %s when testing board %s" % (e, board.unique_id))
118 traceback.print_exc(file=sys.stdout)
119 result.board = board
120 result.test = self
121 return result
122
123
124 def flash_test(board_id):
125 with ConnectHelper.session_with_chosen_probe(unique_id=board_id, **get_session_options()) as session:
126 board = session.board
127 target_type = board.target_type
128
129 memory_map = board.target.get_memory_map()
130 ram_region = memory_map.get_default_region_of_type(MemoryType.RAM)
131
132 ram_start = ram_region.start
133 ram_size = ram_region.length
134
135 target = board.target
136
137 test_params = get_target_test_params(session)
138 session.probe.set_clock(test_params['test_clock'])
139
140 test_pass_count = 0
141 test_count = 0
142 result = FlashTestResult()
143
144 target.reset_and_halt()
145
146 # Test each flash region separately.
147 for rom_region in memory_map.iter_matching_regions(type=MemoryType.FLASH, is_testable=True):
148 rom_start = rom_region.start
149 rom_size = rom_region.length
150
151 flash = rom_region.flash
152 flash_info = flash.get_flash_info()
153
154 # This can be any value, as long as it's not the erased byte value. We take the
155 # inverse of the erased value so that for most flash, the unerased value is 0x00.
156 unerasedValue = invert32(flash.region.erased_byte_value) & 0xff
157
158 print("\n\n===== Testing flash region '%s' from 0x%08x to 0x%08x ====" % (rom_region.name, rom_region.start, rom_region.end))
159
160 binary_file = get_test_binary_path(board.test_binary)
161 with open(binary_file, "rb") as f:
162 data = f.read()
163 data = struct.unpack("%iB" % len(data), data)
164 unused = rom_size - len(data)
165
166 # Make sure data doesn't overflow this region.
167 if unused < 0:
168 data = data[:rom_size]
169 unused = 0
170
171 addr = rom_start
172 size = len(data)
173
174 # Turn on extra checks for the next 4 tests
175 flash.set_flash_algo_debug(True)
176
177 print("\n------ Test Erased Value Check ------")
178 d = [flash.region.erased_byte_value] * 128
179 if flash.region.is_data_erased(d):
180 print("TEST PASSED")
181 test_pass_count += 1
182 else:
183 print("TEST FAILED")
184 test_count += 1
185
186 d = [unerasedValue] + [flash.region.erased_byte_value] * 127
187 if not flash.region.is_data_erased(d):
188 print("TEST PASSED")
189 test_pass_count += 1
190 else:
191 print("TEST FAILED")
192 test_count += 1
193
194 print("\n------ Test Basic Page Erase ------")
195 info = flash.flash_block(addr, data, False, "sector", progress_cb=print_progress())
196 data_flashed = target.read_memory_block8(addr, size)
197 if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_SECTOR_ERASE:
198 print("TEST PASSED")
199 test_pass_count += 1
200 else:
201 print("TEST FAILED")
202 test_count += 1
203
204 print("\n------ Test Basic Chip Erase ------")
205 info = flash.flash_block(addr, data, False, "chip", progress_cb=print_progress())
206 data_flashed = target.read_memory_block8(addr, size)
207 if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE:
208 print("TEST PASSED")
209 test_pass_count += 1
210 else:
211 print("TEST FAILED")
212 test_count += 1
213
214 print("\n------ Test Smart Page Erase ------")
215 info = flash.flash_block(addr, data, True, "sector", progress_cb=print_progress())
216 data_flashed = target.read_memory_block8(addr, size)
217 if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_SECTOR_ERASE:
218 print("TEST PASSED")
219 test_pass_count += 1
220 else:
221 print("TEST FAILED")
222 test_count += 1
223
224 print("\n------ Test Smart Chip Erase ------")
225 info = flash.flash_block(addr, data, True, "chip", progress_cb=print_progress())
226 data_flashed = target.read_memory_block8(addr, size)
227 if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE:
228 print("TEST PASSED")
229 test_pass_count += 1
230 else:
231 print("TEST FAILED")
232 test_count += 1
233
234 flash.set_flash_algo_debug(False)
235
236 print("\n------ Test Basic Page Erase (Entire region) ------")
237 new_data = list(data)
238 new_data.extend(unused * [0x77])
239 info = flash.flash_block(addr, new_data, False, "sector", progress_cb=print_progress())
240 if info.program_type == FlashBuilder.FLASH_SECTOR_ERASE:
241 print("TEST PASSED")
242 test_pass_count += 1
243 result.page_erase_rate = float(len(new_data)) / float(info.erase_time + info.program_time)
244 else:
245 print("TEST FAILED")
246 test_count += 1
247
248 print("\n------ Test Fast Verify ------")
249 if flash.get_flash_info().crc_supported:
250 info = flash.flash_block(addr, new_data, progress_cb=print_progress(), fast_verify=True)
251 if info.analyze_type == FlashBuilder.FLASH_ANALYSIS_CRC32:
252 print("TEST PASSED")
253 test_pass_count += 1
254 else:
255 print("TEST FAILED")
256 test_count += 1
257 else:
258 print("Skipping because analyser isn't supported for this algo")
259
260 print("\n------ Test Offset Write ------")
261 addr = rom_start + rom_size // 2
262 page_size = flash.get_page_info(addr).size
263 new_data = [0x55] * page_size * 2
264 info = flash.flash_block(addr, new_data, progress_cb=print_progress())
265 data_flashed = target.read_memory_block8(addr, len(new_data))
266 if same(data_flashed, new_data) and info.program_type is FlashBuilder.FLASH_SECTOR_ERASE:
267 print("TEST PASSED")
268 test_pass_count += 1
269 else:
270 print("TEST FAILED")
271 test_count += 1
272
273 print("\n------ Test Multiple Block Writes ------")
274 addr = rom_start + rom_size // 2
275 page_size = flash.get_page_info(addr).size
276 more_data = [0x33] * page_size * 2
277 addr = (rom_start + rom_size // 2) + 1 #cover multiple pages
278 fb = flash.get_flash_builder()
279 fb.add_data(rom_start, data)
280 fb.add_data(addr, more_data)
281 fb.erase(progress_cb=print_progress())
282 fb.program(progress_cb=print_progress())
283 data_flashed = target.read_memory_block8(rom_start, len(data))
284 data_flashed_more = target.read_memory_block8(addr, len(more_data))
285 if same(data_flashed, data) and same(data_flashed_more, more_data):
286 print("TEST PASSED")
287 test_pass_count += 1
288 else:
289 print("TEST FAILED")
290 test_count += 1
291
292 print("\n------ Test Overlapping Blocks ------")
293 test_pass = False
294 addr = (rom_start + rom_size // 2) #cover multiple pages
295 page_size = flash.get_page_info(addr).size
296 new_data = [0x33] * page_size
297 fb = flash.get_flash_builder()
298 fb.add_data(addr, new_data)
299 try:
300 fb.add_data(addr + 1, new_data)
301 except ValueError as e:
302 print("Exception: %s" % e)
303 test_pass = True
304 if test_pass:
305 print("TEST PASSED")
306 test_pass_count += 1
307 else:
308 print("TEST FAILED")
309 test_count += 1
310
311 print("\n------ Test Empty Block Write ------")
312 # Freebee if nothing asserts
313 fb = flash.get_flash_builder()
314 fb.erase()
315 fb.program()
316 print("TEST PASSED")
317 test_pass_count += 1
318 test_count += 1
319
320 print("\n------ Test Missing Progress Callback ------")
321 # Freebee if nothing asserts
322 addr = rom_start
323 flash.flash_block(rom_start, data, True)
324 print("TEST PASSED")
325 test_pass_count += 1
326 test_count += 1
327
328 # Only run test if the reset handler can be programmed (rom start at address 0)
329 if rom_start == 0:
330 print("\n------ Test Non-Thumb reset handler ------")
331 non_thumb_data = list(data)
332 # Clear bit 0 of 2nd word - reset handler
333 non_thumb_data[4] = non_thumb_data[4] & ~1
334 flash.flash_block(rom_start, non_thumb_data)
335 flash.flash_block(rom_start, data)
336 print("TEST PASSED")
337 test_pass_count += 1
338 test_count += 1
339
340 # Note - The decision based tests below are order dependent since they
341 # depend on the previous state of the flash
342
343 if rom_start == flash_info.rom_start:
344 print("\n------ Test Chip Erase Decision ------")
345 new_data = list(data)
346 new_data.extend([flash.region.erased_byte_value] * unused) # Pad with erased value
347 data_size = len(new_data)
348 info = flash.flash_block(addr, new_data, progress_cb=print_progress())
349 print(f"Selected erase type is {info.program_type}")
350 print(f"Total byte count = {info.total_byte_count} (expected {data_size})")
351 if info.total_byte_count == data_size:
352 print("TEST PASSED")
353 test_pass_count += 1
354 result.chip_erase_rate_erased = float(len(new_data)) / float(info.erase_time + info.program_time)
355 else:
356 print("TEST FAILED")
357 test_count += 1
358
359 print("\n------ Test Chip Erase Decision 2 ------")
360 new_data = list(data)
361 new_data.extend([unerasedValue] * unused) # Pad with unerased value
362 data_size = len(new_data)
363 info = flash.flash_block(addr, new_data, progress_cb=print_progress())
364 print(f"Selected erase type is {info.program_type}")
365 print(f"Total byte count = {info.total_byte_count} (expected {data_size})")
366 if info.total_byte_count == data_size:
367 print("TEST PASSED")
368 test_pass_count += 1
369 result.chip_erase_rate = float(len(new_data)) / float(info.erase_time + info.program_time)
370 else:
371 print("TEST FAILED")
372 test_count += 1
373
374 print("\n------ Test Page Erase Decision ------")
375 new_data = list(data)
376 new_data.extend([unerasedValue] * unused) # Pad with unerased value
377 data_size = len(new_data)
378 info = flash.flash_block(addr, new_data, progress_cb=print_progress())
379 print(f"Selected erase type is {info.program_type}")
380 print(f"Total byte count = {info.total_byte_count} (expected {data_size})")
381 if info.total_byte_count == data_size:
382 print("TEST PASSED")
383 test_pass_count += 1
384 result.page_erase_rate_same = float(len(new_data)) / float(info.erase_time + info.program_time)
385 result.analyze = info.analyze_type
386 result.analyze_time = info.analyze_time
387 result.analyze_rate = float(len(new_data)) / float(info.analyze_time)
388 else:
389 print("TEST FAILED")
390 test_count += 1
391
392 print("\n------ Test Page Erase Decision 2 ------")
393 new_data = list(data)
394 size_same = unused * 5 // 6
395 size_differ = unused - size_same
396 new_data.extend([unerasedValue] * size_same) # Pad 5/6 with unerased value and 1/6 with 0x55
397 new_data.extend([0x55] * size_differ)
398 data_size = len(new_data)
399 info = flash.flash_block(addr, new_data, progress_cb=print_progress())
400 print(f"Selected erase type is {info.program_type}")
401 print(f"Total byte count = {info.total_byte_count} (expected {data_size})")
402 if info.total_byte_count == data_size:
403 print("TEST PASSED")
404 test_pass_count += 1
405 else:
406 print("TEST FAILED")
407 test_count += 1
408
409 print("\n\nTest Summary:")
410 print("Pass count %i of %i tests" % (test_pass_count, test_count))
411 if test_pass_count == test_count:
412 print("FLASH TEST SCRIPT PASSED")
413 else:
414 print("FLASH TEST SCRIPT FAILED")
415
416 target.reset()
417
418 result.passed = test_count == test_pass_count
419 return result
420
421 if __name__ == "__main__":
422 parser = argparse.ArgumentParser(description='pyOCD flash test')
423 parser.add_argument('-d', '--debug', action="store_true", help='Enable debug logging')
424 parser.add_argument("-da", "--daparg", dest="daparg", nargs='+', help="Send setting to DAPAccess layer.")
425 args = parser.parse_args()
426 level = logging.DEBUG if args.debug else logging.INFO
427 logging.basicConfig(level=level)
428 DAPAccess.set_args(args.daparg)
429 # Set to debug to print some of the decisions made while flashing
430 session = ConnectHelper.session_with_chosen_probe(**get_session_options())
431 test = FlashTest()
432 result = [test.run(session.board)]
433 test.print_perf_info(result)