cryptsetup close CRYPT Fails With “Device CRYPT is still in use.”

Problem: after unmounting a LuKS crypted device, “cryptsetup close” fails with “Deivce is still in use”, even though it is not mounted anymore.

Discussion: you can check with lsblk that it’s not mounted anymore:

# lsblk
...
sdc            8:32   1  1.8T  0 disk  
├─sdc1         8:33   1  502M  0 part  
└─sdc2         8:34   1  1.8T  0 part  
  └─CRYPT    253:1    0  1.8T  0 crypt 

But with “dmsetup info” you can see that is still in use:

# dmsetup info
Name:              CRYPT
State:             ACTIVE 
Read Ahead:        256
Tables present:    LIVE
Open count:        1
Event number:      0
Major, minor:      253, 1
Number of targets: 1

“cryptsetup –debug close” CRYPT also shows device still in use.

The reason was KVM/QEMU running on this system. KVM/QEMU uses mount namespaces. These namespaces may still have mounted the crypted filesystem and block cryptsetup from closing the volume.

Solution: you have to find the namespace that is still holding the mount, and umount from inside the namespace.

You can find namespaces with “ls /proc/*/ns/mnt”

...
lrwxrwxrwx 1 root         root         0 Jan  2 03:00 122/ns/mnt -> mnt:[4026531840]
lrwxrwxrwx 1 root         root         0 Jan  2 03:00 123/ns/mnt -> mnt:[4026531840]
lrwxrwxrwx 1 libvirt-qemu libvirt-qemu 0 Jan  2 03:00 1248/ns/mnt -> mnt:[4026533545]
lrwxrwxrwx 1 root         root         0 Jan  2 03:00 125/ns/mnt -> mnt:[4026531840]
lrwxrwxrwx 1 root         root         0 Jan  2 03:00 1254/ns/mnt -> mnt:[4026531840]
...

most lines will have the same namespace id. Search for those with a different ID. Then check the mounted filesystem of those processes with

nsenter -t <PID> -m mount | grep CRYPT

You will find the umounted filesystem still mounted in some namespaces. Umount them with:

nsenter -t <PID> -m umount /dev/<CRYPTMOUNTPOINT>

After umounting the CRYPT device in all namespace, “cryptsetup close” will work.