Sei sulla pagina 1di 43

INGLES 1 Introduction

GNU ddrescue is a data recovery tool. It copies data from one file or block device (hard disc, cdrom, etc) to another, trying hard to rescue data in case of read errors. The basic operation of ddrescue is fully automatic. That is, you don't have to wait for an error, stop the program, read the log, run it backwards, etc. If you use the logfile feature of ddrescue, the data is rescued very efficiently, (only the needed blocks are read). Also you can interrupt the rescue at any time and resume it later at the same point. Ddrescue does not write zeros to the output when it finds bad sectors in the input, and does not truncate the output file if not asked to. So, every time you run it on the same output file, it tries to fill in the gaps without wiping out the data already rescued. Automatic merging of backups: If you have two or more damaged copies of a file, cdrom, etc, and run ddrescue on all of them, one at a time, with the same output file, you will probably obtain a complete and error-free file. This is so because the probability of having damaged areas at the same places on different input files is very low. Using the logfile, only the needed blocks are read from the second and successive copies. Ddrescue recommends lzip for compression of backups because of its reliability and data recovery capabilities, including error-checked merging of backup copies. The combination ddrescue + lziprecover is the best option for recovering data from multiple damaged copies. See lziprecover-example, for an example. Recordable CD and DVD media keep their data only for a finite time (typically for many years). After that time, data loss develops slowly with read errors growing from the outer media region towards the inside. Just make two (or more) copies of every important CD/DVD you burn so that you can later recover them with ddrescue. Because ddrescue needs to read and write at random places, it only works on seekable (random access) input and output files. If your system supports it, ddrescue can use direct disc access to read the input file, bypassing the kernel cache.

Ddrescue also features a "fill mode" able to selectively overwrite parts of the output file, which has a number of interesting uses like wiping data, marking bad areas or even, in some cases, "repair" damaged sectors. Next: Algorithm, Previous: Introduction, Up: Top

2 Basic Concepts
Block Any amount of data. A block is described by its starting position and its size. Cluster Group of consecutive sectors read or written in one go. Device Piece of hardware containing data. Hard disc drives, cdrom drives, USB pendrives, are devices. /dev/hda, /dev/sdb, are device names. File Files are named units of data which are stored by the operating system for you to retrieve later by name. Devices are accessed by means of their associated file names. Partition Every part in which a device is divided. A partition normally contains a file system. /dev/hda1, /dev/sdb3, are partition names. Recoverable formats As ddrescue uses standard library functions to read data from the device being rescued, only mountable device formats can be rescued with ddrescue. DVDs can be mounted and they can be rescued, "compact disc digital audio" CDs can't, "video CDs"[1] maybe. [1] http://en.wikipedia.org/wiki/Video_CD Rescue domain Block or set of blocks to be acted upon (rescued, listed, etc). You can define it with the options `--input-position', `--max-size' and `--domain-logfile'. The rescue domain defaults to the whole input file or logfile. Sector Hardware block. Smallest accessible amount of data on a device. Next: Invoking Ddrescue, Previous: Basic Concepts, Up: Top

3 Algorithm
GNU ddrescue manages efficiently the status of the rescue in progress and tries to rescue the good parts first, scheduling reads inside bad (or slow) areas

for later. This maximizes the amount of data that can be finally recovered from a failing drive. The standard dd utility can be used to save data from a failing drive, but it reads the data sequentially, which may wear out the drive without rescuing anything if the errors are at the beginning of the drive. Other programs switch to small size reads when they find errors, but they still read the data sequentially. This is a bad idea because it means spending more time at error areas, damaging the surface, the heads and the drive mechanics, instead of getting out of them as fast as possible. This behavior reduces the chances of rescuing the remaining good data. The algorithm of ddrescue is as follows (the user may interrupt the process at any point, but be aware that a bad drive can block ddrescue for a long time until the kernel gives up): 1) Optionally read a logfile describing the status of a multi-part or previously interrupted rescue. If no logfile is specified or is empty or does not exist, mark all the rescue domain as non-tried. 2) Read the non-tried parts of the input file, marking the failed blocks as nontrimmed and skipping beyond them, until all the rescue domain is tried. Only non-tried areas are read in large blocks. Trimming, splitting and retrying are done sector by sector. Each sector is tried at most two times; the first in this step as part of a large block read, the second in one of the steps below as a single sector read. 3) Read backwards one sector at a time the non-trimmed blocks, until a bad sector is found. For each non-trimmed block, mark the bad sector found as bad-sector and mark the rest of that block as non-split. 4) Read forwards one sector at a time the non-split blocks, marking the bad sectors found as bad-sector. After a number of consecutive bad sectors is found in a block large enough, the block is split by half and the reading continues on the second half. This recursively splits the largest failed blocks without producing a logfile too large. 5) Optionally try to read again the bad sectors until the specified number of retries is reached. 6) Optionally write a logfile for later use. Note that as ddrescue splits the failed blocks, making them smaller, the total error size may diminish while the number of errors increases.

The logfile is periodically saved to disc, as well as when ddrescue finishes or is interrupted. So in case of a crash you can resume the rescue with little recopying. Also, the same logfile can be used for multiple commands that copy different areas of the input file, and for multiple recovery attempts over different subsets. See this example: Rescue the most important part of the disc first.
ddrescue -i0 -s50MiB /dev/hdc hdimage logfile ddrescue -i0 -s1MiB -d -r3 /dev/hdc hdimage logfile

Then rescue some key disc areas.


ddrescue -i30GiB -s10GiB /dev/hdc hdimage logfile ddrescue -i230GiB -s5GiB /dev/hdc hdimage logfile

Now rescue the rest (does not recopy what is already done).
ddrescue /dev/hdc hdimage logfile ddrescue -d -r3 /dev/hdc hdimage logfile

Next: Logfile Structure, Previous: Algorithm, Up: Top

4 Invoking Ddrescue
The format for running ddrescue is:
ddrescue [options] infile outfile [logfile]

ddrescue supports the following options: `-h' `--help' Print an informative help message describing the options and exit. `-V' `--version' Print the version number of ddrescue on the standard output and exit. `-a bytes' `--min-read-rate=bytes' Minimum read rate of good non-tried areas, in bytes per second. If the read rate falls below this value, ddrescue will skip ahead a variable amount depending on rate and error history. The skipped blocks are tried in additional passes (before trimming) where the minimum read rate is divided by ten before each pass, until there are no more non-tried

blocks left. If bytes is 0 (auto), the minimum read rate is recalculated for each block read as (average_rate / 10). Note that specifying a minimum read rate above the posibilities of the input device will result in a very low average rate because all reads will be considered slow reads and continuous skipping will occur. This will also make the logfile grow disproportionately. `-A' `--try-again' Mark all non-split and non-trimmed blocks inside the rescue domain as non-tried before beginning the rescue. Try this if the drive stops responding and ddrescue immediately starts splitting failed blocks when restarted. If `--retrim' is also specified, mark all failed blocks inside the rescue domain as non-tried. `-b bytes' `--block-size=bytes' Sector (hardware block) size of input device in bytes (usually 512 for hard discs and 3.5" floppies, 1024 for 5.25" floppies, and 2048 for cdroms). Defaults to 512. `-B' `--binary-prefixes' Show units with binary prefixes (powers of 1024). SI prefixes (powers of 1000) are used by default. (See table below). `-c sectors' `--cluster-size=sectors' Number of sectors to copy at a time. Defaults to 64 KiB / sector_size. Try smaller values for slow drives. The number of sectors per track (18 or 9) is a good value for floppies. `-C' `--complete-only' Limit rescue domain to the blocks listed in the logfile. Do not read new data beyond logfile limits. This is useful when reading from devices of undefined size, like raw devices, or when the drive returns an incorrect size. It can only be used after a first rescue attempt, possibly limited with the `--max-size' option, has produced a complete logfile. `-d' `--direct' Use direct disc access to read from infile, bypassing the kernel cache. (Open the file with the O_DIRECT flag). Use it only on devices or partitions, not on regular files. Sector size must be correctly set for this to work. Not all systems support this.

If your system does not support direct disc access, ddrescue will warn you. If the sector size is not correctly set, all reads will result in errors, and no data will be rescued. `-D' `--synchronous' Use synchronous writes for outfile. (Issue a fsync call after every write). May be useful when forcing the drive to remap its bad sectors. `-e [+]n' `--max-errors=[+]n' Maximum number of error areas allowed before giving up. Defaults to infinity. If n is preceded by `+' the number refers to new error areas found in this run, not counting those already annotated in the logfile. `-E bytes' `--max-error-rate=bytes' Maximum rate of errors allowed before giving up, in bytes per second. Defaults to infinity. The rate being measured is that of actually failed reads, so the rescue may finish because of this rate being exceeded even if the total error size (errsize) does not change because the areas being tried are already marked as errors. `-f' `--force' Force overwrite of outfile. Needed when outfile is not a regular file, but a device or partition. `-F types' `--fill=types' Fill the blocks in outfile specified as any of types in logfile, with data read from infile. types contains one or more of the status characters defined in the chapter Logfile Structure (see Logfile Structure). See the chapter Fill Mode (see Fill Mode) for a complete description of the fill mode. `-g' `--generate-logfile' Generate an approximate logfile from the infile and outfile of the original rescue run. Note that you must keep the original offset between `--input-position' and `--output-position' of the original rescue run. See the chapter Generate Mode (see Generate Mode) for a complete description of the generate mode. `-i bytes' `--input-position=bytes' Starting position in infile, in bytes. Defaults to 0. In fill mode it refers to a position in the infile of the original rescue run. See the chapter Fill Mode (see Fill Mode) for details.

