-
Notifications
You must be signed in to change notification settings - Fork 6
/
serialflash.py
1432 lines (1247 loc) · 54.8 KB
/
serialflash.py
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
# Copyright (c) 2010-2020, Emmanuel Blot <[email protected]>
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
import time
from binascii import hexlify
from typing import Iterable, Optional, Tuple, Union
from jtag_gpio import SpiPort
# from https://github.com/eblot/pyftdi/blob/master/pyftdi/misc.py
def pretty_size(size, sep: str = ' ',
lim_k: int = 1 << 10, lim_m: int = 10 << 20,
plural: bool = True, floor: bool = True) -> str:
"""Convert a size into a more readable unit-indexed size (KiB, MiB)
:param size: integral value to convert
:param sep: the separator character between the integral value and
the unit specifier
:param lim_k: any value above this limit is a candidate for KiB
conversion.
:param lim_m: any value above this limit is a candidate for MiB
conversion.
:param plural: whether to append a final 's' to byte(s)
:param floor: how to behave when exact conversion cannot be
achieved: take the closest, smaller value or fallback to the next
unit that allows the exact representation of the input value
:return: the prettyfied size
"""
size = int(size)
if size > lim_m:
ssize = size >> 20
if floor or (ssize << 20) == size:
return '%d%sMiB' % (ssize, sep)
if size > lim_k:
ssize = size >> 10
if floor or (ssize << 10) == size:
return '%d%sKiB' % (ssize, sep)
return '%d%sbyte%s' % (size, sep, (plural and 's' or ''))
# pylint: disable-msg=too-many-arguments
# pylint: disable-msg=too-many-locals
# pylint: disable-msg=too-many-branches
# pylint: disable-msg=too-many-statements
# pylint: disable-msg=abstract-method
# pylint: disable-msg=invalid-name
class SerialFlashError(Exception):
"""Base class for all Serial Flash errors"""
class SerialFlashNotSupported(SerialFlashError):
"""Exception thrown when a non-existing feature is invoked"""
class SerialFlashUnknownJedec(SerialFlashNotSupported):
"""Exception thrown when a JEDEC identifier is not recognized"""
def __init__(self, jedec):
SerialFlashNotSupported.__init__(self, "Unknown flash device: %s" %
hexlify(jedec))
class SerialFlashTimeout(SerialFlashError):
"""Exception thrown when a flash command cannot be completed in a timely
manner"""
class SerialFlashValueError(ValueError, SerialFlashError):
"""Exception thrown when a parameter is out of range"""
class SerialFlashRequestError(SerialFlashError):
"""Cannot complete a flash device request"""
class SerialFlash:
"""Interface of a generic SPI flash device"""
FEAT_NONE = 0x000 # No special feature
FEAT_LOCK = 0x001 # Basic, revertable locking
FEAT_INVLOCK = 0x002 # Inverted (bottom/top) locking
FEAT_SECTLOCK = 0x004 # Arbitrary sector locking
FEAT_OTPLOCK = 0x008 # OTP locking available
FEAT_UNIQUEID = 0x010 # Unique ID
FEAT_SECTERASE = 0x100 # Can erase whole sectors
FEAT_HSECTERASE = 0x200 # Can erase half sectors
FEAT_SUBSECTERASE = 0x400 # Can erase sub sectors
FEAT_CHIPERASE = 0x800 # Can erase full chip
def set_spi_frequency(self, freq: Optional[float] = None) -> None:
"""Set the SPI bus frequency to communicate with the device. Set
default SPI frequency if none is provided."""
raise NotImplementedError()
def read(self, address: int, length: int) -> bytes:
"""Read a sequence of bytes from the specified address.
:param address: the position of the first byte to read
:param length: the count of bytes to read
:return: an array of bytes
"""
raise NotImplementedError()
def write(self, address: int,
data: Union[bytes, bytearray, Iterable[int]]) -> None:
"""Write a sequence of bytes, starting at the specified address.
:note: the device cells are not automatically erased, which means
that the bytes actually stored to the device match a NAND
operation between the existing content of the cell and the
data values, i.e. it is only possible to write 0s into the
flash cells, not 1s. :py:meth:`erase` should be explictly
called to erase one or more blocks.
:param address: the position of the first byte to write
:param data: a sequence of bytes to write
"""
raise NotImplementedError()
def erase(self, address: int, length: int, verify: bool = False) -> None:
"""Erase a block of bytes.
Address and length depends upon device-specific constraints and
should be aligned on device blocks.
As a special feature, specifying address as 0 and length to -1
triggers a full chip erase.
:param address: the position of the first byte to erase
:param length: the count of bytes to erase
:param verify: optionally check that the selected blocks have been
erased, reading them back.
"""
raise NotImplementedError()
def can_erase(self, address: int, length: int) -> None:
"""Verifies that a defined area can be erased on the flash device.
It does not take into account any locking scheme, only the area
boundary.
:param address: the position of the first byte to erase
:param length: the count of bytes to erase
:raise SerialFlashValueError: if erase cannot be performed
"""
raise NotImplementedError()
def is_busy(self) -> bool:
"""Reports whether the flash may receive commands or is actually
being performing internal work.
:return: True if the device is busy and cannot accept new I/O
commands, False otherwise.
"""
raise NotImplementedError()
def get_capacity(self) -> int:
"""Get the flash device capacity in bytes.
:return: the capacity of the device, in bytes.
"""
raise len(self)
def unlock(self) -> None:
"""Make the whole device read/write.
Some flash devices are write-locked at power up.
"""
raise NotImplementedError()
@property
def unique_id(self) -> int:
"""Return the unique ID of the flash, if it exists.
:return: the unique ID
"""
raise NotImplementedError()
def get_timings(self, timing: str) -> Tuple[float, float]:
"""Get a time tuple (typical, max).
Timings are use to track whether a device successfully completed
a command or if a command timed out.
:param timing: the kind of operation
:return: typical time to complete the operation, maximum time to
complete the operation
"""
raise NotImplementedError()
@classmethod
def has_feature(cls, feature: int) -> bool:
"""Test whether the flash device supports a feature.
:param feature: the feature to test
:return: True if the feature is supported, False otherwise
"""
raise NotImplementedError()
@classmethod
def match(cls, jedec: Union[bytes, bytearray, Iterable[int]]) -> bool:
"""Tells whether this class support this JEDEC identifier.
:param jedec: device type as a sequence of bytes
:return: True if the current class supports the detected device.
"""
raise NotImplementedError()
class SerialFlashManager:
"""Serial flash manager.
Automatically detects and instanciate the proper flash device class
based on the JEDEC identifier which is read out from the device itself.
"""
CMD_JEDEC_ID = 0x9F
@staticmethod
def get_from_controller(spi: SpiPort,
cs: int = 0, freq: Optional[float] = None) \
-> '_SpiFlashDevice':
"""Obtain an instance of the detected flash device, using an
existing SpiController.
:param spictrl: a PyFtdi configured SpiController instance
:param cs: the /CS line to use from the controller
:param freq: the SPI bus frequency for this flash device
:return: new instance of the flash device, if detected
"""
jedec = SerialFlashManager.read_jedec_id(spi)
if not jedec:
# it is likely that the latency setting is too low if this
# condition is encountered
raise SerialFlashUnknownJedec("Unable to read JEDEC Id")
flash = SerialFlashManager._get_flash(spi, jedec)
flash.set_spi_frequency(freq)
return flash
@staticmethod
def get_flash_device(spi: SpiPort, cs: int = 0, freq: Optional[float] = None) \
-> '_SpiFlashDevice':
"""Obtain an instance of the detected flash device.
:param url: PyFtdi controller or a PyUSB UsbDevice
:param cs: the /CS line to use from the controller
:param freq: the SPI bus frequency for this flash device
:return: new instance of the flash device, if detected
"""
jedec = SerialFlashManager.read_jedec_id(spi)
if not jedec:
# it is likely that the latency setting is too low if this
# condition is encountered
raise SerialFlashUnknownJedec("Unable to read JEDEC Id")
flash = SerialFlashManager._get_flash(spi, jedec)
flash.set_spi_frequency(freq)
return flash
@staticmethod
def read_jedec_id(spi: SpiPort) -> bytes:
"""Read flash device JEDEC identifier (3 bytes)"""
jedec_cmd = bytes((SerialFlashManager.CMD_JEDEC_ID,))
return spi.exchange(jedec_cmd, 3)
@staticmethod
def _get_flash(spi: SpiPort, jedec: bytes) -> '_SpiFlashDevice':
devices = []
contents = sys.modules[__name__].__dict__
for name in contents:
if name.endswith('FlashDevice') and not name.startswith('_'):
devices.append(contents[name])
for device in devices:
if device.match(jedec):
return device(spi, jedec)
if any(jedec):
raise SerialFlashUnknownJedec(jedec)
raise SerialFlashError('No serial flash detected')
class _SpiFlashDevice(SerialFlash):
"""Generic flash device implementation.
Most SPI flash devices share commands and parameters. Those devices
generally contains '25' in their reference. However, there are virtually
no '25' device that is fully compliant with any counterpart from
a concurrent manufacturer. Most differences are focused on lock and
security features. Here comes the mess... This class contains the most
common implementation for the basic feature, and each physical device
inherit from this class for feature specialization.
"""
CMD_READ_LO_SPEED = 0x13 # Read @ low speed
CMD_READ_HI_SPEED = 0x0C # Read @ high speed
ADDRESS_WIDTH = 4
def __init__(self, spiport: SpiPort):
self._spi = spiport
@property
def spi_frequency(self) -> float:
"""REturn the current frequency of the SPI bus for this device.
:return: the bus frequency in Hz.
"""
return self._spi and self._spi.frequency
def read(self, address: int, length: int) -> bytes:
if address+length > len(self):
raise SerialFlashValueError('Out of range')
buf = bytearray()
while length > 0:
size = min(length, 0xFFFFFFFF)
data = self._read_hi_speed(address, size)
length -= len(data)
address += len(data)
buf.extend(data)
return bytes(buf)
def erase(self, address: int, length: int, verify: bool = False) -> None:
"""Erase sectors/blocks/chip of a "generic" flash device.
Erasure algorithm:
The area to erase span across one or more sectors, which can be
accounted as bigger blocks, depending on the start and end address
of the location to be erased
address ----------------- length ---------------------->
v v
...|LSS|LSS|LSS| LHS | LHS | S | RHS | RHS |RSS|RSS|RSS|....
LSS: left subsector, RSS: right subsector
LHS: left half-sector, RHS: right half-sector (32KB)
S: (large) sector (64kB)
Depending on the device capabilities, half-sector may or may not be
used. This routine tries to find and erase the biggest flash page
segments so that erasure time is decreased.
Concrete implementation should provide the various sector sizes
"""
# sanity check
if address == 0 and length == -1:
length = len(self)
self.can_erase(address, length)
if address == 0 and length == len(self):
if self.has_feature(SerialFlash.FEAT_CHIPERASE):
self._erase_chip(self.get_erase_command('chip'),
self.get_timings('chip'))
return
self.get_erase_size()
# first page to erase on the left-hand size
start = address
# last page to erase on the left-hand size
end = start + length
# first page to erase on the right-hand size
rstart = start
# last page to erase on the right-hand size
rend = end
if self.has_feature(SerialFlash.FEAT_SECTERASE):
# Check whether one or more whole large sector can be erased
sector_size = self.get_size('sector')
sector_mask = ~(sector_size-1)
s_start = (start+sector_size-1) & sector_mask
s_end = end & sector_mask
if s_start < s_end:
self._erase_blocks(self.get_erase_command('sector'),
self.get_timings('sector'),
s_start, s_end, sector_size)
# update the left-hand end marker
end = s_start
# update the right-hand start marker
if s_end > rstart:
rstart = s_end
if self.has_feature(SerialFlash.FEAT_HSECTERASE):
# Check whether one or more left halfsectors can be erased
hsector_size = self.get_size('hsector')
hsector_mask = ~(hsector_size-1)
hsl_start = (start+sector_size-1) & sector_mask
hsl_end = end & sector_mask
if hsl_start < hsl_end:
self._erase_blocks(self.get_erase_command('hsector'),
self.get_timings('hsector'),
hsl_start, hsl_end, hsector_size)
# update the left-hand end marker
end = hsl_start
# update the right-hand start marker
if hsl_end > rstart:
rstart = hsl_end
if self.has_feature(SerialFlash.FEAT_SUBSECTERASE):
# Check whether one or more left subsectors can be erased
subsector_size = self.get_size('subsector')
subsector_mask = ~(subsector_size-1)
ssl_start = (start+subsector_size-1) & subsector_mask
ssl_end = end & subsector_mask
if ssl_start < ssl_end:
self._erase_blocks(self.get_erase_command('subsector'),
self.get_timings('subsector'),
ssl_start, ssl_end, subsector_size)
# update the right-hand start marker
if ssl_end > rstart:
rstart = ssl_end
if self.has_feature(SerialFlash.FEAT_HSECTERASE):
# Check whether one or more whole left halfsectors can be erased
hsr_start = (rstart+hsector_size-1) & hsector_mask
hsr_end = rend & hsector_mask
if hsr_start < hsr_end:
self._erase_blocks(self.get_erase_command('hsector'),
self.get_timings('hsector'),
hsr_start, hsr_end, hsector_size)
# update the right-hand start marker
if hsr_end > rstart:
rstart = hsr_end
if self.has_feature(SerialFlash.FEAT_SUBSECTERASE):
# Check whether one or more whole right subsectors can be erased
ssr_start = (rstart+subsector_size-1) & subsector_mask
ssr_end = rend & subsector_mask
if ssr_start < ssr_end:
self._erase_blocks(self.get_erase_command('subsector'),
self.get_timings('subsector'),
ssr_start, ssr_end, subsector_size)
if verify:
self._verify_content(address, length, 0xFF)
def can_erase(self, address: int, length: int) -> None:
"""Tells whether a defined area can be erased on the Spansion flash
device. It does not take into account any locking scheme."""
if address == 0 and (length == -1 or length == len(self)):
return
erase_size = self.get_erase_size()
if address & (erase_size-1):
# start address should be aligned on a subsector boundary
raise SerialFlashValueError('Start address not aligned on a ' +
'erase sector boundary')
if ((length-1) & (erase_size-1)) != (erase_size-1):
# length should be a multiple of a subsector
raise SerialFlashValueError('End address not aligned on a ' +
'erase sector boundary')
if (address + length) > len(self):
raise SerialFlashValueError('Would erase over the flash capacity')
def get_erase_size(self) -> int:
"""Return the erase size in bytes"""
if self.has_feature(SerialFlash.FEAT_SUBSECTERASE):
return self.get_size('subsector')
if self.has_feature(SerialFlash.FEAT_HSECTERASE):
return self.get_size('hsector')
if self.has_feature(SerialFlash.FEAT_SECTERASE):
return self.get_size('sector')
raise SerialFlashNotSupported("Unknown erase size")
def get_size(self, kind: str) -> int:
"""Return the size of a device block.
:param kind: the block type
:return: the size of the block, in bytes
"""
raise NotImplementedError()
@classmethod
def get_erase_command(cls, block: str)-> bytes:
"""Get the erase command for a specified block kind"""
raise NotImplementedError()
def _read_lo_speed(self, address: int, length: int) -> bytes:
read_cmd = bytes((self.CMD_READ_LO_SPEED,
(address >> 24) & 0xff, (address >> 16) & 0xff, (address >> 8) & 0xff,
address & 0xff))
return self._spi.exchange(read_cmd, length)
def _read_hi_speed(self, address: int, length: int) -> bytes:
read_cmd = bytes((self.CMD_READ_HI_SPEED,
(address >> 24) & 0xff, (address >> 16) & 0xff, (address >> 8) & 0xff,
address & 0xff, 0))
return self._spi.exchange(read_cmd, length)
def _verify_content(self, address: int, length: int, refbyte: int) -> None:
data = self.read(address, length)
count = data.count(refbyte)
if count != length:
raise SerialFlashError('%d bytes are not erased' % (length-count))
def _wait_for_completion(self, times: Tuple[float, float]) -> None:
typical_time, max_time = times
timeout = time.time()
timeout += typical_time+max_time
cycle = 0
while self.is_busy():
# need to wait at least once
if cycle and time.time() > timeout:
raise SerialFlashTimeout('Command timeout (%d cycles)' % cycle)
time.sleep(typical_time)
cycle += 1
def _erase_blocks(self, command: int, times: Tuple[float, float],
start: int, end: int, size: int) -> None:
"""Erase one or more blocks."""
raise NotImplementedError()
def _erase_chip(self, command: int, times: Tuple[float, float]) -> None:
"""Erase an entire chip."""
raise NotImplementedError()
class _Gen25FlashDevice(_SpiFlashDevice):
"""Generic flash device implementation for '25' series.
Most SPI flash devices share commands and parameters. Those devices
generally contains '25' in their reference. However, there are virtually
no '25' device that is fully compliant with any counterpart from
a concurrent manufacturer. Most differences are focused on lock and
security features. Here comes the mess... This class contains the most
common implementation for the basic feature, and each physical device
inherit from this class for feature specialization.
"""
PAGE_DIV = 8
SUBSECTOR_DIV = 12
HSECTOR_DIV = 15
SECTOR_DIV = 16
# these values should be overriden in concrete implementation
JEDEC_ID = 0xFF
DEVICES = {}
SIZES = {}
SPI_FREQ_MAX = 10 # MHz
SR_WIP = 0b00000001 # Busy/Work-in-progress bit
SR_WEL = 0b00000010 # Write enable bit
SR_BP0 = 0b00000100 # bit protect #0
SR_BP1 = 0b00001000 # bit protect #1
SR_BP2 = 0b00010000 # bit protect #2
SR_BP3 = 0b00100000 # bit protect #3
SR_TBP = SR_BP3 # top-bottom protect bit
SR_SP = 0b01000000
SR_BPL = 0b10000000
SR_PROTECT_NONE = 0 # BP[0..2] = 0
SR_PROTECT_ALL = 0b00011100 # BP[0..2] = 1
SR_LOCK_PROTECT = SR_BPL
SR_UNLOCK_PROTECT = 0
SR_BPL_SHIFT = 2
CMD_READ_STATUS = 0x05 # Read status register
CMD_WRITE_ENABLE = 0x06 # Write enable
CMD_WRITE_DISABLE = 0x04 # Write disable
CMD_PROGRAM_PAGE = 0x12 # Write page
CMD_EWSR = 0x50 # Enable write status register
CMD_WRSR = 0x01 # Write status register
CMD_ERASE_SUBSECTOR = 0x21
CMD_ERASE_HSECTOR = 0x52
CMD_ERASE_SECTOR = 0xDC
CMD_ERASE_CHIP = 0xC7
def __init__(self, spi: SpiPort):
super(_Gen25FlashDevice, self).__init__(spi)
self._size = 0
def __len__(self):
return self._size
def set_spi_frequency(self, freq: Optional[float] = None) -> None:
default_freq = self.SPI_FREQ_MAX*1E06
freq = min(default_freq, freq) if freq else default_freq
self._spi.set_frequency(freq)
def get_size(self, kind):
try:
div = getattr(self, '%s_DIV' % kind.upper())
return 1 << div
except AttributeError:
raise SerialFlashNotSupported('%s size is not supported' %
kind.title())
@classmethod
def get_erase_command(cls, block: str) -> str:
"""Get the erase command for a specified block kind"""
return getattr(cls, 'CMD_ERASE_%s' % block.upper())
@classmethod
def has_feature(cls, feature: int) -> bool:
"""Flash device feature"""
try:
# all '25' devices use the same class properties
features = cls.FEATURES
except AttributeError:
raise NotImplementedError('No FEATURES defined')
return bool(features & feature)
def get_timings(self, timing: str) -> Tuple[float, float]:
"""Get a time tuple (typical, max)"""
try:
# all '25' devices use the same class properties
timings = self.TIMINGS
except AttributeError:
raise NotImplementedError('no TIMINGS defined')
return timings[timing]
@classmethod
def match(cls, jedec: Union[bytes, bytearray, Iterable[int]]) -> bool:
"""Tells whether this class support this JEDEC identifier"""
manufacturer, device, capacity = jedec[:3]
if manufacturer != cls.JEDEC_ID:
return False
if device not in cls.DEVICES:
return False
if capacity not in cls.SIZES:
return False
return True
def unlock(self) -> None:
self._enable_write()
wrsr_cmd = bytes((_Gen25FlashDevice.CMD_WRSR,
_Gen25FlashDevice.SR_WEL |
_Gen25FlashDevice.SR_PROTECT_NONE |
_Gen25FlashDevice.SR_UNLOCK_PROTECT))
self._spi.exchange(wrsr_cmd)
duration = self.get_timings('lock')
if any(duration):
self._wait_for_completion(duration)
status = self._read_status()
if status & _Gen25FlashDevice.SR_PROTECT_ALL:
raise SerialFlashRequestError("Cannot unprotect flash device")
def is_busy(self) -> bool:
return self._is_busy(self._read_status())
def write(self, address: int,
data: Union[bytes, bytearray, Iterable[int]]) -> None:
"""Write a sequence of bytes, starting at the specified address."""
from progressbar.bar import ProgressBar
length = len(data)
if address+length > len(self):
raise SerialFlashValueError('Cannot fit in flash area')
if not isinstance(data, (bytes, bytearray)):
data = bytes(data)
pos = 0
page_size = self.get_size('page')
progress = ProgressBar(min_value=pos, max_value=length, prefix='Programming ').start()
while pos < length:
progress.update(pos)
size = min(length-pos, page_size)
self._write(address, data[pos:pos+size])
address += size
pos += size
progress.finish()
def _read_status(self) -> int:
read_cmd = bytes((self.CMD_READ_STATUS,))
data = self._spi.exchange(read_cmd, 1)
#print("status data len {}, data:{}".format(len(data), data.hex()))
if len(data) != 1:
raise SerialFlashTimeout("Unable to retrieve flash status")
return data[0]
def _enable_write(self) -> None:
wren_cmd = bytes((self.CMD_WRITE_ENABLE,))
self._spi.exchange(wren_cmd)
def _disable_write(self) -> None:
wrdi_cmd = bytes((self.CMD_WRITE_DISABLE,))
self._spi.exchange(wrdi_cmd)
def _write(self, address: int, data: bytes) -> None:
# take care not to roll over the end of the flash page
page_mask = self.get_size('page')-1
if address & page_mask:
up = (address+page_mask) & ~page_mask
count = min(len(data), up-address)
sequences = [(address, data[:count]), (up, data[count:])]
else:
sequences = [(address, data)]
for addr, chunk in sequences:
self._enable_write()
wcmd = bytearray((self.CMD_PROGRAM_PAGE,
(addr >> 24) & 0xff, (addr >> 16) & 0xff, (addr >> 8) & 0xff,
addr & 0xff))
wcmd.extend(chunk)
self._spi.exchange(wcmd)
self._wait_for_completion(self.get_timings('page'))
def _erase_blocks(self, command: int, times: Tuple[float, float],
start: int, end: int, size: int) -> None:
"""Erase one or more blocks."""
from progressbar.bar import ProgressBar
progress = ProgressBar(min_value=start, max_value=end, prefix='Erasing ').start()
while start < end:
progress.update(start)
self._enable_write()
cmd = bytes((command, (start >> 24) & 0xff, (start >> 16) & 0xff,
(start >> 8) & 0xff, start & 0xff))
self._spi.exchange(cmd)
self._wait_for_completion(times)
start += size
progress.finish()
@classmethod
def _is_busy(cls, status: int) -> bool:
return bool(status & cls.SR_WIP)
@classmethod
def _is_wren(cls, status: int) -> bool:
return bool(status & cls.SR_WEL)
class Sst25FlashDevice(_Gen25FlashDevice):
"""SST25 flash device implementation"""
JEDEC_ID = 0xBF
DEVICES = {0x25: 'SST25'}
CMD_PROGRAM_BYTE = 0x02
CMD_PROGRAM_WORD = 0xAD # Auto address increment (for write command)
CMD_WRITE_STATUS_REGISTER = 0x01
SST25_AAI = 0b01000000 # AAI mode activation flag
SIZES = {0x41: 2 << 20, 0x4A: 4 << 20}
SPI_FREQ_MAX = 66 # MHz
TIMINGS = {'subsector': (0.025, 0.025), # 25 ms
'hsector': (0.025, 0.025), # 25 ms
'sector': (0.025, 0.025), # 25 ms
'lock': (0.0, 0.0)} # immediate
FEATURES = (SerialFlash.FEAT_SECTERASE |
SerialFlash.FEAT_SUBSECTERASE |
SerialFlash.FEAT_HSECTERASE)
def __init__(self, spi, jedec):
super(Sst25FlashDevice, self).__init__(spi)
if not Sst25FlashDevice.match(jedec):
raise SerialFlashUnknownJedec(jedec)
device, capacity = jedec[1:3]
self._device = self.DEVICES[device]
self._size = Sst25FlashDevice.SIZES[capacity]
def __str__(self):
return 'SST %s %s' % \
(self._device, pretty_size(self._size, lim_m=1 << 20))
def write(self, address: int, data: Iterable[int]) -> None:
"""SST25 uses a very specific implementation to write data. It offers
very poor performances, because the device lacks an internal buffer
which translates into an ultra-heavy load on SPI bus. However, the
device offers lightning-speed flash erasure.
Although the device supports byte-aligned write requests, the
current implementation only support half-word write requests."""
if address+len(data) > len(self):
raise SerialFlashValueError('Cannot fit in flash area')
if not isinstance(data, (bytes, bytearray)):
data = bytes(data)
length = len(data)
if (address & 0x1) or (length & 0x1) or (length == 0):
raise SerialFlashNotSupported("Alignement/size not supported")
self._unprotect()
self._enable_write()
aai_cmd = bytes((Sst25FlashDevice.CMD_PROGRAM_WORD,
(address >> 16) & 0xff,
(address >> 8) & 0xff,
address & 0xff,
data.pop(0), data.pop(0)))
offset = 0
while True:
offset += 2
self._spi.exchange(aai_cmd)
while self.is_busy():
time.sleep(0.01) # 10 ms
if not data:
break
aai_cmd = bytes((Sst25FlashDevice.CMD_PROGRAM_WORD,
data.pop(0), data.pop(0)))
self._disable_write()
def _unprotect(self):
"""Disable default protection for all sectors"""
unprotect = bytes((Sst25FlashDevice.CMD_WRITE_STATUS_REGISTER, 0x00))
self._enable_write()
self._spi.exchange(unprotect)
while self.is_busy():
time.sleep(0.01) # 10 ms
class S25FlFlashDevice(_Gen25FlashDevice):
"""Spansion S25FL flash device implementation"""
JEDEC_ID = 0x01
DEVICES = {0x02: 'S25FL'}
SIZES = {0x15: 4 << 20, 0x16: 8 << 20}
CR_FREEZE = 0x01
CR_QUAD = 0x02
CR_TBPARM = 0x04
CR_BPNV = 0x08
CR_LOCK = 0x10
CR_TBPROT = 0x20
CMD_READ_CONFIG = 0x35
SPI_FREQ_MAX = 104 # MHz (P series only)
TIMINGS = {'page': (0.0015, 0.003), # 1.5/3 ms
'subsector': (0.2, 0.8), # 200/800 ms
'sector': (0.5, 2.0), # 0.5/2 s
'bulk': (32, 64), # seconds
'lock': (0.0015, 0.1)} # 1.5/100 ms
FEATURES = (SerialFlash.FEAT_SECTERASE |
SerialFlash.FEAT_SUBSECTERASE)
def __init__(self, spi, jedec):
super(S25FlFlashDevice, self).__init__(spi)
if not S25FlFlashDevice.match(jedec):
raise SerialFlashUnknownJedec(jedec)
device, capacity = jedec[1:3]
self._device = self.DEVICES[device]
self._size = S25FlFlashDevice.SIZES[capacity]
def __str__(self):
return 'Spansion %s %s' % \
(self._device, pretty_size(self._size, lim_m=1 << 20))
def can_erase(self, address: int, length: int):
# we first need to check the current configuration register, as a
# previous configuration may prevent from altering some of the bits
readcfg_cmd = bytes((S25FlFlashDevice.CMD_READ_CONFIG,))
config = self._spi.exchange(readcfg_cmd, 1)[0]
if config & S25FlFlashDevice.CR_TBPARM:
# "parameter zone" is defined in the high sectors
border = len(self)-2*self.get_size('sector')
ls_size = self.get_size('sector')
rs_size = self.get_size('subsector')
else:
# "parameter zone" is defined in the low sectors
border = 2*self.get_size('sector')
ls_size = self.get_size('subsector')
rs_size = self.get_size('sector')
start = address
fend = address+length
# sanity check
if (start > fend) or (fend > len(self)):
raise SerialFlashValueError('Out of flash storage range')
if fend > border > start:
end = border
else:
end = fend
if start >= border:
size = rs_size
else:
size = ls_size
while True: # expect 1 (no border cross) or 2 loops (border cross)
# sanity check
if start & (size-1):
# start address should be aligned on a (sub)sector boundary
raise SerialFlashValueError('Start address not aligned on a '
'sector boundary')
# sanity check
if (((end-start)-1) & (size-1)) != (size-1):
# length should be a multiple of a (sub)sector
raise SerialFlashValueError('End address not aligned on a '
'sector boundary')
# stop condition
if (start >= border) or (end >= fend):
break
start = end
end = fend
size = rs_size
class M25PxFlashDevice(_Gen25FlashDevice):
"""Numonix M25P/M25PX flash device implementation"""
JEDEC_ID = 0x20
DEVICES = {0x71: 'M25P', 0x20: 'M25PX'}
SIZES = {0x15: 2 << 20, 0x16: 4 << 20, 0x17: 8 << 20, 0x18: 16 << 20}
SPI_FREQ_MAX = 75 # MHz (P series only)
TIMINGS = {'page': (0.0015, 0.003), # 1.5/3 ms
'subsector': (0.150, 0.150), # 150/150 ms
'sector': (3.0, 3.0), # 3/3 s
'bulk': (32, 64), # seconds
'lock': (0.0015, 0.003)} # 1.5/3 ms
FEATURES = SerialFlash.FEAT_SECTERASE | SerialFlash.FEAT_SUBSECTERASE
def __init__(self, spi, jedec):
super(M25PxFlashDevice, self).__init__(spi)
if not M25PxFlashDevice.match(jedec):
raise SerialFlashUnknownJedec(jedec)
device, capacity = jedec[1:3]
self._device = self.DEVICES[device]
self._size = M25PxFlashDevice.SIZES[capacity]
def __str__(self):
return 'Numonix %s%d %s' % \
(self._device, len(self) >> 17,
pretty_size(self._size, lim_m=1 << 20))
class W25xFlashDevice(_Gen25FlashDevice):
"""Winbond W25Q/W25X flash device implementation"""
JEDEC_ID = 0xEF
DEVICES = {0x30: 'W25X', 0x40: 'W25Q'}
SIZES = {0x11: 1 << 17, 0x12: 1 << 18, 0x13: 1 << 19, 0x14: 1 << 20,
0x15: 2 << 20, 0x16: 4 << 20, 0x17: 8 << 20, 0x18: 16 << 20}
SPI_FREQ_MAX = 104 # MHz
CMD_READ_UID = 0x4B
UID_LEN = 0x8 # 64 bits
READ_UID_WIDTH = 4 # 4 dummy bytes
TIMINGS = {'page': (0.0015, 0.003), # 1.5/3 ms
'subsector': (0.200, 0.200), # 200/200 ms
'sector': (1.0, 1.0), # 1/1 s
'bulk': (32, 64), # seconds
'lock': (0.05, 0.1), # 50/100 ms
'chip': (4, 11)}
FEATURES = (SerialFlash.FEAT_SECTERASE |
SerialFlash.FEAT_SUBSECTERASE |
SerialFlash.FEAT_CHIPERASE)
def __init__(self, spi, jedec):
super(W25xFlashDevice, self).__init__(spi)
if not W25xFlashDevice.match(jedec):
raise SerialFlashUnknownJedec(jedec)
device, capacity = jedec[1:3]
self._device = self.DEVICES[device]
self._size = W25xFlashDevice.SIZES[capacity]
def __str__(self):
return 'Winbond %s%d %s' % \
(self._device, len(self) >> 17,
pretty_size(self._size, lim_m=1 << 20))
def _erase_chip(self, command: int, times: Tuple[float, float]):
"""Erase an entire chip"""
self._enable_write()
cmd = bytes((command,))
self._spi.exchange(cmd)
self._wait_for_completion(times)
class Mx25lFlashDevice(_Gen25FlashDevice):
"""Macronix MX25L flash device implementation"""
JEDEC_ID = 0xC2
DEVICES = {0x9E: 'MX25D', 0x26: 'MX25E', 0x20: 'MX25E06'}
SIZES = {0x15: 2 << 20, 0x16: 4 << 20, 0x17: 8 << 20, 0x18: 16 << 20}
SPI_FREQ_MAX = 104 # MHz
TIMINGS = {'page': (0.0015, 0.0075), # 1.5/3 ms
'subsector': (0.300, 0.300), # 300/300 ms
'hsector': (25.0, 2.0), # 2/2 s
'sector': (25.0, 400), # 2/2 s
'bulk': (150, 300), # seconds
'lock': (0.0015, 0.003)} # 1.5/3 ms
FEATURES = (SerialFlash.FEAT_SECTERASE |
SerialFlash.FEAT_HSECTERASE |
SerialFlash.FEAT_SUBSECTERASE)
CMD_UNLOCK = 0xF3
CMD_GBULK = 0x98
CMD_RDBLOCK = 0xFB
CMD_RDSBLOCK = 0x3C
CMD_RDPLOCK = 0x3F
CMD_BLOCKP = 0xE2
CMD_SBLK = 0x36
CMD_PLOCK = 0x64
def __init__(self, spi, jedec):
super(Mx25lFlashDevice, self).__init__(spi)
if not Mx25lFlashDevice.match(jedec):
raise SerialFlashUnknownJedec(jedec)
device, capacity = jedec[1:3]
self._size = self.SIZES[capacity]
self._device = self.DEVICES[device]
def __str__(self):
return 'Macronix %s%d %s' % \
(self._device, len(self) >> 17,
pretty_size(self._size, lim_m=1 << 20))
def unlock(self):
if self._device.endswith('D'):
unlock = self.CMD_UNLOCK
else:
unlock = self.CMD_GBULK
self._enable_write()
wcmd = bytes((unlock,))
self._spi.exchange(wcmd)
self._wait_for_completion(self.get_timings('page'))
class Mx66umFlashDevice(_Gen25FlashDevice):
"""Macronix MX66UM flash device implementation"""
JEDEC_ID = 0xC2
DEVICES = {0x80: 'MX66UM'}
SIZES = {0x3b: 128 << 20}
SPI_FREQ_MAX = 133 # MHz
TIMINGS = {'page': (0.00015, 0.030), # page program time
'subsector': (0.025, 0.400), # sector erase time