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 <zephyr/kernel.h>
14 
15 #include <ff.h>
16 
17 #if FF_USE_LFN == 3	/* Dynamic memory allocation */
18 /* Allocate a memory block */
ff_memalloc(UINT msize)19 void *ff_memalloc(UINT msize)
20 {
21 	return k_malloc(msize);
22 }
23 
24 /* Free a memory block */
ff_memfree(void * mblock)25 void ff_memfree(void *mblock)
26 {
27 	k_free(mblock);
28 }
29 #endif /* FF_USE_LFN == 3 */
30 
31 #if FF_FS_REENTRANT	/* Mutual exclusion */
32 /* Table of Zephyr mutex. One for each volume and an extra one for the ff system.
33  * See also the template file used as reference. Link is available in the header of this file.
34  */
35 static struct k_mutex fs_reentrant_mutex[FF_VOLUMES + 1];
36 
37 /* Create a Mutex
38  * Mutex ID vol: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES)
39  * Returns 1: Succeeded or 0: Could not create the mutex
40  */
ff_mutex_create(int vol)41 int ff_mutex_create(int vol)
42 {
43 	return (int)(k_mutex_init(&fs_reentrant_mutex[vol]) == 0);
44 }
45 
46 /* Delete a Mutex
47  * Mutex ID vol: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES)
48  */
ff_mutex_delete(int vol)49 void ff_mutex_delete(int vol)
50 {
51 	/* (nothing to do) */
52 	(void)vol;
53 }
54 
55 /* Request Grant to Access the Volume
56  * Mutex ID vol: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES)
57  * Returns 1: Succeeded or 0: Timeout
58  */
ff_mutex_take(int vol)59 int ff_mutex_take(int vol)
60 {
61 	return (int)(k_mutex_lock(&fs_reentrant_mutex[vol], FF_FS_TIMEOUT) == 0);
62 }
63 
64 /* Release Grant to Access the Volume
65  * Mutex ID vol: Volume mutex (0 to FF_VOLUMES - 1) or system mutex (FF_VOLUMES)
66  */
ff_mutex_give(int vol)67 void ff_mutex_give(int vol)
68 {
69 	k_mutex_unlock(&fs_reentrant_mutex[vol]);
70 }
71 #endif /* FF_FS_REENTRANT */
72