`-I' `--verify-input-size' Compare the size of infile with the size calculated from the list of blocks contained in the logfile, and exit with status 1 if they differ. This is not enabled by default because the size of some devices can't be known in advance and because the size derived from the logfile may be incomplete, for example after doing a partial rescue. `-K bytes' `--skip-size=bytes' Set the initial size to skip on the first read error or slow read. The value given will be rounded to the next multiple of sector size. For subsequent read errors or slow reads, ddrescue will modify the skip size depending on error rate and error history. Valid values range from 64 KiB to 1 GiB. Defaults to 64 KiB. `-m file' `--domain-logfile=file' Restrict the rescue domain to the blocks marked as finished in the logfile file. This is useful if the destination drive fails during the rescue. `-M' `--retrim' Mark all failed blocks inside the rescue domain as non-trimmed before beginning the rescue. The effect is similar to `--max-retries=1', but the bad sectors are tried in a different order, making perhaps possible to rescue some of them. `-n' `--no-split' Skip the splitting pass. Avoids spending a lot of time trying to rescue the most difficult parts of the file. `-o bytes' `--output-position=bytes' Starting position in outfile, in bytes. Defaults to `--inputposition'. The bytes below bytes aren't touched if they exist and truncation is not requested. Else they are set to 0. `-p' `--preallocate' Preallocate space on disc for outfile. Only space for regular files can be preallocated. If preallocation succeeds, rescue will not fail due to lack of free space on disc. If ddrescue can't determine the size to preallocate, you may need to specify it with some combination of the `--inputposition', `--output-position', `--max-size', and `-domain-logfile' options. `-q'

`--quiet' Quiet operation. Suppress all messages. `-r n' `--max-retries=n' Exit after given number of retry passes. Defaults to 0. -1 means infinity. Every bad sector is tried only one time per pass. To retry bad sectors detected on a previous run, you must specify a non-zero number of retries. `-R' `--reverse' Reverse direction of all copy operations. This makes copying, splitting and retrying to be run backwards, and trimming to be run forwards. `-s bytes' `--max-size=bytes' Maximum size of the input data to be copied, in bytes. If ddrescue can't determine the size of the input device, you may need to specify it with this option. Note that this option specifies the size of the input data to be copied, not the size of the resulting outfile. So, for example, the following command creates an outfile 300 bytes long, but only writes data on the last 200 bytes:
ddrescue -i 100 -s 200 infile outfile logfile

`-S' `--sparse' Use sparse writes for outfile. (The blocks of zeros are not actually allocated on disc). May save a lot of disc space in some cases. Not all systems support this. Only regular files can be sparse. `-t' `--truncate' Truncate outfile to zero size before writing to it. Only works for regular files, not for drives or partitions. `-T interval' `--timeout=interval' Maximum time since last successful read allowed before giving up. Defaults to infinity. interval is a rational number (like 1.5 or 1/2) optionally followed by one of `s', `m', `h' or `d', meaning seconds, minutes, hours and days respectively. If no unit is specified, it defaults to seconds. `-v' `--verbose' Verbose mode. Further -v's (up to 4) increase the verbosity level. `-x bytes' `--extend-outfile=bytes'

Extend the size of outfile to make it at least bytes long. If the size of outfile is already equal or longer than bytes then this option does nothing. Use this option to guarantee a minimum size for outfile. Only regular files can be extended. Numbers given as arguments to options (positions, sizes, retries, etc) may be followed by a multiplier and an optional `B' for "byte". Table of SI and binary prefixes (unit multipliers):
Prefix Value k M G T P E Z Y | Prefix Value |b hardware blocks kilobyte (10^3 = 1000) | Ki kibibyte (2^10 = 1024) megabyte (10^6) | Mi mebibyte (2^20) gigabyte (10^9) | Gi gibibyte (2^30) terabyte (10^12) | Ti tebibyte (2^40) petabyte (10^15) | Pi pebibyte (2^50) exabyte (10^18) | Ei exbibyte (2^60) zettabyte (10^21) | Zi zebibyte (2^70) yottabyte (10^24) | Yi yobibyte (2^80)

Return values: 0 for a normal exit, 1 for environmental problems (file not found, invalid flags, I/O errors, etc), 2 to indicate a corrupt or invalid input file, 3 for an internal consistency error (eg, bug) which caused ddrescue to panic. Next: Examples, Previous: Invoking Ddrescue, Up: Top

5 Logfile Structure
The logfile is a text file easy to read and edit. It is formed by three parts, the heading comments, the status line, and the list of data blocks. Any line beginning with `#' is a comment line. The blocks in the list of data blocks must be contiguous and non-overlapping. NOTE: Logfiles generated by a version of ddrescue prior to 1.6 lack the status line. If you want to use an old logfile with ddrescue 1.6 or later, you will have to insert a line like `0 +' at the beginning of the logfile. The heading comments contain the version of ddrescue and the command line used to create the logfile. They are intended as information for the user.

The first non-comment line is the status line. It contains a non-negative integer and a status character. The integer is the position being tried in the input file. The status character is one of these:
Character Meaning '?' copying non-tried blocks '*' trimming non-trimmed blocks '/' splitting non-split blocks '-' retrying bad sectors 'F' filling specified blocks 'G' generating approximate logfile '+' finished

Every line in the list of data blocks describes a block of data. It contains 2 non-negative integers and a status character. The first integer is the starting position of the block in the input file, the second integer is the size (in bytes) of the block. The status character is one of these:
Character Meaning '?' non-tried block '*' failed block non-trimmed '/' failed block non-split '-' failed block bad-sector(s) '+' finished block

And here is an example logfile: # Rescue Logfile. Created by GNU ddrescue version 1.16 # Command line: ddrescue /dev/fd0 fdimage logfile # current_pos current_status 0x00120000 ? # pos size status
0x00000000 0x00117000 + 0x00117000 0x00000200 0x00117200 0x00001000 / 0x00118200 0x00007E00 * 0x00120000 0x00048000 ?

If you edit the file, you may use decimal, hexadecimal or octal values, using the same syntax that integer constants in C++. Next: Direct Disc Access, Previous: Logfile Structure, Up: Top

6 A small tutorial with examples


Ddrescue is like any other power tool. You need to understand what it does, and you need to understand some things about the machines it does those things to, in order to use it safely. A failing drive tends to develop more and more errors as time passes. Because of this, you should rescue the data from a drive as soon as you notice the first error. Be diligent because every time a physically damaged drive powers up and is able to output some data, it may be the very last time that it ever will. You should make a copy of the failing drive with ddrescue, and then try to repair the copy. If your data is really important, use the first copy as a master for a second copy, and try to repair the second copy. If something goes wrong, you have the master intact to try again. IMPORTANT! Always use a logfile unless you know you won't need it. Without a logfile, ddrescue can't resume a rescue, only reinitiate it. IMPORTANT! Never try to rescue a r/w mounted partition. The resulting copy may be useless. IMPORTANT! If you use a device or a partition as destination, any data stored there will be overwritten. IMPORTANT! If you interrupt the rescue and then reboot, any partially copied partitions should be hidden before allowing them to be touched by any operating system that tries to mount and "fix" the partitions it sees. IMPORTANT! Never try to repair a file system on a drive with I/O errors; you will probably lose even more data. If you are trying to rescue a whole partition, first repair the copy with e2fsck or some other tool appropiate for the type of partition you are trying to rescue, then mount the repaired copy somewhere and try to recover the files in it. If the drive is so damaged that the file system in the rescued partition can't be repaired or mounted, you will have to browse the rescued data with an hex editor and extract the desired parts by hand or use a file recovery tool like photorec. If the partition table is damaged, you may try to rescue the whole disc, then try to repair the partition table and the partitions on the copy.

If the damaged drive is not listed in /dev, then you cannot rescue it. At least not with ddrescue. Example 1: Rescue a whole disc with two ext2 partitions in /dev/hda to /dev/hdb. Note: you do not need to partition /dev/hdb beforehand, but if the partition table on /dev/hda is damaged, you'll need to recreate it somehow on /dev/hdb.
ddrescue -f -n /dev/hda /dev/hdb logfile ddrescue -d -f -r3 /dev/hda /dev/hdb logfile fdisk /dev/hdb e2fsck -v -f /dev/hdb1 e2fsck -v -f /dev/hdb2

