15
15
*/
16
16
17
17
#include " DataFlashBlockDevice.h"
18
+ #include " mbed_critical.h"
18
19
19
20
#include < inttypes.h>
20
21
@@ -138,7 +139,11 @@ DataFlashBlockDevice::DataFlashBlockDevice(PinName mosi,
138
139
: _spi(mosi, miso, sclk),
139
140
_cs(cs, 1 ),
140
141
_nwp(nwp),
141
- _device_size(0 )
142
+ _device_size(0 ),
143
+ _page_size(0 ),
144
+ _block_size(0 ),
145
+ _is_initialized(0 ),
146
+ _init_ref_count(0 )
142
147
{
143
148
/* check that frequency is within range */
144
149
if (freq > DATAFLASH_LOW_FREQUENCY) {
@@ -161,6 +166,16 @@ int DataFlashBlockDevice::init()
161
166
{
162
167
DEBUG_PRINTF (" init\r\n " );
163
168
169
+ if (!_is_initialized) {
170
+ _init_ref_count = 0 ;
171
+ }
172
+
173
+ uint32_t val = core_util_atomic_incr_u32 (&_init_ref_count, 1 );
174
+
175
+ if (val != 1 ) {
176
+ return BD_ERROR_OK;
177
+ }
178
+
164
179
int result = BD_ERROR_DEVICE_ERROR;
165
180
166
181
/* read ID register to validate model and set dimensions */
@@ -262,20 +277,40 @@ int DataFlashBlockDevice::init()
262
277
/* write protect device when idle */
263
278
_write_enable (false );
264
279
280
+ if (result == BD_ERROR_OK) {
281
+ _is_initialized = true ;
282
+ }
283
+
265
284
return result;
266
285
}
267
286
268
287
int DataFlashBlockDevice::deinit ()
269
288
{
270
289
DEBUG_PRINTF (" deinit\r\n " );
271
290
291
+ if (!_is_initialized) {
292
+ _init_ref_count = 0 ;
293
+ return BD_ERROR_OK;
294
+ }
295
+
296
+ uint32_t val = core_util_atomic_decr_u32 (&_init_ref_count, 1 );
297
+
298
+ if (val) {
299
+ return BD_ERROR_OK;
300
+ }
301
+
302
+ _is_initialized = false ;
272
303
return BD_ERROR_OK;
273
304
}
274
305
275
306
int DataFlashBlockDevice::read (void *buffer, bd_addr_t addr, bd_size_t size)
276
307
{
277
308
DEBUG_PRINTF (" read: %p %" PRIX64 " %" PRIX64 " \r\n " , buffer, addr, size);
278
309
310
+ if (!_is_initialized) {
311
+ return BD_ERROR_DEVICE_ERROR;
312
+ }
313
+
279
314
int result = BD_ERROR_DEVICE_ERROR;
280
315
281
316
/* check parameters are valid and the read is within bounds */
@@ -317,6 +352,10 @@ int DataFlashBlockDevice::program(const void *buffer, bd_addr_t addr, bd_size_t
317
352
{
318
353
DEBUG_PRINTF (" program: %p %" PRIX64 " %" PRIX64 " \r\n " , buffer, addr, size);
319
354
355
+ if (!_is_initialized) {
356
+ return BD_ERROR_DEVICE_ERROR;
357
+ }
358
+
320
359
int result = BD_ERROR_DEVICE_ERROR;
321
360
322
361
/* check parameters are valid and the write is within bounds */
@@ -379,6 +418,10 @@ int DataFlashBlockDevice::erase(bd_addr_t addr, bd_size_t size)
379
418
{
380
419
DEBUG_PRINTF (" erase: %" PRIX64 " %" PRIX64 " \r\n " , addr, size);
381
420
421
+ if (!_is_initialized) {
422
+ return BD_ERROR_DEVICE_ERROR;
423
+ }
424
+
382
425
int result = BD_ERROR_DEVICE_ERROR;
383
426
384
427
/* check parameters are valid and the erase is within bounds */
0 commit comments