date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,379,695,526,000 |
I can't understand why my script, sometimes, won't recognize if my Firefox is running. Analyzing the stdout I could state that this condition (if ps cax | grep firefox > /dev/null) sometimes is skipped even when my Firefox is running.
Currently using Xubuntu 18.10 Livecd
The script called at startup.
#!/bin/bash
[[ -f /home/xubuntu/controle_memoria.lock ]] && exit 1
> /home/xubuntu/controle_memoria.lock
while true ; do
free=`free -m | grep Mem | awk '{print $4}'`
if [ "$free" -gt 0 ]
then
if [ $free -le 120 ]; #When my memory consuptiom goes below 120MB do the commands below.
then
if ps cax | grep firefox > /dev/null
then
sudo killall -9 firefox-bin
firefox &> /dev/null &
else
echo "Stopped"
fi
sudo sysctl -w vm.drop_caches=3
sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
fi
fi & sleep 1; done
|
Ps has -C option without need to grep
killall -0 firefox-bin will tell you if firefox-bin process exist by exit code. Without need of pipe and redirection in a raw.
Just remove your if ps and leave killall -9 firefox-bin && firefox-bin &> /dev/null &. So if process will not be killed, it wouldn't be started.
| Condition sometimes failing to test if a specific process is running or not |
1,379,695,526,000 |
My desktop with i686 CPU is currently running macOS Mavericks and I'm trying to install Fedora 26 i386 via DVD. Unfortunately, when it boots the DVD and I select "Start Fedora-Workstation-Live 26" it returns me this error a couple of seconds later:
dracut-pre-udev[358]: rpcbind: /run/rpcbind/rpcbind.lock: No such file or directory
dracut-pre-udev[358]: rpc.idmapd: conf_reinit: open ("(null)", 0_RDONLY) failed
dracut-pre-udev[358]: rpc.idmapd: conf_reinit: open ("(null)", 0_RDONLY) failed
Then it starts returning line after line of blk_update_request and Buffer I/O error on dev sr8.
After a few minutes, it does actually produce an error report: /run/initramfs/rdsosreport.txt but I haven't succeeded in moving the file to a USB drive. When I run $ ls dev, here's what I get:
When I plug my USB drive in, the shell returns:
sd 11:0:0:0: [sdg] No Caching mode page found
sd 11:0:0:0: [sdg] Assuming drive cache: write through
I thought this meant my USB drive was at /dev/sdg/, but after entering $ cd /dev/sdg/ it returned that it didn't exist.
I can't use the USB drive to install Fedora since computer can't boot from it. It detects the USB drive at the boot screen but it completely ignores it after that. In fact, when booting from the HDD, it treats it as a standard removable drive with nothing to boot from.
Most peculiarly, I have an old CD with Ubuntu 12.04 i686 and I booted from that, it worked perfectly fine!
Edit: I'm installing Fedora with Fedora-Workstation-Live-i386-26-1.5.iso from a DVD-RW.
Edit #2: I previously thought that there was an issue with the optical drive in my laptop, where I was burning the ISO images to the DVD. So I used ImgBurn to find the error, and sure enough there was a power calibration area error but after a few re-tries, it successfully verified the DVD. When I booted the desktop with the DVD again, the error stil occured. I tried using a different distribution: Arch Linux, using arch-anywhere-2.2.8-i686.iso and the shell returned similar results (blk_update_request and Buffer I/O error) but without the aforementioned error.
Edit #3: So far I've had three attempts of installing Fedora via Netinstall;
I burned the ISO onto a DVD-RW and the system wasn't able to boot from it, it couldn't detect a bootable device.
I used a brand new DVD-RW using a different optical drive. The system returned the same rpcbind.lock error like before, however it eventually got itself to the installation setup. There was an issue with the disk partitioning: the HDD has a size of around 450 GiB which already has Arch Linux installed as /, alongside /boot, swap, and the BIOS boot. The setup could only use the 1 GiB available space using the automatic installation, it wasn't able to delete any partition. Custom installation didn't really work either, swap had a bug where it was confined to a maximum of 1024 MiB where the setup rejected that parameter and required that it should be around 5 GiB. It crashed at the Advanced Custom installation, completely shutting down the installation setup.
At my third attempt, using the same DVD, the shell returned that X2-compressed data was corrupt. A few seconds later, kernel panic:
Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0)
Edit #4: Now I can't login through GDM, the screen at the default GDM background. I've made a separate question on this.
|
I have not yet reached a direct answer to this issue, but I believe it's due to the fact the system is using a non-EFI motherboard.
I was eventually able to install Fedora using a Netinstall version, however I had several attempts where the system either did not boot from disc or the disc was corrupt. However, during installation, the boot was not able to fully install, I did my research and found that I had to reinstall GRUB2. The problem was that the motherboard (an ASUS P5QL PRO) did not support UEFI and therefore did not have a boot mode. Unless there is a way to install Fedora without UEFI but that's something else entirely.
Here's a quick summary:
I was able to boot from most of the discs I used burned incorrectly. There was no error when burning, however my optical drive wasn't in the best condition and using a different drive solved half of the problem.
The motherboard did not support UEFI and therefore could not install bootloader properly. I tried to reinstall GRUB2, but that ultimately failed.
| Fedora 26 i386 installation fails: "rpcbind.lock: No such file or directory" |
1,379,695,526,000 |
I have a problem with my Linux Mint installation. So I'm thinking of backing up my files from a Linux Mint 17 live disk (which I'm using right now to post this). I'd like to back up my encfs container, but don't know how to do so without mounting it and copy the contents to an external drive. Is this possible, and how to do it?
I use the following command to mount the container:
encfs ~/.zzz_encfs ~/zzz
But how to tell the live disk terminal where to look for it? I cd'ed to my home directory and ran the command but it returns the error Unable to locate root directory, aborting..
|
The directory ~/.zzz_encfs is located in your home directory. In the shell, ~ at the beginning of a path represents your home directory.
If your live system mounts filesystems of your disk automatically, check the GUI or run cat /proc/mounts to see where they may be mounted. Usually the mount points are sudirectories of /media or subdirectories of subdirectories of /media.
By default, your home directory is at the location /home/user8547 on the installed system, where user8547 is your username. If you have a separate partition for /home, your home directory is /user8547 on that partition.
Once you've located your home directory, create an empty directory anywhere you like, or use the existing zzz directory in your home directory if you like. Then run
encfs /path/to/home/directory/.zzz_encfs /path/to/empty/directory
e.g. it may be something like
encfs /media/sda1/home/user8547/.zzz_encfs /media/sda1/home/user8547/zzz
.
| Can ENCFS container be mounted from live disk? |
1,379,695,526,000 |
Whilst attempting to install Gentoo on my desktop, I ran into some trouble getting my wireless card to work. This is the card I am using. The modules included with the Live CD didn't detect my card, so I downloaded the drivers from the Rosewill website, and followed the build instructions.. up until it told me to use make.
The Gentoo Live CD doesn't come with make.
So, I am confused as to how I should continue from here.
EDIT: I ended up remembering I have a really long cat5 cable, and used that for the initial installation, and then compiled the drivers after chrooting into stage3
|
I don't think it's typical that Live CD's include developer tools such as make and autoconf. Now I realize Gentoo is meant to be built from source but given your situation I think you're options are one of the following:
Compile the drivers on another Gentoo system that does have make and then manually copy the kernel .ko file(s) to the affected system.
Get the binary packages of make, gcc, etc. from portage on another Gentoo system and install them as packages into the Live CD system.
Try SabayonLinux instead of Gentoo.
Pick a different LiveCD distro that does work with your hardware and follow the Gentoo handbook using that distro instead of the Gentoo LiveCD.
Looking through the howto: Installing Gentoo Using Packages on the liveDVD there are several mentions of a "sneakernet" installation method:
excerpt
Second choice is a stage3 install supported by Sneakernet. This
differes only in that things are fetched from the internet using a
remote system or another operating system (or both) and loaded into
the growing install manually. Portage still builds everything. The use
of sneakernet is described elsewhere.
Given that I would think you're left to manually get the various bits you need using a secondary system, and manually load them into this system.
The details for setting up your network manually are here, in section 3 of the Gentoo handbook: Configuring your Network.
| Why is make unavailable on the default Gentoo liveCD? |
1,379,695,526,000 |
After several failed attempts to burn an Ubuntu CD to live boot from (they wouldn't boot, maybe because my CD burning software wouldn't burn slower than 4X speed?), I've managed to get a boot disc working with Puppy linux ("Slacko").
My next task is to figure out how to print. I have an HP PSC2410 printer.
The documentation on puppylinux.org provides some links, and I tried following the instructions here. Unfortunately, it appears python isn't installed in Puppy by default, as I got the error:
./hplip-install: line 2: python: command not found
when I ran the install with sh hplip-3.13.4.run
There's quite a list of system requirements for installing the print drivers, so I wonder if I'm barking up the wrong tree by trying to use Puppy.
Might I be better having another try at getting Ubuntu working, or is there an easier distribution to use that will enable me to print when booting from a live CD? The only functionality I need is print capability, a browser, and being able to read a flash drive, all offline from the web.
|
That error means that python isn't installed. Given you're a novice I'd be inclined to steer you towards either Ubuntu or Linux Mint.
| An easier way to print from a live CD than Puppy? |
1,379,695,526,000 |
I made a live.iso by livemedia-creator. I use it to make livecd. However, when I boot it, the disk(/dev/sda) is always controlled by /dev/mapper. I want to make my iso boot without /dev/mapper enabled. Is there any advice please? Thanks in advance.
|
We can disable device mapper by dracut.
| https://man7.org/linux/man-pages/man7/dracut.cmdline.7.html
| How to disable device mapper for live.iso? |
1,379,695,526,000 |
I'm running on a fairly old HP Pavilion x360 - 13-a110dx (ENERGY STAR) with the newest BIOS firmware available. It has Intel HD 5500 graphics and 4 GB RAM. I'm currently trying to install ANY linux distribution to it from USB -- I can boot into the live USB just fine, however, whether I try to "Try it Without Installing" or "Install" it just goes to a black screen. Both UEFI and CSM mode do this. In CSM mode I can get to the purple screen where I select nomodeset etc, then it goes to splash screen for a hot minute and then to a black screen with a white pointer that freezes. I do not want to keep anything on my Hard Drive currently.
Ubuntu
Manjaro
Arch
All of these do the same thing: black screen.
I have tried in boot options:
nomodeset
text mode
various combinations of acpi="something"
attempting to get to TTY via keyboard shortcuts
I have seen the megapost about this issue with all the workarounds and none of them have worked.
|
So this is how I fixed it --
Upon booting the Ubuntu Live CD I had to changed the Linux boot parameter to have acpi=off nomodeset debug=. I believe this was overkill as to boot Ubuntu I had to just use acpi=off.
Now -- this would disable all of my acpi so I had no battery stats and my computer thought it was in airplane mode -- no good. Eventually I followed a step by step guide to determine why acpi was the issue, turns out it wasn't.
All I ended up having to do was add to my boot parameters acpi_osi= because this HP BIOS is a little funky -- this solved all of my issues.
| Linux Live CD crash after GRUB selection |
1,379,695,526,000 |
Wanted to create a list of all the benefits of always running from a live CD (with or without persistence/as long as personal data is saved on encrypted drive locally)?
|
Using a live ISO without persistence means the main filesystem is read-only, so nothing can be changed or "broken" permanently. It also means all changes (new files & data) are in ram and lost on reboot/shutdown.
Saving your personal data manually could lead to better backup habits...
If you have enough ram to use the toram option, all file reads & writes will be at ram speeds, maybe 2GB-5GB per second, much faster than a regular cd/dvd/hard drive or ssd.
The "best encryption" part of the question really is too broad, but just use the defaults the big distros use: GPG, LUKS, eCryptfs
| what are the benefits of always running from live cd for data protection? [closed] |
1,379,695,526,000 |
I am trying to understand about the file system of bootable system on CD. For CDs which can only be written once, how exactly does system boot?
Aren't there any configuration parameters which need to be changed/added upon every boot? Or are there not folders like tmp which contains the temporary data (although it vanishes away after every boot).
In simpler terms, how does CD-Read-only is able to boot ?
Am I missing something here ?
|
This is achieved using union mounts. The two main methods are OverlayFS and aufs. It works like any other file system in the Linux VFS but as part of its configuration will point to two other file systems. As part of the union fs mount configuration will determine where data written to it will go. This is usually to an in memory file system.
There are varied implementations for semi-persistence live cds. But generically these systems will write what ever is in the temporary part of the union fs onto persistence storage such as a usb drive.
| How are Configuration Parameters 'written' on "Read Only" bootable Linux CD/USB, when plugged into any system? |
1,379,695,526,000 |
I'm using Debian 9 Stretch Live from a USB Stick for testing hardware compatibility.
The firmeware for the Intel Wireless 2230 was not included in the Live image. Therefore I installed it offline from Binary firmware for Intel Wireless cards with
sudo dpkg -i firmware-iwlwifi_20161130-3_all.deb
After that I reinsert the Wifi module with
sudo modprobe -r iwlwifi ; sudo modprobe iwlwifi
The wifi adapter showed up in gnomes network manager and I could access my wlan. IP and subnet was correct via DHCP.
But I cannot ping hostnames like
ping google.com
I get 'hostname not found'. Ping via IP works fine and I receive packages
ping 8.8.8.8
I changed '/etc/resolve.conf' to use 8.8.8.8 and 8.8.4.4 as nameservers and restarted networking with
/etc/init.d/networking restart
I also tried
sudo resolvconf -u
without success.
At normal conditions a restart solved my issue. But with a Live Image a restart is a bit... repeating ; -)
Has someone an idea where I get wrong?
|
Normally to get iwlwifi to work you HAVE to reboot.
BUT which ISO did you use? The official one which has "main" only? Where did you get it from? Can you provide a link.
You could try the unofficial live+non-free, which includes the firmware, from here: https://cdimage.debian.org/cdimage/unofficial/non-free/cd-including-firmware/9.0.0-live+nonfree/
| Debian 9 Stretch firmware-iwlwifi unknown host |
1,291,477,658,000 |
I am mounting an ISO file, and looking at this tutorial. They use the command:
$ mount -o loop disk1.iso /mnt/disk
I'm trying to understand the use of -o loop. I have two questions:
When I look at the long man page for mount, it takes time to find that -o option. If I do man mount | grep "-o" I get an error, and when I look in the file I do not find any info that "loop" is a command text for option -o. Where is that documented?
Also, what is the "loop device" concept for mounting?
|
A loop device is a pseudo ("fake") device (actually just a file) that acts as a block-based device. You want to mount a file disk1.iso that will act as an entire filesystem, so you use loop.
The -o is short for --options.
And the last thing, if you want to search for "-o" you need to escape the '-'.
Try:
man mount | grep "\-o"
| What is a "loop device" when mounting? |
1,291,477,658,000 |
I've read that with qemu-nbd and the network block device kernel module, I can mount a qcow2 image. I haven't seen any tutorials on mounting a qcow2 via a loop device. Is it possible? If not, why?
I don't really understand the difference between a qcow2 and an iso.
|
A loop device just turns a file into a block device. If the file has some special internal mapping of its blocks, the loop device won't translate any of it. qcow2 is special... it has special mapping inside that handles different snapshots of the same blocks stored in different places. If you mount that as a loop device, you'll just get one big block device that doesn't represent the actual data in the image.
Another option is to convert to raw and mount as a loop device:
qemu-img convert -p -O raw oldfile.qcow2 newfile.raw
But then you have to convert it back to qcow2 to use it again as before.
I think using qemu-nbd is not the most efficient IO, but is easy. Mounting it in a VM, like one booted with a live usb, is easy too. Converting doesn't make much sense... it was just an example of how they're different.
| How to mount qcow2 image |
1,291,477,658,000 |
I have a iso file named ubuntu.iso.
I can mount it with the command: mount ubuntu.iso /mnt. After mounting it, I can see it from the outout of the command df -h: /dev/loop0 825M 825M 0 100% /mnt.
However, if I execute the command mount -o loop ubuntu.iso /mnt, I'll get the same result.
As I know, loop device allows us to visit the iso file as a device, I think this is why we add the option -o loop. But I can visit my iso file even if I only execute mount ubuntu.iso /mnt.
So I can't see the difference between mount and mount -o loop.
|
Both versions use loop devices, and produce the same result; the short version relies on “cleverness” added to mount in recent years. mount -o loop tells mount explicitly to use a loop device; it leaves the loop device itself up to mount, which will look for an available device, set it up, and use that. (You can specify the device too with e.g. mount -o loop=/dev/loop1.)
The cleverness is that, when given a file to mount, mount will automatically use a loop device to mount it when necessary — i.e., the file system isn’t specified, or libblkid determines that the file system is only supported on block devices (and therefore a loop device is needed to translate the file into a block device).
The loop device section of the mount man page has more details.
| What is the difference between mount and mount -o loop |
1,291,477,658,000 |
I know I can create and use a loopback device like this:
# Create the file
truncate disk.img --size 2G
# Create a filesystem
mkfs.ext4 disk.img
# Mount to use
mount disk.img /mnt
# Clean up
umount /mnt
However in this case the disk image is fixed at 2GB. It's 2GB when it's empty, and it's 2GB when it's full. It will not grow.
Is there a kind of loopback device that can grow in size? Or, is there a kind of loopback device that only needs as much space that it stores?
|
@jordanm's comment nailed it. I assumed that the file size was fixed when I looked at the output of ls -lh disk.img. When I used ls -s disk.img like in @Stephan's answer the real file size is showed. As a test, I created an image file that is larger than my hard drive:
truncate test.img -s 1000G
And it works just fine, which means the answer is in the question :)
| How to setup a growable loopback device? |
1,291,477,658,000 |
I previously used to create image files using dd, set up a filesystem on them using mkfsand mount them to access them as mounted partitions. Later on, I have seen on the internet that many examples use losetup beforehand to make a loop device entry under /dev, and then mount it. I could not tell why one would practically need an image file to behave as a loop device and have its own /dev entry while the same behaviour can be obtained without all the hassle.
Summary: In a real-life scenario, why do we need a /dev/loopXentry to be present at all, when we can just mount the fs image without it? What's the use of a loop device?
|
Mounts, typically, must be done on block devices. The loop driver puts a block device front-end onto your data file.
If you do a loop mount without losetup then the OS does one in the background.
eg
$ dd if=/dev/zero of=/tmp/foo bs=1M count=100
100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 0.0798775 s, 1.3 GB/s
$ mke2fs /tmp/foo
mke2fs 1.42.9 (28-Dec-2013)
....
$ losetup
$ mount -o loop /tmp/foo /mnt1
$ losetup
NAME SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE
/dev/loop0 0 0 1 0 /tmp/foo
$ umount /mnt1
$ losetup
$
You may need to call losetup directly if your file image has embedded partitions in it.
eg if I have this image:
$ fdisk -l /tmp/foo2
Disk /tmp/foo2: 104 MB, 104857600 bytes, 204800 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x1f25ff39
Device Boot Start End Blocks Id System
/tmp/foo2p1 2048 204799 101376 83 Linux
I can't mount that directly
$ mount -o loop /tmp/foo2 /mnt1
mount: /dev/loop0 is write-protected, mounting read-only
mount: wrong fs type, bad option, bad superblock on /dev/loop0,
missing codepage or helper program, or other error
But if I use losetup and kpartx then I can access the partitions:
$ losetup -f /tmp/foo2
$ losetup
NAME SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE
/dev/loop0 0 0 0 0 /tmp/foo2
$ kpartx -a /dev/loop0
$ mount /dev/mapper/loop0p1 /mnt1
$
| Why does one need a loop device at all? |
1,291,477,658,000 |
According to the following question:
What is a "loop device" when mounting?
A loop device is a file that acts as a block-based device. While I can understand that conceptually, how is this different from mounting any other file? For example, if I take a dd image of an ext2 filesystem and then mount it, I don't have to use the loop option- mount -t ext2 file.dd /mnt/mount-point succeeds.
When should I use the loop option and what difference is there between mounting using the loop option and mounting without it?
|
If you don't have to use the loop option to mount a regular file, it is because mount is detecting this and activating it for you automatically. You used to have to specify it manually.
| When mounting, when should I use a loop device? |
1,291,477,658,000 |
Is there a way to take a disk img file that is broken up into parts and mount it as a single loop device?
|
I don't think you can do it in place but if you have enough space this should work:
# Create the files that will hold your data
dd if=/dev/zero of=part-00 bs=1M count=4k
dd if=/dev/zero of=part-01 bs=1M count=4k
# Create the loop devices
losetup /dev/loop0 part-00
losetup /dev/loop1 part-01
# Create a RAID array
mdadm --create /dev/md0 --level=linear --raid-devices=2 /dev/loop0 /dev/loop1
# Copy the original filesystem
dd if=original-file-00 of=/dev/md0 bs=512
# Look at the records written value
dd if=original-file-01 of=/dev/md0 bs=512 seek=<sum of records written values so far>
# Mount the new filesystem
mount /dev/md0 /mnt
You can't simply create a RAID array from the original files because the RAID disks have a specific header where the number of disks, RAID level, etc is stored. If you do it that part of your original files will be overwritten.
You can use the mdadm --build to create an array without metadata but then you really should make a backup first. Or if read-only mount is enough:
losetup -r /dev/loop0 original-00
losetup -r /dev/loop1 original-11
mdadm --build /dev/md0 --level=linear --raid-devices=2 /dev/loop0 /dev/loop1
mount /dev/md0 /mnt
Why do you want to do this? If your filesystem can't handle >4GB files you should just switch to a sane one.
| Mounting multiple img files as single loop device |
1,291,477,658,000 |
I need to create filesystem with just one partition from nothing (/dev/zero).
I tried this sequence of commands:
dd if=/dev/zero of=mountedImage.img bs=512 count=131072
fdisk mountedImage.img
n
p
2048
131072
Basically, I need to create 64MB image file filled with zeroes. Then I use fdisk to add a new partition for new filesystem (which should finally be FAT32), starting at sector 2048 and using all remaining sectors.
losetup /dev/loop1 mountedImage.img
mkfs -t vfat /dev/loop1
But here I'm hitting problems. If I set up a loop device and format it using mkfs -t vfat, partition table is overwritten and filesystem (FAT32) is placed to disk. I don't need whole disk formatted with FAT32, I just need my primary partition to be so.
Does anybody know how can I format only one partition of raw disk image, not whole image?
|
If on Linux, when loading the loop module, make sure you pass a max_part option to the module so that the loop devices are partitionable.
Check the current value:
cat /sys/module/loop/parameters/max_part
If it's 0:
modprobe -r loop # unload the module
modprobe loop max_part=31
To make this setting persistent, add the following line to /etc/modprobe.conf or to a file in /etc/modprobe.d if that directory exists on your system:
options loop max_part=31
If modprobe -r loop fails because “Module loop is builtin”, you'll need to add loop.max_part=31 to your kernel command line and reboot. If your bootloader is Grub2, add to it to the value of GRUB_CMDLINE_LINUX in /etc/default/grub and update GRUB using update-grub.
Now, you can create a partitionable loop device:
truncate -s 64M file # no need to fill it with zeros, just make it sparse
fdisk file # create partitions
losetup /dev/loop0 file
mkfs.vfat /dev/loop0p1 # for the first partition.
mount /dev/loop0p1 /mnt/
Unmount after using and detach loop device
umount /mnt
losetup -d /dev/loop0
(note that you need a relatively recent version of Linux).
| How to create a formatted partition image file from scratch? |
1,291,477,658,000 |
I am trying to mount root and boot partition of Raspbian image:
mount -v -o offset="70254592" -t ext4 /mnt/X/raspbian-jessie.img /tmp/raspbian
mount -v -o offset="4194304" -t vfat /mnt/X/raspbian-jessie.img /tmp/boot
mounting boot, when root is mounted results in:
mount: /mnt/X/raspbian-jessie.img: overlapping loop device exists
How to mount multiple partitions on one disk image at same time? (for disks it's obviously possible, why not for files?)
|
losetup 2.21 -P option
losetup -P -f --show my.img
Creates one /dev/loopXpY per partition.
Advantage: executable pre-installed in many distros (util-linux package).
Disadvantage: quite recent option, not present in Ubuntu 14.04, before that just use kpartx: https://unix.stackexchange.com/a/405639/32558
losetup -P automation
Usage:
$ los my.img
/dev/loop0
/mnt/loop0p1
/mnt/loop0p2
$ ls /mnt/loop0p1
/whatever
/files
/youhave
/there
$ sudo losetup -l
NAME SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE DIO
/dev/loop1 0 0 0 0 /full/path/to/my.img
$ # Cleanup.
$ losd 0
$ ls /mnt/loop0p1
$ ls /dev | grep loop0
loop0
Source:
los() (
img="$1"
dev="$(sudo losetup --show -f -P "$img")"
echo "$dev"
for part in "$dev"?*; do
if [ "$part" = "${dev}p*" ]; then
part="${dev}"
fi
dst="/mnt/$(basename "$part")"
echo "$dst"
sudo mkdir -p "$dst"
sudo mount "$part" "$dst"
done
)
losd() (
dev="/dev/loop$1"
for part in "$dev"?*; do
if [ "$part" = "${dev}p*" ]; then
part="${dev}"
fi
dst="/mnt/$(basename "$part")"
sudo umount "$dst"
done
sudo losetup -d "$dev"
)
| How to mount multiple partitions from disk image simultaneously? |
1,291,477,658,000 |
GNU/Linux has union mount that overlays dirs. So you can mount a writeable dir on top of a read-only dir. When the writeable dir is unmounted the read-only dir is untouched.
I am looking for the same functionality for block devices - preferably with the writeable part stored in a file. So I would like to run something like:
device-setup /dev/newdevice /dev/read-only-device overlayfile
If I write to /dev/newdevice the changes should be stored in overlayfile. If I read the sectors written to, I should get the data from overlayfile. If I read sectors not written to, I should get the data from /dev/read-only-device.
Does such a tool exist?
|
You can do that with the device mapper and its snapshot target.
Basically, you'd do the same as what LVM does when you create a writable snapshot.
dev=/dev/read-only-device
ovl=/path/to/overlay.file
newdevname=newdevice
size=$(blockdev --getsz "$dev")
loop=$(losetup -f --show -- "$ovl")
printf '%s\n' "0 $size snapshot $dev $loop P 8" |
dmsetup create "$newdevname"
Then you can access the overlayed device as /dev/mapper/newdevice.
If you also need access to the original device at the same time, you can do:
printf '%s\n' "0 $size snapshot-origin $dev" |
dmsetup create originaldevice
And access it over /dev/mapper/originaldevice.
You can write to that device, then in addition to the chunks written to the snapshot device, the overlay file will contain a copy of the chunks that have been overwritten when writing to the snapshot-origin.
The overlay file can be a sparse file. (for instance, create it as truncate -s10G the-file), and doesn't have to be as large as the original device. You can tell how full it is with dmsetup status "$newdevname".
Note: There are size and contents reqirements on a snapshot device.
| GNU/Linux: overlay block device / stackable block device |
1,291,477,658,000 |
I work a lot with imaged drives, meaning a do a dd-copy of the drive in question and then work on the image instead of the drive itself.
For most work, I use kpartx to map the drive's partitions to a device under /dev/mapper/. What I'm wondering here is if there's a way to find which of the mapping belong to which image.
Consider this:
root@vyvyan:/tmp# kpartx -a -v Image1
add map loop1p1 (254:4): 0 10240 linear /dev/loop1 2048
add map loop1p2 (254:5): 0 10240 linear /dev/loop1 12288
add map loop1p3 (254:6): 0 52848 linear /dev/loop1 22528
root@vyvyan:/tmp# kpartx -a -v Image2
add map loop2p1 (254:7): 0 33508 linear /dev/loop2 2048
add map loop2p2 (254:8): 0 39820 linear /dev/loop2 35556
Now, let's say I forget which image went to which mapping. Is there a way to let kpartx - or the kernel, or anything else - tell me which image goes where?
EDIT Also, if I accidentally rm the image-file while kpartx has added the mappings, how do you remove the mappings? kpartx wants the actual image to be present.
|
losetup (the command normally used to set them up) will tell you:
$ /sbin/losetup --list
NAME SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE
/dev/loop0 0 0 0 0 /var/tmp/jigdo/debian-7.6.0-amd64-CD-1.iso
Note that with older versions you may hat to use use -a instead of --list, and this outputs in a different and now deprecated format.
The information comes from /sys:
$ cat /sys/class/block/loop0/loop/backing_file
/var/tmp/jigdo/debian-7.6.0-amd64-CD-1.iso
Another, possibly more portable, option is to get it from udisks:
$ udisksctl info -b /dev/loop0
/org/freedesktop/UDisks2/block_devices/loop0:
⋮
org.freedesktop.UDisks2.Loop:
Autoclear: false
BackingFile: /var/tmp/jigdo/debian-7.6.0-amd64-CD-1.iso
SetupByUID: 1000
⋮
losetup will also happily remove them for you, using the -d option. That just requires the loop device as a parameter; it doesn't care about the backing file/device.
| How to find which images belong to which /dev/loop? |
1,291,477,658,000 |
How to add more /dev/loop* devices on Fedora 19? I do:
# uname -r
3.11.2-201.fc19.x86_64
# lsmod |grep loop
# ls /dev/loop*
/dev/loop0 /dev/loop1 /dev/loop2 /dev/loop3 /dev/loop4 /dev/loop5 /dev/loop6 /dev/loop7 /dev/loop-control
# modprobe loop max_loop=128
# ls /dev/loop*
/dev/loop0 /dev/loop1 /dev/loop2 /dev/loop3 /dev/loop4 /dev/loop5 /dev/loop6 /dev/loop7 /dev/loop-control
So nothing changes.
|
You have to create device nodes into /dev with mknod. The device nodes in dev have a type (block, character and so on), a major number and a minor number. You can find out the type and the major number by doing ls -l /dev/loop0:
user@foo:/sys# ls -l /dev/loop0
brw-rw---- 1 root disk 7, 0 Oct 8 08:12 /dev/loop0
This means loop device nodes should have the block type and major number of 7. The minor numbers increment by one for each device node, starting from 0, so loop0 is simply 0 and loop7 is 7.
To create loop8 you run, as root, command mknod -m 0660 /dev/loop8 b 7 8. This will create the device node /dev/loop8 with permissions specified along the -m switch (that's not necessary as you're probably running a desktop system, but it's a good idea not to let everyone read and write your device nodes).
| How to add more /dev/loop* devices on Fedora 19 |
1,291,477,658,000 |
I am writing some shell scripts to handle some disk image stuff, and I need to use loop devices to access some disk images. However, I am not sure how to properly allocate a loop device without exposing my program to a race condition.
I know that I can use losetup -f to get the next unallocated loop device, and then allocate that loop device like this:
ld=$(losetup -f)
sudo losetup $ld myfile.img
dostuffwith $ld
However, in the case where I want to run multiple instances of the program at the same time, this is almost a textbook example of a race condition, and that bothers me quite a lot. If I had multiple instance of this program running, or other programs trying to also get a loop device, then each process might not be able to allocate the loop device before the next one calls losetup -f, in which case both processes would think that the same loop device is available, but only one can get it.
I could use external synchronization for this, but I would like to (if possible) avoid additional complexity. Also, other programs that use loop devices wouldn't likely respect whatever synchronization I might come up with.
How can I avoid this potential race condition? Ideally, I'd like to be able to discover and bind the loop device atomically, for instance with a command like:
ld=$(sudo losetup -f myfile.img)
dostuffwith $ld
However, when I do that, $ld does not get assigned to the loop device path, and moving the sudo out, as in sudo ld=$(losetup -f myfile.img) gives permission errors.
|
This is a classic problem in concurrency: when allocating a resource, you need to atomically determine that the resource is free and reserve it, otherwise another process could reserve the resource between the time you check that it's free and the time you reserve it.
Do use losetup's automatic allocation mode (-f), and pass the --show option to make it print the loop device path.
ld=$(sudo losetup --show -f /tmp/1m)
This option has been present in util-linux since version 2.13 (initially added as -s, but --show has been supported in all released versions and recent versions have dropped the -s option name). Unfortunately the BusyBox version doesn't have it.
Version 3.1 of the Linux kernel introduced a method to perform the loop device allocation operation directly in the kernel, via the new /dev/loop-control device. This method is only supported since util-linux 2.21. With kernel <3.1 or util-linux <2.21, the losetup program enumerates the loop device entries to reserve one. I can't see a race condition in the code though; it should be safe but it might have a small window during which it will incorrectly report that all devices are allocated even though this is not the case.
| How to atomically allocate a loop device? |
1,291,477,658,000 |
Out of curiosity, I would like to know is there a way to find out the source of mounted partition?
For example, output of df -h is:
/dev/loop1 3M 3M 0 100% /media/loop
From this output, I know a loop device of 3M is mounted at /media/loop, but I have no clue to determine the exact location of the /dev/loop1 device.
root@SHW:~# mount -o loop /home/SHW/Downloads/TinyCore-current.iso
/mnt/loop mount: block device /home/SHW/Downloads/TinyCore-current.iso is write-protected, mounting read-only
root@SHW:~# tail -n1 /proc/mounts
/dev/loop1 /mnt/loop iso9660 ro,relatime 0 0
How do I find out the absolute path of /dev/loop1 f I don't know who mounted those partitions? (In this case the path is /home/SHW/Downloads/TinyCore-current.iso.)
|
Use losetup's --list option:
$ losetup --list /dev/loop0
NAME SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE
/dev/loop0 0 0 0 0 /tmp/backing-file
If you only want the file, use the -O option to pick the column:
$ losetup --list --noheadings -O BACK-FILE /dev/loop0
/tmp/backing-file
This option is part of recent versions of util-linux. Earlier versions support only the -a option, which lists all active devices in a harder-to-process format:
$ losetup -a
/dev/loop0: []: (/tmp/backing-file)
Either way, it's not overly onerous to process however you want.
| Source path of loop-device |
1,291,477,658,000 |
I'm trying to mount and access a floppy image file in the .ima format (raw dump to floppy, similar to .img) on ArchLinux.
This file is part of a set of 30. It is not bootable, but rather a continuation of a set. The purpose is not manipulation for the sake of installation or cloning. I'm interested in the documentation contained with other data on the disk.
Image file information
Here is some info about this image file:
# file U19.IMA
U19.IMA: PC formatted floppy with no filesystem
# fdisk -lu U19.IMA
Disk U19.IMA: 1.4 MiB, 1474560 bytes, 2880 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
(parted) print
Error: /home/meh/Downloads/U19.IMA: unrecognised disk label
Model: (file)
Disk /home/meh/Downloads/U19.IMA: 1475kB
Sector size (logical/physical): 512B/512B
Partition Table: unknown
Disk Flags:
Mount fail
Here's the generic error message:
mount -o ro,loop U19.IMA /mnt/cd/
mount: wrong fs type, bad option, bad superblock on /dev/loop0,
missing codepage or helper program, or other error
I've tried many combinations trying to specify a type with -t i.e. ntfs, msdos, iso9660, vfat, and always getting that same error. I thought it's maybe some kind of ntfs file format but ntfs-3G doesn't do much better so no it's not:
# ntfs-3g -o loop U19.IMA /mnt
NTFS signature is missing.
Failed to mount '/home/meh/Downloads/U19.IMA': Invalid argument
The device '/home/meh/Downloads/U19.IMA' doesn't seem to have a valid NTFS.
Maybe the wrong device is used? Or the whole disk instead of a
partition (e.g. /dev/sda, not /dev/sda1)? Or the other way around?
# ntfsclone -r -o file.img U19.IMA
ntfsclone v2013.1.13 (libntfs-3g)
ERROR: Input file is not an image! (invalid magic)
Someone suggested maybe a Minix fs. While it is not clear if I can really mount such a filesystem with my current configuration I tried:
mount -t minix -o loop U19.IMA /mnt/cd
which gave the generic error but there was this at the bottom of the log:
VFS: Can't find a Minix filesystem V1 | V2 | V3 on device loop0.
It seems this is not conclusive, as when you specify a specific type of filesystem you will have a specific type of error in the log. Also tried [fuseiso][2]:
# fuseiso U19.IMA /mnt/cd
init: wrong standard identifier in volume descriptor 0, skipping..
init: wrong standard identifier in volume descriptor 1, skipping..
init: wrong standard identifier in volume descriptor 2, skipping..
init: wrong standard identifier in volume descriptor 3, skipping..
init: wrong standard identifier in volume descriptor 4, skipping..
init: wrong standard identifier in volume descriptor 5, skipping..
init: wrong standard identifier in volume descriptor 6, skipping..
init: wrong standard identifier in volume descriptor 7, skipping..
init: wrong standard identifier in volume descriptor 8, skipping..
init: wrong standard identifier in volume descriptor 9, skipping..
init: wrong standard identifier in volume descriptor 10, skipping..
init: wrong standard identifier in volume descriptor 11, skipping..
init: wrong standard identifier in volume descriptor 12, skipping..
init: wrong standard identifier in volume descriptor 13, skipping..
init: wrong standard identifier in volume descriptor 14, skipping..
init: wrong standard identifier in volume descriptor 15, skipping..
init: wrong standard identifier in volume descriptor 16, skipping..
init: wrong standard identifier in volume descriptor 17, exiting..
Where I can see such things with dmesg:
[ 5316.082629] FAT-fs (loop0): invalid media value (0xf6)
[ 5316.082644] FAT-fs (loop0): Can't find a valid FAT filesystem
Also, lsmod | grep loop gives
loop 18511 0
There is no alternate superblock of any kind:
# mkfs -n U19.IMA
mke2fs 1.42.8 (20-Jun-2013)
U19.IMA is not a block special device.
Proceed anyway? (y,n) y
Filesystem label=
OS type: Linux
Block size=1024 (log=0)
Fragment size=1024 (log=0)
Stride=0 blocks, Stripe width=0 blocks
184 inodes, 1440 blocks
72 blocks (5.00%) reserved for the super user
First data block=1
Maximum filesystem blocks=1572864
1 block group
8192 blocks per group, 8192 fragments per group
184 inodes per group
Contrary to many cases I read about, there seems to be no need to specify any offset here as there are no partition built in the image. In such cases, sometimes the dd command is used to transfer the content to a similar image using an offset value which allows mounting. This seems the same as specifying an offset to the mount command directly. But this should be easy, like in this other case where a simple losetup is used and then the loop device is mounted. I can link the .ima file with losetup but when I try to mount the loop device I end up with my initial error message.
Data integrity
Finally, safecopy --stage1 doesn't report any issue with the data and the output up to stage 3 remains the same and yields the same error:
# safecopy U19.IMA test.img --stage1
Low level device calls enabled mode: 2
Reported hw blocksize: 4096
Reported low level blocksize: 4096
File size: 1474560
Blocksize: 4096
Fault skip blocksize: 147456
Resolution: 147456
Min read attempts: 1
Head moves on read error: 0
Badblocks output: stage1.badblocks
Marker string: BaDbLoCk
Starting block: 0
Source: U19.IMA
Destination: test.img
. ;-} 100%
Done!
Recovered bad blocks: 0
Unrecoverable bad blocks (bytes): 0 (0)
Blocks (bytes) copied: 360 (1474560)
Here's the top of the file and the content seems to be intact:
dd if=U19.IMA | hexdump -C | head -n 10
00000000 f6 f6 f6 f6 f6 f6 f6 f6 f6 f6 f6 f6 f6 f6 f6 f6 |................|
*
00004600 34 2e 30 2e 32 20 33 38 36 75 6e 69 78 20 46 6e |4.0.2 386unix Fn|
00004610 64 20 53 65 74 20 35 20 6f 66 20 31 30 0a 00 00 |d Set 5 of 10...|
00004620 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
"Forensics"
Since a raw image consists of a sector-by-sector binary copy of the
source medium, the actual format of the file contents will depend on
the file system of the disk from which the image was created (such as
a version of FAT).[...] Since IMG files hold no additional data beyond
the disk contents, these files can only be handled by programs that
can detect their file systems.
Following suggestions, I proceeded to analyze some of the other image files in the set(30):
fdisk -lu U14.IMA
Disk U14.IMA: 1.4 MiB, 1474560 bytes, 2880 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x00000000
This doesn't look like a partition table. Probably you selected the wrong device.
Device Boot Start End Blocks Id System
U14.IMA1 3840 11519 3840 0 Empty
U14.IMA2 2425393152 4850786447 1212696648 0 Empty
U14.IMA3 ? 2425393296 4850786591 1212696648 90 Unknown
U14.IMA4 ? 2425393296 4850786591 1212696648 90 Unknown
Sorry but it does look like a partition table but it is unusual. It includes the id 90 property:
90h MBR, EBR CHS, LBA x86, 68000, 8080/Z80 Hidden, Filesystem FreeDOS Free FDISK Hidden FAT16 (corresponds with 04h i.e. MS Fat16 DOS 3.0+ < 65536 sectors)
So trying to mount the image I get:
# mount -t auto U14.IMA /mnt/cd
mount: unknown filesystem type 'sysv' <-----
As someone hinted, you need to have something specific like 'System V and Coherent filesystem support' compiled in the kernel in order to use something like mount -t sysv. The sysv string is not so suprising, since this is part of AT&T UNIX System V/386 Release 4 Version 2.1 install media - a port which was supported by Sun until 2006 - and these images ended up in the wild in 2007. Actually a text file bundled with the images indicates that they are required for installation because of the nature of the boot sector and the format in use. There is an indication that the material was originally in Teledisk (TD0) format. I want to stress here that this is not original material. In any case I can't actually calculate the offsets like explained in the question - either I don't end up with integers when dividing by 512, and even if I try it seems I can't find the proper offset - dd: cannot skip to specified offset, 0 writes etc. So at this point the answer is about forensics, and no longer about an image file.
Quick historical image source OS emulation with qemu
AT&T UNIX System V Release 4 Version 2.1
LABEL Version X of X
AT&T UNIX SVR4.0 2.1 --------------------------------------------------
U01.IMA Maintanace Disk1 2.1 2 of 2
U02.IMA Remote Terminal 2.1 1 of 1
Package
U03.IMA BSD Comp. Pkg. 2.1 1 of 2
U04.IMA BSD Comp. Pkg. 2.1 2 of 2
U05.IMA Networking Supp. 2.1 1 of 1
Util. Pkg.
U06.IMA Xenix Comp. Pkg 2.1 1 of 1
U07.IMA FACE Pkg. 2.1 1 of 1
U08.IMA FMLI Pkg. 2.1 1 of 1
U09.IMA Editing Utils. 2.1 1 of 1
U10.IMA OA&M Basic & Ext. 2.1 1 of 3
U11.IMA OA&M Basic & Ext. 2.1 2 of 3
U12.IMA OA&M Basic & Ext. 2.1 3 of 3
U13.IMA Foundation Set 2.1 1 of 10
Base System Pkg.
2 User System
U14.IMA Base 2.1a 1 of 10
U15.IMA Base 2.1 2 of 10
U16.IMA Base 2.1a 2 of 10
U17.IMA Base 2.1 3 of 10
U18.IMA Base 2.1 4 of 10
U19.IMA Base 2.1 5 of 10
U20.IMA Base 2.1 6 of 10
U21.IMA Base 2.1 7 of 10
U22.IMA Base 2.1 8 of 10
U23.IMA Base 2.1 10 of 10
U24.IMA Maintanance 1 2.1 1 of 2
U25.IMA Base 2.1 9 of 10
U26.IMA Printer Pkg 2.1 3 of 3
U27.IMA Printer Pkg 2.1 2 of 3
U28.IMA Printer Pkg 2.1 1 of 3
U29.IMA 16 to unlimited 2.1 1 of 1
User License
U30.IMA 2 to 16 User 2.1 1 of 1
License
As was suggested, I installed from a prior image in the set. It involves using qemu like explained here basically starting with image 14 (first losetup /dev/loop0 U14.IMA then a simple qemu-system-x86_64 -m 256 -hda test.img -fda /dev/loop0 -boot a), as U19 is not bootable. What is nice here is that you don't have to mount/umount images in the OS itself, you just use ctrl-alt-2 or 1 with qemu to access or leave the monitor and you use list blocks to see what is mounted and change floppy0 imagename in that interface to change the image file i.e. during install for instance.
I had to supply U19.IMA (disk 5) during installation (for a textual log of the install, see this - a highlight is the reference to MS-DOS!), and I ended up with this i.e. a properly installed AT&T UNIX Sys V 386 OS, so this pretty much confirms U19.IMA is a working disk image:
By default /dev/fd is mounted on /dev/fd and there is also floppy access through a block (/dev/dsk/f0) and raw (/dev/dsk/f0) device. Changing directory to the floppy just shows files numbered from 1 to 23 (this is just the structure of the character device I guess). You can also cat the raw and block devices and see the floppy data is there but that's as close as it gets.
I've noticed that in that OS, you don't install stuff from floppies by launching some script from a directory on them like you do with decompressed binary files for instance - here you use pkgadd -d diskette1 (surely that last word is some alias, but I found a reference to the -d switch in the SCO stuff for pkgadd(1M) and generally it appears often in commercial Unix (Oracle, HP share pkgadd(1M) ). Issuing the command launches a routine where you supply floppies and you have no control, except saying "no" after the routine finds out what's in the drive. In the case of disks which begin an installation sequence (U03, U05 etc.), this will install then ask for the next floppy etc until the package install is complete. If you put a floppy that isn't the beginning of a set, it finds basically nothing but tells you maybe you have to use the installpkg command instead.
Will I be installing a physical floppy drive to my rig to access the data in that image file?
|
If you can't mount the image you might still be able in some cases to "stream out" some of its data with cpio.
Once you've ascertained whether the image is:
An image using a supported filesystem and a partition --> mount
An image using a supported filesystem and more than one partition -->
mount with offset, or use dd to extract a partition with offset then
mount that partition only or use something like kpartx
An image not using a supported filesystem or with no filesystem
at all --> kernel support and further investigation...
You can use the hexdump and strings utilities to try to analyze the header and to extract text strings from the image and gain more information about the image file and its structure.
Something captured my interest in doing so:
@(#)/usr/bin/echo.sl 1.1 4.0 10/01/90 16865 AT&T-SF
There's a line like this for every single binary in the image so you somewhat know what's in there. Also, in this case, when you take a closer look at how the installation process occurs on the original platform with installpkg, you find out that:
The basic mechanism to transfer software from a floppy disk to the
UNIX System V /386 hard disk is cpio.
Basically, the data is extracted with cpio to /usr/tmp/install and a series of files are included with this (an install, ascii, file, name and size file). It so happens here that this command:
cat U19.IMA | cpio -imdv
outputs malformed number errors to begin with, but then creates a /usr/bin folder with the contents of the image! The tr I was looking for is there:
#file tr
tr: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), stripped.
Trying cpio in the first place can't hurt!
| Mounting an old floppy image file (.ima format) - how hard can it be? |
1,291,477,658,000 |
From this answer the solution is to
modprobe loop max_loop=64
Which makes me allowed to use 64 loopback devices then
mknod -m 660 /dev/loop8 b 7 8
To create the devices. I did this for 8, 9, 10 and 8,9 works but 10 does not.
I then tried loopa to loopf and tried to mount a 11th device and i get the error
Error: Failed to set up a loop device:
How do I make >10 loop devices?
|
Make sure you are running mknod -m 660 /dev/loop10 b 7 10. The format is mknod -m 660 /dev/loop<ID> b 7 <ID> where ID is the same.
Update [07/10/2014]
I also found a good blog post to always have more at boot. See https://yeri.be/xen-failed-to-find-an-unused-loop-device
Update [05/25/2016]
I run a CentOS server, and I found that this post was also helpful when the other methods don't work.
This makes my new favorite method:
MAKEDEV /dev/loop
It creates 256 loop devices (which is the max without modifying the kernel).
| How do I setup more then 10 loopback device? |
1,291,477,658,000 |
I like to create a LVM device where physical volumes are loopback devices.
I have read lot of documents and tutorials, like this. Unfortunately all of them are based on the losetup command, which loses its configuration at next reboot.
I would make the LVM settings using FSTAB in place of the RC.LOCAL (where the losetup maybe scripted) in order to get my LVM running before some services startup, but I don't know how to reproduce into the FSTAB the command: "losetup /dev/loop0 /opt/my-data-file-0" and so on...
How could I accomplish this?
|
I have found a convenient way to do this: two SystemD services:
/mnt/systemd/system/loops-setup.service
[Unit]
Description=Setup loopback devices
DefaultDependencies=no
Conflicts=umount.target
Requires=lvm2-lvmetad.service mnt-host.mount
Before=local-fs.target umount.target
After=lvm2-lvmetad.service mnt-host.mount
[Service]
ExecStart=/sbin/losetup /dev/loop0 <LOOPBACK_FILE>
ExecStop=/sbin/losetup -d /dev/loop0
RemainAfterExit=yes
Type=oneshot
[Install]
WantedBy=local-fs-pre.target
/mnt/systemd/system/loops-fsck.service
[Unit]
Description=Loopback devices filesystem check
DefaultDependencies=no
Conflicts=umount.target
Requires=loops-setup.service
Before=local-fs.target umount.target mnt-loops-loop0.mount
After=loops-setup.service
[Service]
ExecStart=/sbin/fsck -pfv /dev/loop0
Type=oneshot
[Install]
WantedBy=local-fs-pre.target
| Persistent LVM device with loopback devices by fstab |
1,291,477,658,000 |
Is there a CPU/RAM overhead associated with using loop-mounted images versus using a physical partition under Linux?
|
On Linux <4.4, there is significant overhead when using loop devices on Linux: data accessed through the loop device has to go through two filesystem layers, each doing its own caching so data ends up cached twice, wasting much memory (the infamous "double cache" issue)
Aside from casual use, other alternatives would be to use a dedicated partition or a chroot so that data can be accessed directly.
Release notes for the first version with improved performance:
Faster and leaner loop device with Direct I/O and Asynchronous I/O support
This release introduces support of Direct I/O and asynchronous I/O for the loop block device. There are several advantages to use direct I/O and AIO on read/write loop's backing file: double cache is avoided due to Direct I/O which reduces memory usage a lot; unlike user space direct I/O there isn't cost of pinning pages; avoids context switches in some cases because concurrent submissions can be avoided. See commits for benchmarks.
| Overhead of using loop-mounted images under Linux |
1,291,477,658,000 |
I'm doing a study about how CD-ROM can be mounted virtually and all I could find out was mounting using loop devices.
mount -o loop disk1.iso /mount-point
This is fairly easy.
I understand that /dev/sr0 is a block device and it point to some buffer in kernel and the kernel device driver puts the filesystem (ot whatever it puts i am not sure) in that buffer and when we use mount it mounts the filesystem to the specified mount-point.
But am wondering whether we can mount an ISO of our choice (e.g. disk1.iso) by using SCSI CD-ROM device /dev/sr0 (without changing anything in the kernel) as it is done in Vmware and Virtualbox, where we can specify the ISO and it automatically emulates a CD-ROM hardware and the ISO can be mounted using /dev/sr0 device?
The major problem which i see here is that how /dev/sr0/ will be linked to the iso?
|
The thing here is that /dev/sr0 is linked to a kernel device driver. That device driver will allow access to a physical CDROM if available through that node; VMWare and VirtualBox emulate hardware as you mention and hence the kernel and device driver think they're communicating with hardware.
The /dev/sr0 doesn't point to a certain buffer directly, it provides an interface to the block device interface that allows userspace processes to acces the contents of the hardware device.
If you want to make an image available as a block device, then your only choice (besides virtualization and emulating hardware) is to use loop devices with losetup... or to write your own replacement device driver, but I expect that's not a viable option for now.
If you want to make that image available as /dev/sr0 (are we talking about faking out some software that demands access to a CDROM at that location?) then you could move that file to e.g. /dev/sr0.moved and then symlink the appropriate /dev/loopX to /dev/sr0. Of course, if the software in question tries special commands that only apply to CDROM devices, then this won't work. Otherwise it shouldn't be a problem.
| Mount an ISO virtually using /dev/sr0 device |
1,291,477,658,000 |
I have a program which creates partitions and filesystems on a disk. To test it, I have created an image file:
dd if=/dev/zero of=disk.img bs=1M count=100
and mounted:
sudo losetup /dev/loop0 disk.img
The partitioning process seemingly works, I get an error from mkfs:
mkfs.vfat: unable to open /dev/loop0p2: No such file or directory
I can see the partitions with fdisk -l:
sudo fdisk -l /dev/loop0
Disk /dev/loop0: 1000 MiB, 1048576000 bytes, 2048000 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: B2CB131D-0091-4102-89E1-1D94EC49484A
Device Start End Sectors Size Type
/dev/loop0p1 2048 10239 8192 4M BIOS boot
/dev/loop0p2 10240 272383 262144 128M EFI System
/dev/loop0p3 272384 1320959 1048576 512M Linux swap
/dev/loop0p4 1320960 2047966 727007 355M Linux filesystem
but not with lsblk:
sudo lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
loop0 7:0 0 1000M 0 loop
sda 8:0 0 465,8G 0 disk
├─sda1 8:1 0 512M 0 part /boot/efi
├─sda2 8:2 0 457,3G 0 part /
└─sda3 8:3 0 8G 0 part [SWAP]
What am I doing wrong?
|
Try using partprobe(which is part of parted package) or kpartx so kernel will get info about partitions.
Mounting / partitioning loopback devices not always causes kernel to re-read partition table.
It is common situation when you've got info:
Re-reading the partition table failed.: Device or resource busy.
The kernel still uses old table [...]
You can also force kernel to re-read partition table of loopback device by using: losetup -P command
As stated in manual:
-P, --partscan
Force the kernel to scan the partition table on a newly created loop device.
| Loopdevice partitions do not show up |
1,291,477,658,000 |
A couple of years ago I upgraded my netbook with a larger hard drive.
I wanted to retain the contents of the old hard drive in case there was anything I still wanted off it.
So I copied the the old hard-drive into a file on the new one:
dd if=/dev/sdd5 of=~/fw-disk-image/fw-sdd5-linux-lvm-partition.raw
and I wrote/copied a script for mounting the lvms on that partition as read-only file-systems:
losetup -r /dev/loop1 ~/fw-disk-image/fw-sdd5-linux-lvm-partition.raw
pvscan
vgscan
vgchange -a y fw
cd /mnt/fw
for i in root tmp usr var home
do
mount -o ro /dev/fw/$i $i
done
Now this worked for a long time and now suddenly it fails at the vgchange -a y fw command:
# vgchange -a y fw
Error writing device /dev/loop1 at 4096 length 512.
bcache_invalidate: block (4, 0) still dirty
Failed to write mda header to /dev/loop1 fd -1
Failed to update old PV extension headers in VG fw.
Volume group "fw" not found
Cannot process volume group fw
I'm guessing that since I created a read-only loop-back device, vgchange is not happy that it can't write to it. I think that the file-system was dirty when last the disk was used but I want to ignore that.
My current system is currently running:
Linux fw 4.19.0-8-686-pae #1 SMP Debian 4.19.98-1 (2020-01-26) i686 GNU/Linux
$ vgchange --version
vgchange --version
LVM version: 2.03.02(2) (2018-12-18)
Library version: 1.02.155 (2018-12-18)
Driver version: 4.39.0
Configuration: ./configure --build=i686-linux-gnu --prefix=/usr --includedir=${prefix}/include --mandir=${prefix}/share/man --infodir=${prefix}/share/info --sysconfdir=/etc --localstatedir=/var --disable-silent-rules --libdir=${prefix}/lib/i386-linux-gnu --libexecdir=${prefix}/lib/i386-linux-gnu --runstatedir=/run --disable-maintainer-mode --disable-dependency-tracking --exec-prefix= --bindir=/bin --libdir=/lib/i386-linux-gnu --sbindir=/sbin --with-usrlibdir=/usr/lib/i386-linux-gnu --with-optimisation=-O2 --with-cache=internal --with-device-uid=0 --with-device-gid=6 --with-device-mode=0660 --with-default-pid-dir=/run --with-default-run-dir=/run/lvm --with-default-locking-dir=/run/lock/lvm --with-thin=internal --with-thin-check=/usr/sbin/thin_check --with-thin-dump=/usr/sbin/thin_dump --with-thin-repair=/usr/sbin/thin_repair --enable-applib --enable-blkid_wiping --enable-cmdlib --enable-dmeventd --enable-dbus-service --enable-lvmlockd-dlm --enable-lvmlockd-sanlock --enable-lvmpolld --enable-notify-dbus --enable-pkgconfig --enable-readline --enable-udev_rules --enable-udev_sync
Is there some way that I can (again) mount the LVs on this partition while remaining strictly read-only?
|
Below is a workaround: given LVM wants a read-write block device, we create one with an overlay block device based on the read-only block device (see this other question).
As root:
Create a sparse file with the same size as the read-only block device
truncate -s`blockdev --getsize64 /dev/loop1` '/tmp/overlay.bin'
(even if larger than the current filesystem)
Create the overlay block device
loop=`losetup -f --show -- '/tmp/overlay.bin'`
size=`blockdev --getsz /dev/loop1`
printf '%s\n' "0 $size snapshot /dev/loop1 $loop P 8" | dmsetup create 'overlayloop1'
To avoid LVM to complain about duplicate PV with the same UUID, edit /etc/lvm/lvm.conf to exclude the original /dev/loop1: either devices { scan = [ "/dev/mapper" ] } either devices { filter = [ "r|/dev/loop1|" ] } (see this FAQ on LVM wiki)
Now vgchange -a y fw works.
During the use, the file /tmp/overlay.bin should be monitored, although it should not increase particularly if the filesystem of the LV is mounted read-only.
To close the loop device:
vgchange -a n fw
dmsetup remove /dev/mapper/overlayloop1
rm /tmp/overlay.bin
losetup -d /dev/loop1
| Mount a PV image as a readonly loop device (again - it used to work) |
1,291,477,658,000 |
i can include loop module for supporting loop files.
loop module supports max_loop option. I've found examples with
options loop max_loop 256 . My question, what is maximal supported loop devices? I can't belive, 256 is the hard limit, and creating more than 256 loop devices is impossible.
Update:
I didn't found nothing interesting in file https://elixir.bootlin.com/linux/v4.0/source/drivers/block/loop.c
But I made some experiment, and run
modprobe max_loops=512
then I see exactly the same count loop block files in /dev/ directory mounted as udev, numbered from loop0 to loop511
I did it with linux kernel 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2+deb10u2 (2019-11-11) x86_64
|
Before kernel 3.1, you had to set a fixed number of loop devices. Since 3.1 there is /dev/loop-control, and loop devices are allocated dynamically as needed, rather than a fixed number. So rather than having a hundred loop devices you never needed (just in case), it starts out with 0 devices (or an optional min count) and only creates them when actually required.
From man 4 loop:
/dev/loop-control
Since Linux 3.1, the kernel provides the /dev/loop-control device,
which permits an application to dynamically find a free device, and to
add and remove loop devices from the system.
The very fine source code (drivers/block/loop.c) describes it:
/*
* If max_loop is specified, create that many devices upfront.
* This also becomes a hard limit. If max_loop is not specified,
* create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
* init time. Loop devices can be requested on-demand with the
* /dev/loop-control interface, or be instantiated by accessing
* a 'dead' device node.
*/
It also recommends not setting it at all:
* Note: Global-for-all-devices, set-only-at-init, read-only module
* parameteters like 'max_loop' and 'max_part' make things needlessly
* complicated, are too static, inflexible and may surprise
* userspace tools. Parameters like this in general should be avoided.
How many loop devices can realistically be used then? The limit is the maximum number of minor devices for a single major device (since loop has a single major, block 7), which is limited by MINORBITS (so 220, just over a million).
I tried to force some large numbers like this:
truncate -s 1M foobar
i=1
while losetup --show /dev/loop$(($i-1)) foobar
do
i=$(($i*2))
done
...but it triggered a kernel panic in the end. ;-)
sysfs: cannot create duplicate filename '/devices/virtual/bdi/7:1048575'
kobject_add_internal failed for 7:1048575 with -EEXIST, don't try to register things with the same name in the same directory.
This matches the 220 limit.
| what is maximum loop devices for linux kernel? |
1,291,477,658,000 |
Using the losetup command, you can turn a regular file into a pretend block device. You can then partition and format it like any other device.
Is there some way to make Linux pretend that this "device" has a 4K logical sector size?
|
Yes it's possible: If you run
losetup --help
you will notice the option
-b, --sector-size
I suggest also testing to use the direct-IO option too on the loop block device
Here is how I create my loop devices :
losetup --sector-size 4096 --direct-io=on $loop_device $diskfile
But maybe in your case, only --sector-size 4096 is sufficient.
You can then display the loop devices with the losetup -l command:
NAME SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE DIO LOG-SEC
/dev/loop4000 0 0 0 0 /mnt/fbx/FBX-24T/testspeed2 1 4096
/dev/loop3000 0 0 0 0 /mnt/fbx/FBX-24T/testspeed 1 4096
Please note the 4K block sectors
Please also note that for the moment, you can specify the sector size from 512 to 4096 but for example it's not possible to use 8K sectors (8192), the losetup command will fail if you try to use sectors size bigger than 4096.
Here is why I suggest using direct-IO option: --direct-io=on
When you have a 4K sectors formated filesystem on the underlying file used to create the loop device (see losetup -P or losetup --partscan option), using the direct-IO option will bypass the kernel storage stack working queue by sending the IO directly to the block device.
It helps keeping coherent (aligned) the block device and the filesystem you're writing on.
In some case, it also provide 8 to 10 times better performance, for example when creating a loop device from a LUKS file hosted on a CIFS share
(LUKS = Linux Unified Key Setup aka Cryptsetup which add a crypted layer between the block device and its hosted filesystems)
| Loop device with 4K sectors |
1,291,477,658,000 |
So my setup is like this.
$ truncate -s 1T volume
$ losetup -f --show volume
/dev/loop0
$ mkfs.ext4 /dev/loop0
$ ls -sh volume
1.1G volume
$ mount /dev/loop0 /mnt/loop
Now I have a 1.1TB volume, as expected. The overhead of ext4 expanded the sparse file to 1.1G, but that's fine. Now to add a file.
$ dd if=/dev/urandom of=/mnt/loop/file bs=1M count=10240
$ ls -sh volume
12G volume
Cool, now I don't want the file.
$ rm /mnt/loop/file
$ ls -sh volume
12G volume
The free space is still taking up space, as expected, and $ fallocate -d volume frees up 1gb.
My question is, how can I zero out the free space here without expanding the volume to the full size? $ dd if=/dev/zero will expand it to full size, and with conv=sparse makes it create a useless sparse file inside the volume.
TL;DR: Is there a way to make losetup ignore writes of null blocks to null sectors, while allowing everything else?
|
To automatically discard data blocks when they are no longer used, use mount -o discard .... Or you can manually run fstrim.
This feature was apparently added to the loop device in Linux 3.2. https://outflux.net/blog/archives/2012/02/15/discard-hole-punching-and-trim/
In the general case, mount -o discard is not guaranteed to be effective, because some types of device are allowed to ignore discard requests when they are busy. This would not be a concern for the size of your sparse file though.
In this general case - e.g. if you also wanted to send discard requests to an underlying physical device - the most robust method is to run fstrim at regular intervals.
| Can losetup be made efficient with sparse files? |
1,291,477,658,000 |
It's a bit indirect, but it's possible to mount a partition with a disk image using mount or losetup's "offset" parameter.
I'm looking to be able to use fuse to do the same thing in user space
Use Case
My use case is building disk images on an autobuild server where the build job is not allowed to have root permissions, and the server should not need a custom setup for particular build jobs.
|
It's possible to do with fuse, but would probably be cleaner with custom tools.
Solution
With apt-get-able tools the following kludge is possible:
mkdir mnt
xmount --in dd --out vdi disk.img mnt
mkdir mnt2
vdfuse -f mnt/disk.vdi
mkdir mnt3
fuseext2 -o "rw" mnt2/Partition1 mnt3
Explanation
The basic idea is that fuse can be used to separate a full disk image in place into files that point to it's partitions. vdfuse does this, but is a VirtualBox tool and requires a VDI or VMDK file to work. xmount uses fuse to make a raw disk image appear as a VDI file.
Finally once the partition file is available via vdfuse, it can be mounted via an ext2/3/4 tool fuseext2.
It's ugly but it works completely in userspace.
Update
vdfuse should be able to mount a raw image without the help of xmount, but there is a bug which ignores the RAW option.
I tracked down and fixed the bug with a patch here:
https://bugs.launchpad.net/ubuntu/+source/virtualbox-ose/+bug/1019075
| How can I mount partitions in a full disk image (i.e. image with partition table) with fuse? |
1,291,477,658,000 |
I'm trying to figure out a clean and safe way to use loop devices inside of a build script. To the best of my knowledge loop devices are required if you want to (GPT) partition and (FAT32, EXT3) format a sparse file1.
Eg: Let's say I have this script:
#!/bin/bash
set -ex
truncate --size 4G target.img
sfdisk target.img < partitions
loop_device=$(losetup -f --show target.img)
trap "losetup -d $loop_device" EXIT
partx -u $(loop_device)
mkfs.vfat ${loop_device}p1
mkfs.ext4 ${loop_device}p2
In most happy and unhappy paths, the loop device will be cleaned up by bash calling losetup. But there are some unhappy paths2 that result in the loop device being left behind.
If this were a question about mounts, then the simple solution would be to run in a mount namespace with unshare -m. That would result in the kernel cleaning up the mount point when the process exits, without the process explicitly performing the same action.
Further, if the loop device was created with a mount in the first place with mount -o loop then the loop device would be cleaned up when the mount point was, and so by proxy a mount namespace could also be used to clean up the loop device.
But since what I'm after is a GPT partition table on a file that's all zeros, no file system would successfully mount on it (AFAIK).
So is there some other way to get the kernel to clean up a loop device when a process, process group, namespace, ... is cleaned up?
1 I'm aware that solutions exist such as formatting a separate file and then using dd to copy with an offset, but that results in multiple GB of zeros being written to disk instead of remaining as a sparse file. So here the word "sparse" is very important
2 One obvious one is what happens when bash is killed with kill -9
|
losetup -d disassociates a loop device lazily, so it can be used to remove a loop device as soon as it is no longer used. Instead of trapping, open a file descriptor to the loop device and disassociate it straight away:
#!/bin/bash
set -ex
truncate --size 4G target.img
sfdisk target.img < partitions
loop_device=$(losetup -f --show target.img)
exec 5< "$loop_device"
losetup -d "$loop_device"
partx -u "$loop_device"
mkfs.vfat "${loop_device}p1"
mkfs.ext4 "${loop_device}p2"
When the script exits, for whatever reason, except in the short window between losetup -f and losetup -d, the loop device will be cleaned up.
| Can loop devices be automatically cleaned up when a process exits? |
1,291,477,658,000 |
I have a dedicated Ubuntu server with hetzner.de. hetzner also provides a separate backup space accessible via samba/ftp/sftp/scp.
In their support document about backups, the following line is mentioned.
"The direct use of rsync is not possible. The backup space can however be locally mounted using smbfs, sshfs or ftpfs, allowing a limited use of rsync. To take full advantage of rsync (such as incremental backups using hardlinks) an image file must be created, which should be mounted via loopback."
I would like to use rsync with incremental backups using hardlinks.
I think by loopback they mean http://en.wikipedia.org/wiki/Loop_device. Can any one help on how I can create an image from the network location?
|
Mount your network location with whichever protocol you're using:
# smbfs example:
mount -o username=your_hetzner_username //server.or.ip.addr/sharename /mnt/server-mountpoint
Create an ext2fs image (or another filesystem, if you prefer) inside a file on that share. Do this only the first time, as it wipes the data in backup-fs.image:
# create a 1000 MB file for the backup disk image (you will need to choose a size that works for you)
dd if=/dev/zero of=/mnt/server-mountpoint/backup-fs.image bs=1048076 count=1000
# create an ext2 filesystem inside the image
mke2fs /mnt/server-mountpoint/backup-fs.image
Mount the newly-created image with as a loopback device.
mount -o loop /mnt/server-mountpoint/backup-fs.image /mnt/backup-mountpoint/
When you're done using it, you can umount /mnt/backup-mountpoint and umount /mnt/server-mountpoint, and then to update your backup later, repeat steps 1 and 3.
The Wikipedia page you linked is the correct topic, but the actual loopback device process is simpler than they make it seem. Dealing with the server mount is more complicated, and may require some experimentation. There are a number of other questions on this site for dealing with each of the above steps, in case you get stuck.
| creating a device image for a network location |
1,291,477,658,000 |
Here's an Ubuntu How-to about booting from ISO-image on flash.
http://ubuntuforums.org/showthread.php?t=1288604
What I don't get is creation of loop-device in GRUB2 prior to booting a kernel:
menuentry "Ubuntu" {
set isofile="/boot/isos/ubuntu.iso"
loopback loop $isofile
linux (loop)/casper/vmlinuz boot=casper iso-scan/filename=$isofile quiet splash noprompt --
initrd (loop)/casper/initrd.lz
}
I don't understand, what is loop-device, irrelevant of OS. I thought, loop devices are Linux entities, non-existing apart from it. Or is it a GRUB2 entity? Where can I read more about them (I failed to google anything)?
I'd understand, if they first loaded the kernel directly from flash and then created a linux loop-device out of ISO. But this way I don't get it.
|
That's just grub2's loop device feature. grub is able to read a number of filesystems and in addition to that to nest them, in that it is able to read files (an initrd and linux kernel above) inside a filesystem inside a file inside another file system.
It has nothing to do with linux loop devices. Grub uses it just to load those kernel and initrd files in memory. They have no life beyond that.
| loop-device: is this a Linux entity or a lower-level one? |
1,291,477,658,000 |
I'm trying to play around with OS development, and I started with a boot loader, where phase 0 loads phase 1 from a file (specified by inode) on an ext4 partition (specified by first LBA). Of course, I need something to boot from, so I grabbed QEMU. Now what?
What has worked fine so far is this:
truncate -s64M /tmp/SomeVolume
/sbin/mke2fs -t ext4 -F /tmp/SomeVolume
yasm phase0.asm
dd if=phase0 of=/tmp/SomeVolume conv=notrunc
I make a volume of about 64 MB, format it as ext4, and overwrite the first 1024 octets with phase0 (which is always 1024 bytes in size). This works fine.
But now I want to make a properly partitioned file, to test it for more realistic scenarios. I know I could /sbin/cfdisk my volume file, but mke2fs doesn't have a parameter that lets me choose a span within the file.
Now I'm aware of solutions using loop, but unfortunately, it doesn't seem to work for me (it seems I'm not able to change max_part in Debian jessie). There seems to be another module called nbd, but I don't have the server and client for that module installed. And it's getting a little ridiculous that I need root privileges for something that could clearly be done in userland.
How can I do this as a user? Or should I just build the MBR/GPT-partitioned volume around the ext4-formatted file I created?
|
The long way around. But for the fun of it:
1. Create a temporary image:
$ truncate -s64MiB tmp.img
2. Create two partitions using fdisk:
Rather detailed, but OK.
$ fdisk tmp.img
First partition:
: n <Enter>
: <Enter> (p)
: <Enter> (1)
: <Enter> (2048)
: +40M <Enter>
Second partition:
: n <Enter>
: <Enter> (p)
: <Enter> (2)
: <Enter> (83968)
: <Enter> (131071)
Print what we are about to write:
: x
: p
Nr AF Hd Sec Cyl Hd Sec Cyl Start Size ID
1 00 32 33 0 57 52 5 2048 81920 83
2 00 57 53 5 40 32 8 83968 47104 83
Write and exit:
:w (Dont! forget ;-) )
We have two partitions of 40 and 23 MiB:
81920 * 512 / 1024 / 1024 = 40MiB
47104 * 512 / 1024 / 1024 = 23MiB
3. Create two file systems:
truncate -s40MiB ext4.img
truncate -s23MiB ext3.img
mke2fs -t ext4 -F -L part_ext4 ext4.img
mke2fs -t ext3 -F -L part_ext3 ext3.img
4. Stitch it all together:
Extract first 2048*512 bytes from temporary image:
dd if=tmp.img of=disk.img bs=512 count=2048
Combine them:
cat ext4.img ext3.img >> disk.img
Fine.
| How can I partition a volume in a regular file without loop? |
1,291,477,658,000 |
I'm trying to setup a Linux system that runs from an LVM-formatted image file. After some tinkering with the initramfs and boot options I managed to make it up and running by mounting the host file system to /run/initramfs/host, losetuping the image to /dev/loop0 and making sure the kernel and udev detect the LVM (and the root LV) in there. So far so good.
The problem is that when shutting down (or rebooting, or …) the system neither the root file system nor the host are unmounted properly, because of a chicken-and-egg scenario: the root (or /oldroot, as it's referred to by the shutdown script) cannot be unmounted, because /oldroot/run/initramfs/host is still mounted, and the host cannot be unmounted, because doing so would make /oldroot inaccessible.
Unclean shutdowns aren't the end of the world, because both file systems are journaled, so during the next boot fsck simply replays the journals, but obviously clean shutdowns would be better.
So the question is: is it somehow possible to arrange the shutdown sequence (I can modify the shutdown script), or the bootup sequence (perhaps by moving the host mount point to a different place) so that both file systems can be cleanly unmounted?
|
In case somebody has the same problem:
All I needed was to move the mount point of the host file system to a place outside the root file system in the shutdown script (that's fine, because it runs in a tmpfs pivot root) before any unmounting takes place:
mount --move /oldroot/run/initramfs/host /host
This allows /oldroot to unmount cleanly. The host file system can be then unmounted with a simple
umount /host
| Ensure that loopback root and host are unmounted on shutdown |
1,291,477,658,000 |
I'd like to recreate a feature of Mac OS X called sparse bundles (disk images made out of smaller files, making them easy to backup after a small change). For that I'm looking for a way to 'virtually' create a single file made by concatenation of smaller ones (big.file shouldn't use all this space, just link to .files):
4096 0.file
4096 1.file
4096 2.file
4096 3.file
4096 4.file
20480 big.file
so that I'd be able to mount big.file using loop device, format as btrfs and upon writing to this disk, data should be written only to certain .files, allowing me to backup easily.
Any suggestions how I could accomplish that? Perhaps something FUSE-related?
|
One way to do this would be to make each file an LVM physical volume, and join those physical volumes in a volume group and make an LVM logical volume using that space. But it's cumbersome: you need to associate the file with a loop device.
dd if=/dev/zero of=0.file bs=1024k count=4
losetup /dev/loop0 0.file
pvcreate /dev/loop0
# … repeat for all parts …
vgcreate -s 1m foo /dev/loop0 /dev/loop1 …
lvcreate -l 19 -n big foo
mkfs.btrfs /dev/mapper/foo-big
Reassembling the parts is not likely to be directly supported by your boot scripts, so you'd have to code quite a few things manually.
I don't see the point: how does splitting files facilitate backups? Many changes are likely to be spread over the whole volume (for example, several parts will contain copies of the superblock). You won't gain much by only backing up the parts that have changed: you'll need to look further inside the parts anyway.
If you want to make incremental backups, make them at the filesystem level.
If you want to make full backups of the whole image but ignore empty space, make sure to create a sparse file, use backup tools that manipulate sparse files efficiently, and periodically fill the empty space in the filesystem with zeroes and sparsify it.
| Virtual file made out of smaller ones (for mac-like sparse bundle solution) |
1,291,477,658,000 |
I was reading Trouble with understanding the concept of mounting and came across this explanation:
By using mount -t iso9660 /dev/cdrom /media/cdrom, you tell the system: "take this very long string of bytes that you have in /dev/cdrom, interpret it as a directory tree in the iso9660 format, and allow me to access it under the location /media/cdrom"
and other answers along this line. This makes sense and from this logic, I understood that mounting essentially couples a filesystem to a device which interprets the contents of the device in a way that the kernel can fit it into the existing filesystem hierarchy.
If this is indeed the case, why is a loop mount needed?
Since a mount -o loop is technically identical to the operation mount is meant to do: read a file and interpret its content in the context of a filesystem, why can we not generalize the mount operation without creating a special device?
Edit: I understand that a loop device provides a block-device API to a file. My question is, however, more general. How is reading from a regular file (iso or similar disk image formats) different from reading from a special file, if they contain the same data?
My mental model of how mount works is this: given an arbitrary set of bytes exposed by a /dev/device file which are consequently interpreted by a filesystem driver (ext4, for example), the mount command associates it with the root hierarchy so that it appears transparent to the end user.
However, this arbitrary set of bytes can occur anywhere. If interpreted by a filesystem driver they should be recognized as a valid filesystem. What constrains a filesystem driver to read only from a special file and not a regular file?
|
Block devices are not normal files, they allow programs like mount to perform special functions on them that are required for it to correctly work.
A loop device is a translation device, it translates block file calls into normal filesystem calls to a specific file. You can use losetup to create fully fledged loopback devices backed by a file (will appear as /dev/loopX and then treat them as normal block devices or pass -o loop to mount to tell it to create the block device transparently. You can also use losetup to inspect loopback devices and what they are backed by.
Note that with modern mount it will attempt to detect a normal file and automatically create the loopback device for you. So you do not need to pass it the loop option.
Also, technically a bind mount is where you remount a directory to a new location (so it is mounted twice). This can be done with the --bind flag to mount. I get your meaning, but it can get confusing as the term bind has a specific meaning in terms of mounting.
Edit: You mental model is effectively correct, but you can think of loop devices as an abstraction layer, it allows mount to talk to any file as though it was a block device, without having to understand the differences between reading/writing to a filesystem or to a raw block device - the kernel handles all of that. All mount needs to know is how to ask the kernel to set up the loop device, then treat is as a block device; this keeps the low level code simpler and allows anything that can talk to a block device talk to a file instead without being modified.
| Loop mounting files vs mounting directories [duplicate] |
1,291,477,658,000 |
I have to map several loopback devices via dmsetup.
I could track which loopback device is mapped to a particular /dev/dm-X device file, but is there an easy way to get this info by the /dev/dm-X itself?
dmsetup info was of no help for me here.
|
The constituent devices are under /sys/block/dm-X/slaves. E.g.,
$ ls /sys/block/dm-2/slaves/
loop0
| Get target device by /dev/dm-X entry |
1,291,477,658,000 |
Goal
I'm trying to make a harddisk image from scratch using a file. This includes MBR, partition table, number of partitions, etc. I cannot for the life of me get Linux to mount the partitions I make though.
edit: See end of question for update - seems to be related to vboxsf
Procedure
I've tried many different approaches by now but the ones that have gotten my the furthest all end up the same place. I've made a simplied version below which should be enough to explain my problem
Generate empty file using dd (or truncate for speed)
dd if=/dev/zero of=test.img bs=1M count=150
Make partition table
parted -s test.img mklabel gpt
Warning: The resulting partition is not properly aligned for best performance.
Make partition(s)
parted -s test.img -- mkpart logical 0 5M
parted -s test.img set 1 bios_grub on
parted -s test.img -- mkpart logical 5M 50M
etc.
Mount as loop device (loop module loaded with max_part=31)
losetup /dev/loop0 test.img
lsblk to check
loop0 7:0 0 150M 0 loop
├─loop0p1 7:1 0 4.8M 0 loop
├─loop0p2 7:2 0 43M 0 loop
└─loop0p3 7:3 0 4M 0 loop
so far so good - I guess. Format the partitions
mkfs.ext4 /dev/loop0p1
mkfs.ext4 /dev/loop0p2
mkfs.ext4 /dev/loop0p3
Now lets mount our new partitions
[root@localhost vmdk test]# mount /dev/loop0p2 boot
mount: /dev/loop0p2 is write-protected, mounting read-only
mount: unknown filesystem type '(null)'
This is where it ends - every time. I've tried mounting the image to a loop right after its created and call parted on /dev/loop0 instead. This yields the same result. I've tried losetup with offsets manually. I've tried kpartx - I cannot figure out how to get beyond this point.
I should note that I also tried this procedure with an actual harddrive (well I'm using a VM but you know what i mean). In this case I called the exact same commands but on /dev/sdb instead. At the end I was able to mount /dev/sdb2 with no problems.
Debug info
I don't know if its relevant but here goes
[root@localhost vmdk test]# uname -a
Linux localhost.localdomain 3.10.0-327.36.2.el7.x86_64 #1 SMP Mon Oct 10 23:08:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
[root@localhost vmdk test]# cat /etc/redhat-release
CentOS Linux release 7.2.1511 (Core)
[root@localhost vmdk test]# file test.img
test.img: x86 boot sector; partition 1: ID=0xee, starthead 0, startsector 1, 307199 sectors, extended partition table (last)\011, code offset 0x0
[root@localhost vmdk test]# file -s /dev/loop0
/dev/loop0: x86 boot sector; partition 1: ID=0xee, starthead 0, startsector 1, 307199 sectors, extended partition table (last)\011, code offset 0x0
[root@localhost vmdk test]# file -s /dev/loop0p2
/dev/loop0p2: data
[root@localhost vmdk test]# fdisk -lu /dev/loop0
WARNING: fdisk GPT support is currently new, and therefore in an experimental phase. Use at your own discretion.
Disk /dev/loop0: 157 MB, 157286400 bytes, 307200 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: gpt
# Start End Size Type Name
1 34 9765 4.8M BIOS boot parti logical
2 10240 98303 43M Microsoft basic logical
3 98304 106495 4M Microsoft basic logical
I don't understand why the loop device does not behave the exact same way as the harddrive does when I follow the same procedure. If anyone has any ideas they would be much appreciated!
Update
By coincidence I observed that a reboot fixes my problem so my mind immediately went to sync. After some testing though it would seem that my problem only occurs when the test.img file is placed on my vboxsf mount (shared folder between host and VM). I haven't really given this any thought but maybe it caches file writes in a weird way ? I'll leave the question open for now - maybe someone can elaborate.
|
If the image file is hosted on a weird filesystem like e.g. vboxsf this could be the problem.
| Cannot mount partition made on loop device (which is pointing to a file) |
1,291,477,658,000 |
I have a disk image file I'm trying to mount locally using a loop device. Using parted I can see the image has two partitions, however, I'm not able to mount the first partition and losetup thinks the second partition doesn't exist. Anyone know how I can mount the second partition?
/m/sf_VMShare ❯❯❯ sudo losetup /dev/loop0 ./imm_image-2017-05-28.img
/m/sf_VMShare ❯❯❯ sudo losetup -a
/dev/loop0: [0023]:99 (/media/sf_VMShare/imm_image-2017-05-28.img)
/m/sf_VMShare ❯❯❯ sudo parted /dev/loop0 print
Model: Loopback device (loop)
Disk /dev/loop0: 1206MB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1 10.5MB 360MB 349MB primary ext4
2 361MB 1205MB 844MB primary ext4
/m/sf_VMShare ❯❯❯ sudo mount -t ext4 /dev/loop0p2 /tmp/vdisk
mount: special device /dev/loop0p2 does not exist
/m/sf_VMShare ❯❯❯ sudo mount -t ext4 /dev/loop0p1 /tmp/vdisk
mount: wrong fs type, bad option, bad superblock on /dev/loop0p1,
missing codepage or helper program, or other error
In some cases useful info is found in syslog - try
dmesg | tail or so
/m/sf_VMShare ❯❯❯ mount | grep /tmp/vdisk
/m/sf_VMShare ❯❯❯
/m/sf_VMShare ❯❯❯ ls /dev/loop*
/dev/loop0 /dev/loop1 /dev/loop3 /dev/loop5 /dev/loop7
/dev/loop0p1 /dev/loop2 /dev/loop4 /dev/loop6 /dev/loop-control
/m/sf_VMShare ❯❯❯ lsblk -f
NAME FSTYPE LABEL MOUNTPOINT
sda
├─sda1 /
├─sda2
└─sda5 [SWAP]
sdb
└─sdb1 /home/foo/workspace
sr0
loop0
└─loop0p1
|
How to mount a partition in a full disk image that contains a msdos partition table.
Tools:
fdisk
mount
calculator
Get the partition layout of the image.
sudo fdisk -l -u=sectors /work/loop_test/disk_image.img
Example output:
Disk /work/loop_test/disk_image.img: 29 MB, 29629952 bytes
255 heads, 63 sectors/track, 3 cylinders, total 57871 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0009d7e5
Device Boot Start End Blocks Id System
/work/loop_test/disk_image.img1 2048 18431 8192 83 Linux
/work/loop_test/disk_image.img2 18432 57343 19456 7 HPFS/NTFS/exFAT
Calculate the offset from the start of the image to the partition start. In this case the ntfs partition.
formula:
Sector size * Start = Offset
512 * 18432 = 9437184
Mount the image, passing the offset for the desired partition.
In this example the ntfs partition.
sudo mount -o loop,offset=9437184 /work/loop_test/disk_image.img /mnt/ntfs_partition
| Can't mount disk image |
1,291,477,658,000 |
I have generated an image file with dd. The image contains two partitions.
I created a loop virtual disk: losetup -P /dev/loop0 $image_file. I mounted the two loop created partitions (loop0p1, loop0p2) to two mounting points.
My problem is the loop disk is too small for the files I want to add. I looked into the options of losetup, without avail.
Is there a way to increase the loop disk?
|
You cannot do that: the way the loopback device in the Linux kernel works it uses the image file size to operate on it and it won't write beyond it.
The only way to achieve what you want is to umount the image, increase its size/repartition it, run resize2fs or whatever FS you're using to resize partitions and then mount it back.
| How to increase the size of a loop virtual disk? |
1,291,477,658,000 |
I have a iscsi disk 2TB large. I make backup of that disk every week. The backup script copies the image of the whole iscsi disk into a file on my NFS. Unfortunately, it does not copy the image in one piece, but splits it into chunks 1TB in size. So in my case, I have two 1TB files (plus one config file):
-r--r----- 1 root root 1099511627776 May 10 02:12 Backup-LUN-itmp-lun-0.000
-r--r----- 1 root root 1099500093440 May 10 03:50 Backup-LUN-itmp-lun-0.001
-rw-r--r-- 1 root root 251 May 10 03:50 Backup-LUN-itmp-lun-0.conf
Now I need to access my backup. Normally, if it was one file, I would map it to /dev/loop0 and then mount it as normal disk. But in my case, I cannot map two files to /dev/loop0. One option would be to cat those two files to create one large file, but I don't have extra 2TB space, and besides this is not a good solution anyway.
Can somebody please suggest a solution?
UPDATE
I have tried using dmsetup with linear target, as suggested by Andreas Wiese, but I get following error.
dmsetup create my-backup << EOF
> 0 2147483648 linear Backup-LUN-itmp-lun-0.000 0
> 2147483648 2147461120 linear Backup-LUN-itmp-lun-0.001 0
> EOF
device-mapper: reload ioctl on my-backup failed: Invalid argument
Command failed
dmesg contains following error:
device-mapper: table: 254:0: linear: dm-linear: Device lookup failed
device-mapper: ioctl: error adding target to table
|
What you want to do could be accomplished using Device Mapper (to be configured via dmsetup(8)). If the data in the two files is really a linear dump of your volume, you could create a DM device composed of several block devices which you could create from the files from loop-devices, similar to this:
# losetup /dev/loop0 /path/to/Backup-LUN-itmp-lun-0.000
# losetup /dev/loop1 /path/to/Backup-LUN-itmp-lun-0.001
# size1=$(blockdev --getsz /dev/loop0)
# size2=$(blockdev --getsz /dev/loop1)
# dmsetup create my-backup << EOF
0 $size1 linear /dev/loop0 0
$size1 $size2 linear /dev/loop1 0
EOF
This reads a table describing your DM device from stdin and creates a block-device called /dev/mapper/my-backup which you should be able to use like any other block-device.
The table format is
<start-sector> <length> <target> <target-args>
<start-sector> and <length> describe start and length (in sectors of 512 bytes) of a part of your DM device, <target> would be linear for, well, linear assembly. The arguments for the linear target are the device to use and the offset inside the device (so if for example your backup software writes some kind of header in front of the dump you could skip this), in this example it's 0 which would be appropriate for a raw dump.
Thus the above example assembles the my-backup device so that the first part is mapped from Backup-LUN-itmp-lun-0.000 (via loop0) and the second part from Backup-LUN-itmp-lun-0.000 (via loop1).
In case your backup isn't just a linear dump (like using dd and splitting the output into multiple files) you could try to get lucky with the other DM targets.
Edit: DM only maps block devices, not files, so added the losetup part. With this you could also use blockdev --getsz and won't have to worry about sizes, as the example shows.
| mapping a split file to /dev/loop0 |
1,291,477,658,000 |
I have multiple external storage-spaces which can be mounted with samba/cifs.
Over these spaces I want to create a raid device.
My idea was the creation of data files with
dd if=/dev/zero of=/extStorages/storage[0..x]/data
Now I created loop devices with
losetup /dev/loop[0..x] /extStorages/storage[0..x]/data
And create the raid device on top of the loop devices
mdadm --create /dev/md/md0 --level=<level> --raid-devices=x /dev/loop0 .. /dev/loopx
mkfs.ext4 /dev/md/md0
mount /dev/md/md0 /Storage
This is working until the next reboot as the loop devices are not persistent.
Therefore mounting the raid on fstab isn't possible.
How can I solve this?
|
I wrote a init.d script which start and stop the volume:
#! /bin/sh
### BEGIN INIT INFO
# Provides: networkRaid
# Required-Start: $network $named $remote_fs $syslog
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: handles the 'network raid'
### END INIT INFO
PATH=/sbin:/usr/sbin:/bin:/usr/bin
. /lib/init/vars.sh
. /lib/lsb/init-functions
do_start() {
losetup /dev/loop0 /extDrives/drive0/data
losetup /dev/loop1 /extDrives/drive1/data
losetup /dev/loop2 /extDrives/drive2/data
mdadm --assemble /dev/md0 /dev/loop0 /dev/loop1 /dev/loop2
mount /dev/md0 /Storage
}
do_stop() {
umount /Storage
mdadm --stop /dev/md0
losetup -d /dev/loop0
losetup -d /dev/loop1
losetup -d /dev/loop2
}
case "$1" in
start)
do_start
exit 0
;;
restart|reload|force-reload)
echo "Error: argument '$1' not supported" >&2
exit 3
;;
stop|status)
do_stop
exit 0
;;
*)
echo "Usage: $0 start|stop" >&2
exit 3
;;
esac
| Persistent use of loop block device in mdadm |
1,641,448,393,000 |
I discovered that is not possible to run fsck on a loopback device at boot by the fsck flag inside the fstab file, nor is it possible to accomplish this by manually running fsck when the loop device is mounted.
Is there an alternative to check the device at boot time?
|
I found an elegant and reliable solution.
I have writteng a script for then"/etc/initramfs-tools/scripts/local-premount/" boot phase in order to process my loop disk just before the file system mounting.
Below the details:
Create the script into /etc/initramfs-tools/scripts/local-premount/.
Update the initrd.img by the command update-initramfs -u.
Here is the script source:
#!/bin/sh
# Antonio Petricca <[email protected]> - 03/01/2018
PREREQ=""
# Output pre-requisites
prereqs()
{
echo "$PREREQ"
}
case "$1" in
prereqs)
prereqs
exit 0
;;
esac
. /scripts/functions
log_begin_msg "Running file system check on loop device(s)"
DEV=/dev/sdb5
MNT=/tmp/mnt
LOOP=$MNT/.linux-loops/242eef08-32d6-42c2-93eb-afdc2111a13e.ext4
mkdir $MNT && \
mount -t ntfs $DEV $MNT && \
fsck.ext4 -p -v $LOOP && \
umount $MNT
# Uncomment next line to hold messages for debugging
# sleep 10
log_end_msg "Done"
# Continue boot anyway
exit 0
Regards!
| Fsck at boot time for loopback device |
1,641,448,393,000 |
Loop devices, i.e. for mounting raw disk images, can be managed without root privileges using udisks.
For testing purposes, an image can be created and formatted like so:
dd if=/dev/urandom of=img.img bs=1M count=16
mkfs.ext4 img.img
And then setup using udisks
udisksctl loop-setup -f img.img
This creates a loop device for the image and mounts it to a new directory under /run/$USER, just like any local hard drive managed by udisks. Only the permissions are not what I expected.
# ls -l /run/media/$USER/
drwxr-xr-x 3 root root 1024 Apr 10 11:19 [some id]
drwx------ 1 auser auser 12288 Oct 30 2012 [a device label]
The first one listed is the loop device, owned by root and not writable by anybody else. The second one is a local hard drive or an USB pen device mounted for comparison, belonging to the user who mounted it. I know that I could fix this with a simple chmod executed as root.
But why does udisks assign different permissions and owners? Can it be configured to do otherwise?
|
I had a detailed look into the udisks2 source code and found the solution there.
The devices correctly mounted under user permissions were formatted with old filesystems, like fat. These accept uid= and gid= mount options to set the owner. Udisks automatically sets these options to user and group id of the user that issued the mount request.
Modern filesystems, like the ext series, do not have such options but instead remember owner and mode of the root node. So chown auser /run/media/auser/[some id] indeed works persistently. An alternative is passing -E root_user to mkfs.ext4 which initializes uid and gid of the newly created filesystem to its creator.
| Mount image user-readable with udisks2 |
1,641,448,393,000 |
Let's suppose I create a file, map it to /dev/loop0, and create a LUKS partition inside
dd if=/dev/zero of=myfile bs=1M count=1000
losetup /dev/loop0 myfile
cryptsetup -c aes-cbc-essiv:sha256 -s 256 -v -y luksFormat /dev/loop0
I then open the encrypted partition
cryptsetup luksOpen /dev/loop0 myfile
Now, I have my encrypted file appear as a disk /dev/mapper/myfile. I need to create a filesystem before I can use it.
Here is my question:
Given that this my new filesystem-inside-file resides on another ext4 filesystem (which already is using journal), what options would be best for this new filesystem ?
Specifically, if I format my new filesystem-inside-file ext4, should I use journal?. Somehow, the idea of journal filesystem inside another journal filesystem seems not right to me, intuitively.
|
From my experience running an encrypted reiserfs with private information you should not put that on an journalling filesystem like ext3. I switched back from ext3 to having the file on an ext2 partition after I had to restore from a backup.
Over the years ( I have had this file for 5 years ), I had to run recovery several times, and when hosted on ext3 this was the only time reiserfsck could not recover. I think that was because ext3 did a recover which confused the internals of the encrypted disk.
I never tried a non-journal filesystem on a journal filesystem (e.g. encrypted ext2 file on reiserfs) for me the important (i.e. encrypted data should be journalled).
I am still running reiserfs, never used ext4 for this (but I am considering btrfs, just need to check some time if that is stable enough)
If you put your homedirectory on there, be prepared that this feels a bit sluggish, I don't think any finetuning with parameters could have helped that, and I don't think the ext4 ones will influence things much, given that encryption is a performance penalty hit in all directions.
| File containing ext filesystem |
1,641,448,393,000 |
I am doing a project in which I need to mount 100+ loop devices and merge it into AUFS mountpoint
As an observation, for sequentially mounting 90 loop devices, it takes 25 seconds.
I am looking for a solution which will minimize time by mounting loop devices in parallel
|
I think this is obvious, but
typeset -i M=1
while [ $M -le 102 ]
do
mount mysourcedevice$M targetdir$M &
let M++
done
wait
Should do the job. The wait will wait until all sub-processess are finished, before executing the next command.
| Loop Mounting in Parallel |
1,641,448,393,000 |
/dev/sda5 is mounted at / and it's my filesystem
piotr@thinkpad:~$ sudo mkdir /home/mpoint
piotr@thinkpad:~$ sudo mount /dev/sda5 /home/mpoint
so now I can do:
piotr@thinkpad:~$ cd /home/mpoint/home/mpoint
and when I'm in second mpoint directory, it's empty.
My questions are:
Why is it possible to "loop" a filesystem by mounting it to one of its folders?
Why this second mpoint dir is empty?
|
When mounting a file system one add an extra layer for the system. The mount-point is an absolute path that normally hides the contents of the target. To have a closer look using stat can be of help. I.e:
First prepare a test case:
# mkdir /mnt/other
# echo hi > /mnt/other/hello.txt
# cat /mnt/other/hello.txt
hi
# stat -c %i /mnt/other
6424680
Then mount
# mount / /mnt/other
# cat /mnt/other/hello.txt
cat: cannot access '/mnt/other/hello.txt': No such file or directory
# stat -c %i /mnt/other
2
# stat -c %i /
2
# stat -c %i /mnt/other/mnt/other
6424680
# cat /mnt/other/mnt/other/hello.txt
hi
As you can see the inode for the mount-point changes from inode 6424680 to 2 (which is the inode for root directory1). The contents of that directory is hidden as far as the mount point is concerned, but still present on the disk. It is a layer above the file-system.
1 and parent to root, . and ..
The path /mnt/other/mnt/other is not a mount-point and holds the original content for the inode of that directory. In your case it is empty, in my case it has one file; Though you could make it a mount point as well:
# mount / /mnt/other/mnt/other
# stat -c %i /mnt/other/mnt/other
2
# stat -c %i /mnt/other/mnt/other/mnt/other
6424680
# cat /mnt/other/mnt/other/mnt/other/hello.txt
hi
As for why, then why not. Unless it damages the system let the user do what ever they want. That's not saying one can not do things that damages the system albeit in this case the incentive to add a blocker is not present from what I can see. For what ever reason people might even want to create another view at a mount-point even of the root tree itself.
Further *nix systems have a single directory tree as opposed to e.g. Windows with drives that has letters A:, B:, C:, …. As per start of man mount:
All files accessible in a Unix system are arranged in one big tree, the file hierarchy, rooted at /. These files can be spread out over several devices. The mount command serves to attach the filesystem found on some device to the big file tree.
| Why is it possible to "loop" a filesystem by mounting it to one of its folders? |
1,641,448,393,000 |
When I create a 400MB file called /tmp/foo, then call losetup -f /tmp/foo, this creates a loop device /dev/loop15. If I then partition the loopdevice and format it to contain ext4,ntfs, and fat32 filesystems respectively, then run lsblk, I get the following:
loop15 7:15 0 390,6M 0 loop
├─loop15p1 259:8 0 100M 0 part
├─loop15p2 259:9 0 200M 0 part
└─loop15p3 259:10 0 83M 0 part
under /etc/dev there is then loop15, loop15p1, loop15p2, and loop15p3.
but after calling losetup -d /dev/loop15 to unbind the loop device, then recall losetup -f /tmp/foo to rebind it, then when running gparted or KDE disk manager, both show me that there are 3 partitions on the device, but all of them unformatted. If I run lsblk -f or ls /dev/loop* I see /dev/loop15, but the partitions are gone.
Is there a way to make the filesystems persistent across un-/binds? How do I restore the blockdevice nodes to the partitions (loop15p1,loop15p2,loop15p3...)?
|
You need to run losetup with -P/--partscan to tell kernel to scan for partitions on the device, it's not enabled by default for loop devices so the partition device nodes are not created without this option.
| Loop partitions disappear on rebind |
1,641,448,393,000 |
I created a file
touch /datastore/virtual/pseudoblock
created a loop device with it
sudo losetup /dev/loop0 /datastore/virtual/pseudoblock
(although I got a warning about its size)
and then initialized it with random data
dd if=/dev/urandom of=/dev/loop0 bs=1M count=100
My questions are
a) why is it not displayed yet in my block devices' list?
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sdb 8:16 0 489.1G 0 disk
├─sdb2 8:18 0 488M 0 part /boot
├─sdb3 8:19 0 488.1G 0 part
│ └─sdb3_crypt 253:0 0 488.1G 0 crypt
│ ├─ubuntu--vg-root 253:1 0 472.2G 0 lvm /
│ └─ubuntu--vg-swap_1 253:2 0 15.9G 0 lvm [SWAP]
└─sdb1 8:17 0 512M 0 part /boot/efi
sda 8:0 0 931.5G 0 disk
└─sda1 8:1 0 931.5G 0 part
└─sda1_crypt 253:3 0 931.5G 0 crypt
└─store--vg-store1tb 253:4 0 931.5G 0 lvm /datastore
b) how can I permanently mount it via /etc/fstab since I cannot get its UUID?
$ blkid
/dev/mapper/sdb3_crypt: UUID="fSHjbj-51K2-QfhI-G0Wb-o3lN-4pE1-BB4wCP" TYPE="LVM2_member"
/dev/mapper/ubuntu--vg-root: UUID="9e452886-4d8g-fj54-854c-80bc171826e8" TYPE="ext4"
working on
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 16.04.5 LTS
Release: 16.04
Codename: xenial
with
$ uname -a
Linux pkara-pc01 4.15.0-42-generic #45~16.04.1-Ubuntu SMP Mon Nov 19 13:02:27 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
|
You're missing steps about creating a filesystem.
dd if=/dev/urandom of=pseudoblock bs=1M count=100
losetup /dev/loop0 pseudoblock
Now you can create a filesystem on it.
mkfs.ext4 /dev/loop0
Once this is done, I can get an UUID (this identifies the filesystem, so if you haven't created one, you won't get an UUID), and then find it.
blkid
/dev/vda1: UUID="a76b548b-f4e4-4616-bea0-469775cb852d" TYPE="ext4" PARTUUID="8395c684-01"
/dev/loop0: UUID="bb784e83-8484-4822-8930-20e02f689450" TYPE="ext4"
Then I mount it, and I can write things in it.
mount /dev/loop0 /mnt/loop
And once that pseudo block device is initialized with a filesystem you can mount it directly with the fstab using a line like (no need to use losetup anymore, and there's no really need for an UUID, the file is not like /dev devices that could get probed in different order, it won't move, so it's no problem using its absolute path).
/root/pseudoblock /mnt/loop auto loop 0 0
| Permanently mounting loop device |
1,641,448,393,000 |
I'm using debootstrap to create a rootfs for a device that I want to then write to an image file. To calculate the size needed from my rootfs, I do the following:
local SIZE_NEEDED=$(du -sb $CHROOT_DIR|awk '{print $1}')
SIZE_NEEDED=$(($SIZE_NEEDED / 1048576 + 50)) # in MB + 50 MB space
dd if=/dev/zero of=$ROOTFS_IMAGE bs=1M count=$SIZE_NEEDED
As you can see I'm leaving 50MB of padding beyond what dd calculates I need.
I then create the loopback device, create a partition table and filesystem:
LO_DEVICE=$(losetup --show -f $ROOTFS_IMAGE)
parted $LO_DEVICE mktable msdos mkpart primary ext4 0% 100%
partprobe $LO_DEVICE
local LO_ROOTFS_PARTITION="${LO_DEVICE}p1"
mkfs.ext4 -O ^64bit $LO_ROOTFS_PARTITION
It seems parted attempts to do some sector alignment (?) as the partition doesn't quite take up the whole virtual disk, but close enough.
I then mount the new partition and start writing files. But then I run out of disk space right near the end!
mount $LO_ROOTFS_PARTITION $LO_MOUNT_POINT
cp -rp $CHROOT_DIR/* $LO_MOUNT_POINT
.....
cp: cannot create directory '/root/buildimage/rootfs_mount/var': No space left on device
I suspect this is some block size conversion issue or maybe difference between MiB and MB? Because up to a certain image size, it seems that I have enough headroom with the 50MB of padding. (I want some free space in the image by default, but not a lot.) The image size isn't off by a factor-of-two so there's some creep or overhead that gets magnified as the image size gets larger and I'm not sure where it's coming from.
For context, here's the last one I did that doesn't fit:
# du -sb build/rootfs
489889774 build/rootfs
Ok, 489MB/1024**2 + 50MB = 517MB image size. So dd looked like:
# dd if=/dev/zero of=build/rootfs.img size=1M count=517
517+0 records in
517+0 records out
542113792 bytes (542 MB, 517 MiB) copied, 2.02757 s, 267 MB/s
Confirmed on disk it looks slightly larger:
# du -sb build/rootfs.img
542113792 build/rootfs.img
The partition looks like:
# parted /dev/loop0 print
Model: Loopback device (loopback)
Disk /dev/loop0: 542MB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:
Number Start End Size Type File system Flags
1 1049kB 542MB 541MB primary ext4
and mounted filesystem:
# df -h /dev/loop0p1
Filesystem Size Used Avail Use% Mounted on
/dev/loop0p1 492M 482M 0 100% /root/buildimage/build/rootfs_mount
So maybe there is overhead in the ext4 filesystem, possibly for superblocks/ journal/ etc? How can I account for that in my size calculation?
EDIT:
Looking into ext4 overhead such as this ServerFault question.
Also looking into mkfs.ext4 options such as -m (reserved) and various journaling and inode options. In general if I know there's a 5% overhead coming from the filesystem, I can factor that in easily enough.
EDIT #2:
Thinking that du might be under-reporting actual on-disk size requirements (e.g. a 10-byte file still takes up a 4k block, right?) I tried a few other options:
# du -sb build/rootfs # This is what I was using
489889774 build/rootfs
# du -sm build/rootfs # bigger
527 build/rootfs
# du -sk build/rootfs # bigger-est
539088 build/rootfs
Furthermore, the manpage for -b notes that it's an alias for --apparent-size which can be smaller than "actual disk usage." So that may be (most) of where my math was wrong.
|
Possibly the simplest solution is to heavily overprovision the space initially, copy all the files, then use resize2fs -M to reduce the size to the minimum this utility can manage. Here's an example:
dir=/home/meuh/some/dir
rm -f /tmp/image
size=$(du -sb $dir/ | awk '{print $1*2}')
truncate -s $size /tmp/image
mkfs.ext4 -m 0 -O ^64bit /tmp/image
sudo mount /tmp/image /mnt/loop
sudo chown $USER /mnt/loop
rsync -a $dir/ /mnt/loop
sync
df /mnt/loop
sudo umount /mnt/loop
e2fsck -f /tmp/image
resize2fs -M /tmp/image
newsize=$(e2fsck -n /tmp/image | awk -F/ '/blocks$/{print $NF*1024}')
truncate -s $newsize /tmp/image
sudo mount /tmp/image /mnt/loop
df /mnt/loop
diff -r $dir/ /mnt/loop
sudo umount /mnt/loop
Some excerpts from the output for an example directory:
+ size=13354874
Creating filesystem with 13040 1k blocks and 3264 inodes
+ df /mnt/loop
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/loop1 11599 7124 4215 63% /mnt/loop
+ resize2fs -M /tmp/image
Resizing the filesystem on /tmp/image to 8832 (1k) blocks.
+ newsize=9043968
+ truncate -s 9043968 /tmp/image
+ df /mnt/loop
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/loop1 7391 7124 91 99% /mnt/loop
| How to calculate the correct size of a loopback device filesystem image for debootstrap? |
1,641,448,393,000 |
I'm trying to loop mount my root filesystem (a loop file) within a busybox initramfs.
I try to run the command:
mount /rootfs.raw /root
... which works on my Ubuntu laptop, however, I simply get
mount: mounting /dev/loop0 on /root failed: Invalid argument
No matter what combination of options I use, (including loading to /loop0 manually and trying to mount it), the system will not mount the loop device.
Why can't I mount it?
|
In order to solve this problem, I had to be more verbose about my mounting command. I ended up using:
modprobe loop
mount -t iso9660 -o loop /bootpart/rootfs.raw /root
This worked properly.
| busybox initramfs loop mount |
1,641,448,393,000 |
I have a loop device which shows up when I do losetup --all that I have been unable to remove.
So, I basically got myself into this issue because a created a raw image of a microSD card and then I used kpartx to mount the partitions contained within the image.
The commands that I initially used to mount the image and partitions were as follows:-
user@server:~$ sudo kpartx -arsv '/path/to/microsd.img';
add map loop1p1 (254:12): 0 819168 linear 7:14 32
add map loop1p2 (254:13): 0 29351936 linear 7:14 819200
user@server:~$ sudo mount /dev/mapper/loop1p2 /mnt/sdimage1p2;
user@server:~$ ls -alh /mnt/sdimage1p2;
As this was just a test I then wanted to unmount remove the loop device, so I ran the following commands, I have tried running them in different orders so see if my ordering was the problem.
sudo umount /mnt/sdimage1p2;
sudo dmsetup info;
sudo losetup --detach /dev/mapper/loop1p1;
sudo losetup --detach /dev/mapper/loop1p2;
sudo losetup --detach /dev/mapper/loop1;
sudo dmsetup remove /dev/mapper/loop1p1;
sudo dmsetup remove /dev/mapper/loop1p2;
sudo kpartx -dsv '/path/to/microsd.img';
sudo losetup --all;
Also dmsetup info returns no devices found.
But losetup --all returns the following:-
/dev/loop1: [2082]:1809010 (/path/to/microsd.img)
I have also tried the following commands which return nothing.
fuser -c /dev/loop1;
fuser -f /dev/loop1;
I have also tried lsof | grep loop this returns the output below.
loop1 10693 root cwd DIR 8,2 4096 2 /
loop1 10693 root rtd DIR 8,2 4096 2 /
loop1 10693 root txt unknown /proc/10693/exe
But I was unsure what to do with the above information, I did try kill -9 10693 but that didn't work, the PID 10693 does show up in htop.
user@server:~$ ps -fp 10693
UID PID PPID C STIME TTY TIME CMD
root 10693 2 0 08:17 ? 00:00:00 [loop1]
|
Since the PPID is 2, this process 10693 is a kernel process, and that explains why your kill -9 did not work.
You said you have tried sudo losetup --detach /dev/mapper/loop1. That was almost but not quite correct: try sudo losetup -d /dev/loop1 instead. But it only works after the partition loop devices have already been removed, so if you tried it before your sudo losetup --detach /dev/mapper/loop1p* commands, it would have failed.
The fewest commands to achieve the removal of the loop devices would probably have been something like:
sudo umount /mnt/sdimage1p2
sudo kpartx -d /dev/loop1
sudo losetup -d /dev/loop1
exactly in this order.
| Can't remove or unmount loop device on Debian |
1,641,448,393,000 |
I want to mount the contents of an iso9600 (CD) image via a loop to access its contents. To do so I execute
mount -r -t iso9600 -o loop file.iso mountpoint/
and would expect the contents in the (existing) directory mountpoint.
However, I get mount: mounting /dev/loop0 on mountpoint/ failed: No such device.
What are the likely reasons for this?
|
There are multiple reasons I can think of. Probably the more common one is that something with the loop devices is not in order, e.g., there are too many loop device in use already. You can check if this is the case by setting up the loop device manually:
# losetup --find --show file.iso
/dev/loop0
# mount -o ro /dev/loop0 mountpoint/
...
# losetup --detach /dev/loop0
If the first command does not print a legal loop device (/dev/loop*) but gives an error message then the infrastructure for loop devices themselves is somehow the issue. See if losetup -a shows any devices. The maximum number might be reached. In that case you could try creating more via the module's max_loop option (and reboot) or manually with mknod as explained in this answer.
However, there is another option that is explained concisely in the mount syscall's manpage:
ENODEV filesystemtype not configured in the kernel.
Your kernel might not support the required file system.
In the example above using a CD image this would be iso9660.
Try loading the respective module via
# modprobe iso9660
and retry. If you get modprobe: module iso9660 not found then you are kind of out of luck because your kernel does not support the file system at all and there is no easy way to enable it. You can verify the supported filesystems listed in /proc/filesystems. To make it work you have to recompile the kernel or at least the respective module (matching the exact kernel version of course).
PS: The module is named isofs in newer kernels but at least for modprobe and friends there exists an alias iso9660.
| Why does mount -o loop return "No such device"? |
1,641,448,393,000 |
I'm having an issue with loopback. It looks like there is only 8. I did a search and apparently the problem is grub by default only has 8 loopback (devices?). If i look in /dev/ i see loop 0-7 so that does seem to make sense.
How do i change the amount of loopbacks?
|
I'm not sure how GRUB comes into this, as you don't explain the connection, but you can increase the number of simultaneously usable loop devices using the loop module (without a reboot).
modprobe loop max_loop=64
You can then manually make more loop devices with mknod like so:
mknod -m 660 /dev/loop8 b 7 8
Make sure the new loop device is owned by root:disk for consistency:
chown root:disk /dev/loop8
In the mknod command:
The major number for loop devices is 7. That's what the 7 represents (constant for all loop devices)
The minor number is unique for each loop device. It starts from 0 for /dev/loop0, 1 for /dev/loop1, and so on.
The 8 represents the minor number for /dev/loop8.
So, for /dev/loop9, you would increase the minor number by one:
mknod -m 660 /dev/loop9 b 7 9
Here's a shell command to create a large number of them at one time (starting with 10 through 254):
for i in {10..254}; do
mknod -m 660 /dev/loop$i b 7 $i
chown root:disk /dev/loop$i
done
| Grub change loopback amount? |
1,641,448,393,000 |
When mounting a filesystem image via mount -o loop, is there any mechanism to prevent the same file to be mounted a second time?
|
There is no specific command that may stop the file to be mounted several times with different mountpoints, but you may use this script to not mount it if it is already mounted:
#!/bin/bash
mount |grep -qF "$1" || mount "$1" $2 -o loop
the first parameter is a file to mount, and second is a mount point to use.
| How to make sure a loopfile is only mounted once? |
1,641,448,393,000 |
To be able to test out of disk situations I tried to set up a file-based size-limited file system like this:
$ dd if=/dev/zero of=file.fs bs=1MiB count=1
$ mkfs.ext4 file.fs
$ udisksctl loop-setup -f file.fs
Mapped file file.fs as /dev/loop1.
$ udisksctl mount --options rw -b /dev/loop1
Mounted /dev/loop1 at /media/myuser/29877abe-283b-4345-a48d-d172b7252e39
$ ls -l /media/myuser/29877abe-283b-4345-a48d-d172b7252e39/
total 16
drwx------ 2 root root 16384 Dec 2 22:08 lost+found
But as can be seen, it's made writable only for root. How do I make it writable for the user that is running the commands?
I can't chown or chmod it since that also gives "Operation not permitted".
I tried with some options to udisksctl like -o uid=<id> but then I get an error about that mount option not being allowed.
Since this should be able to run for normal users I can't use root or sudo.
I am on Ubuntu 22.04.1.
|
Yeah, that's kind of mean :) But you can work around:
mkfs.ext4 takes a -d directory/ option with which you can specify a directory containing an initial content for the file system; if you already know which directories you'll later want to populate, that would be a good place to start.
mkfs.xfs supports -p protofile; that probably does exactly what you want to do. A file myprotofile containing naught but:
thislinejustforbackwardscompatibility/samefornextline
1337 42
d--777 1234 5678
where the first line is just a single string for backwards compatibility, which will be ignored; the second line must contain two numbers that will be ignored. (See man mkfs.xfs for more details than I remember from the top of my head.)
The third line contains a filemode uid gid tuple, describing the root directory. Replace 1234 with your user id of choice, and 5678 with the group id of your choice.
A subsequent
mkfs.xfs -p myprotofile -f file.fs
should do (but your image file needs to be at least 16 MB in size for a default-configure mkfs.xfs), so
dd if=/dev/zero of=file.fs bs=1MiB count=16
mkfs.xfs -p myprotofile -f file.fs
udisksctl loop-setup -f file.fs
works and automounts the filesystem rw on my system (but that's not necessarily the case on your system – your mount thing should work; but --options rw seems a bit superfluous).
| Create writable file system using udisksctl |
1,641,448,393,000 |
I tried the process from this post resize partition on an image file. I didn't succeed in understanding why it goes wrong in my case.
I produced a 8GB image using dd. The image contains two partitions.
I map the image with losetup -P /dev/loop0 $image-file.
Then:
resize2fs /dev/loop0p2 4000M
resize2fs 1.44.1 (24-Mar-2018)
Resizing the filesystem on /dev/loop0p2 to 1536000 (4k) blocks.
The filesystem on /dev/loop0p2 is now 1536000 (4k) blocks long.
e2fsck -f /dev/loop0p2 ->>> clean
parted /dev/loop0
(parted) resizepart 2 4000MB` ; print gives 4GB partition
(parted) quit
partprobe -s /dev/loop0
lsblk /dev/loop0
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
loop0 7:0 0 7,5G 0 loop
├─loop0p1 259:2 0 256M 0 loop
└─loop0p2 259:3 0 3,5G 0 loop
root@O3:/home/m/tmp# e2fsck -f /dev/loop0p2
e2fsck 1.44.1 (24-Mar-2018)
The filesystem size (according to the superblock) is 1903360 blocks
The physical size of the device is 1154143 blocks
**Either the superblock or the partition table is likely to be corrupt**!
Abort? yes
The partition resize with parted creates the inconsistency, because after resize2fs the e2fsck is clean.
Any ideas to explore to be able to shrink the image file?
|
Thank you @sudodus and @fra-san.
I think there is a compatibility issue when combining resize2fs and parted for shrinking a fs/partition. resize2fs uses 4k blocks, when parted uses Byte or MB, GB etc.
I eventually found another way to shrink the 2nd partition: gnome-disks. It is provided with Linux Mint and works pretty well. Where parted and gparted failed in shrinking the 2nd partition, gnome-disks succeeded in resizing both fs and partition, in one operation.
After the fs/partition shrink, there was trailing empty space in loop0p2. I want to shrink the image file. So, I did:
root@O3:/home/m# fdisk -l /dev/loop0
Disk /dev/loop0: 7,5 GiB, 8068792320 bytes, 15759360 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x8889db7f
Device Boot Start End Sectors Size Id Type
/dev/loop0p1 8192 532479 524288 256M c W95 FAT32 (LBA)
/dev/loop0p2 532480 8355839 7823360 3,7G 83 Linux
truncate size? (8192 + 524288 + 7823360) * 512 = 4278190080 B
truncate --size=4278190080 image-file.img
After mapping again the resulting image file to loop0, no more fs/partition errors.
| How to shrink a file image, produced with dd? |
1,641,448,393,000 |
By mistake, I deleted an lxc image file. The container is still running and the file is therefore not yet actually deleted until I stop the container. I'd like to avoid stopping the container as it is quite sensitive.
I tried to find the deleted file with:
for i in $(ls /proc/|grep '^[0-9]*$'); do ls -l /proc/$i/fd|grep delete; done
But this doesn't find my loop device. Same with a simple lsof | vm-
If I run lsof on another image that is not delete, it doesn't show me any process using it: lsof /var/lib/vz/images/100/vm-100-disk-0.raw. Probably because it's open by the kernel, not a process.
As suggested in comment:
# losetup -l
NAME SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE DIO
/dev/loop1 0 0 1 0 /var/lib/vz/images/200/vm-200-disk-0.raw (deleted) 0
/dev/loop0 0 0 1 0 /var/lib/vz/images/100/vm-100-disk-0.raw 0
I tried:
debugfs /dev/mapper/pve-data
debugfs: cd images/200
debugfs: lsdel
Inode Owner Mode Size Blocks Time deleted
0 deleted inodes found.
I guess that's because it's not deleted yet. It is a bit risky to just let it get deleted and hope that it appears here and doesn't get corrupted (it's >300Gb)
Inside the container, mount gives:
/var/lib/vz/images/200/vm-200-disk-0.raw (deleted) on / type ext4 (rw,relatime,data=ordered)
Any solution apart from dumping the entire filesystem and recreating the container entirely ? (Also, the host drive is almost full, I don't have enough space right now to create a second container next to it. I'm afraid that downsizing the storage would actually result it the actual deletion. :(
|
[not a complete answer, but too long to put in a comment]
You can find the inode of a (possibly deleted) backing file of a loop device with the LOOP_GET_STATUS or LOOP_GET_STATUS64 ioctls: it's the .lo_inode field of the loop_info and loop_info64 structs.
As I wasn't able to find any command line utility exposing that info, here is perl one-liner that should do it:
perl -le 'ioctl STDIN, 0x4C05, $s = pack "a512" or die "ioctl: $!"; print unpack "x[Q]Q", $s' </dev/loop1
1179684
More info in the loop(4) manpage and in the /usr/include/linux/loop.h file.
But I don't know if there's any safe way to resurect a deleted file by its inode: I don't think that you can use debugfs(8) on a mounted live file system without corrupting it beyond repair, and there's no way to create a link to a deleted file.
The only safe way I can think of is to copy the whole loop device / partition while it's still live:
cp --sparse=always /dev/loop1 /path/where/to/save/it
| Recover deleted but mounted loop file/filesystem |
1,641,448,393,000 |
in an attempt to access a truecrypt container, I stumbled about the prerequisite of setting up a loop device...
ncoghlan suggested in an earlier answer
When you run it as root, losetup -f will automatically create loop devices as needed if there aren't any free ones available.
So rather than doing it yourself with mknod, the easiest way to create a new loop device is with sudo losetup -f. That approach will give you a free existing loop device if one exists, or automatically create a new one if needed.
My result of "sudo losetup –f" is
losetup: –f: failed to use device: No such file or directory
Searching for this message+losetup so far does not help.
Result of "lsmod |grep loop" is
loop 28672 0
uname -r
4.5.7-200.fc23.x86_64
|
Serge's comment made me do my homework - study the man page in more depth than before. The solution was simply to enter in the shell
losetup
(without any arguments). Then, afterwards,
losetup -f
resulted, successfully, in
/dev/loop0
| how to add a loop device on fedora 23 with losetup? |
1,641,448,393,000 |
I want to create a loop device myself, I want it to have a special name, say /dev/loop-test-0. I want it to be up after I reboot the machine. I though that I can use mknod for this, but this doesn't seem to work. I look on the other loop device I have in the system and they all look like
brw-rw----. 1 root disk 7, 0 Jul 27 09:35 /dev/loop0
I added number with mknod /dev/loop8 b 7 8 so it looks like
brw-rw----. 1 root disk 7, 8 Jul 27 11:32 /dev/loop8
When I use losetup /dev/loop8 testfs I get losetup: /dev/loop8: failed to set up loop device: No such device or address while when I use losetup /dev/loop0 testfs I get no error.
What is the problem? I don't want to use
echo loop > /etc/modules-load.d/loop.conf
echo options loop max_loop=8 > /etc/modprobe.d/eightloop.conf
I want to create loop devices myself, is it possible?
|
A loop device is a particular type of block device, managed by the loop device driver. A loop device is a block device whose content is stored in a file, similar to the way a SCSI disk device is a block device whose content is stored on a SCSI disk, a USB storage device is a block device whose content is stored on a USB storage peripheral, etc.
Linux has a kernel parameter which determines the number of loop devices that can be used on the system. Creating entries in /dev will not change that number: you have as many devices as the driver allows, no more. If you create additional entries, there's no driver to handle them, hence the error “No such device or address” (ENODEV) when you try to access that device.
On a modern Linux system (from the last decade or thereabouts), udev automatically creates entries in /dev, so creating entries manually is not needed — if the entry isn't there, it means you don't have the corresponding driver.
| What is the difference between loop device and block device? [closed] |
1,641,448,393,000 |
busybox (at least version 1.7, which I'm bound to use) to not provide the losetup -a switch to obtain a list of currently used loop devices plus the associated filename. Is there any way to obtain such a list with busybox?
|
From https://stackoverflow.com/questions/10832350/howto-find-the-file-for-a-loopmounted-device:
From losetup(8) man page
If only the loopdev argument is given, the status of the corresponding
loop device is shown.
So you only need to use
$ losetup /dev/loop1
/dev/loop1: [0802]:4751362 (/volumes/jfs.dsk)
If you have a recent kernel (2.6.37 or above), you can also get the target file in /sys/block/loopX/loop/backing_file.
$ cat /sys/block/loop1/loop/backing_file
/volumes/jfs.dsk
...
Substitite busybox losetup for losetup above.
| How to achieve `losetup -a` behaviour with busybox? |
1,641,448,393,000 |
I have backed up a drive with all its partitions using the command
dd if=/dev/sda of=/media/oshirowanen/external-drive/backups-2019/full_drive_backup.img
/dev/sda is an ssd which has a Linux OS with full encryption.
Before I wipe this drive and re-purpose it, I want to make sure the backup has worked.
I have tried the following by searching unix.stackexchange and other stackexchange sites:
sudo losetup -P /dev/loop0 /media/oshirowanen/external-drive/backups-2019/full_drive_backup.img
[sudo] password for oshirowanen: [password goes here]
losetup: /media/oshirowanen/external-drive/backups-2019/full_drive_backup.img: failed to set up loop device: Device or resource busy
sudo losetup -P /dev/loop100 /media/oshirowanen/external-drive/backups-2019/full_drive_backup.img
sudo cryptsetup luksOpen /dev/loop100p5 img5
Enter passphrase for /dev/loop100p5: [password goes here]
cd /mnt
mkdir img5
sudo mount /dev/mapper/img5 img5
mount: /mnt/img5: unknown filesystem type 'LVM2_member'.
What am I doing wrong? Both cryptsetup and lvm2 are already installed.
If this is not the best way to backup the drive, please suggest something else which is better.
UPDATE 1:
Here is a screenshot of /dev/sda's partitions:
UPDATE 2:
Output from LiveUSB:
liveusb@liveusb:~$ sudo losetup -P /dev/loop100 /media/external-drive/backups-2019/full_drive_backup.img
liveusb@liveusb:~$ sudo cryptsetup luksOpen /dev/loop100p5 img5
Enter passphrase for /dev/loop100p5:
liveusb@liveusb:~$ cd /mnt
liveusb@liveusb:/mnt$ sudo mkdir img5
liveusb@liveusb:/mnt$ sudo mount /dev/mapper/img5 img5
mount: /mnt/img5: unknown filesystem type 'LVM2_member'.
liveusb@liveusb:/mnt$ sudo pvscan
PV /dev/mapper/img5 VG ubuntu-vg lvm2 [232.16 GiB / 0 free]
Total: 1 [232.16 GiB] / in use: 1 [232.16 GiB] / in no VG: 0 [0 ]
liveusb@liveusb:/mnt$ sudo vgscan
Reading volume groups from cache.
Found volume group "ubuntu-vg" using metadata type lvm2
liveusb@liveusb:/mnt$ sudo vgs
VG #PV #LV #SN Attr VSize VFree
ubuntu-vg 1 2 0 wz--n- 232.16g 0
liveusb@liveusb:/mnt$ sudo lvs
LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert
root ubuntu-vg -wi-a----- <231.21g
swap_1 ubuntu-vg -wi-a----- 980.00m
liveusb@liveusb:/mnt$ ls /dev/mapper/
control img5 ubuntu--vg-root ubuntu--vg-swap_1
liveusb@liveusb:/mnt$
|
Judging from the image, the partition seems to be a physical volume. This is verified by pvscan.
lvs lists two logical volumes, one of them a swap partition (LV swap_1) it seems, and the other the actual file system (LV root). This is the relevant one, to be mounted by
mount -o ro /dev/mapper/ubuntu--vg-root /mnt/img5
When the devices are missing, vgscan --mknodes
--mknodes
Also checks the LVM special files in /dev that are needed
for active LVs and creates any missing ones and removes
unused ones.
or vgmknodes might be helpful
vgmknodes checks the LVM device nodes in /dev that are needed for
active LVs and creates any that are missing and removes unused
ones.
| Mounting a Luks partition |
1,641,448,393,000 |
I am trying to set up a virtual drive from a file. This file will then be written to a flash device (not relevant). Because creating and manipulating the virtual drive will be in a script, I need to do it in user space, i.e., not as root. The script is for building and creating an image for a flash device; so, running as root will be problematic.
In order to mount the file as a virtual drive, I added the following line to /etc/fstab:
/home/user/drive.img /home/user/mnt ext4 loop,rw,user,noauto,noexec 0 0
The problem is that when I mount the virtual drive, root takes ownership of ~/mnt, defeating the purpose of mounting it as a regular user.
I know that other file systems allow you to mount while specifying the uid/gid, but the virtual drive must be ext4 to be compatible with an existing process. I tried udisksctl, but it requires root authentication for loopback.
I am going to try mounting then changing ownership (as root) but never unmount it. I will do a 'sync' then take a snapshot of the virtual drive. I do not like it because it is not clean, but it may work for now.
|
The step you haven't mentioned is how you created the ext4 filesystem, which is the source of the problem. Using mkfs.ext4 /home/user/drive.img will create a root inode owned by root, so when you mount it, it will still belong to root.
The solution is to add option -E root_owner to make it belong to the user running mkfs.ext4, or even -E root_owner=$uid:$gid for some explicit numeric user and group id.
(Another solution is to use debugfs (package e2fsprogs for Fedora) to edit the inode.) This example worked for me:
uid=$(id -u)
gid=$(id -g)
rm -f /tmp/ext4fs
truncate -s 50M /tmp/ext4fs
if true
then mkfs.ext4 -E root_owner=$uid:$gid /tmp/ext4fs
else mkfs.ext4 /tmp/ext4fs
debugfs -w -R "set_inode_field . uid $uid" /tmp/ext4fs
debugfs -w -R "set_inode_field . gid $gid" /tmp/ext4fs
fi
# echo '/tmp/ext4fs /tmp/mymnt ext4 loop,rw,user,noauto,noexec' >>/etc/fstab
mkdir -p /tmp/mymnt
mount /tmp/ext4fs
ls -lRa /tmp/mymnt
touch /tmp/mymnt/afile
ls -l /tmp/mymnt
umount /tmp/ext4fs
On mount the ls shows the mount point as
drwxr-xr-x 3 meuh users 1024 May 15 21:04 .
and allows me to create a file there.
| Mounting as <user>, a loop still assigns root ownership |
1,641,448,393,000 |
I wish to create a file to loop mount as a root filesystem that grows dynamically as required (up to a limit).
The commonly quoted solution to this is to use a sparse file, which would do exactly what I want, however I wish to do this with fat32 / exfat (for compatibility across operating systems) as the host filesystem, neither of which support sparse files.
Is there an automated / semi-automated way to do this without rolling my own filesystem / loop driver?
|
qemu-nbd can be used to bind a qemu image (a grow-on-demand qcow2 image) to a block device, which can then be mounted as a filesystem of choice.
With this method however, performance as a root filesystem is very poor, and the image size grows very quickly with the resulting image being 6~7 times larger than an equivalent squashfs after short use.
A qcow2 image (unpartitioned, ext4) can be mounted with:
# qemu-nbd --connect=/dev/nbd0 --persistent /path/to/image.qcow2
# mount -t ext4 /dev/nbd0 /path/to/mountpoint/
| Creating a grow-on-demand loop filesystem without sparse files |
1,514,882,843,000 |
I have a system that generates embedded Linux systems. The system outputs three files:
a tarball containing rootfs excluding the kernel modules
a tarball containing the kernel modules
uImage
The system is deployed on a 1 GB SD card, of which 10 MB is given to a FAT boot partition and the rest to an ext4 root partition.
The most optimal output format for the system would be an image file that could be written on the SD card using dd. Right now, that image file is created by partitioning and formatting the SD card manually, extracting/copying the files on it and then reading the contents of the card using dd. It works, but the process could be a lot easier.
I know it's possible to create a loop file system representing the card, create the file systems on that and then extract/copy the files on them. I have tried that, and it works to some extent, but not well enough. The problem seems to be related to partitioning and the "geometry" (as in the geometry of a hard-disk, which, as far as I know, shouldn't matter in the case of a memory card) of the SD card, as if the partitioning should be specific to the model of the card, but I am not enough an expert on that area to say more than that.
What would be the proper way to get from the two tarballs and uImage to an image that could be copied on the SD card with dd?
|
If you are sure that the SD card always is of the same size (or greater) as the one you actually have, and the 1G is enough for what you want to copy there, you could proceed as follows:
Manually partition an appropriate SD card, but leave the partitions empty (but create the required filesystems on them)
Copy the whole SD card (say, /dev/sdb) to your system with dd if=/dev/sdb of=empty.image bs=4M
Every time you have to create a new SD card, copy the empty image to a new image: cp empty.image new.image
Now create a loop evice on that file: losetup -f -P new.image (-P is important, as this will force the kernel to read the partition info).
This will create a new loop device (say /dev/loop0) and the partitions /dev/loop0p1.../dev/loop0pn. These now can be mounted and used like any "normal" partition. After finishing your work, call losetup -d /dev/loop0 and copy the created image to your SD using dd if=new.image of=/dev/sdb bs=4M. All those steps may be scipted.
Edit:
Instead of 2) and 3) above:
You might also only copy the partition block (if it's MBR) and keep that (dd if=/dev/sdb of=empty_MBR bs=512 count=1); then for the new SD, ceate empty file (truncate -s 1G empty.file), which is just a sparse file (size=0), copy the partition table (dd if=empty_MBR of=empty.file), create loop device (losetup -f -P empty.file), format the partitions, and proceed like shown above.
Edit2:
If you even don't want to keep the small MBR file, you are also able to use sfdisk scripted (see man sfdisk or https://superuser.com/questions/332252/creating-and-formating-a-partition-using-a-bash-script). This means: Create empty file (s.a.), create loop device (no partitions, without -P), partition that device with sfdisk, detach loop device, reattach loop device (with partitions -P) and proceed.
| Creating dual-partition SD card image by a script |
1,514,882,843,000 |
I have an interesting case, where e2fsck refuses to recognize the file system inside a qcow2 image file. Using testdisk I am able to see the partition, so some markers would be left.
The reason this problem occurred in the first place was because the host of the virtual machine died.
So I choose None as the "type" of partition and get the following.
TestDisk 6.14, Data Recovery Utility, July 2013
Christophe GRENIER <[email protected]>
http://www.cgsecurity.org
Disk /dev/loop0 - 120 GB / 112 GiB - 235156929 sectors
The harddisk (120 GB / 112 GiB) seems too small! (< 4079258 TB / 3710063 TiB)
Check the harddisk size: HD jumpers settings, BIOS detection...
The following partitions can't be recovered:
Partition Start End Size in sectors
> ext3 640 251657855 251657216 [DATA]
ext3 1864062 253521277 251657216 [DATA]
ext3 1864064 253521279 251657216 [DATA]
ext3 2387454 254044669 251657216 [DATA]
ext3 2387456 254044671 251657216 [DATA]
ext3 2911614 254568829 251657216 [DATA]
ext3 2911616 254568831 251657216 [DATA]
ext3 3435774 255092989 251657216 [DATA]
ext3 3435776 255092991 251657216 [DATA]
ext3 3959934 255617149 251657216 [DATA]
[ Continue ]
ext3 blocksize=4096 Large file Sparse superblock, 128 GB / 119 GiB
It seems superblocks still exist and are intact, but how can I convince mount to use one of those superblocks as long as I don't know where they are located?
kpartx doesn't see anything on /dev/loop0 after I did the usual losetup -o 32256 /dev/loop0 imagefile for qcow2.
The image itself is (qemu-img info):
file format: qcow2
virtual size: 120G (128849018880 bytes)
disk size: 112G
cluster_size: 65536
Format specific information:
compat: 0.10
NB: I do have backups, but they are a few weeks old and if at all possible, I'd diff the stuff on the disk against the backups. Most are Git and Mercurial repos, so it's possible to fetch them again from elsewhere.
|
Okay, sorry for answering my own question so soon, but I noticed something flabbergasting. The .qcow2 file was of size 120400379904 Bytes, whereas the conversion of the image with qemu-img convert -O raw gave me an image of size 128849018880 Bytes.
Quite a difference.
Now, if we take the size in sectors found by testdisk, we will indeed notice that 512*251657216 is 128848494592, which happens to be 512 Bytes more than the file size of the "raw" image. That looks promising, I thought to myself.
I generated these files a few years ago, so I am not sure whether I created them as sparse images. Nevertheless, if qemu-img info shows it that way, I thought to myself, let's try to convert the image format. Keep in mind that this doesn't change the original file!
qemu-img convert -O raw input output
does that job, albeit slowly.
Running testdisk again on that file worked surprisingly well, although I was still unable to convince mount to use a different superblock, despite -o sb=....
TestDisk 6.14, Data Recovery Utility, July 2013
Christophe GRENIER <[email protected]>
http://www.cgsecurity.org
Disk bigdata/vm_disk_vdb.img - 128 GB / 120 GiB - CHS 15666 255 63
Partition Start End Size in sectors
>P ext3 0 1 1 15664 239 62 251657216 [DATA]
Structure: Ok.
Keys T: change type, P: list files,
Enter: to continue
ext3 blocksize=4096 Large file Sparse superblock, 128 GB / 119 GiB
After that, I could get testdisk to copy the files into a directory and diff it against my backups.
There were a few corruptions, such:
ext2fs_read_inode(ino=384492884) failed with error 2133571369.
and also other minor issues, but the problems were affecting only about 0.1% of all files and folders. Start testdisk as follows to be able to figure out which files must be considered damaged:
testdisk /log imagefile.img
| How to find alternative superblocks in ext3 file system of partition-less qcow2? |
1,514,882,843,000 |
I am trying to mount a bitlocker encrypted drive with dislocker.
Here are the exact commands I ran:
sudo dislocker -r -V /dev/sdb7 -u -- /media/bitlocker
sudo mount -r -o loop /media/bitlocker/dislocker-file /media/mount
After running the last one, I get
mount: /media/mount: wrong fs type, bad option, bad superblock on /dev/loop0, missing codepage or helper program, or other error.
Edit: I checked the dislocker-file, and the OEM-ID field below has spaces after NTFS. Is it the culprit, and how do I fix it regardless?
$ sudo file -s /media/bitlocker/dislocker-file | tr , '\n'
/media/bitlocker/dislocker-file: DOS/MBR boot sector
code offset 0x52+2
OEM-ID "NTFS "
sectors/cluster 8
Media descriptor 0xf8
sectors/track 63
heads 255
hidden sectors 63
dos < 4.0 BootSector (0x80)
FAT (1Y bit by descriptor); NTFS
sectors/track 63
sectors 560084065
$MFT start cluster 786432
$MFTMirror start cluster 7680070
bytes/RecordSegment 2^(-1*246)
clusters/index block 1
serial number 0feb8f9cbb8f98307; contains bootstrap NTLDR
|
I see that you are missing specify the filesystem of your device (this case NTFS).
Let's try with this mounting command:
sudo mount -t ntfs-3g -r -o loop /media/bitlocker/dislocker-file /media/mount
Here are some sample parameters for tag -t:
exFAT: exFAT-fuse
NTFS: ntfs-3g
| Cannot mount dislocker-file loop: wrong fs type, bad option, bad superblock |
1,514,882,843,000 |
Debian 8.2. I want to umount the /dev/loop5 device that I mounted, but I can't. I'm getting the message that
/dev/loop5 is not mounted.
Could anyone explain to me what I'm doing wrong here, please?
touch file
mkdir /mnt/partition
dd if=/dev/zero of=file bs=1M count=10
losetup /dev/loop5 file
mkfs.ext2 /dev/loop5
mount –t auto –o loop /dev/loop5 /mnt/partition
umount /dev/loop5
|
Because you didn't mount /dev/loop5.
mount -oloop SRC MNT means to create a loop device for the file SRC, and then mount that loop device at MNT. Apparently SRC is allowed to be a loop device itself if you really want :).
You could have seen this in the output of mount or findmnt; they would show that the loop device /dev/loop5 is not mounted and a different loop device is mounted.
| Debian. Can't umount loop device |
1,514,882,843,000 |
How can I allow the traffic to be sent on the loopback device (lo)? What is the iptables command for it?
|
By your question, I presume that you either have default xtables policies of DROP on your chains, or you have explicit DROP/REJECT rules near the end of your chains. Any ACCEPT rules must come before these.
Rule examples:
-A INPUT -i lo -j ACCEPT # accept any traffic coming from lo.
-A OUTPUT -o lo -j ACCEPT # accept any traffic sent to lo.
If you want to play around with testing this, here is a dump to load into iptables-restore. I've explicitly added the -s/-d 127.0.0.1 so you can see how what is normally being matched on (you could match -d in OUTPUT and -s in INPUT if you wanted). Also, I've used non-standard ICMP reject responses, so you can tell which rule matched your patches easily. If you change the order of these rules (they accept for now), you can trigger the rejections. You can also try adding another IP like 127.0.0.2/8 to your loopback interface and testing between that IP and the normal 127.0.0.1/8 IP (you'll want to explicitly specify a source IP in ping).
# Generated by iptables-save v1.4.20 on Sat Dec 7 23:10:52 2013
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -s 127.0.0.1/32 -i lo -j ACCEPT
-A INPUT -s 127.0.0.1/32 -i lo -j REJECT --reject-with icmp-host-prohibited
-A OUTPUT -d 127.0.0.1/32 -o lo -j ACCEPT
-A OUTPUT -d 127.0.0.1/32 -o lo -j REJECT --reject-with icmp-net-prohibited
COMMIT
The FORWARD chain is seldom used with loopback interfaces, unless you're doing things with tunneling traffic (and you might bind to loopback locally).
| How is the loopback device traffic allowed? |
1,514,882,843,000 |
I'll start this question by listing all drives available on my system right after the login into my Linux Mint 19.2 Cinnamon:
# fdisk -l
Disk /dev/loop0: 89,1 MiB, 93454336 bytes, 182528 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk /dev/loop1: 89,1 MiB, 93429760 bytes, 182480 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk /dev/loop2: 202,9 MiB, 212713472 bytes, 415456 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk /dev/nvme0n1: 477 GiB, 512110190592 bytes, 1000215216 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 989573D5-37E7-437A-B680-9410F7234A94
Device Start End Sectors Size Type
/dev/nvme0n1p1 2048 194559 192512 94M EFI System
/dev/nvme0n1p2 194560 1000214527 1000019968 476,9G Linux filesystem
Disk /dev/sda: 232,9 GiB, 250059350016 bytes, 488397168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: B05FAE90-8E4B-4CCC-AC77-D35D4B260C8A
Device Start End Sectors Size Type
/dev/sda1 2048 1026047 1024000 500M EFI System
/dev/sda2 1026048 1288191 262144 128M Microsoft reserved
/dev/sda3 1288192 459608774 458320583 218,6G Microsoft basic data
/dev/sda4 459610112 461398015 1787904 873M Windows recovery environment
/dev/sda5 461398016 485992447 24594432 11,7G Windows recovery environment
/dev/sda6 485992448 488396799 2404352 1,2G Windows recovery environment
Here, I should probably add, I don't even know what a loop device is. I just mount a lot of disks daily, make images of them, work with those and such. I have noticed those loop devices 0, 1, 2 as of this moment, but they might very well be here for ages, maybe I just did not pay attention to them, due to work stress.
Listing them does not reveal when they originated probably as I see today's date:
# ll /dev/loop[012]
brw-rw---- 1 root disk 7, 0 Nov 13 2019 /dev/loop0
brw-rw---- 1 root disk 7, 1 Nov 13 2019 /dev/loop1
brw-rw---- 1 root disk 7, 2 Nov 13 2019 /dev/loop2
Why they're on my system even if I reboot? Isn't that strange?
Here is my /etc/fstab:
UUID=f1fc7345-be7a-4c6b-9559-fc6e2d445bfa / ext4 errors=remount-ro 0 1
UUID=4966-E925 /boot/efi vfat umask=0077 0 1
none /ramdisk tmpfs size=1G,mode=0777 0 0
UUID=01D480EF7EDA45C0 /mnt/windows ntfs nosuid,nodev,nofail,noexec,rw 0 0
How do I get more information about these 3 loop devices?
I tried fdisk now:
# fdisk /dev/loop0
Welcome to fdisk (util-linux 2.31.1).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.
The old squashfs signature will be removed by a write command.
Device does not contain a recognized partition table.
Created a new DOS disklabel with disk identifier 0xc54bc258.
Command (m for help): v
Remaining 182527 unallocated 512-byte sectors.
Command (m for help): p
Disk /dev/loop0: 89,1 MiB, 93454336 bytes, 182528 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xc54bc258
I've already regenerated my initramfs image with no change, they're still there after reboot.
I'd rather know more about them before actually trying to delete them.
Questions and answers to comments:
Why are you not as concerned by the various /dev/tty* devices as by the loop devices?
Well, this is a tough question, as I don't know exactly what those tty devices purpose is. So, I guess ignorance is bliss, sort of speak.
Why do you want to delete the /dev/loop* devices specifically?
I said I want to know more about them, to investigate what they contain, well, and as per fdisk output, they do not, correction, contain any partition table. What's more, these loop devices are not present on any other Linux I am directly working with.
It seems, it has some relation to Snap daemon.
# losetup -a
/dev/loop1: [66306]:6161256 (/var/lib/snapd/snaps/core_8039.snap)
/dev/loop2: [66306]:6160663 (/var/lib/snapd/snaps/core_7917.snap)
/dev/loop0: [66306]:6160545 (/var/lib/snapd/snaps/vlc_1049.snap)
# losetup -l
NAME SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE DIO LOG-SEC
/dev/loop1 0 0 1 1 /var/lib/snapd/snaps/core_8039.snap 0 512
/dev/loop2 0 0 1 1 /var/lib/snapd/snaps/core_7917.snap 0 512
/dev/loop0 0 0 1 1 /var/lib/snapd/snaps/vlc_1049.snap 0 512
|
The existence of /dev/loop* devices doesn’t necessarily indicate anything; some systems pre-populate them, others don’t. However, if they show up in fdisk -l’s output, that means they’ve been set up to provide a loop device over either a file or another block device.
You can see what loop devices are set up, and what they “loop” over, by running
losetup -l
as root. In your case, the devices are being used to access Snap volumes;
snap list
will list the running Snaps on your system (apparently VLC and the core Snap). See the Ubuntu Snap tutorial for a brief introduction.
| Why there are 3 loop devices on my system right after boot? |
1,514,882,843,000 |
I'm working on a huge complex application. You connect a disk, press a button, and it partitions and formats the disk, mounts it, and copies some files onto it.
To test this application, we have a test system which loop-mounts a disk image and runs through the same process. Except we changed the application logic, and now the test system doesn't work. If you give the program a real disk, everything works fine. But if you give it a loop device, it fails.
Specifically, the application partitions the disk, formats it, and then whines that it can't mount the partition. The exact command is
mount /dev/vda /mnt --rw -o offset=111149056,sizelimit=314572800
(Here /dev/vda is merely a symlink to /dev/loop0. It makes no difference if I refer to loop0 directly.)
If I run the command by hand, I get this:
root# mount /dev/vda /mnt --rw -o offset=111149056,sizelimit=314572800
FUSE exfat 1.0.1
ERROR: exFAT file system is not found.
root# echo $?
1
I can run this command over and over again, and it just doesn't work. No reason, it just doesn't.
Here is the terrifying part: If I run cfdisk /dev/vda and then immediately quit without changing anything, now it mounts!!
What the hell does cfdisk do to the disk that makes it suddenly start working? And how can I remove the need to call this program?
(I tried in vain to call sfdisk -R /dev/vda; it just complains about "invalid parameter" or something.)
I can kludge the application to call cfdisk -Ps /dev/vda or something, but I would really, really rather not do that. I want to find out why any of this is even necessary. Before we changed the application, everything worked fine...
|
I made a small change to the test framework, and the problem went away.
Specifically, rather than calling kpartx -u /dev/vda after I repartition the device, I call kpartx -d followed by kpartx -a. And now everything is fine. Weird...
| How does cfdisk fix my disk image? |
1,514,882,843,000 |
Given any file on an ext4 filesystem, it is possible (using filefrag -v) to get the list of real offsets+lengths where that file is located on the underlying block device.
Is it safe to open the device and write to them, all that while the filesystem is mounted read-write? Can it cause fs corruption?
I'm asking because I'm going to implement an alternative loop driver, which will bypass the filesystem layer completely, therefore having much better performance.
If I remember correctly, swapfile is implemented exactly that way. Please correct me if told something wrong.
Is the answer filesystem-dependent? What can happen if the file is suddenly deleted, and these offsets become reused for some metadata?
Finally, is there a way to lock a file from being relocated by e4defrag or similar things? What is the best way to prevent a file from being deleted (being in kernel space)? Is there some kernel internals I can use to get the list of file's extents?
|
If the writes are only to the blocks of the file, then it wouldn't corrupt the ext4 filesystem. However, there is a definitely a bigger risk that some error in the code could corrupt the filesystem, which wouldn't happen with a regular loop device that is only using the file mapping.
The question is whether writing directly to the block device will actually make a difference in performance?
You can prevent the file from being deleted by marking it immutable with chattr +i FILENAME.
| Is it safe to write to file's extents directly while the FS is r/w? |
1,514,882,843,000 |
I have created a loop device and added it to /etc/fstab
I got its UUID from the output of the blkid command (it does print a UUID for the particular device after running mkfs.ext4 /path/to/loop)
However despite the fact that after editing /etc/fstab the command mount -a was successful, the system after the reboot halted.
Insted the following entry in /etc/fstab seems to do the job:
/path/to/loop /mountpoint ext4 loop 0 0
Why replacing /path/to/loop with UUID breaks things?
|
Only block devices have UUIDs (that can be found).
A file is not a block device, the loop device turns it into one.
So for the UUID of an image file to be found, the loop device must exist first.
However, your fstab entry is a loop mount, i.e. the loop device is only created when you mount it (and immediately removed on umount), so it does not exist before you mount it (and after you umount it), and so... the UUID is not found because the loop device does not exist.
For loop mounts, it's completely fine to specify the file by path.
Otherwise you'd need an init script that sets up loop devices before attempting to mount them (and then get rid of the loop mount option).
| mounting loop not working with UUID |
1,514,882,843,000 |
I have a file, called "some.img", created with fallocate, that has a filesystem on it. I can mount the img file using mount -o loop some.img /media/where, and I see the filesystem. When I reboot, however, the file is no longer mounted.
How do I automatically mount this at boot?
Update: SuSE Linux
|
Essentially, add the following to /etc/fstab:
/path/to/file /path/to/mount ext4 loop 0 0
As described in
https://superuser.com/questions/799162/permanent-loop-device
| How to automatically mount at boot? [duplicate] |
1,514,882,843,000 |
Dir created inside a loop fs denies access, but has correct permissions.
init.sh - creates an fs image and mounts it (user and group ids are 1000):
#!/bin/bash
mkdir -p out-dir
dd if=/dev/zero of=out-dir.img bs=1024 count=125
/sbin/mkfs.ext4 out-dir.img
guestmount -o uid=$(id -u) -o gid=$(id -g) -a out-dir.img -m/dev/sda out-dir
create.sh - creates a dir and does cd:
#!/bin/bash
mkdir -m 700 out-dir/test
cd out-dir/test
The cd gives:
./create.sh: line 4: cd: out-dir/test: Permission denied
Then, ls -lan out-dir:
drwxr-xr-x 4 1000 1000 1024 Mar 21 15:27 .
drwxrwxr-x 3 1000 1000 4096 Mar 21 15:27 ..
drwx------ 2 1000 1000 12288 Mar 21 15:27 lost+found
drwx------ 2 1000 1000 1024 Mar 21 15:27 test
How to establish the correct mapping?
|
This is the option: -o default_permissions.
guestmount --fuse-help:
...
-o default_permissions enable permission checking by kernel
| guestunmount: can't cd into a dir, but the permissions are ok |
1,514,882,843,000 |
I'm having trouble with this piece of code:
22 for filename in "$( ls "$1" | grep ".*\.flac$" )"; do
23 file_path="$1${filename}"
24 ffmpeg -i "${file_path}" -f ffmetadata $HOME/metadata
Instead of a metadata file on each iteration, I'm getting this error message:
Downloads/Ariel Pink's Haunted Graffiti - Worn Copy (2005)/01
Trepanated Earth.flac ... 17 Jagged Carnival Tours.flac: File name too long
So it appears that inside the loop the $filename variable is equal the names of all FLAC files lumped together.
Of course, omitting quote marks on line 22 results in whitespace problems.
How do I make this work? I'm new to bash and very confused.
|
how about
for filepath in "$1/"*.flac
do
ffmpeg -i "${file_path}" -f ...
where
"$1/"*.flac will garantee .flac suffix in the end
be sure to quote "${file_path}"
basename can be found using bn=$(basename "${file_path}")
un flac'ed basename can be found using bnnf=$(basename "${file_path}" .flac)
sample
A > ls -l Music
total 0
-rw-rw-r-- 1 Arc Arc 0 Mar 14 03:37 foo bar
-rw-rw-r-- 1 Arc Arc 0 Mar 14 03:37 foo bar.flac
-rw-rw-r-- 1 Arc Arc 0 Mar 14 03:37 fubar
-rw-rw-r-- 1 Arc Arc 0 Mar 14 03:37 fubar.flac
now run:
A > for f in Music/*.flac; do echo $f; ls -l "$f" ; done
Music/foo bar.flac
-rw-rw-r-- 1 Arc Arc 0 Mar 14 03:37 Music/foo bar.flac
Music/fubar.flac
-rw-rw-r-- 1 Arc Arc 0 Mar 14 03:37 Music/fubar.flac
| BASH: looping through ls [duplicate] |
1,514,882,843,000 |
How to add files or directories to the qemu-img created raw disk file. For example. I use qemu-img create -f raw disk.raw 1G to generate a disk.raw file. I want to copy some /bin, /usr directories to the disk.raw file.
I have tried the following commands. With the reference to here
qemu-img create -f raw disk.raw 1G
mkdir /image
losetup /dev/loop0 disk.raw
fdisk /dev/loop0
> n
> p
> ENTER
> ENTER
> ENTER
> a
> w
kpartx -a /dev/loop0
mount /dev/mapper/loop0p1 /image
However, the last commands output the following error messages: mount: /image: wrong fs type, bad option, bad superblock on /dev/mapper/loop0p1, missing codepage or helper program, or other error.
|
To mount your /dev/mapper/loop0p1 partition, you must format it first.
# mke2fs -t ext4 /dev/mapper/loop0p1
# mount /dev/mapper/loop0p1 /image
| How to modify (add files or directories) to the qemu-img created raw disk file? |
1,514,882,843,000 |
I installed a very old Slack version (3.2) on VirtualBox and then converted it to RAW format (ext2). However, for some reason I'm unable to mount it using losetup but qemu-nbd works fine. Why?
I tried,
losetup -P -f --show slack-3.2.img
but it doesn't create partitions.
I modified /etc/default/grub so that GRUB_CMDLINE_LINUX="loop.max_part=63" and grub-mkconfig, etc. but it still won't create the partitions from the image.
I tried, kpartx -av slack-3.2.img and I get
read error, sector 0
read error, sector 1
read error, sector 29
I even tried dd if=slack-3.2.img of=slack.part bs=512 skip=63 count=409185
and sudo losetup -P -f --show slack.part but it still fails. Why won't it work?
sudo fdisk -l slack-3.2.img
Disk slack-3.2.img: 200 MiB, 209715200 bytes, 409600 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x00000000
Device Boot Start End Sectors Size Id Type
slack-3.2.img1 63 409247 409185 199.8M 83 Linux
|
read error, sector 0
This indicates trouble of the kernel to access your file and I have the strong suspicion that vboxfs is causing it. I have a long open bug about it not supporting symlinks and hardlinks and I think they only fixed the former.
qemu-nbd OTOH will just read the file, so it is fine, but the kernel uses mmap and other low level accesses.
A solution would be to copy the image onto a ext2/4 on a (virtual) partition.
| Raw disk image from VDI file can be mounted using qemu-nbd but not loop device? |
1,514,882,843,000 |
Since the kernel started supporting it, losetup was modified to enable direct IO by default. This can avoid having redundant page cache and also has performance advantages.
http://man7.org/linux/man-pages/man8/losetup.8.html
--direct-io[=on|off]
Enable or disable direct I/O for the backing file. The
optional argument can be either on or off. If the argument is
omitted, it defaults to on.
I noticed, when the kernel added this feature, one commit mentions adding a feature specifically for mount -oloop. Has mount -oloop also been modified so that it defaults to enabling direct IO (if the kernel is new enough)? I can't find it mentioned in the documentation.
http://man7.org/linux/man-pages/man8/mount.8.html
|
No, I don't think this has been implemented so far (util-linux v2.31.1).
mount and losetup use common code to create loop devices, but the loopcxt_set_dio() function is only called inside the main() function of losetup.c.
https://github.com/karelzak/util-linux/search?q=loopcxt_set_dio
https://github.com/karelzak/util-linux/search?q=LOOP_SET_DIRECT_IO
| Does `mount -oloop` use direct IO by default (when the kernel is new enough)? |
1,300,135,516,000 |
I want to determine which process has the other end of a UNIX socket.
Specifically, I'm asking about one that was created with socketpair(), though the problem is the same for any UNIX socket.
I have a program parent which creates a socketpair(AF_UNIX, SOCK_STREAM, 0, fds), and fork()s. The parent process closes fds[1] and keeps fds[0] to communicate. The child does the opposite, close(fds[0]); s=fds[1]. Then the child exec()s another program, child1. The two can communicate back and forth via this socketpair.
Now, let's say I know who parent is, but I want to figure out who child1 is. How do I do this?
There are several tools at my disposal, but none can tell me which process is on the other end of the socket. I have tried:
lsof -c progname
lsof -c parent -c child1
ls -l /proc/$(pidof server)/fd
cat /proc/net/unix
Basically, I can see the two sockets, and everything about them, but cannot tell that they are connected. I am trying to determine which FD in the parent is communicating with which child process.
|
Since kernel 3.3, it is possible using ss or lsof-4.89 or above — see Stéphane Chazelas's answer.
In older versions, according to the author of lsof, it was impossible to find this out: the Linux kernel does not expose this information. Source: 2003 thread on comp.unix.admin.
The number shown in /proc/$pid/fd/$fd is the socket's inode number in the virtual socket filesystem. When you create a pipe or socket pair, each end successively receives an inode number. The numbers are attributed sequentially, so there is a high probability that the numbers differ by 1, but this is not guaranteed (either because the first socket was N and N+1 was already in use due to wrapping, or because some other thread was scheduled between the two inode allocations and that thread created some inodes too).
I checked the definition of socketpair in kernel 2.6.39, and the two ends of the socket are not correlated except by the type-specific socketpair method. For unix sockets, that's unix_socketpair in net/unix/af_unix.c.
| Who's got the other end of this unix socketpair? |
1,300,135,516,000 |
I know I can view the open files of a process using lsof at that moment in time on my Linux machine. However, a process can open, alter and close a file so quickly that I won't be able to see it when monitoring it using standard shell scripting (e.g. watch) as explained in "monitor open process files on linux (real-time)".
So, I think I'm looking for a simple way of auditing a process and see what it has done over the time passed. It would be great if it's also possible to see what network connections it (tried to) make and to have the audit start before the process got time to run without the audit being started.
Ideally, I would like to do this:
sh $ audit-lsof /path/to/executable
4530.848254 OPEN read /etc/myconfig
4530.848260 OPEN write /var/log/mylog.log
4540.345986 OPEN read /home/gert/.ssh/id_rsa <-- suspicious
4540.650345 OPEN socket TCP ::1:34895 -> 1.2.3.4:80 |
[...]
4541.023485 CLOSE /home/gert/.ssh/id_rsa <-- would have missed
4541.023485 CLOSE socket TCP ::1:34895 -> 1.2.3.4:80 | this when polling
Would this be possible using strace and some flags to not see every system call?
|
Running it with
strace -e trace=open,openat,close,read,write,connect,accept your-command-here
would probably be sufficient.
You'll need to use the -o option to put strace's output somewhere other than the console, if the process can print to stderr. If your process forks, you'll also need -f or -ff.
Oh, and you might want -t as well, so you can see when the calls happened.
Note, you may need to tweak the function call list depending on what your process does - I needed to add getdents for example, to get better sample using ls:
$ strace -t -e trace=open,openat,close,read,getdents,write,connect,accept ls >/dev/null
...
09:34:48 open("/etc/ld.so.cache", O_RDONLY) = 3
09:34:48 close(3) = 0
09:34:48 open("/lib64/libselinux.so.1", O_RDONLY) = 3
09:34:48 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0@V\0\0\0\0\0\0"..., 832) = 832
09:34:48 close(3) = 0
...
09:34:48 open("/proc/filesystems", O_RDONLY) = 3
09:34:48 read(3, "nodev\tsysfs\nnodev\trootfs\nnodev\tb"..., 1024) = 366
09:34:48 read(3, "", 1024) = 0
09:34:48 close(3) = 0
09:34:48 open("/usr/lib/locale/locale-archive", O_RDONLY) = 3
09:34:48 close(3) = 0
09:34:48 open(".", O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC) = 3
09:34:48 getdents(3, /* 5 entries */, 32768) = 144
09:34:48 getdents(3, /* 0 entries */, 32768) = 0
09:34:48 close(3) = 0
09:34:48 write(1, "file-A\nfile-B\nfile-C\n", 21) = 21
09:34:48 close(1) = 0
09:34:48 close(2) = 0
| How do I monitor opened files of a process in realtime? |
1,300,135,516,000 |
root@host [/home2]# lsof /home2
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
php 3182 ctxmortg cwd DIR 8,17 4096 32858196 /home2/ctxmortg/public_html/hello
php 3182 ctxmortg 3r REG 8,17 46404 55781766 /home2/ctxmortg/public_html/hello/cache/subprimemortgagemorgage.com/cache-zch-8284-cache.txt
php 3185 ctxmortg cwd DIR 8,17 4096 32858196 /home2/ctxmortg/public_html/hello
php 3185 ctxmortg 3r REG 8,17 4185 35962154 /home2/ctxmortg/public_html/hello/cache/curl/http%3A%2F%2Fimage.yahoo.cn%2Fs%3Fq%3DNudity%26c%3D0%26s%3D%26page%3D277
php 3187 ctxmortg cwd DIR 8,17 4096 32858196 /home2/ctxmortg/public_html/hello
php 3187 ctxmortg 3r REG 8,17 54640 69699731 /home2/ctxmortg/public_html/hello/cache/newdatingfriends.com/cache-zch-1545-cache.txt
php 3188 ctxmortg cwd DIR 8,17 4096 32858196 /home2/ctxmortg/public_html/hello
php 3188 ctxmortg 3r REG 8,17 54640 21557063 /home2/ctxmortg/public_html/hello/cache/customersdeals.com/cache-zch-5715-cache.txt
php 3189 ctxmortg cwd DIR 8,17 4096 32858196 /home2/ctxmortg/public_html/hello
php 3189 ctxmortg 3r REG 8,17 4185 36028071 /home2/ctxmortg/public_html/hello/cache/curl/http%3A%2F%2Fimage.yahoo.cn%2Fs%3Fq%3DVideos%26c%3D0%26s%3D%26page%3D329
php 3200 ctxmortg cwd DIR 8,17 4096 32858196 /home2/ctxmortg/public_html/hello
php 3200 ctxmortg 3r REG 8,17 21036 9155614 /home2/ctxmortg/public_html/hello/cache/indorealestates.com/cache-zch-8562-cache.txt
lsof 3201 root cwd DIR 8,17 4096 2 /home2
lsof 3202 root cwd DIR 8,17 4096 2 /home2
webalizer 32342 ctxmortg cwd DIR 8,17 4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32342 ctxmortg 5uW REG 8,17 12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32360 ctxmortg cwd DIR 8,17 4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32360 ctxmortg 5u REG 8,17 12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32361 ctxmortg cwd DIR 8,17 4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32361 ctxmortg 5u REG 8,17 12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32362 ctxmortg cwd DIR 8,17 4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32362 ctxmortg 5u REG 8,17 12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32363 ctxmortg cwd DIR 8,17 4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32363 ctxmortg 5u REG 8,17 12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32364 ctxmortg cwd DIR 8,17 4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32364 ctxmortg 5u REG 8,17 12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32365 ctxmortg cwd DIR 8,17 4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32365 ctxmortg 5u REG 8,17 12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32366 ctxmortg cwd DIR 8,17 4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32366 ctxmortg 5u REG 8,17 12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32367 ctxmortg cwd DIR 8,17 4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32367 ctxmortg 5u REG 8,17 12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32368 ctxmortg cwd DIR 8,17 4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32368 ctxmortg 5u REG 8,17 12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32369 ctxmortg cwd DIR 8,17 4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32369 ctxmortg 5u REG 8,17 12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
bash 32409 root cwd DIR 8,17 4096 2 /home2
I want to umount a drive but cannot.
So, what does cwd, 3r dir, and reg mean anyway?
|
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
webalizer 32342 ctxmortg 5uW REG 8,17 12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
FD - File Descriptor
If you are looking for file being written, look for following flag
# - The number in front of flag(s) is the file descriptor number of used by the process to associated with the file
u - File open with Read and Write permission
r - File open with Read permission
w - File open with Write permission
W - File open with Write permission and with Write Lock on entire file
mem - Memory mapped file, usually for share library
So 3r means webalizer has a descriptor number 3 associated with ...dns_cache.db, with read permission.
TYPE - File Type
In Linux, almost everything are files, but with different type.
REG - REGgular file, file that show up in directory
DIR - Directory
NODE
inode number in filesystem
You can find complete details in the man page.
| How to interpret this output of lsof command? |
1,300,135,516,000 |
Hi I have many files that have been deleted but for some reason the disk space associated with the deleted files is unable to be utilized until I explicitly kill the process for the file taking the disk space
$ lsof /tmp/
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
cron 1623 root 5u REG 0,21 0 395919638 /tmp/tmpfPagTZ4 (deleted)
The disk space taken up by the deleted file above causes problems such as when trying to use the tab key to autocomplete a file path I get the error bash: cannot create temp file for here-document: No space left on device
But after I run kill -9 1623 the space for that PID is freed and I no longer get the error.
My questions are:
why is this space not immediately freed when the file is first deleted?
what is the best way to get back the file space associated with the deleted files?
and please let me know any incorrect terminology I have used or any other relevant and pertinent info regarding this situation.
|
On unices, filenames are just pointers (inodes) that point to the memory where the file resides (which can be a hard drive or even a RAM-backed filesystem). Each file records the number of links to it: the links can be either the filename (plural, if there are multiple hard links to the same file), and also every time a file is opened, the process actually holds the "link" to the same space.
The space is physically freed only if there are no links left (therefore, it's impossible to get to it). That's the only sensible choice: while the file is being used, it's not important if someone else can no longer access it: you are using it and until you close it, you still have control over it - you won't even notice the filename is gone or moved or whatever. That's even used for tempfiles: some implementations create a file and immediately unlink it, so it's not visible in the filesystem, but the process that created it is using it normally. Flash plugin is especially fond of this method: all the downloaded video files are held open, but the filesystem doesn't show them.
So, the answer is, while the processes have the files still opened, you shouldn't expect to get the space back. It's not freed, it's being actively used. This is also one of the reasons that applications should really close the files when they finish using them. In normal usage, you shouldn't think of that space as free, and this also shouldn't be very common at all - with the exception of temporary files that are unlinked on purpose, there shouldn't really be any files that you would consider being unused, but still open. Try to review if there is a process that does this a lot and consider how you use it, or just find more space.
| Best way to free disk space from deleted files that are held open |
1,300,135,516,000 |
Is there a way to make lsof work continuously to monitor every file that is being opened in real time?
I don't know the name of the process. I want lsof to work continuously for a period of time until I see the the list contains what I want.
|
I believe since you do not know the file name/process id, you could specify user name option as below.
lsof -r 2 -u username
The "-r 2" option puts lsof in repeat mode, with updates every 2
seconds. (Ctrl -c quits)
The "-u' option can be used to keep an eye on a users activity.
If you know the directory name under which the application is being run and do not want to specify the user name,you could use the command like,
lsof +D /some/dir -r 2
References
View Network Activity of any application or user in real time
| Monitoring files continuously with lsof |
1,300,135,516,000 |
In many cases lsof is not installed on the machines that I have to work with, but the "function" of lsof would be needed very much (for example on AIX). :\
Are there any lsof like applications in the non-Windows world?
For example, I need to know which processes use the /home/username directory?
|
I know of fuser, see if it's available on your system.
| Alternatives for "lsof" command? |
1,300,135,516,000 |
Commands, for instance sed, are programs and programs are codified logic inside a file and these files are somewhere on the hard disk. However when commands are being run, a copy of their files from the hard disk is put into the RAM, where they come to life and can do stuff and are called processes.
Processes can make use of other files, read or write into them, and if they do those files are called open files. There is a command to list all open files by all running processes: lsof.
OK, so what I wonder about is if the double life of a command, one on the hard disk, the other in the RAM is also true for other kind of files, for instance those who have no logic programmed, but are simply containers for data.
My assumption is, that files opened by processes are also loaded into the RAM. I do not know if it is true, it is just an intuition.
Please, could someone make sense of it?
|
However when commands are being run, a copy of their files from the hard disk is put into the RAM,
This is wrong (in general). When a program is executed (thru execve(2)...) the process (running that program) is changing its virtual address space and the kernel is reconfiguring the MMU for that purpose. Read also about virtual memory. Notice that application programs can change their virtual address space using mmap(2) & munmap & mprotect(2), also used by the dynamic linker (see ld-linux(8)). See also madvise(2) & posix_fadvise(2) & mlock(2).
Future page faults will be processed by the kernel to load (lazily) pages from the executable file. Read also about thrashing.
The kernel maintains a large page cache. Read also about copy-on-write. See also readahead(2).
OK, so what I wonder about is if the double life of a command, one on the hard disk, the other in the RAM is also true for other kind of files, for instance those who have no logic programmed, but are simply containers for data.
For system calls like read(2) & write(2) the page cache is also used. If the data to be read is sitting in it, no disk IO will be done. If disk IO is needed, the read data would be very likely put in the page cache.
So, in practice, if you run the same command twice, it could happen that no physical I/O is done to the disk on the second time (if you have an old rotating hard disk - not an SSD - you might hear that; or observe carefully your hard disk LED).
I recommend reading a book like Operating Systems : Three Easy Pieces (freely downloadable, one PDF file per chapter) which explains all this.
See also Linux Ate My RAM and run commands like xosview, top, htop or cat /proc/self/maps or cat /proc/$$/maps (see proc(5)).
PS. I am focusing on Linux, but other OSes also have virtual memory and page cache.
| Are files opened by processes loaded into RAM? |
1,300,135,516,000 |
Is there any way to find some process which is periodically writing to disk (according to hdd led) on FreeBSD 10 with ZFS (maybe turn ZFS into verbose logging mode)?
lsof and other instantly aggregating statistics utilities seems not able to catch anything due to a short time of a moment of a disk access.
|
DTrace is able to report on vfs information in FreeBSD (as well as a raft of other probes). DTrace is enabled by default in the 10 kernel so all you need to do is load the module then run the dtrace script.
Load the DTrace module
kldload dtraceall
Get the vfssnoop.d script from the FreeBSD forums. The whole thread is a treasure trove for disk monitoring.
Run it:
./vfssnoop.d
Watch the output for what is accessed:
# ./vfssnoop.d
cc1: warning: is shorter than expected
TIMESTAMP UID PID PROCESS CALL SIZE PATH/FILE
1555479476691083 0 1225 nfsd vop_getattr - /share/netboot
1555479478601010 0 1225 nfsd vop_inactive - /share/netboot
1555479482457241 0 1225 nfsd vop_getattr - /share/wpad.dat
1555480557262388 0 1432 cron vop_getattr - /var/cron/tabs
1555480557302178 0 1432 cron vop_inactive - /var/cron/tabs
1555480557336414 0 1432 cron vop_inactive - /etc
1555480557346224 0 1432 cron vop_getattr - /etc/crontab
| FreeBSD 10 trace disk activity |
1,300,135,516,000 |
I want to move large file created by external process as soon as it's closed.
Is this test command correct?
if lsof "/file/name"
then
# file is open, don't touch it!
else
if [ 1 -eq $? ]
then
# file is closed
mv /file/name /other/file/name
else
# lsof failed for some other reason
fi
fi
EDIT: the file represents a dataset and I have to wait until it's complete to move it so another program can act on it. That's why I need to know if the external process is done with the file.
|
From the lsof man page
Lsof returns a one (1) if any error was detected, including the failure
to locate command names, file names, Internet addresses or files, login
names, NFS files, PIDs, PGIDs, or UIDs it was asked to list. If the -V
option is specified, lsof will indicate the search items it failed to
list.
So that would suggest that your lsof failed for some other reason clause would never be executed.
Have you tried just moving the file while your external process still has it open? If the destination directory is on the same filesystem, then there should be no problems with doing that unless you need to access it under the original path from a third process as the underlying inode will remain the same. Otherwise I think mv will fail anyway.
If you really need to wait until your external process is finished with the file, you are better to use a command that blocks instead of repeatedly polling. On Linux, you can use inotifywait for this. Eg:
inotifywait -e close_write /path/to/file
If you must use lsof (maybe for portability), you could try something like:
until err_str=$(lsof /path/to/file 2>&1 >/dev/null); do
if [ -n "$err_str" ]; then
# lsof printed an error string, file may or may not be open
echo "lsof: $err_str" >&2
# tricky to decide what to do here, you may want to retry a number of times,
# but for this example just break
break
fi
# lsof returned 1 but didn't print an error string, assume the file is open
sleep 1
done
if [ -z "$err_str" ]; then
# file has been closed, move it
mv /path/to/file /destination/path
fi
Update
As noted by @JohnWHSmith below, the safest design would always use an lsof loop as above as it is possible that more than one process would have the file open for writing (an example case may be a poorly written indexing daemon that opens files with the read/write flag when it should really be read only). inotifywait can still be used instead of sleep though, just replace the sleep line with inotifywait -e close /path/to/file.
| Move file but only if it's closed |
1,300,135,516,000 |
Consider this simple scenario:
I open a text file ~/textfile.txt with vim in one terminal (tried with both edit and read-only modes).
In a different terminal, I run
/usr/sbin/lsof ~/textfile.txt
Get no results
Why?
|
When you use vi/vim to edit a file you aren't actually holding ~/<filename>open you are reading the file into ~/.<filename>.swp and then holding that temp file open.
If you run lsof ~/.<filename>.swp it will show you the information you are looking for.
NOTE: If you have multiple people editing the same file you will need to lsof ~/.<filename>.s* as each vi/vim session will create its own swap file but will name it differently
| lsof doesn't return files open by the same user |
1,300,135,516,000 |
I want to extract the process id of a certain process in order to shut it down. The process is a local web server using a certain port (localhost:3000), and I am currently doing it like this to extract the relevant line:
lsof|grep localhost:3000
but the lsof command is too slow. Is there a faster way to extract the process id?
|
Try netstat, I cannot say whether its faster or slower, however.
netstat -tanp | awk '$4 ~ /:8443$/ {sub(/\/.*/, "", $7); print $7}' | sort -u
| Faster alternatives to lsof |
1,300,135,516,000 |
On my CentOS 7, at one point, sudo ss -plt listed a port marked as LISTENING on *:30565, but there was no information whatsoever in the process column of its row. The other listening ports were showing their owning process as usual, like users:(("sshd",pid=1381,fd=3)), but that one row did not have any process information. lsof -i :30565 or netstat -p did not yield any information either.
I haven't been able to reproduce this, and I struggle to think of a situation a "non-process" might be listening on a port (as I'm quite sure Linux does the intended cleanup work when a tcp-listening process dies). As it happens with multiple programs too, the only explanation I can think of is that this is an "intended but very rootkit-y" behaviour of CentOS, but I'm most surely missing something. What might possibly have caused this?
|
The point on netstat not showing the process information on some situations, for instance NFS, is that NFS is a kernel module, and as such, it does not run as a normal process, and does not have a PID.
You can regularly find threads about this situation if including NFS on your google searches:
netstat doesn't report PID/Program name for some ports
Note: for other users not using sudo, using -p needs root privileges to be able to show the related process of a port.
| "netstat -p"/"ss -p" not showing the process of a listening port |
1,300,135,516,000 |
I want to know if my server establishes a connection to a remote server or if the remote server tries to reach my server. I tried to read the output of lsof and obtain this information:
lsof -i TCP:25
USER FD TYPE DEVICE SIZE/OFF NODE NAME
master 2657 root 12u IPv4 8086 0t0 TCP *:smtp (LISTEN)
smtpd 12950 postfix 6u IPv4 8086 0t0 TCP *:smtp (LISTEN)
smtpd 12950 postfix 9u IPv4 35762406 0t0 TCP hostname:smtp->spe.cif.ic.IP:55277 (ESTABLISHED)
smtp 13007 postfix 13u IPv4 35762309 0t0 TCP hostname:34434->fake.VVVVV.fr:smtp (ESTABLISHED)
smtpd 14188 postfix 6u IPv4 8086 0t0 TCP *:smtp (LISTEN)
smtpd 14188 postfix 9u IPv4 35748921 0t0 TCP hostname:smtp->XX.XX.XX.XX:55912 (ESTABLISHED)
smtpd 14897 postfix 6u IPv4 8086 0t0 TCP *:smtp (LISTEN)
I'd like to know if this information means that my server tries to connect to spe.cif.ic.IP or if it's the other way around.
Is the sign -> relevant, or I should use a different command?
|
I think the clue is in the port numbers, take these two entries
smtpd 12950 postfix 9u IPv4 35762406 0t0 TCP hostname:smtp->spe.cif.ic.IP:55277 (ESTABLISHED)
smtp 13007 postfix 13u IPv4 35762309 0t0 TCP hostname:34434->fake.VVVVV.fr:smtp (ESTABLISHED)
smtpd has received a connection on port smtp(25) from a high port number, whilst smtp connects to remote port smtp(25) and has a local high port number.
So -> means connected to
| How to use lsof to identify incoming TCP connections? |
1,300,135,516,000 |
I was using lsof to track down deleted files that were still taking up space and I realized that I wasn't quite sure what an offset is with respect to a file. lsof's man page was less than helpful in this regard and searching around I couldn't get a clear picture of what it is.
What is a file offset and why is it useful to have that piece of information?
|
The offset is the current position in the file, as maintained by the kernel for a given file description (see the lseek(2) and open(2) manpages for details).
As to why it's useful in lsof's output, I'm not really sure. It can give some idea of a process's progress through a file, although it won't cover all cases (memory-mapped files won't show offset changes).
| What exactly is a file offset in lsof output? |
1,300,135,516,000 |
I've been getting some suggestions on how to figure out why my serial port is busy. Specifically, when I try to start gammu-smsd, it refuses to start on /dev/ttyS0 because it says that port is busy:
sudo /etc/init.d/gammu-smsd start
Sep 30 16:16:51 porkypig gammu-smsd[25355]: Starting phone communication...
Sep 30 16:16:51 porkypig gammu-smsd[25355]: gammu: [Gammu - 1.26.1 built 21:46:06 Nov 24 2009 using GCC 4.4]
Sep 30 16:16:51 porkypig gammu-smsd[25355]: gammu: [Connection - "at115200"]
Sep 30 16:16:51 porkypig gammu-smsd[25355]: gammu: [Connection index - 0]
Sep 30 16:16:51 porkypig gammu-smsd[25355]: gammu: [Model type - ""]
Sep 30 16:16:51 porkypig gammu-smsd[25355]: gammu: [Device - "/dev/ttyS0"]
Sep 30 16:16:51 porkypig gammu-smsd[25355]: gammu: [Runing on - Linux, kernel 2.6.32-42-server (#95-Ubuntu SMP Wed Jul 25 16:10:49 UTC 2012)]
Sep 30 16:16:51 porkypig gammu-smsd[25355]: gammu: [System error - open in serial_open, 16, "Device or resource busy"]
Sep 30 16:16:51 porkypig gammu-smsd[25355]: gammu: Init:GSM_TryGetModel failed with error DEVICEOPENERROR[2]: Error opening device. Unknown, busy or no permissions.
Sep 30 16:16:51 porkypig gammu-smsd[25355]: Can't open device (Error opening device. Unknown, busy or no permissions.:2)
Sep 30 16:16:51 porkypig gammu-smsd[25355]: Using PGSQL service
Sep 30 16:16:51 porkypig gammu-smsd[25355]: Disconnecting from PostgreSQL
I used two different commands. Both of them find different processes culpable. First I try fuser:
fuser -m -u /dev/ttyS0
/dev/ttyS0: 21624(guarddoggps)
cd /proc/21624
cat status
Name: dropbox
State: S (sleeping)
Tgid: 21624
Pid: 21624
PPid: 1
TracerPid: 0
Uid: 1001 1001 1001 1001
Gid: 1001 1001 1001 1001
FDSize: 64
Groups: 5 27 1001 5004
VmPeak: 873732 kB
VmSize: 806040 kB
VmLck: 0 kB
VmHWM: 207668 kB
VmRSS: 131864 kB
VmData: 547820 kB
VmStk: 160 kB
VmExe: 3524 kB
VmLib: 29660 kB
VmPTE: 1244 kB
Threads: 21
SigQ: 0/16382
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000001001000
SigCgt: 00000001800004c8
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: ffffffffffffffff
Cpus_allowed: ff
Cpus_allowed_list: 0-7
Mems_allowed: 00000000,00000001
Mems_allowed_list: 0
voluntary_ctxt_switches: 202
nonvoluntary_ctxt_switches: 1
So fuser says dropbox is using it.
Then I use lsof:
sudo lsof | grep ttyS0
screen 23520 root 6u CHR 4,64 0t0 1421 /dev/ttyS0
lsof says screen (rather than dropbox) is using it.
So which of these programs (dropbox or screen) is really causing gammu-smsd to refuse to start because of the resourcing being "busy"?
|
The short answer is: screen.
The slightly longer answer is that the -m flag to fuser tells it to list everything using the mountpoint. Depending on your setup, that probably means all of /dev, but it could also be /. Clearly not what you intended. You'll get a very long list if you do fuser -vm /dev/ttyS0, over 60 lines on my system.
Take off the -m and it'll probably give you the same answer as lsof did.
| fuser vs lsof to check files in use |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.