Example 2: Rescue an ext2 partition in /dev/hda2 to /dev/hdb2. Note: you need to create the hdb2 partition with fdisk first. hdb2 should be of appropiate type and size.
ddrescue -f -n /dev/hda2 /dev/hdb2 logfile ddrescue -d -f -r3 /dev/hda2 /dev/hdb2 logfile e2fsck -v -f /dev/hdb2 mount -t ext2 -o ro /dev/hdb2 /mnt (read rescued files from /mnt)

Example 3: Rescue a CD-ROM in /dev/cdrom.


ddrescue -n -b2048 /dev/cdrom cdimage logfile ddrescue -d -b2048 /dev/cdrom cdimage logfile (write cdimage to a blank CD-ROM)

Example 4: Rescue a CD-ROM in /dev/cdrom from two copies.


ddrescue -n -b2048 /dev/cdrom cdimage logfile ddrescue -d -b2048 /dev/cdrom cdimage logfile (insert second copy in the CD drive) ddrescue -d -r1 -b2048 /dev/cdrom cdimage logfile (write cdimage to a blank CD-ROM)

Example 5: Rescue a lzip compressed backup from two copies on CD-ROM with error-checked merging of copies (See the lziprecover manual for details about lziprecover).
ddrescue -b2048 /dev/cdrom cdimage1 logfile1 mount -t iso9660 -o loop,ro cdimage1 /mnt/cdimage cp /mnt/cdimage/backup.tar.lz rescued1.tar.lz umount /mnt/cdimage (insert second copy in the CD drive) ddrescue -b2048 /dev/cdrom cdimage2 logfile2 mount -t iso9660 -o loop,ro cdimage2 /mnt/cdimage cp /mnt/cdimage/backup.tar.lz rescued2.tar.lz umount /mnt/cdimage lziprecover -m -v -o rescued.tar.lz rescued1.tar.lz rescued2.tar.lz

Example 6: While rescuing the whole drive /dev/hda to /dev/hdb, /dev/hdb fails and you have to rescue data to a third drive, /dev/hdc.
ddrescue -f -n /dev/hda /dev/hdb logfile1 here ddrescue -f -m logfile1 /dev/hdb /dev/hdc logfile2 <-- /dev/hdb fails

ddrescue -f -n /dev/hda /dev/hdc logfile2 ddrescue -d -f -r3 /dev/hda /dev/hdc logfile2

Example 7: While rescuing the whole drive /dev/hda to /dev/hdb, /dev/hda stops responding and disappears from /dev.
ddrescue -f -n /dev/hda /dev/hdb logfile here (restart /dev/hda or reboot computer as many times as needed) ddrescue -f -n -A /dev/hda /dev/hdb logfile ddrescue -d -f -r3 /dev/hda /dev/hdb logfile <-- /dev/hda fails

Next: Fill Mode, Previous: Examples, Up: Top

7 Direct Disc Access


If you notice that the positions and sizes in the log file are ALWAYS multiples of the sector size, maybe your kernel is caching the disc accesses and grouping them. In this case you may want to use direct disc access or a raw device to bypass the kernel cache and rescue more of your data. NOTE! Sector size must be correctly set with the `--block-size' option for this to work. Try the `--direct' option first. If direct disc access is not available in your system, try raw devices. Read your system documentation to find how to bind a raw device to a regular block device. Ddrescue aligns its I/O buffer to the sector size so that it can be used for direct disc access or to read from raw devices. For efficiency reasons, also aligns it to the memory page size if page size is a multiple of sector size. Ddrescue can't determine the size of a raw device, so an explicit `--max-size' or `-complete-only' option is needed. Using direct disc access, or reading from a raw device, may be slower or faster than normal cached reading depending on your OS and hardware. In case it is slower you may want to make a first pass using normal cached reads and use direct disc access, or a raw device, only to recover the good sectors inside the failed blocks. Example 1: using direct disc access.
ddrescue -f -n /dev/hdb1 /dev/hdc1 logfile ddrescue -d -f -r3 /dev/hdb1 /dev/hdc1 logfile e2fsck -v -f /dev/hdc1 mount -t ext2 -o ro /dev/hdc1 /mnt

Example 2: using a raw device.


raw /dev/raw/raw1 /dev/hdb1 ddrescue -f -n /dev/hdb1 /dev/hdc1 logfile ddrescue -C -f -r3 /dev/raw/raw1 /dev/hdc1 logfile raw /dev/raw/raw1 0 0 e2fsck -v -f /dev/hdc1

mount -t ext2 -o ro /dev/hdc1 /mnt

Next: Generate Mode, Previous: Direct Disc Access, Up: Top

8 Fill Mode
When ddrescue is invoked with the `--fill' option it operates in "fill mode", which is different from the default "rescue mode". That is, if you use the `--fill' option, ddrescue does not rescue anything. It only fills with data read from the input file the blocks of the output file whose status character from the logfile coincides with one of the type characters specified as argument to the `--fill' option. In fill mode the input file may have any size. If it is too small, the data will be duplicated as many times as necessary to fill the input buffer. If it is too big, only the data needed to fill the input buffer will be read. Then the same data will be written to every block or sector to be filled. Note that in fill mode the input file is always read from position 0. If you specify a `--input-position', it refers to the original input file from which the logfile was built, and is only used to calculate the offset between input and output positions. Note also that when filling the input file of the original rescue run you should set `--input-position' and `--output-position' to identical values, whereas when filling the output file of the original rescue run you should keep the original offset between `--input-position' and `-output-position'. The `--fill' option implies the `--complete-only' option. In fill mode the logfile is updated to allow resumability when interrupted or in case of a crash, but as nothing is being rescued the logfile is not destroyed. The status line is the only part of the logfile that is modified. The fill mode has a number of uses. See the following examples: Example 1: Mark parts of the rescued copy to allow finding them when examined in an hex editor. For example, the following command line fills all blocks marked as `-' (bad-sector) with copies of the string `BAD SECTOR ':
printf "BAD SECTOR " > tmpfile ddrescue --fill=- tmpfile outfile logfile

Example 2: Wipe only the good sectors, leaving the bad sectors alone. This way, the drive will still test bad (i.e., with unreadable sectors). This is the fastest way of wiping a failing drive, and is specially useful when sending the drive back to the manufacturer for warranty replacement.
ddrescue --fill=+ --force /dev/zero bad_drive logfile

Example 3: Force the drive to remap the bad sectors, making it usable again. If the drive has only a few bad sectors, and they are not caused by drive age, you can probably just rewrite those sectors, and the drive will reallocate them automatically to new "spare" sectors that it keeps for just this purpose. WARNING! This may not work on your drive.
ddrescue --fill=- --force --synchronous /dev/zero bad_drive logfile

