Восстановление секторов hdd linux

How to fix the hard-drive Bad Sector

A bad sector on a drive is a sign of permanent damage to the drive. Unless you have reason to believe that your drive marked these sectors as bad incorrectly, you cannot «fix» them.

It means that a part of your drive is damaged to the extent that it can no longer reliably be read from and/or written to.

Your system can continue to use the drive by marking that sector as unusable, but if you have enough bad sectors, or a SMART tool triggers a warning level, you might consider a drive replacement, as bad sectors can be a sign that more sectors, or the whole drive, might fail soon.

While there may be ways to force the drive to un-mark a sector as bad, allowing you to use it again, this is likely not a good idea. The sector may stay good, but it will just as likely become bad again. Some data may be lost or corrupted depending on how it fails.

Now, as for the error message you’ve pasted in your question (as of my writing this), that error has nothing to do with bad sectors. It means that you don’t have access to the drive. Being sudo can give you access, so:

However, this is still probably not what you want, because /dev/sdb refers to the entire drive, whereas fsck is designed to work on filesystems, which are usually (but not always, and you may have an exception here) placed in partitions. If the above didn’t work, you may instead have wanted to do this to the 1st partition on that drive:

You can get a list of partitions per drive with:

Its probably just a bad block. It can’t read the data, is all. After remapping the block the drive is likely good for another three years. So goes my experience.

A HDD with a bad sector is much, much more likely to fail at any moment than one which has never had a bad sector. How many drives is your experience based on? I would still call it a bigger gamble.

More likely? Sure. But it isn’t immediately doomed. So much depends on why that block went bad. Like I said, I’ve had drives that slowly remap a few bad blocks over their lifetime and just keep working.

it isn’t immediately doomed — you have no way of knowing or guaranteeing that. In some cases it might be. So much depends on why that block went bad — it would be impossible to reliably find out the why, without opening it up and effectively destroying it. As I said it’s always an increased risk. If you are absolutely fine with such a risk I have no problem with that. Most of the time, maybe even >90% of the time, the drive won’t quickly fail after a bad sector is found and in some cases it might even last for years after. Keep good backups and any future failure won’t hurt as much.

Читайте также:  Asp net server linux

In short: Boot a rescue system and use badblocks:

to have the hard disk controller replace bad blocks by spare blocks.

I have answered the same question in detail here.

You probably want to use this indirectly with fsck’s -c option. AFAIK using badblocks standalone will never change the behaviour of anything, it will only report on where the bad blocks are. Of course, the drive firmware might transparently modify its behaviour when put under the usage patterns characteristic of badblocks , but surely this would be drive dependent?

