注册 登录
自由的生活_软路由 返回首页

心想事成的个人空间 https://bbs.routerclub.com/?681 [收藏] [复制] [分享] [RSS]

日志

使用bch算法进行数据校正

已有 155 次阅读2024-10-15 14:08

https://github.com/jkent/python-bchlib

import random
import bchlib

ECC_POLY = 8219
ECC_BITS = 16  # 16-bit ECC encoder
bch = bchlib.BCH(ECC_BITS, prim_poly=ECC_POLY)

# 待编码数据
text = 'hello world ' * 30

# 转 bytearray
data = bytearray('hello world ' * 30, 'utf-8')

# 创建一个包含数据和错误校正码的数据包
ecc = bch.encode(data)
packet = data + ecc

# 展示原始数据包
print('original packet: %s' % packet)


# 模拟在数据包上引入错误
def bit_flip(packet):
    byte_num = random.randint(0, len(packet) - 1)
    bit_num = random.randint(0, 7)
    packet[byte_num] ^= (1 << bit_num)


# 引入5个错误
for _ in range(5):
    bit_flip(packet)

# 展示引入错误后的数据包
print('corrupt packet: %s' % packet)

# 解码并纠正数据包
data, ecc = packet[:-bch.ecc_bytes], packet[-bch.ecc_bytes:]
bitflips = bch.decode(data, ecc)

if bitflips >= 0:
    print('bitflips: %d' % bitflips)
else:
    print('unrecoverable error')

bch.correct(data, ecc)
print('corrected packet: %s' % (data + ecc))

#!/usr/bin/env python3
# BCH ECC decoder for Qualcomm NAND controller
# This script assumes no bad block on flash
# Ref:
# https://elixir.bootlin.com/linux/latest/source/drivers/mtd/nand/raw/qcom_nandc.c
# https://github.com/ecsv/qcom-nandc-pagify
import bchlib
# 128MiB Flash, Page Size:2048+128
page_size = 2048
oob_size = 128
page_count = 128 * 1024 * 1024 // page_size
# 8-Bit BCH, 8x bus: 13 bytes ECC
bbm_size = 1
ecc_bits = 8
chunk_count = page_size // 512
chunk_size = 532 if ecc_bits == 8 else 528
data_size = 516
data1_size = page_size - (chunk_count - 1) * chunk_size
data2_size = data_size - data1_size
bch = bchlib.BCH(8219, ecc_bits)
f = open('nand-dump.bin', 'rb')
fo = open('decoded.bin', 'wb')
for page in range(page_count):
for chunk in range(chunk_count):
data = bytearray(f.read(data1_size))
f.read(bbm_size)
data += f.read(data2_size)
ecc = bytearray(f.read(bch.ecc_bytes))
bit_flip = bch.decode_inplace(data, ecc)
if (bit_flip > 0):
print('ecc corrected ' + bit_flip + 'bits on page ' + page + ' chunk ' + chunk)
elif (bit_flip < 0):
print('uncorrectable ecc at page ' + page + ' chunk ' + chunk)
if (chunk == chunk_count - 1):
fo.write(data[:-4 * chunk_count])
else:
fo.write(data)
f.read(chunk_size - data_size - bbm_size - bch.ecc_bytes)
f.read(page_size + oob_size - chunk_size * chunk_count)

路过

雷人

握手

鲜花

鸡蛋

评论 (0 个评论)

facelist doodle 涂鸦板

您需要登录后才可以评论 登录 | 注册

QQ|Archiver|手机版|小黑屋|软路由 ( 渝ICP备15001194号-1|渝公网安备 50011602500124号 )

GMT+8, 2024-11-21 17:48 , Processed in 0.065127 second(s), 6 queries , Gzip On, Redis On.

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

返回顶部