Fill mode can also help you to figure out, independently of the file system used, what files are partially or entirely in the bad areas of the disc. Just follow these steps: 1) Copy the damaged drive with ddrescue until finished. Do not use sparse writes. This yields a logfile with only finished (`+') and bad-sector (`-') blocks. 2) Fill the bad-sector blocks of the copied drive or image file with a string not present in any file, for example "DEADBEEF". 3) Mount the copied drive (or the image file, via loopback device). 4) Grep for the fill string in all the files. Those files containing the string reside (at least partially) in damaged disc areas. 5) Unmount the copied drive or image file. 6) Optionally fill the bad-sector blocks of the copied drive or image file with zeros to restore the disc image. Example 4: Figure out what files are in the bad areas of the disc.
ddrescue -b2048 /dev/cdrom cdimage logfile printf "DEADBEEF" > tmpfile ddrescue --fill=- tmpfile cdimage logfile rm tmpfile mount -t iso9660 -o loop,ro cdimage /mnt/cdimage find /mnt/cdimage -type f -exec grep "DEADBEEF" '{}' ';' umount /mnt/cdimage ddrescue --fill=- /dev/zero cdimage logfile

Next: Ddrescuelog, Previous: Fill Mode, Up: Top

9 Generate-logfile Mode
So you didn't read the tutorial and started ddrescue without a logfile. Now, two days later, your computer crashed and you can't know how much data ddrescue managed to save. And even worse, you can't resume the rescue; you have to restart it from the very beginning. Or maybe you started copying a drive with `dd conv=noerror,sync' and are now in the same situation described above. In this case, note that you can't use a copy made by dd unless it was invoked with the `sync' conversion argument. Don't despair (yet). Ddrescue can in some cases generate an approximate logfile, from the input file and the (partial) copy, that is almost as good as an exact logfile. It makes this by simply assuming that sectors containing all zeros were not rescued. However, if the destination of the copy was a drive or a partition, (or an existing regular file and truncation was not requested), most probably you will need to restart ddrescue from the very beginning. (This time with a logfile, of course). The reason is that old data may be present in the drive that have not been overwritten yet, and may be thus non-tried but non-zero. For example, if you first tried one of these commands:
ddrescue infile outfile or dd if=infile of=outfile conv=noerror,sync

then you can generate an approximate logfile with this command:


ddrescue --generate-logfile infile outfile logfile

Note that you must keep the original offset between `--input-position' and `--output-position' of the original rescue run. Next: Invoking Ddrescuelog, Previous: Generate Mode, Up: Top

10 Ddrescuelog
Ddrescuelog is a tool that manipulates ddrescue logfiles, shows logfile contents, converts logfiles to/from other formats, compares logfiles, tests rescue status, and can delete a logfile if the rescue is done. Ddrescuelog operations can be restricted to one or several parts of the logfile if the domain setting options are used.

Here are some examples of how to use ddrescuelog, alone or in combination with other tools. Example 1: Delete the logfile if the rescue is finished (all data is recovered without errors left).
ddrescue -f /dev/hda /dev/hdb logfile ddrescuelog -d logfile

Example 2: Rescue two ext2 partitions in /dev/hda to /dev/hdb and repair the file systems using badblock lists generated with ddrescuelog. File system block size is 4096. Note: you do need to partition /dev/hdb beforehand.
fdisk /dev/hdb /deb/hdb ddrescue -f /dev/hda1 /dev/hdb1 logfile1 ddrescue -f /dev/hda2 /dev/hdb2 logfile2 ddrescuelog -l- -b4096 logfile1 > badblocks1 ddrescuelog -l- -b4096 logfile2 > badblocks2 e2fsck -v -f -L badblocks1 /dev/hdb1 e2fsck -v -f -L badblocks2 /dev/hdb2 <-- partition

Example 3: Rescue a whole disc with two ext2 partitions in /dev/hda to /dev/hdb and repair the file systems using badblock lists generated with ddrescuelog. Disc sector size is 512, file system block size is 4096. Arguments to options `-i' and `-s' are the starting positions and sizes of the partitions being rescued. Note: you do not need to partition /dev/hdb beforehand, but if the partition table on /dev/hda is damaged, you'll need to recreate it somehow on /dev/hdb.
ddrescue -f /dev/hda /dev/hdb logfile fdisk /dev/hdb sizes ddrescuelog -lbadblocks1 ddrescuelog -lbadblocks2 e2fsck -v -f -L e2fsck -v -f -L -b512 -i63b -o0 -s9767457b -b4096 logfile > -b512 -i9767520b -o0 -s128520b -b4096 logfile > badblocks1 /dev/hdb1 badblocks2 /dev/hdb2 <-- get partition

Next: Problems, Previous: Ddrescuelog, Up: Top

11 Invoking Ddrescuelog
The format for running ddrescuelog is:
ddrescuelog [options] logfile

Ddrescuelog supports the following options: `-h' `--help'

Print an informative help message describing the options and exit. `-V' `--version' Print the version number of ddrescuelog on the standard output and exit. `-a old_types,new_types' `--change-types=old_types,new_types' Change the status of every block in the rescue domain from one type in old_types to the corresponding type in new_types, much like the `tr' command does, and write the resulting logfile to standard output.old_types and new_types are strings of block status characters as defined in the chapter Logfile Structure (see Logfile Structure). Blocks whose status is not in old_types are left unchanged. If new_types is shorter than old_types the last type of new_types is repeated as many times as necessary. `-b bytes' `--block-size=bytes' Block size used by ddrescuelog. Depending on the requested operation it may be the sector size of the input device, the block size of the rescued file system, etc. Defaults to 512. `-c[type1type2]' `--create-logfile[=type1type2]' Create a logfile from a list of block numbers read from standard input. Only blocks included in the rescue domain will be added to logfile. type1 and type2 are block status characters as defined in the chapter Logfile Structure (see Logfile Structure). type1 sets the type for blocks included in the list, while type2 sets the type for the rest of the logfile. If not specified, type1 defaults to `+' and type2 defaults to `-'. `-d' `--delete-if-done' Delete the given logfile if all the blocks in the rescue domain have been successfuly recovered. The exit status is 0 if logfile could be deleted, 1 otherwise. `-D' `--done-status' Test if all the blocks in the rescue domain have been successfuly recovered. The exit status is 0 if all tested blocks are finished, 1 otherwise. `-f' `--force' Force overwrite of logfile. `-i bytes'

`--input-position=bytes' Starting position of the rescue domain, in bytes. Defaults to 0. It refers to a position in the original input file. `-l types' `--list-blocks=types' Print on standard output the block numbers of the blocks specified as any of types in logfile and included in the rescue domain. types contains one or more of the block status characters defined in the chapter Logfile Structure (see Logfile Structure). The list format is one block number per line in decimal, like the output of the badblocks program, so that it can be used as input for e2fsck or other similar filesystem repairing tool. `-m file' `--domain-logfile=file' Restrict the rescue domain to the blocks marked as finished in the logfile file. `-n' `--invert-logfile' Invert the types of the blocks in logfile which are included in the rescue domain, and write the resulting logfile to standard output. Finished blocks (`+') are changed to bad-sector (`-'), all other types are changed to finished. `--invert-logfile' is equivalent to `--changetypes=?*/-+,++++-' `-o bytes' `--output-position=bytes' Starting position in output file, in bytes. Is used by the `--listblocks' option. Defaults to `--input-position'. `-p file' `--compare-logfile=file' Compare the types of the blocks included in the rescue domain. The exit status is 0 if all tested blocks are the same in both files, 1 otherwise. `-q' `--quiet' Quiet operation. Suppress all messages. `-s bytes' `--max-size=bytes' Maximum size of the rescue domain, in bytes. It refers to a size in the original input file. `-t' `--show-status'

Print a summary of logfile contents on the standard output. The summary can be restricted to one or several parts of logfile if the domain setting options are used. `-v' `--verbose' Verbose mode. Further -v's (up to 4) increase the verbosity level. `-x file' `--xor-logfile=file' Perform a logical XOR (exclusive OR) operation between the finished blocks in file and those in logfile, and write the resulting logfile to standard output. In other words, in the resulting logfile a block is only shown as finisned if it was finisned in either of the two input logfiles but not in both. `-y file' `--and-logfile=file' Perform a logical AND operation between the finished blocks in file and those in logfile, and write the resulting logfile to standard output. In other words, in the resulting logfile a block is only shown as finisned if it was finisned in both input logfiles. `-z file' `--or-logfile=file' Perform a logical OR operation between the finished blocks in file and those in logfile, and write the resulting logfile to standard output. In other words, in the resulting logfile a block is shown as finisned if it was finisned in either of the two input logfiles. Return values: 0 for a normal exit, 1 for environmental problems (file not found, invalid flags, I/O errors, etc), 2 to indicate a corrupt or invalid input file, 3 for an internal consistency error (eg, bug) which caused ddrescuelog to panic.

ESPAOL
1 Introduccin

GNU ddrescue es una herramienta de recuperacin de datos. Copia los datos de un archivo o dispositivo de bloques (disco duro, CD-ROM, etc) a otro, tratando de rescatar los datos en caso de errores de lectura.

El funcionamiento bsico de ddrescue es totalmente automtico. Es decir, usted no tiene que esperar a que un error, detenga el programa, lea el registro, ejecute al revs, etc

Si utiliza la funcin de archivo de registro de ddrescue, los datos se rescat de manera muy eficiente, (slo los bloques necesarios se leen). Tambin puede interrumpir el rescate en cualquier momento y reanudarla ms tarde en el mismo punto.

Ddrescue no escribe ceros a la salida cuando encuentra los sectores defectuosos en la entrada, y no trunca el archivo de salida si no se le pidi. As, cada vez que se ejecuta en el mismo archivo de salida, intenta llenar los vacos sin borrar los datos ya rescatados.

Fusin automtica de copias de seguridad: Si tiene dos o ms copias daadas de un archivo, cdrom, etc, y ejecutar ddrescue en todos ellos, uno a la vez, con el mismo archivo de salida, es probable que obtener una completa y sin errores archivo. Esto es as debido a que la probabilidad de tener reas daadas en los mismos lugares en los diferentes archivos de entrada es muy baja. Utilizando el archivo de registro, slo los bloques necesarios se leen de las segunda y sucesivas copias.

Ddrescue lzip recomienda para la compresin de las copias de seguridad debido a su fiabilidad y capacidad de recuperacin de datos, incluyendo errores comprobado combinacin de copias de seguridad. La combinacin ddrescue + lziprecover es la mejor opcin para la recuperacin de datos de varias copias daadas. Ver lziprecover-ejemplo, para ver un ejemplo.

CD y DVD grabables mantener sus datos slo durante un tiempo determinado (habitualmente durante muchos aos). Despus de ese tiempo, la prdida de datos se desarrolla lentamente con errores de lectura de crecimiento de la regin exterior del papel hacia el interior. Simplemente haga dos (o ms) copias de todos los CD / DVD que se quema para que luego los puede recuperar con ddrescue importante.

Debido ddrescue necesita leer y escribir en lugares al azar, que slo funciona en seekable (acceso aleatorio) archivos de entrada y de salida.

Si su sistema lo soporta, ddrescue puede utilizar el acceso directo del disco para leer el archivo de entrada, sin pasar por la cach del kernel.

Ddrescue tambin cuenta con un "modo de relleno", capaz de sobrescribir de forma selectiva partes del archivo de salida, que tiene un nmero de usos interesantes como limpieza de datos, marcando zonas malas o incluso, en algunos casos, "reparar" los sectores daados.

