filesystem_fat.c 13.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
 * Implementation of efs_ API functions for a FatFS specific
 * EpicFileSystem
 */

#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include <ff.h>
#include <diskio.h>

#include <FreeRTOS.h>
#include <semphr.h>

#include "fs/internal.h"
#include "modules/filesystem.h"
#include "epicardium.h"
#include "card10.h"
#include "modules/log.h"
25
26
#include "modules/modules.h"
#include "api/common.h"
27

28
#define SSLOG_DEBUG(...) LOG_DEBUG("fatfs", __VA_ARGS__)
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#define SSLOG_INFO(...) LOG_INFO("fatfs", __VA_ARGS__)
#define SSLOG_ERR(...) LOG_ERR("fatfs", __VA_ARGS__)

#ifndef EPIC_FAT_STATIC_SEMAPHORE
#define EPIC_FAT_STATIC_SEMAPHORE 0
#endif

/* clang-format off */
#define EPIC_FAT_MAX_OPENED           (1 << (EPIC_FAT_FD_INDEX_BITS))
#define EPIC_FAT_FD_GENERATION_BITS   (31 - (EPIC_FAT_FD_INDEX_BITS))
#define EPIC_FAT_FD_INDEX_MASK        (uint32_t)((1u << EPIC_FAT_FD_INDEX_BITS) - 1)
#define EPIC_FAT_FD_INDEX(fd)         ((uint32_t)(fd)&EPIC_FAT_FD_INDEX_MASK)
#define EPIC_FAT_FD_GENERATION(fd)    ((uint32_t)(fd) >> EPIC_FAT_FD_INDEX_BITS)
#define EPIC_FAT_FD_MAX_GENERATION    (uint32_t)((1u << EPIC_FAT_FD_GENERATION_BITS) - 1)
#define EPIC_FAT_FD(idx, gen)         (int)(((uint32_t)(gen) << EPIC_FAT_FD_INDEX_BITS) \
                                      | ((uint32_t)(idx)&EPIC_FAT_FD_INDEX_MASK))
/* clang-format on */

struct FatObject {
	uint32_t generation;
49
	int coreMask;
50
51
52
53
54
55
56
57
58
59
60
61
	enum epic_stat_type type;
	union {
		FIL file;
		DIR dir;
	};
};

struct EpicFileSystem {
	struct FatObject pool[EPIC_FAT_MAX_OPENED];
	uint32_t generationCount;
	bool initialized;
	FATFS FatFs;
62
	int lockCoreMask;
63
64
65
66
67
68
69
70
};

// this table converts from FRESULT to POSIX errno
static const int s_libffToErrno[20];

static const char *f_get_rc_string(FRESULT rc);
static bool globalLockAccquire();
static void globalLockRelease();
71
static void efs_close_all(EpicFileSystem *fs, int coreMask);
72

73
74
75
/**
 * if EPICSTAT_NONE is passed to `expected`, the type is not checked.
 */
76
77
78
79
80
81
82
83
static bool efs_get_opened(
	EpicFileSystem *fs,
	int i,
	enum epic_stat_type expected,
	struct FatObject **res,
	int *rc
);

84
85
86
87
88
89
90
91
92
93
94
95
96
static bool
efs_get_new(EpicFileSystem *fs, uint32_t *idx, struct FatObject **obj, int *rc);

static int efs_obj_init(
	EpicFileSystem *fs,
	struct FatObject *obj,
	uint32_t index,
	enum epic_stat_type type
);

static void efs_obj_deinit(EpicFileSystem *fs, struct FatObject *obj);
static void efs_init_stat(struct epic_stat *stat, FILINFO *finfo);

97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
static EpicFileSystem s_globalFileSystem;

#if (EPIC_FAT_STATIC_SEMAPHORE == 1)
static StaticSemaphore_t s_globalLockBuffer;
#endif

static SemaphoreHandle_t s_globalLock = NULL;

