1313_LFS_READ_SIZE = 32
1414_LFS_MIN_BLOCK_SIZE = 128
1515
16+ _COUNTER_LIMIT = 65535
17+ _COUNTER_NAMES = (
18+ "mount_attempts" , "format_attempts" , "format_completions" ,
19+ "remount_attempts" , "remount_completions" , "program_calls" , "erase_calls" ,
20+ "recovery_attempts" , "recovery_emissions" ,
21+ )
22+ _RECOVERY_MESSAGE = "PyBLE workspace recovery is required; reconnect by USB."
23+ _boot_observation = None
24+ _observation_started = False
25+ _unobserved_recovery_attempted = False
26+
27+
28+ class _BootObservation :
29+ """One bounded VM-local measurement; never an admission authority."""
30+
31+ def __init__ (self ):
32+ import os
33+ from binascii import hexlify
34+
35+ identity = os .urandom (16 )
36+ if type (identity ) is not bytes or len (identity ) != 16 :
37+ raise ValueError ("unavailable workspace boot identity" )
38+ self .boot_id = hexlify (identity ).decode ()
39+ self .counts = [0 ] * len (_COUNTER_NAMES )
40+ self .workspace_attached = False
41+ self .complete = False
42+ self .fault = False
43+ self .overflow = False
44+ self .media_state = "uninspected"
45+ self .sealed = False
46+ self .mount_returned = False
47+ self .nonblank_refusal = False
48+
49+ def increment (self , index ):
50+ if self .sealed :
51+ return
52+ if self .counts [index ] == _COUNTER_LIMIT :
53+ self .overflow = True
54+ self .fault = True
55+ raise OverflowError ("workspace observation counter overflow" )
56+ self .counts [index ] += 1
57+
58+ def mark_fault (self ):
59+ if not self .sealed :
60+ self .fault = True
61+
62+
63+ class _ObservedBlockDevice :
64+ """Observe the native program/erase boundary without copying read data."""
65+
66+ def __init__ (self , bdev , observation ):
67+ # VfsLfs2 caches this original bound method directly. Reads do not
68+ # acquire a Python forwarding layer or qualification-owned buffer.
69+ self .readblocks = bdev .readblocks
70+ self ._writeblocks = bdev .writeblocks
71+ self ._ioctl = bdev .ioctl
72+ self ._observation = observation
73+
74+ def writeblocks (self , block , data , * offset ):
75+ observation = self ._observation
76+ observation .increment (5 )
77+ try :
78+ result = self ._writeblocks (block , data , * offset )
79+ except BaseException :
80+ observation .mark_fault ()
81+ raise
82+ # Preserve the pinned VFS protocol's return value, including failed
83+ # and idempotent writes. A false/invalid result cannot look healthy.
84+ if result is False or (result is not None and result is not True and result != 0 ):
85+ observation .mark_fault ()
86+ return result
87+
88+ def ioctl (self , command , argument ):
89+ observation = self ._observation
90+ if command == 6 :
91+ observation .increment (6 )
92+ try :
93+ result = self ._ioctl (command , argument )
94+ except BaseException :
95+ observation .mark_fault ()
96+ raise
97+ if command == 6 and result is not None and result != 0 :
98+ observation .mark_fault ()
99+ return result
100+
101+
102+ def read_boot_observation (challenge ):
103+ """Read detached retained state; never rerun storage or change a count."""
104+ if (type (challenge ) is not str or len (challenge ) != 32 or
105+ any (value not in "0123456789abcdef" for value in challenge )):
106+ raise ValueError ("invalid workspace observation challenge" )
107+ observation = _boot_observation
108+ if observation is None :
109+ raise RuntimeError ("workspace boot observation unavailable" )
110+ value = {
111+ "schema_version" : 1 ,
112+ "boot_id" : observation .boot_id ,
113+ "challenge" : challenge ,
114+ }
115+ for index in range (len (_COUNTER_NAMES )):
116+ value [_COUNTER_NAMES [index ]] = observation .counts [index ]
117+ value ["workspace_attached" ] = observation .workspace_attached
118+ value ["complete" ] = observation .complete
119+ value ["fault" ] = observation .fault
120+ value ["overflow" ] = observation .overflow
121+ value ["media_state" ] = observation .media_state
122+ return value
123+
124+
125+ def boot_attached ():
126+ """Seal only after the overlay's actual VFS attachment succeeded."""
127+ observation = _boot_observation
128+ if observation is None or observation .sealed :
129+ raise RuntimeError ("workspace observation cannot attach" )
130+ if not observation .mount_returned or observation .fault or observation .overflow :
131+ observation .mark_fault ()
132+ raise RuntimeError ("workspace observation is not attachable" )
133+ observation .workspace_attached = True
134+ observation .complete = True
135+ observation .sealed = True
136+
137+
138+ def boot_recovery ():
139+ """Emit the bounded local message once, measuring the real print call."""
140+ global _unobserved_recovery_attempted
141+ observation = _boot_observation
142+ if observation is None :
143+ # An allocation/entropy fault may precede record creation. Guidance
144+ # still exists, but no zero-filled or otherwise passing record does.
145+ if _unobserved_recovery_attempted :
146+ raise RuntimeError ("workspace recovery already attempted" )
147+ _unobserved_recovery_attempted = True
148+ print (_RECOVERY_MESSAGE )
149+ return
150+ if observation .sealed :
151+ raise RuntimeError ("workspace recovery already sealed" )
152+ if not observation .nonblank_refusal or observation .mount_returned :
153+ observation .mark_fault ()
154+ observation .increment (7 )
155+ try :
156+ print (_RECOVERY_MESSAGE )
157+ observation .increment (8 )
158+ except BaseException :
159+ observation .mark_fault ()
160+ observation .sealed = True
161+ raise
162+ observation .complete = True
163+ observation .sealed = True
164+
16165
17166def _recovery_geometry (bdev , progsize ):
18167 """Return validated ``(count, block_size)`` for destructive recovery."""
@@ -36,18 +185,51 @@ def _recovery_geometry(bdev, progsize):
36185 return count , block_size
37186
38187
39- def mount_lfs2 (bdev , vfs_module , progsize = 256 ):
188+ def mount_lfs2 (bdev , vfs_module , progsize = 256 , * , observe_boot = False ):
40189 """Mount LFS2, formatting once only when every device byte is erased.
41190
42191 Unexpected constructor faults propagate without inspection. Invalid or
43192 unreadable geometry and any non-erased byte perform no write. The original
44193 mount ``OSError`` is re-raised for nonblank media so the board overlay can
45194 enter its bounded operator-recovery path.
46195 """
196+ global _boot_observation , _observation_started
197+ if type (observe_boot ) is not bool :
198+ raise ValueError ("invalid workspace observation mode" )
199+ if not observe_boot :
200+ return _mount_lfs2 (bdev , vfs_module , progsize , None )
201+ if _observation_started :
202+ raise RuntimeError ("workspace boot already observed" )
203+ _observation_started = True
204+ observation = _BootObservation ()
205+ _boot_observation = observation
47206 try :
48- return vfs_module .VfsLfs2 (bdev , progsize = progsize )
207+ return _mount_lfs2 (_ObservedBlockDevice (bdev , observation ),
208+ vfs_module , progsize , observation )
209+ except BaseException :
210+ if not observation .nonblank_refusal :
211+ observation .mark_fault ()
212+ if observation .media_state == "uninspected" :
213+ observation .media_state = "uncertain"
214+ raise
215+
216+
217+ def _mount_lfs2 (bdev , vfs_module , progsize , observation ):
218+ if observation is not None :
219+ observation .increment (0 )
220+ try :
221+ mounted = vfs_module .VfsLfs2 (bdev , progsize = progsize )
49222 except OSError as error :
50223 mount_failure = error
224+ else :
225+ if observation is not None :
226+ observation .mount_returned = True
227+ return mounted
228+
229+ if observation is not None :
230+ if observation .fault or observation .overflow :
231+ raise mount_failure
232+ observation .media_state = "uncertain"
51233
52234 count , block_size = _recovery_geometry (bdev , progsize )
53235 block = bytearray (block_size )
@@ -58,14 +240,33 @@ def mount_lfs2(bdev, vfs_module, progsize=256):
58240 for index in range (block_size ):
59241 block [index ] = 0
60242 result = bdev .readblocks (block_number , block )
61- if result not in (None , 0 ) or len (block ) != block_size :
243+ read_succeeded = (result is None or result is True or
244+ (type (result ) is int and result == 0 ))
245+ if not read_succeeded or len (block ) != block_size :
62246 raise ValueError ("uncertain block-device read" )
63247 for value in block :
64248 if value != 0xFF :
65249 erased = False
66250
67251 if not erased :
252+ if observation is not None :
253+ observation .media_state = "nonblank"
254+ observation .nonblank_refusal = True
68255 raise mount_failure
69256
257+ if observation is not None :
258+ observation .media_state = "erased"
259+ if observation .fault or observation .overflow :
260+ raise RuntimeError ("uncertain workspace observation" )
261+ observation .increment (1 )
70262 vfs_module .VfsLfs2 .mkfs (bdev , progsize = progsize )
71- return vfs_module .VfsLfs2 (bdev , progsize = progsize )
263+ if observation is not None :
264+ observation .increment (2 )
265+ if observation .fault or observation .overflow :
266+ raise RuntimeError ("uncertain workspace format observation" )
267+ observation .increment (3 )
268+ mounted = vfs_module .VfsLfs2 (bdev , progsize = progsize )
269+ if observation is not None :
270+ observation .increment (4 )
271+ observation .mount_returned = True
272+ return mounted
0 commit comments