Siguiente: Algoritmo, Previous: Introduccin, Up: Top 2 Conceptos bsicos

Bloquear Cualquier cantidad de datos. Un bloque se describe por su posicin inicial y su tamao. Grupo Grupo de los sectores consecutivos ledos o escritos de una sola vez. Dispositivo Pedazo de datos que contienen hardware. Los discos duros de disco, unidades de CDROM, pendrives USB, son dispositivos. / Dev / hda, / dev / sdb, son los nombres de dispositivos. Expediente Los archivos se denominan unidades de datos que son almacenados por el sistema operativo para que usted pueda recuperar ms adelante por su nombre. Los dispositivos son accedidos por medio de sus nombres de archivo asociados. Tabique Cada parte en la que un dispositivo est dividido. Una particin contiene normalmente un sistema de archivos. / Dev/hda1, / dev/sdb3, son nombres de particin. Formatos recuperables Como ddrescue utiliza funciones de la biblioteca estndar para leer los datos del dispositivo que se rescat, slo formatos de dispositivos montables pueden ser rescatados con ddrescue. DVDs se pueden montar y pueden ser rescatados ", audio digital de disco compacto" CD no se puede, "CD de vdeo" [1] tal vez. [1] http://en.wikipedia.org/wiki/Video_CD Dominio Rescate Bloquear o conjunto de bloques que se acta (rescatado, lista, etc). Se puede definir con las opciones `- de entrada-position ',` - max-size' y '- domain-logfile. El dominio por defecto de rescate en el archivo de entrada total o archivo de registro.

Sector Bloque de Hardware. Pequea cantidad accesible de datos en un dispositivo. Siguiente: Invocar Ddrescue, Previous: Conceptos bsicos, Up: Top 3 Algoritmo

GNU ddrescue gestiona eficazmente la situacin de rescate en curso y trata de rescatar las partes buenas primero, programacin lee reas dentro malos (o lento) para ms tarde. Esto maximiza la cantidad de datos que pueden ser finalmente recuperado de una unidad en su defecto.

La utilidad dd estndar se puede utilizar para guardar datos de una unidad en su defecto, pero lee los datos de forma secuencial, lo que puede llevar a cabo sin la unidad de rescate de nada si los errores son en el principio de la unidad.

Otros programas cambian al pequeo tamao se lee cuando se encuentran errores, pero todava leen los datos de forma secuencial. Esta es una mala idea porque significa pasar ms tiempo en las zonas de error, se dae la superficie, los jefes y la mecnica del disco, en lugar de salir de ellos lo ms rpido posible. Este comportamiento reduce las posibilidades de rescatar a los buenos datos restantes.

El algoritmo de ddrescue es el siguiente (el usuario puede interrumpir el proceso en cualquier momento, pero tenga en cuenta que una mala unidad puede bloquear ddrescue durante mucho tiempo hasta que el kernel se da por vencido):

1) Opcionalmente leer un archivo de registro que describe el estado de un rescate de varias partes o interrumpida anteriormente. Si no se especifica o est vaco no logfile o no existe, marcar todo el dominio de rescate como no probado.

2) Lea las piezas no probados del archivo de entrada, marcando los bloques fallidos como no recortado y saltar ms all de ellos, hasta que se prueba todo el dominio de rescate. Slo las reas no probados se leen grandes bloques. Cortar, dividir y volver a intentarlo se realizan sector por sector. Cada sector se trat como mximo dos veces, la primera en este paso como parte de un gran bloque de lectura, el segundo en uno de los pasos como un nico sector de leer.

3) Leer al revs un sector a la vez los bloques no recortadas, hasta que se encuentre con un sector defectuoso. Para cada bloque no recortado, marque el sector defectuoso encontrado tan mal-sector y marcar el resto de la manzana que no dividida.

4) Lea hacia delante un sector a la vez los bloques no-split, marcando los sectores defectuosos encontrados tan malo-sector. Despus de una serie de sectores consecutivos malos se encuentra en un bloque lo suficientemente grande, el bloque se divide a la mitad y la lectura contina en la segunda mitad. Esto divide de forma recursiva los mayores bloques fallidos sin producir un archivo de registro demasiado grande.

5) Opcionalmente tratar de leer de nuevo los sectores defectuosos hasta que se alcanza el nmero especificado de reintentos.

6) Opcionalmente escribe un archivo de registro para su uso posterior.

Tenga en cuenta que como ddrescue divide los bloques fallados, hacindolas ms pequeas, el tamao de error total puede disminuir, mientras que el nmero de errores aumenta. El archivo de registro se guarda peridicamente en un disco, as como cuando termina ddrescue o se interrumpe. As que en caso de un accidente que pueda reanudar el rescate con poco recopiado.

Tambin, el mismo archivo de registro puede ser utilizado para mltiples comandos que copian diferentes reas del archivo de entrada, y para mltiples intentos de recuperacin sobre diferentes subconjuntos. Vase el ejemplo:

Rescatar a la parte ms importante del disco primero.

ddrescue-i0-s50MiB / dev / hdc hdimage logfile ddrescue-i0-s1MiB-d-r3 / dev / hdc hdimage logfile Entonces rescatar algunas reas clave de disco.

ddrescue-i30GiB-s10GiB / dev / hdc hdimage logfile ddrescue-i230GiB-s5GiB / dev / hdc hdimage logfile Ahora rescatar al resto (no volver a copiar lo que ya est hecho).

ddrescue / dev / hdc hdimage logfile ddrescue-d-r3 / dev / hdc hdimage logfile Siguiente: Estructura del archivo de registro, Previous: Algoritmo, Up: Top 4 Invocacin Ddrescue

El formato para el funcionamiento de ddrescue es:

ddrescue [opciones] fichero-infile [logfile] ddrescue soporta las siguientes opciones:

`-H ' `- Help ' Imprime un mensaje de ayuda informativa que describe las opciones y salir. `-V ' `- Version ' Imprime el nmero de versin de ddrescue en la salida y la salida estndar. `-Una bytes ' `- Min-read-rate = bytes ' Lectura mnima tasa de buenas zonas no probadas, en bytes por segundo. Si la velocidad de lectura es inferior a este valor, ddrescue se salte una cantidad variable dependiendo de la velocidad y el historial de errores. Los bloques saltados son juzgados pasadas adicionales (antes del recorte), donde la velocidad de lectura mnima se divide por diez antes de cada pase, hasta que ya no hay bloques no probados izquierda. Si es 0 bytes (automtico), la velocidad de lectura mnima se vuelve a calcular para cada bloque redactado como (average_rate / 10).

Tenga en cuenta que especificando una tasa de lectura mnimo por encima de las posibilidades del dispositivo de entrada dar lugar a una tasa promedio muy bajo, porque todas las lecturas se considerar lee lenta y continua saltarse ocurrir. Esto tambin har que el archivo de registro crezca de manera desproporcionada.

`-A ' `- Intentar de nuevo ' Marcar todos los bloques no dividida y no recortado dentro del dominio de rescate como no tratado antes de comenzar el rescate. Pruebe esta opcin si la unidad deja de responder y ddrescue comienza inmediatamente divisin fallado bloquea cuando se reinicia. Si `- tambin se especifica Retrim ', marque todos los bloques fallidos dentro del dominio de rescate como no probado. `-B bytes ' `- Block-size = bytes ' Sector tamao (bloque hardware) del dispositivo de entrada en bytes (generalmente 512 para discos duros y disquetes de 3.5 ", 1024 de 5.25" disquetes y 2048 para cdroms). El valor predeterminado es 512. `-B ' `- Binario prefijos ' Mostrar unidades con prefijos binarios (potencias de 1024). Prefijos del SI (potencias de 1000) se utilizan de forma predeterminada. (Ver tabla). Sectores `-c ' `- Cluster-size = sectores ' Nmero de sectores para copiar a la vez. El valor predeterminado es 64 Kb / sector_size. Pruebe valores menores para las unidades lentas. El nmero de sectores por pista (18 y 9) es un buen valor para disquetes. `-C ' `- Completa-slo" Limite el dominio de rescate a los bloques que figuran en el archivo de registro. No lea nuevos datos ms all de los lmites de archivo de registro. Esto es til cuando la lectura de los dispositivos de tamao indefinido, como dispositivos en bruto, o cuando la unidad devuelve un tamao incorrecto. Esto slo se puede utilizar despus de un primer intento de rescate, posiblemente limitado con la opcin `- max-size ', ha producido un archivo de registro completo.

`-D ' `- Directa ' Utilice el acceso directo del disco para leer infile, sin pasar por la cach de kernel. (Abra el archivo con la bandera O_DIRECT). selo slo en dispositivos o particiones, no en archivos regulares. Tamao del Sector debe ajustarse correctamente para que esto funcione. No todos los sistemas admiten. Si su sistema no admite el acceso directo de discos, ddrescue le avisar. Si el tamao del sector no est configurado correctamente, todas las lecturas se traducir en errores, y sern rescatados hay datos.