As a new user you first need to gain «reputation» before being allowed to do certain activities on this site. So it was not possible to duplicate this. Still the question deserved an answer. As bad blocks are an issue of the physical disk (check out SMART values, the filesystem is not directly affected. It might suffer corruption due to data loss. So doing a fsck is a good idea as well. As original question was about how to «repair» bad blocks this was the answer.

@amoe the documentation supposes the behaviour will change, here: «Run sudo badblocks -n on a device name to run it by itself and report badblocks right in your terminal. You can use the -w option to use a write-mode test, but don’t use the -n and -w options together since they’re mutually exclusive. You should under no circumstance ever use the -w option on a volume that has data, since it will erase everything clean. Use the slower -n option since it will preserve your data in this case. The -w option is fine for volumes that you don’t mind erasing.»

In the olden days you used to have to take a note of the badblocks that were written on the drive and enter those in the defect list before formatting the drive, because hard disk surfaces were never «perfect», manufacturer’s got wise to this because people buying disks would look at the defect table printed on the disk and buy the ones with the least amount of defects.

Now scroll forward 20 or so years and hard disk manufacturers hide the fact a brand new disk has bad blocks with the firmware, when you buy a brand new disk it will have in all probability bad blocks already, the firmware will detect newly grown badblocks and maps them out from a set of spare cylinders it has, but this only happens when a write operation occurs on that sector and the ECC algorithm detects bit failure, only then will it map the block out. So getting back to the point you can force a drive to map out the badblocks by simply using DD, ie/ [edit: following example was edited to prevent accidental drive destruction: removed wildcard character, replaced with X].

WARNING: DO NOT BLINDLY USE THE dd COMMAND BELOW IF YOU DO NOT KNOW WHAT IT DOES.

dd if=/dev/zero of=/dev/sdX bs=1M 

obviously alter the of=target to reflect the drive you want to zero this is the quickest way to re-map a drives defects, its also the quickest way to totally trash your Linux setup by getting the target drive wrong, so check, double check then check again, before you press the enter key. You can increase the size of the blocksize in the dd command to optimize read/writes and perhaps make things go quicker, but there are diminishing returns after a point. I find anything between 1M and 8M works best for me

Читайте также:  Как сбросить терминал linux

You can get DD to just write one sector, the bad one. to get it remapped, so you don’t have to backup your drive, but that’s a whole different kettle of fish and Russian roulette if you don’t know exactly what you’re doing .

This command WILL destroy everything on your hard drive including any partitions. But it will force the drive to map out any bad sectors it may have.

It is perfectly ok for a disk to have bad sectors as long as they aren’t on the boot sector, if they are then the drive is useless, if you notice a few months later that your drive has developed more bad sectors then it’s time to start shopping for a replacement.

I’ve revived hundreds of drives like this and they’ve lived on for many years afterwards, a bad sector isn’t necessarily the death knell for the drive.

Источник

Восстановление сбойных секторов SATA дисков в линукс

Восстановление сбойных секторов HDD и SATA дисков в Linux.

Предыстория: давно искал аналоги HDD Regenerator, Victoria, MHDD для линукс, и ничего не находил. Натолкнулся на hdrecover 0.5, но реального восстановления сбойных секторов не произошло. HDrecover час шел до сбойного сектора, аттемпил с разных мест, угрожал, что убьёт данные, я соглашался на data destory, но сбойные сектора не восстанавливал.

И вот упершись рогом, решительно взялся за линукс. Уже лет 20 где-то и как-то восстановление происходит, но в линуксе никак. С жестким диском повезло, на нём была куча сбойных секторов. 250GB Seagate 5400rpm из ноубука. Так как было время для экспериментов, HDD Regenerator на старом компе через IDE бодро восстанавливал сектора, а hdrecover — нет.

Сначала в hdrecover во второй параметр командной строки я дописал указание сектора, с которого нужно начинать сканирование, потому как ждать по часу было невозможно долго.

Как-раз мне на этом жестком диске попался сектор, который иногда поддавался attemp pounce — то есть автор hdrecover на каких-то моделях жестких дисков может быть увидел эффект, когда можно добиться восстановления данных из сбойного сектора путём попыток чтения этого сектора сразу после чтения далеко и близко расположенных мест диска. Физически головка движется с края диска не так позиционируясь, как если бы она передвинулась с соседней дорожки.. В итоге у меня: сектор иногда читался, но 100% не восстанавливался.

Теперь вводные: Мне НЕ нужно было восстанавливать данные. Мне нужно было восстановить только сбойные секторы с потерей информации. Если же вам нужно восстановить максимум информации: Копируйте всё на другой несбойный диск: ddrescue, dd sync,noerror и после этого с нормального диска восстанавливайте через R-Studio Recovery. Если диск сыпется, то все эксперименты с восстановлением секторов и попыток запуска десятков «лучших программ восстановления данных» приводят только к ещё большей потере данных.

Читайте также:  Линукс показать файлы в директории

Так как мне не нужны были attemp pounce сектора, которые бы то читались, то не читались, из программы была убрана эта функциональность множественных попыток чтения, так как толку от этого не было, это сильно занимало время восстановления, и далее при использовании программ восстановления данных сильно бы их замедляло. Так даже лучше — при первой ошибке чтения перезаписываем сектор, а диск там уж сам что-то сделает: перепишет или remap. Как именно remap в линуксе сделать, я ещё не понял. Да и практики мало (чем remap в victoria отличается, то же непонятно, чаще не восстанавливает никак сектора)

hdrecover, записывая в устройство сектор, не восстанавливал данные. Попробовав dd if=/dev/zero of=/dev/sdX count=1 seek=XXX, увидел, что сектор XXX восстановился. Добавив 2-й попыткой восстановления команду dd уже в саму программу hdrecover, был получен положительный результат.

Восстановление секторов конкретного жесткого диска было успешным и на старом компьютере с IDE — SATA контроллере (не AHCI), и на переходнике USB 3.0-SATA.

Оставляйте комментарии по результатам своего восстановления.

Что ещё можно добавить в программу для функциональности: первичное быстрое чтение всего диска скачками для выявления большой сбойной области сразу.

Для чего может быть нужно множественное восстановление сбойных секторов: когда надоело смотреть лог и давать команду dd восстанавливая вручную, когда невозможно достать жесткий диск и провести процедуру на старом SATA контроллере через HDD Regenerator, когда данные не сильно нужны (восстановится — нормально, прогоним chkdsk или fsck, не восстановится — переустановим систему). Ну а сама программа hdrecover может использоваться для тестирования жестких дисков сразу с режимом восстановления.

P.S. Если диск сильно цыкает — то скорее всего он не может спозиционироваться на дорожку, и hdrecover вряд ли поможет.

P.S.S. для новичков в линукс: вывод хвоста сислога в отдельном окне: tail -f /var/log/syslog — и там видны результаты подключения USB устройств, ошибок дисков и номера сбойных секторов.

Исходные тексты и скомпилированная на 64 бит программа:

Файл [download url=»http://agansk.ru/tech/wp-content/uploads/2019/04/hdrecover-0.5-dd.tar.gz»]

3 thoughts on “ Восстановление сбойных секторов SATA дисков в линукс ”

Если сбойные сектора не восстанавливаются, то для работы на таком диске можно сделать такое:
глянуть, что где: fdisk -l
глянуть mount, если надо отмонтировать нужный диск: umount /dev/sdb1
проверим на сбойные сектора: badblocks -s /dev/sdb1 > /home/user/sdb1_badblocks
Выполним команду для игнорирования сбойных секторов, что бы исключить их от использования в ОС:
e2fsck -l /home/user/sdb1_badblocks /dev/sdb1 Сам не пробовал, если у меня сбойные сектора не восстанавливаются — диск идёт с пометкой сбойный, максимум: для хранения неважной информации..

Если сбойных секторов очень много, не сотни, а десятки тысяч, можно изменить в тексте hdrecover.cpp команду перезаписи на count=16 или больше, для ускорения процесса

whdd для командной строки удалось скомпилять в ubuntu 16.04 (apt install dialog libncurses5-dev libncursesw5-dev). И на debian 8 и на убунту выбор ata или posix приводил к ошибке сегментирования.
hddsuperclone для графического экрана не копирует смонтированный диск..

Источник

Оцените статью
Adblock
detector