void fatfs_init()
{
	static volatile bool s_initCalled = false;
	//this has to be called vefore any tasks have been started!
	// ...not 100% water-tight though, since tick count might be zero even after vTaskStartScheduler
	// has been called...
	assert(xTaskGetTickCount() == configINITIAL_TICK_COUNT);
	assert(!s_initCalled);
	s_initCalled = true;

#if (EPIC_FAT_STATIC_SEMAPHORE == 1)
	s_globalLock = xSemaphoreCreateMutexStatic(&s_globalLockBuffer);
#else
	s_globalLock = xSemaphoreCreateMutex();
#endif
120
	s_globalFileSystem.generationCount = 1;
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
	fatfs_attach();
}

/*
 * NOTE about attach/detach:
 *
 * while in detach, we're calling diskio_deinitialize (a function that is
 * originally not present in libff's diskio.h), we do not need to call
 * diskio_initialize in attach, since it will implicitly be called by
 * any f_ operation, via libff's find_volume for volumes that have not
 * been mounted yet.
 *
 */
int fatfs_attach()
{
	FRESULT ff_res;
	int rc = 0;
	if (globalLockAccquire()) {
		EpicFileSystem *fs = &s_globalFileSystem;
		if (!fs->initialized) {
			ff_res = f_mount(&fs->FatFs, "/", 0);
			if (ff_res == FR_OK) {
				fs->initialized = true;
144
				SSLOG_DEBUG("FatFs mounted\n");
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
			} else {
				SSLOG_ERR(
					"f_mount error %s\n",
					f_get_rc_string(ff_res)
				);
				rc = -s_libffToErrno[ff_res];
			}
		}

		globalLockRelease();
	} else {
		SSLOG_ERR("Failed to lock\n");
	}
	return rc;
}

void fatfs_detach()
{
	FRESULT ff_res;
	EpicFileSystem *fs;
	if (efs_lock_global(&fs) == 0) {
166
		efs_close_all(fs, EPICARDIUM_COREMASK_BOTH);
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183

		//unmount by passing NULL as fs object, will destroy our sync object via ff_del_syncobj
		ff_res = f_mount(NULL, "/", 0);
		if (ff_res != FR_OK) {
			SSLOG_ERR(
				"f_mount (unmount) error %s\n",
				f_get_rc_string(ff_res)
			);
		}

		fs->initialized = false;
		disk_deinitialize();
		SSLOG_INFO("detached\n");
		efs_unlock_global(fs);
	}
}

184
185
186
187
188
189
190
191
void fatfs_close_all(int coreMask)
{
	EpicFileSystem *fs;
	if (efs_lock_global(&fs) == 0) {
		efs_close_all(fs, coreMask);
		efs_unlock_global(fs);
	}
}
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
static const char *f_get_rc_string(FRESULT rc)
{
	static const TCHAR *rcstrings =
		_T("OK\0DISK_ERR\0INT_ERR\0NOT_READY\0NO_FILE\0NO_PATH\0INVALID_NAME\0")
		_T("DENIED\0EXIST\0INVALID_OBJECT\0WRITE_PROTECTED\0INVALID_DRIVE\0")
		_T("NOT_ENABLED\0NO_FILESYSTEM\0MKFS_ABORTED\0TIMEOUT\0LOCKED\0")
		_T("NOT_ENOUGH_CORE\0TOO_MANY_OPEN_FILES\0INVALID_PARAMETER\0");

	FRESULT i;
	const char *p = rcstrings;

	for (i = 0; i != rc && *p; i++) {
		while (*p++)
			;
	}
	return p;
}

static bool globalLockAccquire()
{
	return (int)(xSemaphoreTake(s_globalLock, FF_FS_TIMEOUT) == pdTRUE);
}

static void globalLockRelease()
{
	xSemaphoreGive(s_globalLock);
}