'-D' `- Sncrono ' Utilice sncrono escribe para archivo de salida. (Emitir una llamada fsync despus de cada escritura). Puede ser til cuando se fuerza la unidad para reasignar sus sectores defectuosos. `-E [+] n ' `- Max-errors = [+] n ' El nmero mximo de reas de error permitido antes de darse por vencido. El valor predeterminado es infinito. Si n es precedido por '+' el nmero se refiere a las nuevas reas de error se encuentran en este plazo, sin contar los que ya estn anotados en el archivo de registro. Bytes `-E ' `- Max-error-rate = bytes ' La velocidad mxima de errores permitidos antes de renunciar, en bytes por segundo. El valor predeterminado es infinito. La tasa de que se est midiendo es la de realidad no lee, por lo que el rescate puede terminar porque de esta tasa se supere incluso si el tamao de error total (errsize) no cambia porque las reas que estn siendo tratado ya estn marcados como errores. `-F ' `- Force ' Forzar sobrescribir de archivo de salida. Necesario cuando archivosalida no es un archivo normal, pero un dispositivo o particin. `-F tipos ' `- Llene = tipo '

Rellene los bloques en archivosalida especificados como cualquiera de los tipos de archivo de registro, con los datos ledos del infile. tipos contienen uno o ms de los caracteres de estado definidos en el Estructura Logfile captulo (vase Estructura del archivo de registro). Ver el modo de relleno captulo (ver modo de relleno) para obtener una descripcin completa del modo de relleno. '-G' `- Generate-logfile" Generar un archivo de registro aproximada de la infile y archivo de salida de la carrera de rescate inicial. Recuerde que debe mantener el desplazamiento entre `originales - Entradaposition 'y' - output-position 'de la carrera de rescate inicial. Ver el modo Generate captulo (vase Modo Generar) para obtener una descripcin completa del modo de generacin. `-I bytes ' `- Entrada de posicin = bytes ' Situacin inicial en infile, en bytes. El valor predeterminado es 0. En el modo de relleno, se refiere a una posicin en el infile del plazo de rescate inicial. Ver el modo de relleno captulo (ver modo de relleno) para ms detalles. `-I ' `- Verify-input-size ' Comparar el tamao de archivoentrada con el tamao calculado a partir de la lista de bloques contenidos en el archivo de registro, y salir con el estado 1 si difieren. Esto no est activada por defecto porque el tamao de algunos de los dispositivos no se puede saber de antemano y porque el tamao derivada del archivo de registro puede ser incompleta, por ejemplo, despus de hacer un rescate parcial. Bytes `-K ' `- Skip-size = bytes ' Establezca el tamao inicial para saltar en el primer error de lectura o de lectura lenta. El valor determinado se redondear al siguiente mltiplo del tamao de sector. Por errores de lectura posteriores o lee lento, ddrescue modificar el tamao de salto dependiendo de la tasa de error y la historia error. Los valores vlidos van de 64 Kb a 1 GiB. El valor predeterminado es 64 KB. Archivo `-m ' `- Domain-logfile = file ' Restringir el dominio de rescate a los bloques marcados como terminado en el archivo logfile. Esto es til si la unidad de destino falla durante el rescate. `-M '

`- Retrim ' Marcar todos los bloques fallidos dentro del dominio de rescate como no recortado antes de comenzar el rescate. El efecto es similar a `- max-retries = 1 ', pero los sectores defectuosos son juzgados en un orden diferente, por lo que tal vez sea posible para rescatar a algunos de ellos. `-N ' `- No-split ' Saltar el pase de cabeza. Evita pasar mucho tiempo tratando de rescatar a las partes ms difciles del archivo. Bytes `-o ' `- Output-posicin = bytes ' Situacin inicial en archivo de salida, en bytes. El valor predeterminado es `- de entradaposition '. Los bytes siguientes bytes no se tocan si existen y no se pida truncamiento. Lo dems que se establecen en 0. `-P ' `- Asignar previamente ' Preasignar espacio en disco para el archivo de salida. Slo espacio para los archivos normales se asigna previamente. Si tiene xito preasignacin, rescate no fallar debido a la falta de espacio libre en disco. Si ddrescue no puede determinar el tamao de asignar previamente, es posible que tenga que especificar con una combinacin de `- Entrada-position ',` - Salidaposition', `- max-size 'y` - opciones domain-logfile. '-Q' `- Quiet ' Funcionamiento silencioso. Suprime todos los mensajes. `-R n ' `- Max-retries = n ' Salir despus de determinado nmero de reintentos pases. El valor predeterminado es 0. -1 Significa infinito. Cada sector defectuoso se trat slo una vez por cada pasada. Para volver a intentar sectores defectuosos detectados en una ejecucin anterior, debe especificar un nmero diferente a cero de reintentos. `-R ' `- Reverse '

Invierta la direccin de todas las operaciones de copia. Esto hace que copiar, dividir y volver a intentar a correr hacia atrs, y el recorte a ejecutar hacia adelante. `-S bytes ' `- Max-size = bytes ' El tamao mximo de los datos de entrada que se desea copiar, en bytes. Si ddrescue no puede determinar el tamao del dispositivo de entrada, es posible que tenga que especificar con esta opcin. Tenga en cuenta que esta opcin especifica el tamao de los datos de entrada que desea copiar, no el tamao del archivo de salida resultante. As, por ejemplo, el siguiente comando crea un archivo de salida 300 bytes de longitud, pero slo escribe datos en los ltimos 200 bytes: ddrescue-i 100-s 200 infile archivosalida logfile

`-S ' `- Dispersa ' Uso escasa escribe para archivo de salida. (Los bloques de ceros no estn realmente asignados en el disco). Puede ahorrar mucho espacio en el disco, en algunos casos. No todos los sistemas admiten. Slo los archivos regulares pueden ser escasos. `-T ' `- Truncate ' Truncar archivo de salida de tamao cero antes de escribir en l. Slo funciona para los archivos normales, no para unidades o particiones. Intervalo de `-T ' `- Timeout = intervalo ' El tiempo mximo desde la ltima lectura correcta permitido antes de darse por vencido. El valor predeterminado es infinito. intervalo es un nmero racional (como 1.5 o 1/2), seguido opcionalmente por uno de `s ',' m ',' h 'o' d ', es decir, segundos, minutos, horas y das, respectivamente. Si no se especifica ninguna unidad, el valor predeterminado es segundo. `-V ' `- Verbose ' El modo detallado. Adems-v de (hasta 4) aumentar el nivel de detalle. Bytes `-x '

`- Extend-outfile = bytes ' Ampliar el tamao del archivo de salida para que sea lo menos bytes de longitud. Si el tamao de archivo de salida ya es igual o ms largo que bytes a continuacin, esta opcin no hace nada. Utilice esta opcin para garantizar un tamao mnimo de archivo de salida. Slo los archivos regulares se pueden ampliar.

