Wednesday, November 17, 2021

[SOLVED] Correct auto unmount of pen drive

Issue

I searched for similar posts but couldn't find any. I'm looking for some advice or a point in the right direction as I can't find much information on this subject.

I'm trying to write a daemon on a raspberry pi 4 running custom linux build from buildroot. The daemon, using udev (libudev.h) and epoll (sys/epoll.h), detects a newly plugged pen drive, creates a directory and mounts the device. It also detects the removal of said device, unmounts and then removes the directory.

It works well until the removal of the pen drive, which, despite the unmount being executed (without any error return), I always get this message when I re plug the pen drive "FAT-fs (sda1) Volume was not properly unmounted. Some data may be corrupt. Please run fsck". What am I doing wrong? How can I properly unmount it?

 //pen removed
 if(!action.compare("remove") && !partition.compare("partition")){
    //if directory exists
    dir = opendir(path.c_str());
    if(dir){
       //close directory to be able to unmount
       close(dir);
       //unmount
       status = umount(path.c_str());
       if(status != 0)
           syslog(LOG_ERR, "%m\n");
       //remove the directory
       status = rmdir(path.c_str());
       if(status != 0)
           syslog(LOG_ERR, "%m\n");
       }
}
//pen inserted
else if(!action.compare("add") && !partition.compare("partition")){
    //if directory doesn't exist
    dir = opendir(path.c_str());
    if(!dir){
        //create the directory 
        status = mkdir(path.c_str(), 777); 
        if(status != 0)
           syslog(LOG_ERR, "%m\n");
        }
        //mount 
        status = mount(devicenode.c_str(), path.c_str(), "vfat", MS_NOATIME, NULL);
        if(status != 0)
           syslog(LOG_ERR, "%m\n");
        }
}

Solution

The drive has to be unmounted before removing the pen drive. This is obviously not possible to do automatically.

One option is to mount with the -o sync mount option; this will make sure that files are flushed immediately, which reduces the chance of filesystem corruption. However, AFAIK, it doesn't remove the warning message.

The warning message is due to a dirty bit that is set on the pen drive when it is mounted, and that is cleared when it is unmounted. When it is mounted and the dirty bit is already set, the warning is printed.

Windows solves this problem by clearing the dirty bit when it has finished a write to the pen drive, and setting it again when it starts a new write. As far as I know, Linux doesn't have similar functionality. You could try to implement it in the kernel.



Answered By - Arnout