int efs_lock_global(EpicFileSystem **fs)
{
	*fs = NULL;
	if (!globalLockAccquire()) {
		return -EBUSY;
	}
	if (!s_globalFileSystem.initialized) {
		globalLockRelease();
		return -ENODEV;
	}
	*fs = &s_globalFileSystem;
231
232
233
234
235
	if (xTaskGetCurrentTaskHandle() == dispatcher_task_id) {
		s_globalFileSystem.lockCoreMask = EPICARDIUM_COREMASK_1;
	} else {
		s_globalFileSystem.lockCoreMask = EPICARDIUM_COREMASK_0;
	}
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
	return 0;
}

void efs_unlock_global(EpicFileSystem *fs)
{
	(void)fs;
	globalLockRelease();
}

static bool efs_get_opened(
	EpicFileSystem *fs,
	int fd,
	enum epic_stat_type expected,
	struct FatObject **obj,
	int *rc
) {
	uint32_t index      = EPIC_FAT_FD_INDEX(fd);
	uint32_t generation = EPIC_FAT_FD_GENERATION(fd);

	*obj = NULL;
	*rc  = -EBADF;

	if (index >= EPIC_FAT_MAX_OPENED ||
	    generation >= EPIC_FAT_FD_MAX_GENERATION) {
		return false;
	}
262
263
264
265
	if (fs->pool[index].generation != generation) {
		return false;
	}
	if (expected != EPICSTAT_NONE && fs->pool[index].type != expected) {
266
267
268
269
270
271
272
273
		return false;
	}

	*obj = &fs->pool[index];
	*rc  = 0;
	return true;
}

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
static bool
efs_get_new(EpicFileSystem *fs, uint32_t *idx, struct FatObject **obj, int *rc)
{
	uint32_t index;

	*obj = NULL;
	*rc  = 0;
	*idx = 0;

	//find free object to use
	for (index = 0; index < EPIC_FAT_MAX_OPENED; ++index) {
		if (fs->pool[index].type == EPICSTAT_NONE) {
			break;
		}
	}
	if (index == EPIC_FAT_MAX_OPENED) {
		*rc = -s_libffToErrno[FR_TOO_MANY_OPEN_FILES];
		return false;
	}

	*obj = &fs->pool[index];
	return true;
}

static int efs_obj_init(
	EpicFileSystem *fs,
	struct FatObject *obj,
	uint32_t index,
	enum epic_stat_type type
) {
	uint32_t generation;

	generation = fs->generationCount++;
	if (generation == EPIC_FAT_FD_MAX_GENERATION) {
		fs->generationCount = 1;
	}
	obj->type       = type;
	obj->generation = generation;
312
	obj->coreMask   = fs->lockCoreMask;
313
314
315
316
317
318
319
320

	return EPIC_FAT_FD(index, generation);
}

