#define ACT_SDCARD_ATTACH 1
#define ACT_SDCARD_DETACH_STATUS 2
#define ACT_SDCARD_ATTACH_STATUS 3
-#define ACT_SDCARD_DETACH_FAIL 4
-#define ACT_SDCARD_ATTACH_FAIL 5
-#define ACT_SDCARD_NO_ATTACH_FOUND 6
+#define ACT_SDCARD_DETACH_FAIL 4 /* No sdcard attached */
+#define ACT_SDCARD_ATTACH_FAIL 5 /* Already sdcard attached */
+#define ACT_SDCARD_NO_ATTACH_FOUND 6 /* Other sdcard attached */
#define MAXBUFLEN 1024
void handle_sdcard(char* dataBuf, size_t dataLen);
#include "osutil.h"
#include "emulator.h"
#include "emul_state.h"
-
#include "new_debug_ch.h"
DECLARE_DEBUG_CHANNEL(osutil)
.l_len = 0,
};
-static sdcard_info info;
+static sdcard_info info = {
+ .fd = -1,
+ .lock_file = NULL,
+};
static int fd_lock(int fd)
{
g_assert(lock_file != -1);
if (fd_unlock(lock_file)) {
- LOG_WARNING("Failed to remove lock from lock file");
+ LOG_INFO("Failed to remove lock from lock file");
}
close(lock_file);
bool make_sdcard_lock_posix(char *sdcard)
{
- char *lock_file = g_strdup_printf("%s-%d.lck", sdcard, getpid());
- int fd = open(lock_file, O_CREAT|O_RDWR, 0666);
- if (fd == -1)
- {
- perror("file open error : ");
+ int fd;
+
+ if (info.fd != -1) {
+ g_assert(info.lock_file != NULL);
+ LOG_INFO("sdcard(%s) is already attached\n", info.lock_file);
return false;
}
- if (fd_lock(fd) == -1)
- {
- perror("file is lock ");
- close(fd);
+
+ fd = qemu_open(sdcard, O_WRONLY);
+ if (fd == -1) {
+ LOG_WARNING("Failed to open sdcard file: %s\n", strerror(errno));
return false;
}
+
+ if (fd_lock(fd) == -1) {
+ LOG_WARNING("Failed to lock sdcard file: %s\n", strerror(errno));
+ qemu_close(fd);
+ return false;
+ }
+
info.fd = fd;
- LOG_INFO("Get file lock: %s\n", lock_file);
+ info.lock_file = g_strdup(sdcard);
+ LOG_INFO("Locked sdcard\n");
return true;
}
int remove_sdcard_lock_posix(char *sdcard)
{
- errno = 0;
- char *lock_file = g_strdup_printf("%s-%d.lck", sdcard, getpid());
- int fd = open(lock_file, O_RDWR, 0666);
- if (fd == -1)
- {
- perror("file open error : ");
- if(errno == ENOENT) {
- return ERR_NOENT;
- }
- return ERR_UNLCK;
+ /* check whether the sdcard is attached or not */
+ if (info.fd == -1) {
+ LOG_INFO("No attached sdcard\n");
+ return ERR_NODEV;
}
- if (fd_unlock(fd) == -1)
- {
- perror("file unlock error ");
- close(fd);
- return ERR_UNLCK;
+ if (strcmp(sdcard, info.lock_file) != 0) {
+ LOG_INFO("%s is already attached\n", info.lock_file);
+ return ERR_NOENT;
}
- if (unlink(lock_file) < 0) {
- perror("unlink error ");
- close(fd);
- return ERR_UNLCK;
+ /*
+ * Even though we failed to unlock the file, fall through and close fd.
+ * Closing fd makes the any lock on the file released.
+ */
+ if (fd_unlock(info.fd) == -1) {
+ LOG_INFO("Failed to unlock sdcard file, %d: %s\n",
+ info.fd, strerror(errno));
}
- LOG_INFO("unlock success: %s\n", lock_file);
- close(fd);
- close(info.fd);
+ LOG_INFO("Unlocked sdcard\n");
+ qemu_close(info.fd);
+ info.fd = -1;
+ g_free(info.lock_file);
+ info.lock_file = NULL;
return ERR_SUCCESS;
}
#endif