Error Checking the Root File System on Raspbian

Recently I upgraded the packages and the kernels on my Raspberry Pi. All seemed to go well. I rebooted the RPi and checked the dmesg logs. Things weren’t looking quite so good here. There appeared to be power related issues. I though this was a little odd considering that all was good before the upgrade.

When I took the SD card out (after powering down obviously) I found that I was in fact using an 8GB microSD card in an SD adapter. Now, I know this works but it appears that the connection had become loose somewhere along the line. I also found that the Lock switch down the side was also loose. Now I wondered whether this was also causing me issues.

I had a spare 16GB SDHC card kicking around so decided to apply the image I had just taken to that card to see how things went. The RPi powered back up. All was looking good. I decided that I should expand the rootfs to fill the extra 8GB. After running raspi-config and selecting the expand_rootfs option I followed the prompts and rebooted the device. Again, checking the dmesg log things weren’t looking so good. There were entries saying that the resize couldn’t take place due to errors being on the partition. Sure enough running sudo e2fsck -n /dev/mmcblk0p2 told me that there were 3 errors on the partition.

Hmmm… How could I now fix these? I mean that device is mounted and is the rootfs, I can’t just unmount it. I decided to try creating the file /forcefsck in the root directory. I rebooted the RPi. However this didn’t seem to help (the same errors appeared).

Back to the drawing board. This time I realised that the shutdown command in Raspbian still accepts the -F switch. In theory this should also force fsck to run on next boot. So I issued sudo shutdown -Fr now. Checked the dmesg logs when the RPi had rebooted. Still no joy.

Now I started to think that it was time for a rebuild. Not being one to give in though I gave it one last shot by doing the following.

  1. Take a copy of the image that I had previously created
  2. Run fdisk -l <path_to_image> (this will help me work out the offset I need for later)
  3. Workout the offset (<sector_size> * <partition_start>)
  4. Configure a loop device for this partition (losetup --offset /dev/loop2 <path_to_image>)
  5. Now I can run e2fsck -p /dev/loop2 (this will fix any errors that it can and write the changes straight into the image file)
  6. Need to detach from the loop device now (losetup -d /dev/loop2)
  7. Apply this fixed image back to the SD card
  8. Reboot the RPi

After these steps all seemed fine. So I’m now all back up and running and didn’t have to rebuild the RPi and apply all my tweaks again.