1 /*
2  * OS Dependent Functions for FatFs
3  *
4  * Copyright (c) 2023 Husqvarna AB
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 /* The file is based on template file by (C)ChaN, 2022, as
9  * available from FAT FS module source:
10  * https://github.com/zephyrproject-rtos/fatfs/blob/master/option/ffsystem.c
11  */
12 
13 #include <ff.h>
14 
15 #if FF_USE_LFN == 3	/* Dynamic memory allocation */
16 /* Allocate a memory block */
ff_memalloc(UINT msize)17 void *ff_memalloc(UINT msize)
18 {
19 	return k_malloc(msize);
20 }
21 
22 /* Free a memory block */
ff_memfree(void * mblock)23 void ff_memfree(void *mblock)
24 {
25 	k_free(mblock);
26 }
27 #endif /* FF_USE_LFN == 3 */
28 
29 #if FF_FS_REENTRANT	/* Mutual exclusion */
30 /* Table of Zephyr mutex. One for each volume and an extra one for the ff system.
31  * See also the template file used as reference. Link is available in the header of this file.
32  */
33 static struct k_mutex fs_reentrant_mutex[FF_VOLUMES + 1];
34 
35 /* Create a Mutex
36  * Mutex ID vol: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES)
37  * Returns 1: Succeeded or 0: Could not create the mutex
38  */
ff_mutex_create(int vol)39 int ff_mutex_create(int vol)
40 {
41 	return (int)(k_mutex_init(&fs_reentrant_mutex[vol]) == 0);
42 }
43 
44 /* Delete a Mutex
45  * Mutex ID vol: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES)
46  */
ff_mutex_delete(int vol)47 void ff_mutex_delete(int vol)
48 {
49 	/* (nothing to do) */
50 	(void)vol;
51 }
52 
53 /* Request Grant to Access the Volume
54  * Mutex ID vol: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES)
55  * Returns 1: Succeeded or 0: Timeout
56  */
ff_mutex_take(int vol)57 int ff_mutex_take(int vol)
58 {
59 	return (int)(k_mutex_lock(&fs_reentrant_mutex[vol], FF_FS_TIMEOUT) == 0);
60 }
61 
62 /* Release Grant to Access the Volume
63  * Mutex ID vol: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES)
64  */
ff_mutex_give(int vol)65 void ff_mutex_give(int vol)
66 {
67 	k_mutex_unlock(&fs_reentrant_mutex[vol]);
68 }
69 #endif /* FF_FS_REENTRANT */
70