Los nmeros dados como argumentos a las opciones (posiciones, tamaos, reintentos, etc) pueden ser seguidos por un multiplicador y un `B 'opcional para" byte ". Tabla de SI y prefijos binarios (multiplicadores de unidad):

Valor Prefijo | Valor de prefijo | Bloques b hardware k kilobyte (10 ^ 3 = 1000) | Ki kibibyte (2 ^ 10 = 1024) M megabyte (10 ^ 6) | Mi mebibyte (2 ^ 20) T gigabyte (10 ^ 9) | Gi gibibyte (2 ^ 30) T terabyte (10 ^ 12) | Ti tebibyte (2 ^ 40) P petabyte (10 ^ 15) | Pi pebibyte (2 ^ 50) E Exabyte (10 ^ 18) | Ei exbibyte (2 ^ 60) Z zetabyte (10 ^ 21) | Zi zebibyte (2 ^ 70) Y Yottabyte (10 ^ 24) | Yi yobibyte (2 ^ 80)

Valores de retorno: 0 para una salida normal, 1 para los problemas ambientales (archivo no encontrado, opciones no vlidas, errores de E / S, etc), 2 para indicar un archivo de entrada daado o no vlido, 3 por un error de coherencia interna (por ejemplo, errores) lo que provoc ddrescue en pnico. Siguiente: Ejemplos, los anteriores: Invocando ddrescue, Up: Top 5 Estructura del archivo de registro

El archivo de registro es un archivo de texto fcil de leer y editar. Est formado por tres partes, los comentarios partida, la barra de estado, y la lista de bloques de datos.

Cualquier lnea que comienza con # es un comentario. Los bloques en la lista de bloques de datos deben ser contiguos y que no se superponen.

NOTA: Los archivos de registro generados por una versin del anterior a 1.6 ddrescue falta la lnea de estado. Si desea utilizar un viejo archivo de registro con ddrescue 1.6 o posterior, tendr que insertar una lnea como '0 + 'al principio del archivo de registro.

Los comentarios epgrafe contiene la versin del ddrescue y la lnea de comandos que se utiliza para crear el archivo de registro. Se pretende que la informacin para el usuario.

La primera lnea de comentario no es la lnea de estado. Contiene un nmero entero no negativo y un carcter de estado. El entero es la posicin de ser juzgado en el archivo de entrada. El carcter de estado es uno de los siguientes:

Carcter Significado "?" copiar bloques no probados '*' Corte de bloques no recortadas / Dividir bloques no-split '-' Reintentar sectores defectuosos 'F' llenar bloques especificados 'G' generacin logfile aproximada '+' Terminado Cada lnea de la lista de bloques de datos describe un bloque de datos. Contiene 2 nmeros enteros no negativos y un carcter de estado. El primer nmero entero es la posicin inicial del bloque en el archivo de entrada, el segundo nmero entero es el tamao (en bytes) del bloque. El carcter de estado es uno de los siguientes:

Carcter Significado "?" bloque no probado '*' No cuadra no recortada '/' Fracasado bloque no dividida

'-' Error de bloques malos del sector (s) '+' Termin bloque Y aqu est un ejemplo logfile:

# Rescate del archivo de registro. Creado por GNU ddrescue versin 1.16 # Lnea de comandos: ddrescue / dev/fd0 fdimage logfile # Current_pos current_status 0x00120000? # Status tamao pos 0x00000000 0x00117000 + 0x00117000 0x00000200 0x00117200 0x00001000 / 0x00118200 0x00007E00 * 0x00120000 0x00048000? Si edita el archivo, puede utilizar decimal, hexadecimal o valores octales, usando la misma sintaxis que las constantes de enteros en C + +.

Siguiente: El acceso directo de discos, Previous: Estructura del archivo de registro, Up: Top 6 Un pequeo tutorial con ejemplos

Ddrescue es como cualquier otra herramienta. Es necesario comprender lo que hace, y que hay que entender algunas cosas sobre las mquinas que hace esas cosas, con el fin de utilizar de forma segura.

Un coche no tiende a desarrollar ms y ms errores como pasa el tiempo. Debido a esto, se debe rescatar a los datos desde una unidad tan pronto como note el primer error. Procura con diligencia, porque cada vez que un disco daado fsicamente poderes y es capaz de emitir algunos datos, puede ser la ltima vez que lo har.

Usted debe hacer una copia de la unidad en su defecto con ddrescue y, a continuacin, tratar de reparar la copia. Si sus datos es muy importante, utilizar la primera copia como un maestro para una segunda copia, y tratar de reparar la segunda copia. Si algo sale mal, usted tiene el maestro intacto para volver a intentarlo.

IMPORTANTE! Siempre use un archivo de registro a menos que sepa que no lo necesitar. Sin un archivo de registro, ddrescue no puede reanudar el rescate, slo reiniciarlo.

IMPORTANTE! Nunca trate de rescatar a una particin montada r / w. La copia resultante puede ser intil.

IMPORTANTE! Si utiliza un dispositivo o una particin como destino, los datos almacenados no se puede sobrescribir.

IMPORTANTE! Si se interrumpe el rescate y reiniciar el sistema, las particiones parcialmente copiados deben ser ocultados antes de permitir que entren en contacto con cualquier sistema operativo que intenta montar y "arreglar" las particiones que ve.

IMPORTANTE! Nunca trate de reparar un sistema de archivos en una unidad con errores de E / S, es probable que pierda an ms datos.

Si usted est tratando de rescatar a toda una particin, primero reparar la copia con e2fsck o alguna otra herramienta apropiada para el tipo de particin que est tratando de rescatar, a continuacin, montar la copia reparado en algn lugar y tratar de recuperar los archivos en l.

Si la unidad est tan daado que el sistema de archivos en la particin de rescate no puede ser reparado o montado, tendr que examinar los datos rescatados con un editor hexadecimal y extraer las partes deseadas a mano o con una herramienta de recuperacin de archivos como photorec.

Si la tabla de particiones est daada, puede tratar de rescatar a todo el disco, y luego tratar de reparar la tabla de particiones y las particiones en la copia.

Si la unidad daada no se encuentra en / dev, entonces usted no puede rescatarlo. Al menos no con ddrescue.

Ejemplo 1: Rescate de todo el disco con dos particiones ext2 en / dev / hda con / dev / hdb. Nota: no es necesario que la particin / dev / hdb de antemano, pero si la tabla de particin en / dev / hda es daado, tendr que volver a crear de alguna manera en / dev / hdb. ddrescue-f-n / dev / hda / dev / hdb logfile ddrescue-d-f-r3 / dev / hda / dev / hdb logfile fdisk / dev / hdb e2fsck-v-f / dev/hdb1 e2fsck-v-f / dev/hdb2

Ejemplo 2: Rescatar una particin ext2 en / dev/hda2 a / dev/hdb2. Nota: es necesario crear la particin con fdisk hdb2 primero. hdb2 debe ser del tipo apropiado y el tamao. ddrescue-f-n / dev/hda2 / dev/hdb2 logfile ddrescue-d-f-r3 / dev/hda2 / dev/hdb2 logfile e2fsck-v-f / dev/hdb2 mount-t ext2-o ro / dev/hda2 / mnt (Leer archivos rescatados desde / mnt)

Ejemplo 3: Rescate de un CD-ROM en / dev / cdrom. ddrescue-n-b2048 / dev / cdrom logfile cdimage ddrescue-d-b2048 / dev / cdrom logfile cdimage (Escribe cdimage en un CD-ROM en blanco)

Ejemplo 4: Rescate de un CD-ROM en / dev / cdrom a partir de dos copias. ddrescue-n-b2048 / dev / cdrom logfile cdimage

ddrescue-d-b2048 / dev / cdrom logfile cdimage (Inserte el segundo ejemplar en la unidad de CD) ddrescue-d-r1-b2048 / dev / cdrom logfile cdimage (Escribe cdimage en un CD-ROM en blanco)

Ejemplo 5: Rescatar una copia de seguridad comprimida lzip a partir de dos copias en CD-ROM con el error a comprobar la fusin de copias (consulte el manual para obtener detalles sobre lziprecover lziprecover). ddrescue-b2048 / dev / cdrom cdimage1 logfile1 mount-t iso9660-o loop, ro cdimage1 / mnt / cdimage cp / mnt / cdimage / backup.tar.lz rescued1.tar.lz umount / mnt / cdimage (Inserte el segundo ejemplar en la unidad de CD) ddrescue-b2048 / dev / cdrom cdimage2 logfile2 mount-t iso9660-o loop, ro cdimage2 / mnt / cdimage cp / mnt / cdimage / backup.tar.lz rescued2.tar.lz umount / mnt / cdimage lziprecover-m-v-o rescued.tar.lz rescued1.tar.lz rescued2.tar.lz

Ejemplo 6: Si bien el rescate de todo el disco / dev / hda con / dev / hdb, / dev / hdb falla y hay que rescatar a los datos de una tercera unidad, / dev / hdc. ddrescue-f-n / dev / hda / dev / hdb logfile1 <- / dev / hdb falla aqu ddrescue-f-m logfile1 / dev / hdb / dev / hdc logfile2 ddrescue-f-n / dev / hda / dev / hdc logfile2 ddrescue-d-f-r3 / dev / hda / dev / hdc logfile2

Ejemplo 7: Si bien el rescate de todo el disco / dev / hda con / dev / hdb, / dev / hda deja de responder y desaparece desde / dev. ddrescue-f-n / dev / hda / dev / hdb logfile <- / dev / hda falla aqu

(Reiniciar / dev / hda o computadora reiniciar tantas veces como sea necesario) ddrescue-f-n-A / dev / hda / dev / hdb logfile ddrescue-d-f-r3 / dev / hda / dev / hdb logfile Modo de llenado, Anterior: Siguiente: Ejemplos, Up: Top 7 Acceso directo a disco

Si usted nota que las posiciones y tamaos en el archivo de registro son siempre mltiplos del tamao del sector, tal vez su kernel es el almacenamiento en cach de los accesos a disco y de agruparlos. En este caso es posible que desee utilizar el acceso directo del disco o un dispositivo sin pasar por alto la cach del ncleo y rescatar a ms de sus datos.

NOTA! Tamao del sector se debe establecer correctamente con la opcin `- block-size" para que esto funcione. Pruebe la opcin `- directa" en primer lugar. Si el acceso directo de discos no est disponible en su sistema, trate de dispositivos bsicos. Lea la documentacin de su sistema para saber cmo enlazar un dispositivo sin formato a un dispositivo de bloque regular.

Ddrescue alinea su bfer de E / S para el tamao de sector de modo que se puede utilizar para el acceso directo del disco o para leer desde los dispositivos en bruto. Por razones de eficiencia, tambin se alinea con el tamao de pgina de memoria si el tamao de pgina es un mltiplo del tamao de sector. Ddrescue no puede determinar el tamao de un dispositivo en bruto, por lo que una explcita `- max-size 'o` - completa-slo "es necesaria opcin.

Usando el acceso directo del disco, o la lectura de un dispositivo en bruto, puede ser ms lento o ms rpido que lo normal en cach de lectura en funcin de su sistema operativo y hardware. En caso de que sea ms lento es posible que desee hacer una primera pasada con cach normal, lee y utiliza el acceso directo del disco, o un dispositivo sin formato, slo para recuperar las buenas sectores dentro de los bloques que han fallado.