static void efs_obj_deinit(EpicFileSystem *fs, struct FatObject *obj)
{
	obj->type       = EPICSTAT_NONE;
	obj->generation = 0;
321
	obj->coreMask   = 0;
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
/* here we're trying to mirror glibc's behaviour:
 * any combination of rwax parses but only the first of those flags wins:
 *    - rw, ra, rr all open read-only
 * a `+` at any position but the first turns into read-write
 * any other character at any position yields EINVAL
 */
static inline bool parse_mode(const char *mstring, int *mode)
{
	switch (mstring[0]) {
	case 'r':
		*mode = FA_READ;
		break;
	case 'w':
		*mode = FA_CREATE_ALWAYS | FA_WRITE;
		break;
	case 'x':
		//in constrast to FA_CREATE_ALWAYS, FA_CREATE_NEW fails for existing files
		*mode = FA_WRITE | FA_CREATE_NEW;
		break;
	case 'a':
		//in constrast to FA_CREATE_ALWAYS, FA_CREATE_NEW fails for existing files
		*mode = FA_WRITE | FA_OPEN_APPEND;
		break;
	default:
		return false;
	}
	while (*mstring) {
		switch (*mstring++) {
		case '+': //turns any of r,w,x into read&write
			*mode |= FA_READ | FA_WRITE;
			break;
		case 'r': //fallthrough intentional
		case 'w': //fallthrough intentional
		case 'a': //fallthrough intentional
		case 'x': //fallthrough intentional
		case 'b': //fallthrough intentional
			break;
		default:
			return false;
		}
	}
	return true;
}

int efs_open(EpicFileSystem *fs, const char *filename, const char *modeString)
{
	struct FatObject *o = NULL;
371
	uint32_t index;
372
373
374
375
376
377
378
	int mode = 0;
	int res;

	if (!parse_mode(modeString, &mode)) {
		return -EINVAL;
	}

379
380
381
382
	if (!efs_get_new(fs, &index, &o, &res)) {
		return res;
	}

383
384
385
386
387
388
389
390
391
392
	res = f_open(&o->file, filename, mode);
	if (res != FR_OK) {
		return -s_libffToErrno[res];
	}

	// for 'a' mode, we must begin at the end of the file
	if ((mode & FA_OPEN_APPEND) != 0) {
		f_lseek(&o->file, f_size(&o->file));
	}

393
	return efs_obj_init(fs, o, index, EPICSTAT_FILE);
394
395
396
397
398
399
}

int efs_close(EpicFileSystem *fs, int fd)
{
	int res;
	struct FatObject *o;
400
401
402
403
404
405
	if (efs_get_opened(fs, fd, EPICSTAT_NONE, &o, &res)) {
		if (o->type == EPICSTAT_FILE) {
			res = f_close(&o->file);
		} else {
			res = f_closedir(&o->dir);
		}
406
407
408
		if (res != FR_OK) {
			return -s_libffToErrno[res];
		}
409
		efs_obj_deinit(fs, o);
410
411
412
413
	}
	return res;
}

414
void efs_close_all(EpicFileSystem *fs, int coreMask)
415
{
416
	assert(coreMask != 0);
417
	for (int i = 0; i < EPIC_FAT_MAX_OPENED; ++i) {
418
419
420
		if (!(fs->pool[i].coreMask & coreMask)) {
			continue;
		}
421
422
423
424
425
		switch (fs->pool[i].type) {
		case EPICSTAT_FILE:
			f_close(&fs->pool[i].file);
			break;
		case EPICSTAT_DIR:
426
			f_closedir(&fs->pool[i].dir);
427
428
429
430
			break;
		case EPICSTAT_NONE:
			break;
		}
431
		efs_obj_deinit(fs, &fs->pool[i]);
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
	}
}

int efs_read(EpicFileSystem *fs, int fd, void *buf, size_t nbytes)
{
	unsigned int nread = 0;

	int res;
	struct FatObject *o;
	if (efs_get_opened(fs, fd, EPICSTAT_FILE, &o, &res)) {
		res = f_read(&o->file, buf, nbytes, &nread);
		if (res != FR_OK) {
			return -s_libffToErrno[res];
		}
		res = (int)nread;
	}

	return res;
}

int efs_write(EpicFileSystem *fs, int fd, const void *buf, size_t nbytes)
{
	unsigned int nwritten = 0;

	int res;
	struct FatObject *o;
	if (efs_get_opened(fs, fd, EPICSTAT_FILE, &o, &res)) {
		res = f_write(&o->file, buf, nbytes, &nwritten);
		if (res != FR_OK) {
			res = -s_libffToErrno[res];
		} else {
			res = (int)nwritten;
		}
	}
	return res;
}

int efs_flush(EpicFileSystem *fs, int fd)
{
	int res = 0;
	struct FatObject *o;
	if (efs_get_opened(fs, fd, EPICSTAT_FILE, &o, &res)) {
		res = f_sync(&o->file);
		if (res != FR_OK) {
			res = -s_libffToErrno[res];
		}
	}

	return res;
}

int efs_seek(EpicFileSystem *fs, int fd, long offset, int whence)
{
	int res = 0;
	struct FatObject *o;
	if (efs_get_opened(fs, fd, EPICSTAT_FILE, &o, &res)) {
		switch (whence) {
		case SEEK_SET:
			res = f_lseek(&o->file, offset);
			break;

		case SEEK_CUR:
			res = f_lseek(&o->file, f_tell(&o->file) + offset);
			break;

		case SEEK_END:
			res = f_lseek(&o->file, f_size(&o->file) + offset);
			break;
		default:
			return -EINVAL;
		}
		res = -s_libffToErrno[res];
	}
	return res;
}

int efs_tell(EpicFileSystem *fs, int fd)
{
	int res;
	struct FatObject *o;
	if (efs_get_opened(fs, fd, EPICSTAT_FILE, &o, &res)) {
		//f_tell simply accesses fp->fptr so no errors are expected - return directly
		res = f_tell(&o->file);
	}
	return res;
}

519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
static void efs_init_stat(struct epic_stat *stat, FILINFO *finfo)
{
	if (finfo->fname[0] != 0) {
		if (finfo->fattrib & AM_DIR) {
			stat->type = EPICSTAT_DIR;
		} else {
			stat->type = EPICSTAT_FILE;
		}
		strncpy(stat->name, finfo->fname, EPICSTAT_MAX_PATH);
	} else {
		stat->name[0] = 0;
		stat->type    = EPICSTAT_NONE;
	}
}

534
535
536
int efs_stat(EpicFileSystem *fs, const char *filename, struct epic_stat *stat)
{
	int res = 0;
537
	static FILINFO finfo;
538
539
	res = f_stat(filename, &finfo);
	if (res == 0) {
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
		efs_init_stat(stat, &finfo);
	}
	return -s_libffToErrno[res];
}

int efs_opendir(EpicFileSystem *fs, const char *path)
{
	int res;
	struct FatObject *o;
	uint32_t index;

	if (efs_get_new(fs, &index, &o, &res)) {
		res = f_opendir(&o->dir, path);
		if (res != FR_OK) {
			return -s_libffToErrno[res];
555
		}
556
		return efs_obj_init(fs, o, index, EPICSTAT_DIR);
557
	}
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
	return res;
}

int efs_readdir(EpicFileSystem *fs, int fd, struct epic_stat *stat)
{
	int res;
	struct FatObject *o;
	if (efs_get_opened(fs, fd, EPICSTAT_DIR, &o, &res)) {
		FILINFO finfo;
		res = f_readdir(&o->dir, stat ? &finfo : NULL);
		if (res == FR_OK && stat) {
			efs_init_stat(stat, &finfo);
		}
	}
	return res;
}

int efs_unlink(EpicFileSystem *fs, const char *path)
{
	int res = f_unlink(path);
578
579
580
	return -s_libffToErrno[res];
}

swym's avatar
swym committed
581
582
583
584
585
586
587
588
589
590
591
592
int efs_rename(EpicFileSystem *fs, const char *oldp, const char *newp)
{
	int res = f_rename(oldp, newp);
	return -s_libffToErrno[res];
}

int efs_mkdir(EpicFileSystem *fs, const char *dirname)
{
	int res = f_mkdir(dirname);
	return -s_libffToErrno[res];
}

593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
static const int s_libffToErrno[20] = {
	[FR_OK]                  = 0,
	[FR_DISK_ERR]            = EIO,
	[FR_INT_ERR]             = EIO,
	[FR_NOT_READY]           = EBUSY,
	[FR_NO_FILE]             = ENOENT,
	[FR_NO_PATH]             = ENOENT,
	[FR_INVALID_NAME]        = EINVAL,
	[FR_DENIED]              = EACCES,
	[FR_EXIST]               = EEXIST,
	[FR_INVALID_OBJECT]      = EINVAL,
	[FR_WRITE_PROTECTED]     = EROFS,
	[FR_INVALID_DRIVE]       = ENODEV,
	[FR_NOT_ENABLED]         = ENODEV,
	[FR_NO_FILESYSTEM]       = ENODEV,
	[FR_MKFS_ABORTED]        = EIO,
	[FR_TIMEOUT]             = EIO,
	[FR_LOCKED]              = EIO,
	[FR_NOT_ENOUGH_CORE]     = ENOMEM,
	[FR_TOO_MANY_OPEN_FILES] = EMFILE,
	[FR_INVALID_PARAMETER]   = EINVAL,
};