Ejemplo 1: utilizando el acceso directo del disco. ddrescue-f-n / dev/hdb1 / dev/hdc1 logfile ddrescue-d-f-R3 / dev/hdb1 / dev/hdc1 logfile e2fsck-v-f / dev/hdc1

mount-t ext2-o ro / dev/hdc1 / mnt

Ejemplo 2: el uso de un dispositivo sin formato. crudo / dev/raw/raw1 / dev/hdb1 ddrescue-f-n / dev/hdb1 / dev/hdc1 logfile ddrescue-C-F-r3 / dev/raw/raw1 / dev/hdc1 logfile crudo / dev/raw/raw1 0 0 e2fsck-v-f / dev/hdc1 mount-t ext2-o ro / dev/hdc1 / mnt Siguiente: El acceso directo de discos, Up:: Top Mode, anterior Genere 8 Modo de llenado

Cuando ddrescue se invoca con la opcin `- relleno 'que opera en" modo de relleno ", que es diferente del" modo de rescate "por defecto. Es decir, si se utiliza la opcin `- fill", ddrescue no rescata nada. Slo se llena con los datos ledos desde el archivo de entrada de los bloques del archivo de salida cuyo estado personaje del archivo de registro coincide con uno de los caracteres de tipo especificado como argumento a la opcin - fill ".

En el modo de llenado el archivo de entrada puede tener cualquier tamao. Si es demasiado pequeo, los datos se duplican tantas veces como sea necesario para llenar el buffer de entrada. Si es demasiado grande, slo se leern los datos necesarios para llenar el buffer de entrada. A continuacin, los mismos datos se escribirn en cada cuadra o sector a cubrir.

Tenga en cuenta que en el modo de llenado del archivo de entrada siempre se lee desde la posicin 0. Si se especifica un `- Entrada-position ', se refiere al archivo de entrada original de la que fue construido el archivo de registro, y slo se utiliza para el clculo de la compensacin entre la entrada y las posiciones de salida.

Tenga en cuenta tambin que cuando se llena el archivo de entrada de la carrera de rescate original, debe configurar `- Entrada-position 'y' - output-position 'al mismo valor, mientras que cuando se llena el archivo de salida de la carrera de rescate original, se debe mantener el original de desplazamiento entre `- Entrada-position 'y' - output-position '.

El `- fill" opcin implica la `- de slo completa" opcin.

En el modo de llenado el archivo de registro se actualiza para permitir resumability cuando se interrumpe o en caso de un accidente, pero como nada est siendo rescatado el archivo de registro no se destruye. La lnea de estado es la nica parte del archivo de registro que se ha modificado.

El modo de relleno tiene un nmero de usos. Vea los siguientes ejemplos: Ejemplo 1: Marcar partes de la copia rescatada para permitir la bsqueda de ellos cuando son examinados en un editor hexadecimal. Por ejemplo, la siguiente lnea de comandos se llena todos los bloques marcados como `- '(bad-sector) con copias de la cadena` SECTOR BAD':

printf "BAD SECTOR"> tmpfile ddrescue - fill = - tmpfile logfile archivosalida Ejemplo 2: Limpie slo los buenos sectores, dejando a los sectores defectuosos solamente. De esta manera, la unidad sigue probar mal (es decir, con sectores ilegibles). Esta es la manera ms rpida de acabar con una unidad en su defecto, y es especialmente til al enviar la unidad al fabricante para el reemplazo de la garanta.

ddrescue - fill = + - force / dev / logfile bad_drive cero Ejemplo 3: Fuerza de la unidad para reasignar los sectores defectuosos, por lo que es til de nuevo. Si la unidad tiene slo unos pocos sectores defectuosos, y no son causados por la edad en coche, usted probablemente puede reescribir esos sectores, y la unidad se reasignar automticamente a nuevos sectores "sobrantes" que guarda slo para este fin. ADVERTENCIA! Esto puede no funcionar en su unidad.

ddrescue - fill = --- force - sncrono / dev / zero logfile bad_drive

Modo de relleno tambin puede ayudar a averiguar, con independencia del sistema de archivos utilizado, qu archivos son parcial o totalmente en los malos reas del disco. Slo tienes que seguir estos pasos:

1) Copia de la unidad daada con ddrescue hasta que termine. No utilice escasa escribe. Esto produce un archivo de registro con un solo acabado ('+') y el mal en el sector ('-') bloques.

2) Llenar los bloques malos del sector de la unidad de copia o archivo de imagen con una cadena no est presente en ningn fichero, por ejemplo "DeaDBeeF".

3) Monte la unidad de copiado (o el archivo de imagen, a travs del dispositivo de bucle de retorno).

4) GREP para la cadena de llenado en todos los archivos. Los archivos que contienen la cadena residen (al menos parcialmente) en reas de disco daados.

5) Desmonte la unidad de copia o archivo de imagen.

6) Opcionalmente llenar los bloques malos del sector de la unidad o archivo de imagen copiado con ceros para restaurar la imagen del disco.

Ejemplo 4: Averiguar qu archivos estn en malas zonas del disco.

ddrescue-b2048 / dev / cdrom logfile cdimage printf "DeaDBeeF"> tmpfile ddrescue - fill = - tmpfile cdimage logfile tmpfile rm mount-t iso9660-o loop, ro cdimage / mnt / cdimage tipo cdimage find / mnt / f-exec grep "DeaDBeeF" '{}' ';' umount / mnt / cdimage ddrescue - fill = - / dev / zero logfile cdimage Siguiente: Ddrescuelog, Previous: Modo de llenado, Up: Top 9 Modo Generate-logfile

As que usted no ha ledo el tutorial y comenzar ddrescue sin un archivo de registro. Ahora, dos das ms tarde, el equipo se estrell y no se puede saber la cantidad de datos ddrescue logr salvar. Y lo que es peor, no se puede reanudar el rescate, hay que reiniciarlo desde el principio.

O tal vez usted comenz copiando un disco con `dd conv = noerror, sync 'y ahora est en la misma situacin descrita anteriormente. En este caso, tenga en cuenta que usted no puede utilizar una copia realizada por dd menos que se invoca con el argumento de conversin `sync '.

No se desespere (todava). Ddrescue puede en algunos casos generar un archivo de registro aproximada, desde el archivo de entrada y la copia (parcial), que es casi tan bueno como un archivo de registro exacta. Hace esto simplemente asumiendo que los sectores que contienen todos los ceros no fueron rescatados.

Sin embargo, si el destino de la copia era una unidad o una particin, (o no se solicit un archivo y el truncamiento ordinario existente), probablemente tendr que reiniciar ddrescue desde el principio. (Esta vez con un archivo de registro, por supuesto). La razn es que los datos antiguos pueden estar presentes en la unidad que no han sido sobrescritos, sin embargo, y pueden ser por lo tanto no probado, pero no cero.

Por ejemplo, si primero se trat uno de los siguientes comandos:

ddrescue infile archivosalida o dd if = infile del archivo de salida = conv = noerror, sincronizacin entonces se puede generar un archivo de registro aproximado con este comando:

ddrescue - generate-logfile logfile infile archivosalida Recuerde que debe mantener el desplazamiento entre `originales - Entrada-position 'y' output-position 'de la carrera de rescate inicial.

Siguiente: Invocar Ddrescuelog, Previous: Modo Generar, Up: Top

10 Ddrescuelog

Ddrescuelog es una herramienta que manipula archivos de registro ddrescue, muestra el contenido de archivos de registro, convierte archivos de registro a / desde otros formatos, compara archivos de registro, el estado de las pruebas de rescate, y se puede eliminar un archivo de registro si el rescate se realiza. Operaciones Ddrescuelog pueden limitarse a una o varias partes del archivo de registro si se utilizan las opciones de configuracin de dominio.

Estos son algunos ejemplos de cmo utilizar ddrescuelog, solo o en combinacin con otras herramientas.

Ejemplo 1: eliminar el archivo de registro si se termina el rescate (todos los datos se recuper sin errores de la izquierda). ddrescue-f / dev / hda / dev / hdb logfile ddrescuelog-d archivo de registro

Ejemplo 2: Rescue dos particiones ext2 en / dev / hda con / dev / hdb y reparar los sistemas de archivos utilizando listas badblock generados con ddrescuelog. Tamao de archivo sistema de bloque 4096. Nota: no necesita particionar / dev / hdb antemano. fdisk / dev / hdb <- particin / deb / hdb ddrescue-f / dev/hda1 / dev/hdb1 logfile1 ddrescue-f / dev/hda2 / dev/hdb2 logfile2 ddrescuelog-l--b4096 logfile1> badblocks1 ddrescuelog-l--b4096 logfile2> badblocks2 e2fsck-v-f-L badblocks1 / dev/hdb1 e2fsck-v-f-L badblocks2 / dev/hdb2 `-H ' `-V ' `- Version '

`-N ' '-Q' `- Quiet '

Potrebbero piacerti anche