1
0
Fork 0
mirror of https://github.com/Ysurac/openmptcprouter.git synced 2025-03-09 15:40:20 +00:00

Update 6.12 kernel patches

This commit is contained in:
Ycarus (Yannick Chabanois) 2024-12-26 18:19:04 +01:00
parent bdb9b0046f
commit 9d83c70ced
247 changed files with 53301 additions and 589 deletions

View file

@ -0,0 +1,31 @@
menuconfig MIKROTIK
bool "Platform support for MikroTik RouterBoard virtual devices"
help
Say Y here to get to see options for the MikroTik RouterBoard platform.
This option alone does not add any kernel code.
if MIKROTIK
config MIKROTIK_RB_SYSFS
tristate "RouterBoot sysfs support"
depends on MTD
select LZO_DECOMPRESS
select CRC32
help
This driver exposes RouterBoot configuration in sysfs.
config NVMEM_LAYOUT_MIKROTIK
tristate "RouterBoot NVMEM layout support"
depends on NVMEM_LAYOUTS
help
This driver exposes MikroTik hard_config via NVMEM layout.
config MIKROTIK_WLAN_DECOMPRESS_LZ77
tristate "Mikrotik factory Wi-Fi caldata LZ77 decompression support"
depends on MIKROTIK_RB_SYSFS
help
Allow Mikrotik LZ77 factory flashed Wi-Fi calibration data to be
decompressed
endif # MIKROTIK

View file

@ -0,0 +1,6 @@
#
# Makefile for MikroTik RouterBoard platform specific drivers
#
obj-$(CONFIG_MIKROTIK_RB_SYSFS) += routerboot.o rb_hardconfig.o rb_softconfig.o
obj-$(CONFIG_NVMEM_LAYOUT_MIKROTIK) += rb_nvmem.o
obj-$(CONFIG_MIKROTIK_WLAN_DECOMPRESS_LZ77) += rb_lz77.o

View file

@ -0,0 +1,844 @@
// SPDX-License-Identifier: GPL-2.0-only
/*
* Driver for MikroTik RouterBoot hard config.
*
* Copyright (C) 2020 Thibaut VARÈNE <hacks+kernel@slashdirt.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* This driver exposes the data encoded in the "hard_config" flash segment of
* MikroTik RouterBOARDs devices. It presents the data in a sysfs folder
* named "hard_config". The WLAN calibration data is available on demand via
* the 'wlan_data' sysfs file in that folder.
*
* This driver permanently allocates a chunk of RAM as large as the hard_config
* MTD partition, although it is technically possible to operate entirely from
* the MTD device without using a local buffer (except when requesting WLAN
* calibration data), at the cost of a performance penalty.
*
* Note: PAGE_SIZE is assumed to be >= 4K, hence the device attribute show
* routines need not check for output overflow.
*
* Some constant defines extracted from routerboot.{c,h} by Gabor Juhos
* <juhosg@openwrt.org>
*/
#include <linux/types.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/kobject.h>
#include <linux/bitops.h>
#include <linux/string.h>
#include <linux/mtd/mtd.h>
#include <linux/sysfs.h>
#include <linux/lzo.h>
#include "rb_hardconfig.h"
#include "routerboot.h"
#include "rb_lz77.h"
#define RB_HARDCONFIG_VER "0.08"
#define RB_HC_PR_PFX "[rb_hardconfig] "
/* Bit definitions for hardware options */
#define RB_HW_OPT_NO_UART BIT(0)
#define RB_HW_OPT_HAS_VOLTAGE BIT(1)
#define RB_HW_OPT_HAS_USB BIT(2)
#define RB_HW_OPT_HAS_ATTINY BIT(3)
#define RB_HW_OPT_PULSE_DUTY_CYCLE BIT(9)
#define RB_HW_OPT_NO_NAND BIT(14)
#define RB_HW_OPT_HAS_LCD BIT(15)
#define RB_HW_OPT_HAS_POE_OUT BIT(16)
#define RB_HW_OPT_HAS_uSD BIT(17)
#define RB_HW_OPT_HAS_SIM BIT(18)
#define RB_HW_OPT_HAS_SFP BIT(20)
#define RB_HW_OPT_HAS_WIFI BIT(21)
#define RB_HW_OPT_HAS_TS_FOR_ADC BIT(22)
#define RB_HW_OPT_HAS_PLC BIT(29)
/*
* Tag ID values for ERD data.
* Mikrotik used to pack all calibration data under a single tag id 0x1, but
* recently switched to a new scheme where each radio calibration gets a
* separate tag. The new scheme has tag id bit 15 always set and seems to be
* mutually exclusive with the old scheme.
*/
#define RB_WLAN_ERD_ID_SOLO 0x0001
#define RB_WLAN_ERD_ID_MULTI_8001 0x8001
#define RB_WLAN_ERD_ID_MULTI_8201 0x8201
static struct kobject *hc_kobj;
static u8 *hc_buf; // ro buffer after init(): no locking required
static size_t hc_buflen;
/*
* For LZOR style WLAN data unpacking.
* This binary blob is prepended to the data encoded on some devices as
* RB_ID_WLAN_DATA, the result is then first decompressed with LZO, and then
* finally RLE-decoded.
* This binary blob has been extracted from RouterOS by
* https://forum.openwrt.org/u/ius
*/
static const u8 hc_lzor_prefix[] = {
0x00, 0x05, 0x4c, 0x4c, 0x44, 0x00, 0x34, 0xfe,
0xfe, 0x34, 0x11, 0x3c, 0x1e, 0x3c, 0x2e, 0x3c,
0x4c, 0x34, 0x00, 0x52, 0x62, 0x92, 0xa2, 0xb2,
0xc3, 0x2a, 0x14, 0x00, 0x00, 0x05, 0xfe, 0x6a,
0x3c, 0x16, 0x32, 0x16, 0x11, 0x1e, 0x12, 0x46,
0x32, 0x46, 0x11, 0x4e, 0x12, 0x36, 0x32, 0x36,
0x11, 0x3e, 0x12, 0x5a, 0x9a, 0x64, 0x00, 0x04,
0xfe, 0x10, 0x3c, 0x00, 0x01, 0x00, 0x00, 0x28,
0x0c, 0x00, 0x0f, 0xfe, 0x14, 0x00, 0x24, 0x24,
0x23, 0x24, 0x24, 0x23, 0x25, 0x22, 0x21, 0x21,
0x23, 0x22, 0x21, 0x22, 0x21, 0x2d, 0x38, 0x00,
0x0c, 0x25, 0x25, 0x24, 0x25, 0x25, 0x24, 0x23,
0x22, 0x21, 0x20, 0x23, 0x21, 0x21, 0x22, 0x21,
0x2d, 0x38, 0x00, 0x28, 0xb0, 0x00, 0x00, 0x22,
0x00, 0x00, 0xc0, 0xfe, 0x03, 0x00, 0xc0, 0x00,
0x62, 0xff, 0x62, 0xff, 0xfe, 0x06, 0x00, 0xbb,
0xff, 0xba, 0xff, 0xfe, 0x08, 0x00, 0x9e, 0xff,
0xfe, 0x0a, 0x00, 0x53, 0xff, 0xfe, 0x02, 0x00,
0x20, 0xff, 0xb1, 0xfe, 0xfe, 0xb2, 0xfe, 0xfe,
0xed, 0xfe, 0xfe, 0xfe, 0x04, 0x00, 0x3a, 0xff,
0x3a, 0xff, 0xde, 0xfd, 0x5f, 0x04, 0x33, 0xff,
0x4c, 0x74, 0x03, 0x05, 0x05, 0xff, 0x6d, 0xfe,
0xfe, 0x6d, 0xfe, 0xfe, 0xaf, 0x08, 0x63, 0xff,
0x64, 0x6f, 0x08, 0xac, 0xff, 0xbf, 0x6d, 0x08,
0x7a, 0x6d, 0x08, 0x96, 0x74, 0x04, 0x00, 0x08,
0x79, 0xff, 0xda, 0xfe, 0xfe, 0xdb, 0xfe, 0xfe,
0x56, 0xff, 0xfe, 0x04, 0x00, 0x5e, 0xff, 0x5e,
0xff, 0x6c, 0xfe, 0xfe, 0xfe, 0x06, 0x00, 0x41,
0xff, 0x7f, 0x74, 0x03, 0x00, 0x11, 0x44, 0xff,
0xa9, 0xfe, 0xfe, 0xa9, 0xfe, 0xfe, 0xa5, 0x8f,
0x01, 0x00, 0x08, 0x01, 0x01, 0x02, 0x04, 0x08,
0x02, 0x04, 0x08, 0x08, 0x01, 0x01, 0xfe, 0x22,
0x00, 0x4c, 0x60, 0x64, 0x8c, 0x90, 0xd0, 0xd4,
0xd8, 0x5c, 0x10, 0x09, 0xd8, 0xff, 0xb0, 0xff,
0x00, 0x00, 0xba, 0xff, 0x14, 0x00, 0xba, 0xff,
0x64, 0x00, 0x00, 0x08, 0xfe, 0x06, 0x00, 0x74,
0xff, 0x42, 0xff, 0xce, 0xff, 0x60, 0xff, 0x0a,
0x00, 0xb4, 0x00, 0xa0, 0x00, 0xa0, 0xfe, 0x07,
0x00, 0x0a, 0x00, 0xb0, 0xff, 0x96, 0x4d, 0x00,
0x56, 0x57, 0x18, 0xa6, 0xff, 0x92, 0x70, 0x11,
0x00, 0x12, 0x90, 0x90, 0x76, 0x5a, 0x54, 0x54,
0x4c, 0x46, 0x38, 0x00, 0x10, 0x10, 0x08, 0xfe,
0x05, 0x00, 0x38, 0x29, 0x25, 0x23, 0x22, 0x22,
0x1f, 0x00, 0x00, 0x00, 0xf6, 0xe1, 0xdd, 0xf8,
0xfe, 0x00, 0xfe, 0x15, 0x00, 0x00, 0xd0, 0x02,
0x74, 0x02, 0x08, 0xf8, 0xe5, 0xde, 0x02, 0x04,
0x04, 0xfd, 0x00, 0x00, 0x00, 0x07, 0x50, 0x2d,
0x01, 0x90, 0x90, 0x76, 0x60, 0xb0, 0x07, 0x07,
0x0c, 0x0c, 0x04, 0xfe, 0x05, 0x00, 0x66, 0x66,
0x5a, 0x56, 0xbc, 0x01, 0x06, 0xfc, 0xfc, 0xf1,
0xfe, 0x07, 0x00, 0x24, 0x95, 0x70, 0x64, 0x18,
0x06, 0x2c, 0xff, 0xb5, 0xfe, 0xfe, 0xb5, 0xfe,
0xfe, 0xe2, 0x8c, 0x24, 0x02, 0x2f, 0xff, 0x2f,
0xff, 0xb4, 0x78, 0x02, 0x05, 0x73, 0xff, 0xed,
0xfe, 0xfe, 0x4f, 0xff, 0x36, 0x74, 0x1e, 0x09,
0x4f, 0xff, 0x50, 0xff, 0xfe, 0x16, 0x00, 0x70,
0xac, 0x70, 0x8e, 0xac, 0x40, 0x0e, 0x01, 0x70,
0x7f, 0x8e, 0xac, 0x6c, 0x00, 0x0b, 0xfe, 0x02,
0x00, 0xfe, 0x0a, 0x2c, 0x2a, 0x2a, 0x28, 0x26,
0x1e, 0x1e, 0xfe, 0x02, 0x20, 0x65, 0x20, 0x00,
0x00, 0x05, 0x12, 0x00, 0x11, 0x1e, 0x11, 0x11,
0x41, 0x1e, 0x41, 0x11, 0x31, 0x1e, 0x31, 0x11,
0x70, 0x75, 0x7a, 0x7f, 0x84, 0x89, 0x8e, 0x93,
0x98, 0x30, 0x20, 0x00, 0x02, 0x00, 0xfe, 0x06,
0x3c, 0xbc, 0x32, 0x0c, 0x00, 0x00, 0x2a, 0x12,
0x1e, 0x12, 0x2e, 0x12, 0xcc, 0x12, 0x11, 0x1a,
0x1e, 0x1a, 0x2e, 0x1a, 0x4c, 0x10, 0x1e, 0x10,
0x11, 0x18, 0x1e, 0x42, 0x1e, 0x42, 0x2e, 0x42,
0xcc, 0x42, 0x11, 0x4a, 0x1e, 0x4a, 0x2e, 0x4a,
0x4c, 0x40, 0x1e, 0x40, 0x11, 0x48, 0x1e, 0x32,
0x1e, 0x32, 0x2e, 0x32, 0xcc, 0x32, 0x11, 0x3a,
0x1e, 0x3a, 0x2e, 0x3a, 0x4c, 0x30, 0x1e, 0x30,
0x11, 0x38, 0x1e, 0x27, 0x9a, 0x01, 0x9d, 0xa2,
0x2f, 0x28, 0x00, 0x00, 0x46, 0xde, 0xc4, 0xbf,
0xa6, 0x9d, 0x81, 0x7b, 0x5c, 0x61, 0x40, 0xc7,
0xc0, 0xae, 0xa9, 0x8c, 0x83, 0x6a, 0x62, 0x50,
0x3e, 0xce, 0xc2, 0xae, 0xa3, 0x8c, 0x7b, 0x6a,
0x5a, 0x50, 0x35, 0xd7, 0xc2, 0xb7, 0xa4, 0x95,
0x7e, 0x72, 0x5a, 0x59, 0x37, 0xfe, 0x02, 0xf8,
0x8c, 0x95, 0x90, 0x8f, 0x00, 0xd7, 0xc0, 0xb7,
0xa2, 0x95, 0x7b, 0x72, 0x56, 0x59, 0x32, 0xc7,
0xc3, 0xae, 0xad, 0x8c, 0x85, 0x6a, 0x63, 0x50,
0x3e, 0xce, 0xc3, 0xae, 0xa4, 0x8c, 0x7c, 0x6a,
0x59, 0x50, 0x34, 0xd7, 0xc2, 0xb7, 0xa5, 0x95,
0x7e, 0x72, 0x59, 0x59, 0x36, 0xfc, 0x05, 0x00,
0x02, 0xce, 0xc5, 0xae, 0xa5, 0x95, 0x83, 0x72,
0x5c, 0x59, 0x36, 0xbf, 0xc6, 0xa5, 0xab, 0x8c,
0x8c, 0x6a, 0x67, 0x50, 0x41, 0x64, 0x07, 0x00,
0x02, 0x95, 0x8c, 0x72, 0x65, 0x59, 0x3f, 0xce,
0xc7, 0xae, 0xa8, 0x95, 0x86, 0x72, 0x5f, 0x59,
0x39, 0xfe, 0x02, 0xf8, 0x8b, 0x7c, 0x0b, 0x09,
0xb7, 0xc2, 0x9d, 0xa4, 0x83, 0x85, 0x6a, 0x6b,
0x50, 0x44, 0xb7, 0xc1, 0x64, 0x01, 0x00, 0x06,
0x61, 0x5d, 0x48, 0x3d, 0xae, 0xc4, 0x9d, 0xad,
0x7b, 0x85, 0x61, 0x66, 0x48, 0x46, 0xae, 0xc3,
0x95, 0xa3, 0x72, 0x7c, 0x59, 0x56, 0x38, 0x31,
0x7c, 0x0b, 0x00, 0x0c, 0x96, 0x91, 0x8f, 0x00,
0xb7, 0xc0, 0xa5, 0xab, 0x8c, 0x8a, 0x6a, 0x64,
0x50, 0x3c, 0xb7, 0xc0, 0x9d, 0xa0, 0x83, 0x80,
0x6a, 0x64, 0x50, 0x3d, 0xb7, 0xc5, 0x9d, 0xa5,
0x83, 0x87, 0x6c, 0x08, 0x07, 0xae, 0xc0, 0x9d,
0xa8, 0x83, 0x88, 0x6a, 0x6d, 0x50, 0x46, 0xfc,
0x05, 0x00, 0x16, 0xbf, 0xc0, 0xa5, 0xa2, 0x8c,
0x7f, 0x6a, 0x57, 0x50, 0x2f, 0xb7, 0xc7, 0xa5,
0xb1, 0x8c, 0x8e, 0x72, 0x6d, 0x59, 0x45, 0xbf,
0xc6, 0xa5, 0xa8, 0x8c, 0x87, 0x6a, 0x5f, 0x50,
0x37, 0xbf, 0xc2, 0xa5, 0xa4, 0x8c, 0x83, 0x6a,
0x5c, 0x50, 0x34, 0xbc, 0x05, 0x00, 0x0e, 0x90,
0x00, 0xc7, 0xc2, 0xae, 0xaa, 0x95, 0x82, 0x7b,
0x60, 0x61, 0x3f, 0xb7, 0xc6, 0xa5, 0xb1, 0x8c,
0x8d, 0x72, 0x6b, 0x61, 0x51, 0xbf, 0xc4, 0xa5,
0xa5, 0x8c, 0x82, 0x72, 0x61, 0x59, 0x39, 0x6c,
0x26, 0x03, 0x95, 0x82, 0x7b, 0x61, 0x61, 0x40,
0xfc, 0x05, 0x00, 0x00, 0x7e, 0xd7, 0xc3, 0xb7,
0xa8, 0x9d, 0x80, 0x83, 0x5d, 0x6a, 0x3f, 0xbf,
0xc7, 0xa5, 0xa8, 0x8c, 0x84, 0x72, 0x60, 0x61,
0x46, 0xbf, 0xc2, 0xae, 0xb0, 0x9d, 0x92, 0x83,
0x6f, 0x6a, 0x50, 0xd7, 0xc3, 0xb7, 0xa7, 0x9d,
0x80, 0x83, 0x5e, 0x6a, 0x40, 0xfe, 0x02, 0xf8,
0x8d, 0x96, 0x90, 0x90, 0xfe, 0x05, 0x00, 0x8a,
0xc4, 0x63, 0xb8, 0x3c, 0xa6, 0x29, 0x97, 0x16,
0x81, 0x84, 0xb7, 0x5b, 0xa9, 0x33, 0x94, 0x1e,
0x83, 0x11, 0x70, 0xb8, 0xc2, 0x70, 0xb1, 0x4d,
0xa3, 0x2a, 0x8d, 0x1b, 0x7b, 0xa8, 0xbc, 0x68,
0xab, 0x47, 0x9d, 0x27, 0x87, 0x18, 0x75, 0xae,
0xc6, 0x7d, 0xbb, 0x4d, 0xaa, 0x1c, 0x84, 0x11,
0x72, 0xa3, 0xbb, 0x6e, 0xad, 0x3c, 0x97, 0x24,
0x85, 0x16, 0x71, 0x80, 0xb2, 0x57, 0xa4, 0x30,
0x8e, 0x1c, 0x7c, 0x10, 0x68, 0xbb, 0xbd, 0x75,
0xac, 0x4f, 0x9e, 0x2b, 0x87, 0x1a, 0x76, 0x96,
0xc5, 0x5e, 0xb5, 0x3e, 0xa5, 0x1f, 0x8c, 0x12,
0x7a, 0xc1, 0xc6, 0x42, 0x9f, 0x27, 0x8c, 0x16,
0x77, 0x0f, 0x67, 0x9d, 0xbc, 0x68, 0xad, 0x36,
0x95, 0x20, 0x83, 0x11, 0x6d, 0x9b, 0xb8, 0x67,
0xa8, 0x34, 0x90, 0x1f, 0x7c, 0x10, 0x67, 0x9e,
0xc9, 0x6a, 0xbb, 0x37, 0xa4, 0x20, 0x90, 0x11,
0x7b, 0xc6, 0xc8, 0x47, 0xa4, 0x2a, 0x90, 0x18,
0x7b, 0x10, 0x6c, 0xae, 0xc4, 0x5d, 0xad, 0x37,
0x9a, 0x1f, 0x85, 0x13, 0x75, 0x70, 0xad, 0x42,
0x99, 0x25, 0x84, 0x17, 0x74, 0x0b, 0x56, 0x87,
0xc8, 0x57, 0xb8, 0x2b, 0x9e, 0x19, 0x8a, 0x0d,
0x74, 0xa7, 0xc8, 0x6e, 0xb9, 0x36, 0xa0, 0x1f,
0x8b, 0x11, 0x75, 0x94, 0xbe, 0x4b, 0xa5, 0x2a,
0x92, 0x18, 0x7c, 0x0f, 0x6b, 0xaf, 0xc0, 0x58,
0xa8, 0x34, 0x94, 0x1d, 0x7d, 0x12, 0x6d, 0x82,
0xc0, 0x52, 0xb0, 0x25, 0x94, 0x14, 0x7f, 0x0c,
0x68, 0x84, 0xbf, 0x3e, 0xa4, 0x22, 0x8e, 0x10,
0x76, 0x0b, 0x65, 0x88, 0xb6, 0x42, 0x9b, 0x26,
0x87, 0x14, 0x70, 0x0c, 0x5f, 0xc5, 0xc2, 0x3e,
0x97, 0x23, 0x83, 0x13, 0x6c, 0x0c, 0x5c, 0xb1,
0xc9, 0x76, 0xbc, 0x4a, 0xaa, 0x20, 0x8d, 0x12,
0x78, 0x93, 0xbf, 0x46, 0xa3, 0x26, 0x8d, 0x14,
0x74, 0x0c, 0x62, 0xc8, 0xc4, 0x3b, 0x97, 0x21,
0x82, 0x11, 0x6a, 0x0a, 0x59, 0xa3, 0xb9, 0x68,
0xa9, 0x30, 0x8d, 0x1a, 0x78, 0x0f, 0x61, 0xa0,
0xc9, 0x73, 0xbe, 0x50, 0xb1, 0x30, 0x9f, 0x14,
0x80, 0x83, 0xb7, 0x3c, 0x9a, 0x20, 0x84, 0x0e,
0x6a, 0x0a, 0x57, 0xac, 0xc2, 0x68, 0xb0, 0x2e,
0x92, 0x19, 0x7c, 0x0d, 0x63, 0x93, 0xbe, 0x62,
0xb0, 0x3c, 0x9e, 0x1a, 0x80, 0x0e, 0x6b, 0xbb,
0x02, 0xa0, 0x02, 0xa0, 0x02, 0x6f, 0x00, 0x75,
0x00, 0x75, 0x00, 0x00, 0x00, 0xad, 0x02, 0xb3,
0x02, 0x6f, 0x00, 0x87, 0x00, 0x85, 0xfe, 0x03,
0x00, 0xc2, 0x02, 0x82, 0x4d, 0x92, 0x6e, 0x4d,
0xb1, 0xa8, 0x84, 0x01, 0x00, 0x07, 0x7e, 0x00,
0xa8, 0x02, 0xa4, 0x02, 0xa4, 0x02, 0xa2, 0x00,
0xa6, 0x00, 0xa6, 0x00, 0x00, 0x00, 0xb4, 0x02,
0xb4, 0x02, 0x92, 0x00, 0x96, 0x00, 0x96, 0x46,
0x04, 0xb0, 0x02, 0x64, 0x02, 0x0a, 0x8c, 0x00,
0x90, 0x02, 0x98, 0x02, 0x98, 0x02, 0x0e, 0x01,
0x11, 0x01, 0x11, 0x50, 0xc3, 0x08, 0x88, 0x02,
0x88, 0x02, 0x19, 0x01, 0x02, 0x01, 0x02, 0x01,
0xf3, 0x2d, 0x00, 0x00
};
/* Array of known hw_options bits with human-friendly parsing */
static struct hc_hwopt {
const u32 bit;
const char *str;
} const hc_hwopts[] = {
{
.bit = RB_HW_OPT_NO_UART,
.str = "no UART\t\t",
}, {
.bit = RB_HW_OPT_HAS_VOLTAGE,
.str = "has Vreg\t",
}, {
.bit = RB_HW_OPT_HAS_USB,
.str = "has usb\t\t",
}, {
.bit = RB_HW_OPT_HAS_ATTINY,
.str = "has ATtiny\t",
}, {
.bit = RB_HW_OPT_NO_NAND,
.str = "no NAND\t\t",
}, {
.bit = RB_HW_OPT_HAS_LCD,
.str = "has LCD\t\t",
}, {
.bit = RB_HW_OPT_HAS_POE_OUT,
.str = "has POE out\t",
}, {
.bit = RB_HW_OPT_HAS_uSD,
.str = "has MicroSD\t",
}, {
.bit = RB_HW_OPT_HAS_SIM,
.str = "has SIM\t\t",
}, {
.bit = RB_HW_OPT_HAS_SFP,
.str = "has SFP\t\t",
}, {
.bit = RB_HW_OPT_HAS_WIFI,
.str = "has WiFi\t",
}, {
.bit = RB_HW_OPT_HAS_TS_FOR_ADC,
.str = "has TS ADC\t",
}, {
.bit = RB_HW_OPT_HAS_PLC,
.str = "has PLC\t\t",
},
};
/*
* The MAC is stored network-endian on all devices, in 2 32-bit segments:
* <XX:XX:XX:XX> <XX:XX:00:00>. Kernel print has us covered.
*/
static ssize_t hc_tag_show_mac(const u8 *pld, u16 pld_len, char *buf)
{
if (8 != pld_len)
return -EINVAL;
return sprintf(buf, "%pM\n", pld);
}
/*
* Print HW options in a human readable way:
* The raw number and in decoded form
*/
static ssize_t hc_tag_show_hwoptions(const u8 *pld, u16 pld_len, char *buf)
{
char *out = buf;
u32 data; // cpu-endian
int i;
if (sizeof(data) != pld_len)
return -EINVAL;
data = *(u32 *)pld;
out += sprintf(out, "raw\t\t: 0x%08x\n\n", data);
for (i = 0; i < ARRAY_SIZE(hc_hwopts); i++)
out += sprintf(out, "%s: %s\n", hc_hwopts[i].str,
(data & hc_hwopts[i].bit) ? "true" : "false");
return out - buf;
}
static ssize_t hc_wlan_data_bin_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t off, size_t count);
static struct hc_wlan_attr {
const u16 erd_tag_id;
struct bin_attribute battr;
u16 pld_ofs;
u16 pld_len;
} hc_wd_multi_battrs[] = {
{
.erd_tag_id = RB_WLAN_ERD_ID_MULTI_8001,
.battr = __BIN_ATTR(data_0, S_IRUSR, hc_wlan_data_bin_read, NULL, 0),
}, {
.erd_tag_id = RB_WLAN_ERD_ID_MULTI_8201,
.battr = __BIN_ATTR(data_2, S_IRUSR, hc_wlan_data_bin_read, NULL, 0),
}
};
static struct hc_wlan_attr hc_wd_solo_battr = {
.erd_tag_id = RB_WLAN_ERD_ID_SOLO,
.battr = __BIN_ATTR(wlan_data, S_IRUSR, hc_wlan_data_bin_read, NULL, 0),
};
static ssize_t hc_attr_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf);
/* Array of known tags to publish in sysfs */
static struct hc_attr {
const u16 tag_id;
ssize_t (* const tshow)(const u8 *pld, u16 pld_len, char *buf);
struct kobj_attribute kattr;
u16 pld_ofs;
u16 pld_len;
} hc_attrs[] = {
{
.tag_id = RB_ID_FLASH_INFO,
.tshow = routerboot_tag_show_u32s,
.kattr = __ATTR(flash_info, S_IRUSR, hc_attr_show, NULL),
}, {
.tag_id = RB_ID_MAC_ADDRESS_PACK,
.tshow = hc_tag_show_mac,
.kattr = __ATTR(mac_base, S_IRUSR, hc_attr_show, NULL),
}, {
.tag_id = RB_ID_BOARD_PRODUCT_CODE,
.tshow = routerboot_tag_show_string,
.kattr = __ATTR(board_product_code, S_IRUSR, hc_attr_show, NULL),
}, {
.tag_id = RB_ID_BIOS_VERSION,
.tshow = routerboot_tag_show_string,
.kattr = __ATTR(booter_version, S_IRUSR, hc_attr_show, NULL),
}, {
.tag_id = RB_ID_SERIAL_NUMBER,
.tshow = routerboot_tag_show_string,
.kattr = __ATTR(board_serial, S_IRUSR, hc_attr_show, NULL),
}, {
.tag_id = RB_ID_MEMORY_SIZE,
.tshow = routerboot_tag_show_u32s,
.kattr = __ATTR(mem_size, S_IRUSR, hc_attr_show, NULL),
}, {
.tag_id = RB_ID_MAC_ADDRESS_COUNT,
.tshow = routerboot_tag_show_u32s,
.kattr = __ATTR(mac_count, S_IRUSR, hc_attr_show, NULL),
}, {
.tag_id = RB_ID_HW_OPTIONS,
.tshow = hc_tag_show_hwoptions,
.kattr = __ATTR(hw_options, S_IRUSR, hc_attr_show, NULL),
}, {
.tag_id = RB_ID_WLAN_DATA,
.tshow = NULL,
}, {
.tag_id = RB_ID_BOARD_IDENTIFIER,
.tshow = routerboot_tag_show_string,
.kattr = __ATTR(board_identifier, S_IRUSR, hc_attr_show, NULL),
}, {
.tag_id = RB_ID_PRODUCT_NAME,
.tshow = routerboot_tag_show_string,
.kattr = __ATTR(product_name, S_IRUSR, hc_attr_show, NULL),
}, {
.tag_id = RB_ID_DEFCONF,
.tshow = routerboot_tag_show_string,
.kattr = __ATTR(defconf, S_IRUSR, hc_attr_show, NULL),
}, {
.tag_id = RB_ID_BOARD_REVISION,
.tshow = routerboot_tag_show_string,
.kattr = __ATTR(board_revision, S_IRUSR, hc_attr_show, NULL),
}
};
/*
* If the RB_ID_WLAN_DATA payload starts with RB_MAGIC_ERD, then past
* that magic number the payload itself contains a routerboot tag node
* locating the LZO-compressed calibration data. So far this scheme is only
* known to use a single tag at id 0x1.
*/
static int hc_wlan_data_unpack_erd(const u16 tag_id, const u8 *inbuf, size_t inlen,
void *outbuf, size_t *outlen)
{
u16 lzo_ofs, lzo_len;
int ret;
/* Find embedded tag */
ret = routerboot_tag_find(inbuf, inlen, tag_id, &lzo_ofs, &lzo_len);
if (ret) {
pr_debug(RB_HC_PR_PFX "no ERD data for id 0x%04x\n", tag_id);
goto fail;
}
if (lzo_len > inlen) {
pr_debug(RB_HC_PR_PFX "Invalid ERD data length\n");
ret = -EINVAL;
goto fail;
}
ret = lzo1x_decompress_safe(inbuf+lzo_ofs, lzo_len, outbuf, outlen);
if (ret)
pr_debug(RB_HC_PR_PFX "LZO decompression error (%d)\n", ret);
fail:
return ret;
}
/*
* If the RB_ID_WLAN_DATA payload starts with RB_MAGIC_LZOR, then past
* that magic number is a payload that must be appended to the hc_lzor_prefix,
* the resulting blob is LZO-compressed.
* If payload starts with RB_MAGIC_LZ77, a separate (bit level LZ77)
* decompression function needs to be used. In the decompressed result,
* the RB_MAGIC_ERD magic number (aligned) must be located. Following that
* magic, there is one or more routerboot tag node(s) locating the RLE-encoded
* calibration data payload.
*/
static int hc_wlan_data_unpack_lzor_lz77(const u16 tag_id, const u8 *inbuf, size_t inlen,
void *outbuf, size_t *outlen, u32 magic)
{
u16 rle_ofs, rle_len;
const u32 *needle;
u8 *tempbuf;
size_t templen, lzo_len;
int ret;
const char lzor[] = "LZOR";
const char lz77[] = "LZ77";
const char *lz_type;
/* Temporary buffer same size as the outbuf */
templen = *outlen;
tempbuf = kmalloc(templen, GFP_KERNEL);
if (!tempbuf)
return -ENOMEM;
lzo_len = inlen;
if (magic == RB_MAGIC_LZOR)
lzo_len += sizeof(hc_lzor_prefix);
if (lzo_len > *outlen)
return -EFBIG;
switch (magic) {
case RB_MAGIC_LZOR:
lz_type = lzor;
/* Concatenate into the outbuf */
memcpy(outbuf, hc_lzor_prefix, sizeof(hc_lzor_prefix));
memcpy(outbuf + sizeof(hc_lzor_prefix), inbuf, inlen);
/* LZO-decompress lzo_len bytes of outbuf into the tempbuf */
ret = lzo1x_decompress_safe(outbuf, lzo_len, tempbuf, &templen);
if (ret) {
if (LZO_E_INPUT_NOT_CONSUMED == ret) {
/*
* The tag length is always aligned thus the LZO payload may be padded,
* which can trigger a spurious error which we ignore here.
*/
pr_debug(RB_HC_PR_PFX "LZOR: LZO EOF before buffer end - this may be harmless\n");
} else {
pr_debug(RB_HC_PR_PFX "LZOR: LZO decompression error (%d)\n", ret);
goto fail;
}
}
break;
case RB_MAGIC_LZ77:
lz_type = lz77;
/* LZO-decompress lzo_len bytes of inbuf into the tempbuf */
ret = rb_lz77_decompress(inbuf, inlen, tempbuf, &templen);
if (ret) {
pr_err(RB_HC_PR_PFX "LZ77: LZ77 decompress error %d\n", ret);
goto fail;
}
pr_debug(RB_HC_PR_PFX "LZ77: decompressed from %zu to %zu\n",
inlen, templen);
break;
default:
return -EINVAL;
break;
}
/*
* Post decompression we have a blob (possibly byproduct of the lzo
* dictionary). We need to find RB_MAGIC_ERD. The magic number seems to
* be 32bit-aligned in the decompression output.
*/
needle = (const u32 *)tempbuf;
while (RB_MAGIC_ERD != *needle++) {
if ((u8 *)needle >= tempbuf+templen) {
pr_warn(RB_HC_PR_PFX "%s: ERD magic not found. Decompressed first word: 0x%08x\n", lz_type, *(u32 *)tempbuf);
ret = -ENODATA;
goto fail;
}
};
templen -= (u8 *)needle - tempbuf;
/* Past magic. Look for tag node */
ret = routerboot_tag_find((u8 *)needle, templen, tag_id, &rle_ofs, &rle_len);
if (ret) {
pr_debug(RB_HC_PR_PFX "%s: no RLE data for id 0x%04x\n", lz_type, tag_id);
goto fail;
}
if (rle_len > templen) {
pr_debug(RB_HC_PR_PFX "%s: Invalid RLE data length\n", lz_type);
ret = -EINVAL;
goto fail;
}
/* RLE-decode tempbuf from needle back into the outbuf */
ret = routerboot_rle_decode((u8 *)needle+rle_ofs, rle_len, outbuf, outlen);
if (ret)
pr_debug(RB_HC_PR_PFX "%s: RLE decoding error (%d)\n", lz_type, ret);
fail:
kfree(tempbuf);
return ret;
}
static int hc_wlan_data_unpack(const u16 tag_id, const size_t tofs, size_t tlen,
void *outbuf, size_t *outlen)
{
const u8 *lbuf;
u32 magic;
int ret;
/* Caller ensure tlen > 0. tofs is aligned */
if ((tofs + tlen) > hc_buflen)
return -EIO;
lbuf = hc_buf + tofs;
magic = *(u32 *)lbuf;
ret = -ENODATA;
switch (magic) {
case RB_MAGIC_LZ77:
/* no known instances of lz77 without 8001/8201 data, skip SOLO */
if (tag_id == RB_WLAN_ERD_ID_SOLO) {
pr_debug(RB_HC_PR_PFX "skipped LZ77 decompress in search for SOLO tag\n");
break;
}
fallthrough;
case RB_MAGIC_LZOR:
/* Skip magic */
lbuf += sizeof(magic);
tlen -= sizeof(magic);
ret = hc_wlan_data_unpack_lzor_lz77(tag_id, lbuf, tlen, outbuf, outlen, magic);
break;
case RB_MAGIC_ERD:
/* Skip magic */
lbuf += sizeof(magic);
tlen -= sizeof(magic);
ret = hc_wlan_data_unpack_erd(tag_id, lbuf, tlen, outbuf, outlen);
break;
default:
/*
* If the RB_ID_WLAN_DATA payload doesn't start with a
* magic number, the payload itself is the raw RLE-encoded
* calibration data. Only RB_WLAN_ERD_ID_SOLO makes sense here.
*/
if (RB_WLAN_ERD_ID_SOLO == tag_id) {
ret = routerboot_rle_decode(lbuf, tlen, outbuf, outlen);
if (ret)
pr_debug(RB_HC_PR_PFX "RLE decoding error (%d)\n", ret);
}
break;
}
return ret;
}
static ssize_t hc_attr_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
const struct hc_attr *hc_attr;
const u8 *pld;
u16 pld_len;
hc_attr = container_of(attr, typeof(*hc_attr), kattr);
if (!hc_attr->pld_len)
return -ENOENT;
pld = hc_buf + hc_attr->pld_ofs;
pld_len = hc_attr->pld_len;
return hc_attr->tshow(pld, pld_len, buf);
}
/*
* This function will allocate and free memory every time it is called. This
* is not the fastest way to do this, but since the data is rarely read (mainly
* at boot time to load wlan caldata), this makes it possible to save memory for
* the system.
*/
static ssize_t hc_wlan_data_bin_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t off, size_t count)
{
struct hc_wlan_attr *hc_wattr;
size_t outlen;
void *outbuf;
int ret;
hc_wattr = container_of(attr, typeof(*hc_wattr), battr);
if (!hc_wattr->pld_len)
return -ENOENT;
outlen = RB_ART_SIZE;
/* Don't bother unpacking if the source is already too large */
if (hc_wattr->pld_len > outlen)
return -EFBIG;
outbuf = kmalloc(outlen, GFP_KERNEL);
if (!outbuf)
return -ENOMEM;
ret = hc_wlan_data_unpack(hc_wattr->erd_tag_id, hc_wattr->pld_ofs, hc_wattr->pld_len, outbuf, &outlen);
if (ret) {
kfree(outbuf);
return ret;
}
if (off >= outlen) {
kfree(outbuf);
return 0;
}
if (off + count > outlen)
count = outlen - off;
memcpy(buf, outbuf + off, count);
kfree(outbuf);
return count;
}
int rb_hardconfig_init(struct kobject *rb_kobj, struct mtd_info *mtd)
{
struct kobject *hc_wlan_kobj;
size_t bytes_read, buflen, outlen;
const u8 *buf;
void *outbuf;
int i, j, ret;
u32 magic;
hc_buf = NULL;
hc_kobj = NULL;
hc_wlan_kobj = NULL;
ret = __get_mtd_device(mtd);
if (ret)
return -ENODEV;
hc_buflen = mtd->size;
hc_buf = kmalloc(hc_buflen, GFP_KERNEL);
if (!hc_buf) {
__put_mtd_device(mtd);
return -ENOMEM;
}
ret = mtd_read(mtd, 0, hc_buflen, &bytes_read, hc_buf);
__put_mtd_device(mtd);
if (ret)
goto fail;
if (bytes_read != hc_buflen) {
ret = -EIO;
goto fail;
}
/* Check we have what we expect */
magic = *(const u32 *)hc_buf;
if (RB_MAGIC_HARD != magic) {
ret = -EINVAL;
goto fail;
}
/* Skip magic */
buf = hc_buf + sizeof(magic);
buflen = hc_buflen - sizeof(magic);
/* Populate sysfs */
ret = -ENOMEM;
hc_kobj = kobject_create_and_add(RB_MTD_HARD_CONFIG, rb_kobj);
if (!hc_kobj)
goto fail;
/* Locate and publish all known tags */
for (i = 0; i < ARRAY_SIZE(hc_attrs); i++) {
ret = routerboot_tag_find(buf, buflen, hc_attrs[i].tag_id,
&hc_attrs[i].pld_ofs, &hc_attrs[i].pld_len);
if (ret) {
hc_attrs[i].pld_ofs = hc_attrs[i].pld_len = 0;
continue;
}
/* Account for skipped magic */
hc_attrs[i].pld_ofs += sizeof(magic);
/*
* Special case RB_ID_WLAN_DATA to prep and create the binary attribute.
* We first check if the data is "old style" within a single tag (or no tag at all):
* If it is we publish this single blob as a binary attribute child of hc_kobj to
* preserve backward compatibility.
* If it isn't and instead uses multiple ERD tags, we create a subfolder and
* publish the known ones there.
*/
if ((RB_ID_WLAN_DATA == hc_attrs[i].tag_id) && hc_attrs[i].pld_len) {
outlen = RB_ART_SIZE;
outbuf = kmalloc(outlen, GFP_KERNEL);
if (!outbuf) {
pr_warn(RB_HC_PR_PFX "Out of memory parsing WLAN tag\n");
continue;
}
/* Test ID_SOLO first, if found: done */
ret = hc_wlan_data_unpack(RB_WLAN_ERD_ID_SOLO, hc_attrs[i].pld_ofs, hc_attrs[i].pld_len, outbuf, &outlen);
if (!ret) {
hc_wd_solo_battr.pld_ofs = hc_attrs[i].pld_ofs;
hc_wd_solo_battr.pld_len = hc_attrs[i].pld_len;
ret = sysfs_create_bin_file(hc_kobj, &hc_wd_solo_battr.battr);
if (ret)
pr_warn(RB_HC_PR_PFX "Could not create %s sysfs entry (%d)\n",
hc_wd_solo_battr.battr.attr.name, ret);
}
/* Otherwise, create "wlan_data" subtree and publish known data */
else {
hc_wlan_kobj = kobject_create_and_add("wlan_data", hc_kobj);
if (!hc_wlan_kobj) {
kfree(outbuf);
pr_warn(RB_HC_PR_PFX "Could not create wlan_data sysfs folder\n");
continue;
}
for (j = 0; j < ARRAY_SIZE(hc_wd_multi_battrs); j++) {
outlen = RB_ART_SIZE;
ret = hc_wlan_data_unpack(hc_wd_multi_battrs[j].erd_tag_id,
hc_attrs[i].pld_ofs, hc_attrs[i].pld_len, outbuf, &outlen);
if (ret) {
hc_wd_multi_battrs[j].pld_ofs = hc_wd_multi_battrs[j].pld_len = 0;
continue;
}
hc_wd_multi_battrs[j].pld_ofs = hc_attrs[i].pld_ofs;
hc_wd_multi_battrs[j].pld_len = hc_attrs[i].pld_len;
ret = sysfs_create_bin_file(hc_wlan_kobj, &hc_wd_multi_battrs[j].battr);
if (ret)
pr_warn(RB_HC_PR_PFX "Could not create wlan_data/%s sysfs entry (%d)\n",
hc_wd_multi_battrs[j].battr.attr.name, ret);
}
}
kfree(outbuf);
}
/* All other tags are published via standard attributes */
else {
ret = sysfs_create_file(hc_kobj, &hc_attrs[i].kattr.attr);
if (ret)
pr_warn(RB_HC_PR_PFX "Could not create %s sysfs entry (%d)\n",
hc_attrs[i].kattr.attr.name, ret);
}
}
pr_info("MikroTik RouterBOARD hardware configuration sysfs driver v" RB_HARDCONFIG_VER "\n");
return 0;
fail:
kfree(hc_buf);
hc_buf = NULL;
return ret;
}
void rb_hardconfig_exit(void)
{
kobject_put(hc_kobj);
hc_kobj = NULL;
kfree(hc_buf);
hc_buf = NULL;
}

View file

@ -0,0 +1,32 @@
// SPDX-License-Identifier: GPL-2.0-only
/*
* Common definitions for MikroTik RouterBoot hard config data.
*
* Copyright (C) 2020 Thibaut VARÈNE <hacks+kernel@slashdirt.org>
*
* Some constant defines extracted from routerboot.{c,h} by Gabor Juhos
* <juhosg@openwrt.org>
*/
#ifndef _ROUTERBOOT_HARD_CONFIG_H_
#define _ROUTERBOOT_HARD_CONFIG_H_
/* ID values for hardware settings */
#define RB_ID_FLASH_INFO 0x03
#define RB_ID_MAC_ADDRESS_PACK 0x04
#define RB_ID_BOARD_PRODUCT_CODE 0x05
#define RB_ID_BIOS_VERSION 0x06
#define RB_ID_SDRAM_TIMINGS 0x08
#define RB_ID_DEVICE_TIMINGS 0x09
#define RB_ID_SOFTWARE_ID 0x0A
#define RB_ID_SERIAL_NUMBER 0x0B
#define RB_ID_MEMORY_SIZE 0x0D
#define RB_ID_MAC_ADDRESS_COUNT 0x0E
#define RB_ID_HW_OPTIONS 0x15
#define RB_ID_WLAN_DATA 0x16
#define RB_ID_BOARD_IDENTIFIER 0x17
#define RB_ID_PRODUCT_NAME 0x21
#define RB_ID_DEFCONF 0x26
#define RB_ID_BOARD_REVISION 0x27
#endif /* _ROUTERBOOT_HARD_CONFIG_H_ */

View file

@ -0,0 +1,446 @@
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (C) 2023 John Thomson
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/minmax.h>
#include "rb_lz77.h"
#define MIKRO_LZ77 "[rb lz77] "
/*
* The maximum number of bits used in a counter.
* For the look behind window, long instruction match offsets
* up to 6449 have been seen in provided compressed caldata blobs
* (that would need 21 counter bits: 4 to 12 + 11 to 0).
* conservative value here: 27 provides offset up to 0x8000 bytes
* uses a u8 in this code
*/
#define MIKRO_LZ77_MAX_COUNT_BIT_LEN 27
enum rb_lz77_instruction {
INSTR_ERROR = -1,
INSTR_LITERAL_BYTE = 0,
/* a (non aligned) byte follows this instruction,
* which is directly copied into output
*/
INSTR_PREVIOUS_OFFSET = 1,
/* this group is a match, with a bytes length defined by
* following counter bits, starting at bitshift 0,
* less the built-in count of 1
* using the previous offset as source
*/
INSTR_LONG = 2
/* this group has two counters,
* the first counter starts at bitshift 4,
* if this counter == 0, this is a non-matching group
* the second counter (bytes length) starts at bitshift 4,
* less the built-in count of 11+1.
* The final match group has this count 0,
* and following bits which pad to byte-alignment.
*
* if this counter > 0, this is a matching group
* this first count is the match offset (in bytes)
* the second count is the match length (in bytes),
* less the built-in count of 2
* these groups can source bytes that are part of this group
*/
};
struct rb_lz77_instr_opcodes {
/* group instruction */
enum rb_lz77_instruction instruction;
/* if >0, a match group,
* which starts at byte output_position - 1*offset
*/
size_t offset;
/* how long the match group is,
* or how long the (following counter) non-match group is
*/
size_t length;
/* how many bits were used for this instruction + op code(s) */
size_t bits_used;
/* input char */
u8 *in;
/* offset where this instruction started */
size_t in_pos;
};
/**
* rb_lz77_get_bit
*
* @in: compressed data ptr
* @in_offset_bit: bit offset to extract
*
* convert the bit offset to byte offset,
* shift to modulo of bits per bytes, so that wanted bit is lsb
* and to extract only that bit.
* Caller is responsible for ensuring that in_offset_bit/8
* does not exceed input length
*/
static inline u8 rb_lz77_get_bit(const u8 *in, const size_t in_offset_bit)
{
return ((in[in_offset_bit / BITS_PER_BYTE] >>
(in_offset_bit % BITS_PER_BYTE)) &
1);
}
/**
* rb_lz77_get_byte
*
* @in: compressed data
* @in_offset_bit: bit offset to extract byte
*/
static inline u8 rb_lz77_get_byte(const u8 *in, const size_t in_offset_bit)
{
u8 buf = 0;
int i;
/* built a reversed byte from (likely) unaligned bits */
for (i = 0; i <= 7; ++i)
buf += rb_lz77_get_bit(in, in_offset_bit + i) << (7 - i);
return buf;
}
/**
* rb_lz77_decode_count - decode bits at given offset as a count
*
* @in: compressed data
* @in_len: length of compressed data
* @in_offset_bit: bit offset where count starts
* @shift: left shift operand value of first count bit
* @count: initial count
* @bits_used: how many bits were consumed by this count
* @max_bits: maximum bit count for this counter
*
* Returns the decoded count
*/
static int rb_lz77_decode_count(const u8 *in, const size_t in_len,
const size_t in_offset_bit, u8 shift,
size_t count, u8 *bits_used, const u8 max_bits)
{
size_t pos = in_offset_bit;
const size_t max_pos = min(pos + max_bits, in_len * BITS_PER_BYTE);
bool up = true;
*bits_used = 0;
pr_debug(MIKRO_LZ77
"decode_count inbit: %zu, start shift:%u, initial count:%zu\n",
in_offset_bit, shift, count);
while (true) {
/* check the input offset bit does not overflow the minimum of
* a reasonable length for this encoded count, and
* the end of the input */
if (unlikely(pos >= max_pos)) {
pr_err(MIKRO_LZ77
"max bit index reached before count completed\n");
return -EFBIG;
}
/* if the bit value at offset is set */
if (rb_lz77_get_bit(in, pos))
count += (1 << shift);
/* shift increases until we find an unsed bit */
else if (up)
up = false;
if (up)
++shift;
else {
if (!shift) {
*bits_used = pos - in_offset_bit + 1;
return count;
}
--shift;
}
++pos;
}
return -EINVAL;
}
/**
* rb_lz77_decode_instruction
*
* @in: compressed data
* @in_offset_bit: bit offset where instruction starts
* @bits_used: how many bits were consumed by this count
*
* Returns the decoded instruction
*/
static enum rb_lz77_instruction
rb_lz77_decode_instruction(const u8 *in, size_t in_offset_bit, u8 *bits_used)
{
if (rb_lz77_get_bit(in, in_offset_bit)) {
*bits_used = 2;
if (rb_lz77_get_bit(in, ++in_offset_bit))
return INSTR_LONG;
else
return INSTR_PREVIOUS_OFFSET;
} else {
*bits_used = 1;
return INSTR_LITERAL_BYTE;
}
return INSTR_ERROR;
}
/**
* rb_lz77_decode_instruction_operators
*
* @in: compressed data
* @in_len: length of compressed data
* @in_offset_bit: bit offset where instruction starts
* @previous_offset: last used match offset
* @opcode: struct to hold instruction & operators
*
* Returns error code
*/
static int rb_lz77_decode_instruction_operators(
const u8 *in, const size_t in_len, const size_t in_offset_bit,
const size_t previous_offset, struct rb_lz77_instr_opcodes *opcode)
{
enum rb_lz77_instruction instruction;
u8 bit_count = 0;
u8 bits_used = 0;
int offset = 0;
int length = 0;
instruction = rb_lz77_decode_instruction(in, in_offset_bit, &bit_count);
/* skip bits used by instruction */
bits_used += bit_count;
switch (instruction) {
case INSTR_LITERAL_BYTE:
/* non-matching char */
offset = 0;
length = 1;
break;
case INSTR_PREVIOUS_OFFSET:
/* matching group uses previous offset */
offset = previous_offset;
length = rb_lz77_decode_count(in, in_len,
in_offset_bit + bits_used, 0, 1,
&bit_count,
MIKRO_LZ77_MAX_COUNT_BIT_LEN);
if (unlikely(length < 0))
return length;
/* skip bits used by count */
bits_used += bit_count;
break;
case INSTR_LONG:
offset = rb_lz77_decode_count(in, in_len,
in_offset_bit + bits_used, 4, 0,
&bit_count,
MIKRO_LZ77_MAX_COUNT_BIT_LEN);
if (unlikely(offset < 0))
return offset;
/* skip bits used by offset count */
bits_used += bit_count;
if (offset == 0) {
/* non-matching long group */
length = rb_lz77_decode_count(
in, in_len, in_offset_bit + bits_used, 4, 12,
&bit_count, MIKRO_LZ77_MAX_COUNT_BIT_LEN);
if (unlikely(length < 0))
return length;
/* skip bits used by length count */
bits_used += bit_count;
} else {
/* matching group */
length = rb_lz77_decode_count(
in, in_len, in_offset_bit + bits_used, 0, 2,
&bit_count, MIKRO_LZ77_MAX_COUNT_BIT_LEN);
if (unlikely(length < 0))
return length;
/* skip bits used by length count */
bits_used += bit_count;
}
break;
case INSTR_ERROR:
return -EINVAL;
}
opcode->instruction = instruction;
opcode->offset = offset;
opcode->length = length;
opcode->bits_used = bits_used;
opcode->in = (u8 *)in;
opcode->in_pos = in_offset_bit;
return 0;
}
/**
* rb_lz77_decompress
*
* @in: compressed data ptr
* @in_len: length of compressed data
* @out: buffer ptr to decompress into
* @out_len: length of decompressed buffer in input,
* length of decompressed data in success
*
* Returns 0 on success, or negative error
*/
int rb_lz77_decompress(const u8 *in, const size_t in_len, u8 *out,
size_t *out_len)
{
u8 *output_ptr;
size_t input_bit = 0;
const u8 *output_end = out + *out_len;
struct rb_lz77_instr_opcodes *opcode;
size_t match_offset = 0;
int rc = 0;
size_t match_length, partial_count, i;
output_ptr = out;
if (unlikely((in_len * BITS_PER_BYTE) > SIZE_MAX)) {
pr_err(MIKRO_LZ77 "input longer than expected\n");
return -EFBIG;
}
opcode = kmalloc(sizeof(*opcode), GFP_KERNEL);
if (!opcode)
return -ENOMEM;
while (true) {
if (unlikely(output_ptr > output_end)) {
pr_err(MIKRO_LZ77 "output overrun\n");
rc = -EOVERFLOW;
goto free_lz77_struct;
}
if (unlikely(input_bit > in_len * BITS_PER_BYTE)) {
pr_err(MIKRO_LZ77 "input overrun\n");
rc = -ENODATA;
goto free_lz77_struct;
}
rc = rb_lz77_decode_instruction_operators(in, in_len, input_bit,
match_offset, opcode);
if (unlikely(rc < 0)) {
pr_err(MIKRO_LZ77
"instruction operands decode error\n");
goto free_lz77_struct;
}
pr_debug(MIKRO_LZ77 "inbit:0x%zx->outbyte:0x%zx", input_bit,
output_ptr - out);
input_bit += opcode->bits_used;
switch (opcode->instruction) {
case INSTR_LITERAL_BYTE:
pr_debug(" short");
fallthrough;
case INSTR_LONG:
if (opcode->offset == 0) {
/* this is a non-matching group */
pr_debug(" non-match, len: 0x%zx\n",
opcode->length);
/* test end marker */
if (opcode->length == 0xc &&
((input_bit +
opcode->length * BITS_PER_BYTE) >
in_len)) {
*out_len = output_ptr - out;
pr_debug(
MIKRO_LZ77
"lz77 decompressed from %zu to %zu\n",
in_len, *out_len);
rc = 0;
goto free_lz77_struct;
}
for (i = opcode->length; i > 0; --i) {
*output_ptr =
rb_lz77_get_byte(in, input_bit);
++output_ptr;
input_bit += BITS_PER_BYTE;
}
/* do no fallthrough if a non-match group */
break;
}
match_offset = opcode->offset;
fallthrough;
case INSTR_PREVIOUS_OFFSET:
match_length = opcode->length;
partial_count = 0;
pr_debug(" match, offset: 0x%zx, len: 0x%zx",
opcode->offset, match_length);
if (unlikely(opcode->offset == 0)) {
pr_err(MIKRO_LZ77
"match group missing opcode->offset\n");
rc = -EBADMSG;
goto free_lz77_struct;
}
/* overflow */
if (unlikely((output_ptr + match_length) >
output_end)) {
pr_err(MIKRO_LZ77
"match group output overflow\n");
rc = -ENOBUFS;
goto free_lz77_struct;
}
/* underflow */
if (unlikely((output_ptr - opcode->offset) < out)) {
pr_err(MIKRO_LZ77
"match group offset underflow\n");
rc = -ESPIPE;
goto free_lz77_struct;
}
/* there are cases where the match (length) includes
* data that is a part of the same match
*/
while (opcode->offset < match_length) {
++partial_count;
memcpy(output_ptr, output_ptr - opcode->offset,
opcode->offset);
output_ptr += opcode->offset;
match_length -= opcode->offset;
}
memcpy(output_ptr, output_ptr - opcode->offset,
match_length);
output_ptr += match_length;
if (partial_count)
pr_debug(" (%zu partial memcpy)",
partial_count);
pr_debug("\n");
break;
case INSTR_ERROR:
rc = -EINVAL;
goto free_lz77_struct;
}
}
pr_err(MIKRO_LZ77 "decode loop broken\n");
rc = -EINVAL;
free_lz77_struct:
kfree(opcode);
return rc;
}
EXPORT_SYMBOL_GPL(rb_lz77_decompress);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Mikrotik Wi-Fi caldata LZ77 decompressor");
MODULE_AUTHOR("John Thomson");

View file

@ -0,0 +1,35 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
* Copyright (C) 2024 John Thomson
*/
#ifndef __MIKROTIK_WLAN_LZ77_H__
#define __MIKROTIK_WLAN_LZ77_H__
#include <linux/errno.h>
#ifdef CONFIG_MIKROTIK_WLAN_DECOMPRESS_LZ77
/**
* rb_lz77_decompress
*
* @in: compressed data ptr
* @in_len: length of compressed data
* @out: buffer ptr to decompress into
* @out_len: length of decompressed buffer in input,
* length of decompressed data in success
*
* Returns 0 on success, or negative error
*/
int rb_lz77_decompress(const u8 *in, const size_t in_len, u8 *out,
size_t *out_len);
#else /* CONFIG_MIKROTIK_WLAN_DECOMPRESS_LZ77 */
static inline int rb_lz77_decompress(const u8 *in, const size_t in_len, u8 *out,
size_t *out_len)
{
return -EOPNOTSUPP;
}
#endif /* CONFIG_MIKROTIK_WLAN_DECOMPRESS_LZ77 */
#endif /* __MIKROTIK_WLAN_LZ77_H__ */

View file

@ -0,0 +1,230 @@
// SPDX-License-Identifier: GPL-2.0-only
/*
* NVMEM layout driver for MikroTik Routerboard hard config cells
*
* Copyright (C) 2024 Robert Marko <robimarko@gmail.com>
* Based on the sysfs hard config driver by Thibaut VARÈNE <hacks+kernel@slashdirt.org>
* Comments documenting the format carried over from routerboot.c
*/
#include <linux/bitfield.h>
#include <linux/etherdevice.h>
#include <linux/mod_devicetable.h>
#include <linux/nvmem-consumer.h>
#include <linux/nvmem-provider.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include "rb_hardconfig.h"
#include "routerboot.h"
#define TLV_TAG_MASK GENMASK(15, 0)
#define TLV_LEN_MASK GENMASK(31, 16)
static const char *rb_tlv_cell_name(u16 tag)
{
switch (tag) {
case RB_ID_FLASH_INFO:
return "flash-info";
case RB_ID_MAC_ADDRESS_PACK:
return "base-mac-address";
case RB_ID_BOARD_PRODUCT_CODE:
return "board-product-code";
case RB_ID_BIOS_VERSION:
return "booter-version";
case RB_ID_SERIAL_NUMBER:
return "board-serial";
case RB_ID_MEMORY_SIZE:
return "mem-size";
case RB_ID_MAC_ADDRESS_COUNT:
return "mac-count";
case RB_ID_HW_OPTIONS:
return "hw-options";
case RB_ID_WLAN_DATA:
return "wlan-data";
case RB_ID_BOARD_IDENTIFIER:
return "board-identifier";
case RB_ID_PRODUCT_NAME:
return "product-name";
case RB_ID_DEFCONF:
return "defconf";
case RB_ID_BOARD_REVISION:
return "board-revision";
default:
break;
}
return NULL;
}
static int rb_tlv_mac_read_cb(void *priv, const char *id, int index,
unsigned int offset, void *buf,
size_t bytes)
{
if (index < 0)
return -EINVAL;
if (!is_valid_ether_addr(buf))
return -EINVAL;
eth_addr_add(buf, index);
return 0;
}
static nvmem_cell_post_process_t rb_tlv_read_cb(u16 tag)
{
switch (tag) {
case RB_ID_MAC_ADDRESS_PACK:
return &rb_tlv_mac_read_cb;
default:
break;
}
return NULL;
}
static int rb_add_cells(struct device *dev, struct nvmem_device *nvmem,
const size_t data_len, u8 *data)
{
u32 node, offset = sizeof(RB_MAGIC_HARD);
struct nvmem_cell_info cell = {};
struct device_node *layout;
u16 tlv_tag, tlv_len;
int ret;
layout = of_nvmem_layout_get_container(nvmem);
if (!layout)
return -ENOENT;
/*
* Routerboot tag nodes are u32 values:
* - The low nibble is the tag identification number,
* - The high nibble is the tag payload length (node excluded) in bytes.
* Tag nodes are CPU-endian.
* Tag nodes are 32bit-aligned.
*
* The payload immediately follows the tag node.
* Payload offset will always be aligned. while length may not end on 32bit
* boundary (the only known case is when parsing ERD data).
* The payload is CPU-endian when applicable.
* Tag nodes are not ordered (by ID) on flash.
*/
while ((offset + sizeof(node)) <= data_len) {
node = *((const u32 *) (data + offset));
/* Tag list ends with null node */
if (!node)
break;
tlv_tag = FIELD_GET(TLV_TAG_MASK, node);
tlv_len = FIELD_GET(TLV_LEN_MASK, node);
offset += sizeof(node);
if (offset + tlv_len > data_len) {
dev_err(dev, "Out of bounds field (0x%x bytes at 0x%x)\n",
tlv_len, offset);
break;
}
cell.name = rb_tlv_cell_name(tlv_tag);
if (!cell.name)
goto skip;
cell.offset = offset;
/*
* MikroTik stores MAC-s with length of 8 bytes,
* but kernel expects it to be ETH_ALEN (6 bytes),
* so we need to make sure that is the case.
*/
if (tlv_tag == RB_ID_MAC_ADDRESS_PACK)
cell.bytes = ETH_ALEN;
else
cell.bytes = tlv_len;
cell.np = of_get_child_by_name(layout, cell.name);
cell.read_post_process = rb_tlv_read_cb(tlv_tag);
ret = nvmem_add_one_cell(nvmem, &cell);
if (ret) {
of_node_put(layout);
return ret;
}
/*
* The only known situation where len may not end on 32bit
* boundary is within ERD data. Since we're only extracting
* one tag (the first and only one) from that data, we should
* never need to forcefully ALIGN(). Do it anyway, this is not a
* performance path.
*/
skip:
offset += ALIGN(tlv_len, sizeof(offset));
}
of_node_put(layout);
return 0;
}
static int rb_parse_table(struct nvmem_layout *layout)
{
struct nvmem_device *nvmem = layout->nvmem;
struct device *dev = &layout->dev;
size_t mtd_size;
u8 *data;
u32 hdr;
int ret;
ret = nvmem_device_read(nvmem, 0, sizeof(hdr), &hdr);
if (ret < 0)
return ret;
if (hdr != RB_MAGIC_HARD) {
dev_err(dev, "Invalid header\n");
return -EINVAL;
}
mtd_size = nvmem_dev_size(nvmem);
data = devm_kmalloc(dev, mtd_size, GFP_KERNEL);
if (!data)
return -ENOMEM;
ret = nvmem_device_read(nvmem, 0, mtd_size, data);
if (ret != mtd_size)
return ret;
return rb_add_cells(dev, nvmem, mtd_size, data);
}
static int rb_nvmem_probe(struct nvmem_layout *layout)
{
layout->add_cells = rb_parse_table;
return nvmem_layout_register(layout);
}
static void rb_nvmem_remove(struct nvmem_layout *layout)
{
nvmem_layout_unregister(layout);
}
static const struct of_device_id rb_nvmem_of_match_table[] = {
{ .compatible = "mikrotik,routerboot-nvmem", },
{},
};
MODULE_DEVICE_TABLE(of, rb_nvmem_of_match_table);
static struct nvmem_layout_driver rb_nvmem_layout = {
.probe = rb_nvmem_probe,
.remove = rb_nvmem_remove,
.driver = {
.owner = THIS_MODULE,
.name = "rb_nvmem",
.of_match_table = rb_nvmem_of_match_table,
},
};
module_nvmem_layout_driver(rb_nvmem_layout);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Robert Marko <robimarko@gmail.com>");
MODULE_DESCRIPTION("NVMEM layout driver for MikroTik Routerboard hard config cells");

View file

@ -0,0 +1,795 @@
// SPDX-License-Identifier: GPL-2.0-only
/*
* Driver for MikroTik RouterBoot soft config.
*
* Copyright (C) 2020 Thibaut VARÈNE <hacks+kernel@slashdirt.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* This driver exposes the data encoded in the "soft_config" flash segment of
* MikroTik RouterBOARDs devices. It presents the data in a sysfs folder
* named "soft_config". The data is presented in a user/machine-friendly way
* with just as much parsing as can be generalized across mikrotik platforms
* (as inferred from reverse-engineering).
*
* The known soft_config tags are presented in the "soft_config" sysfs folder,
* with the addition of one specific file named "commit", which is only
* available if the driver supports writes to the mtd device: no modifications
* made to any of the other attributes are actually written back to flash media
* until a true value is input into this file (e.g. [Yy1]). This is to avoid
* unnecessary flash wear, and to permit to revert all changes by issuing a
* false value ([Nn0]). Reading the content of this file shows the current
* status of the driver: if the data in sysfs matches the content of the
* soft_config partition, the file will read "clean". Otherwise, it will read
* "dirty".
*
* The writeable sysfs files presented by this driver will accept only inputs
* which are in a valid range for the given tag. As a design choice, the driver
* will not assess whether the inputs are identical to the existing data.
*
* Note: PAGE_SIZE is assumed to be >= 4K, hence the device attribute show
* routines need not check for output overflow.
*
* Some constant defines extracted from rbcfg.h by Gabor Juhos
* <juhosg@openwrt.org>
*/
#include <linux/types.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/kobject.h>
#include <linux/string.h>
#include <linux/mtd/mtd.h>
#include <linux/sysfs.h>
#include <linux/version.h>
#include <linux/capability.h>
#include <linux/spinlock.h>
#include <linux/crc32.h>
#ifdef CONFIG_ATH79
#include <asm/mach-ath79/ath79.h>
#endif
#include "routerboot.h"
#define RB_SOFTCONFIG_VER "0.05"
#define RB_SC_PR_PFX "[rb_softconfig] "
#define RB_SC_HAS_WRITE_SUPPORT true
#define RB_SC_WMODE S_IWUSR
#define RB_SC_RMODE S_IRUSR
/* ID values for software settings */
#define RB_SCID_UART_SPEED 0x01 // u32*1
#define RB_SCID_BOOT_DELAY 0x02 // u32*1
#define RB_SCID_BOOT_DEVICE 0x03 // u32*1
#define RB_SCID_BOOT_KEY 0x04 // u32*1
#define RB_SCID_CPU_MODE 0x05 // u32*1
#define RB_SCID_BIOS_VERSION 0x06 // str
#define RB_SCID_BOOT_PROTOCOL 0x09 // u32*1
#define RB_SCID_CPU_FREQ_IDX 0x0C // u32*1
#define RB_SCID_BOOTER 0x0D // u32*1
#define RB_SCID_SILENT_BOOT 0x0F // u32*1
/*
* protected_routerboot seems to use tag 0x1F. It only works in combination with
* RouterOS, resulting in a wiped board otherwise, so it's not implemented here.
* The tag values are as follows:
* - off: 0x0
* - on: the lower halfword encodes the max value in s for the reset feature,
* the higher halfword encodes the min value in s for the reset feature.
* Default value when on: 0x00140258: 0x14 = 20s / 0x258= 600s
* See details here: https://wiki.mikrotik.com/wiki/Manual:RouterBOARD_settings#Protected_bootloader
*/
/* Tag values */
#define RB_UART_SPEED_115200 0
#define RB_UART_SPEED_57600 1
#define RB_UART_SPEED_38400 2
#define RB_UART_SPEED_19200 3
#define RB_UART_SPEED_9600 4
#define RB_UART_SPEED_4800 5
#define RB_UART_SPEED_2400 6
#define RB_UART_SPEED_1200 7
#define RB_UART_SPEED_OFF 8
/* valid boot delay: 1 - 9s in 1s increment */
#define RB_BOOT_DELAY_MIN 1
#define RB_BOOT_DELAY_MAX 9
#define RB_BOOT_DEVICE_ETHER 0 // "boot over Ethernet"
#define RB_BOOT_DEVICE_NANDETH 1 // "boot from NAND, if fail then Ethernet"
#define RB_BOOT_DEVICE_CFCARD 2 // (not available in rbcfg)
#define RB_BOOT_DEVICE_ETHONCE 3 // "boot Ethernet once, then NAND"
#define RB_BOOT_DEVICE_NANDONLY 5 // "boot from NAND only"
#define RB_BOOT_DEVICE_FLASHCFG 7 // "boot in flash configuration mode"
#define RB_BOOT_DEVICE_FLSHONCE 8 // "boot in flash configuration mode once, then NAND"
/*
* ATH79 9xxx CPU frequency indices.
* It is unknown if they apply to all ATH79 RBs, and some do not seem to feature
* the upper levels (QCA955x), while F is presumably AR9344-only.
*/
#define RB_CPU_FREQ_IDX_ATH79_9X_A (0 << 3)
#define RB_CPU_FREQ_IDX_ATH79_9X_B (1 << 3) // 0x8
#define RB_CPU_FREQ_IDX_ATH79_9X_C (2 << 3) // 0x10 - factory freq for many devices
#define RB_CPU_FREQ_IDX_ATH79_9X_D (3 << 3) // 0x18
#define RB_CPU_FREQ_IDX_ATH79_9X_E (4 << 3) // 0x20
#define RB_CPU_FREQ_IDX_ATH79_9X_F (5 << 3) // 0x28
#define RB_CPU_FREQ_IDX_ATH79_9X_MIN 0 // all devices support lowest setting
#define RB_CPU_FREQ_IDX_ATH79_9X_AR9334_MAX 5 // stops at F
#define RB_CPU_FREQ_IDX_ATH79_9X_QCA953X_MAX 4 // stops at E
#define RB_CPU_FREQ_IDX_ATH79_9X_QCA9556_MAX 2 // stops at C
#define RB_CPU_FREQ_IDX_ATH79_9X_QCA9558_MAX 3 // stops at D
/* ATH79 7xxx CPU frequency indices. */
#define RB_CPU_FREQ_IDX_ATH79_7X_A ((0 * 9) << 4)
#define RB_CPU_FREQ_IDX_ATH79_7X_B ((1 * 9) << 4)
#define RB_CPU_FREQ_IDX_ATH79_7X_C ((2 * 9) << 4)
#define RB_CPU_FREQ_IDX_ATH79_7X_D ((3 * 9) << 4)
#define RB_CPU_FREQ_IDX_ATH79_7X_E ((4 * 9) << 4)
#define RB_CPU_FREQ_IDX_ATH79_7X_F ((5 * 9) << 4)
#define RB_CPU_FREQ_IDX_ATH79_7X_G ((6 * 9) << 4)
#define RB_CPU_FREQ_IDX_ATH79_7X_H ((7 * 9) << 4)
#define RB_CPU_FREQ_IDX_ATH79_7X_MIN 0 // all devices support lowest setting
#define RB_CPU_FREQ_IDX_ATH79_7X_AR724X_MAX 3 // stops at D
#define RB_CPU_FREQ_IDX_ATH79_7X_AR7161_MAX 7 // stops at H - check if applies to all AR71xx devices
#define RB_SC_CRC32_OFFSET 4 // located right after magic
static struct kobject *sc_kobj;
static u8 *sc_buf;
static size_t sc_buflen;
static rwlock_t sc_bufrwl; // rw lock to sc_buf
/* MUST be used with lock held */
#define RB_SC_CLRCRC() *(u32 *)(sc_buf + RB_SC_CRC32_OFFSET) = 0
#define RB_SC_GETCRC() *(u32 *)(sc_buf + RB_SC_CRC32_OFFSET)
#define RB_SC_SETCRC(_crc) *(u32 *)(sc_buf + RB_SC_CRC32_OFFSET) = (_crc)
struct sc_u32tvs {
const u32 val;
const char *str;
};
#define RB_SC_TVS(_val, _str) { \
.val = (_val), \
.str = (_str), \
}
static ssize_t sc_tag_show_u32tvs(const u8 *pld, u16 pld_len, char *buf,
const struct sc_u32tvs tvs[], const int tvselmts)
{
const char *fmt;
char *out = buf;
u32 data; // cpu-endian
int i;
// fallback to raw hex output if we can't handle the input
if (tvselmts < 0)
return routerboot_tag_show_u32s(pld, pld_len, buf);
if (sizeof(data) != pld_len)
return -EINVAL;
read_lock(&sc_bufrwl);
data = *(u32 *)pld; // pld aliases sc_buf
read_unlock(&sc_bufrwl);
for (i = 0; i < tvselmts; i++) {
fmt = (tvs[i].val == data) ? "[%s] " : "%s ";
out += sprintf(out, fmt, tvs[i].str);
}
out += sprintf(out, "\n");
return out - buf;
}
static ssize_t sc_tag_store_u32tvs(const u8 *pld, u16 pld_len, const char *buf, size_t count,
const struct sc_u32tvs tvs[], const int tvselmts)
{
int i;
if (tvselmts < 0)
return tvselmts;
if (sizeof(u32) != pld_len)
return -EINVAL;
for (i = 0; i < tvselmts; i++) {
if (sysfs_streq(buf, tvs[i].str)) {
write_lock(&sc_bufrwl);
*(u32 *)pld = tvs[i].val; // pld aliases sc_buf
RB_SC_CLRCRC();
write_unlock(&sc_bufrwl);
return count;
}
}
return -EINVAL;
}
struct sc_boolts {
const char *strfalse;
const char *strtrue;
};
static ssize_t sc_tag_show_boolts(const u8 *pld, u16 pld_len, char *buf,
const struct sc_boolts *bts)
{
const char *fmt;
char *out = buf;
u32 data; // cpu-endian
if (sizeof(data) != pld_len)
return -EINVAL;
read_lock(&sc_bufrwl);
data = *(u32 *)pld; // pld aliases sc_buf
read_unlock(&sc_bufrwl);
fmt = (data) ? "%s [%s]\n" : "[%s] %s\n";
out += sprintf(out, fmt, bts->strfalse, bts->strtrue);
return out - buf;
}
static ssize_t sc_tag_store_boolts(const u8 *pld, u16 pld_len, const char *buf, size_t count,
const struct sc_boolts *bts)
{
u32 data; // cpu-endian
if (sizeof(data) != pld_len)
return -EINVAL;
if (sysfs_streq(buf, bts->strfalse))
data = 0;
else if (sysfs_streq(buf, bts->strtrue))
data = 1;
else
return -EINVAL;
write_lock(&sc_bufrwl);
*(u32 *)pld = data; // pld aliases sc_buf
RB_SC_CLRCRC();
write_unlock(&sc_bufrwl);
return count;
}
static struct sc_u32tvs const sc_uartspeeds[] = {
RB_SC_TVS(RB_UART_SPEED_OFF, "off"),
RB_SC_TVS(RB_UART_SPEED_1200, "1200"),
RB_SC_TVS(RB_UART_SPEED_2400, "2400"),
RB_SC_TVS(RB_UART_SPEED_4800, "4800"),
RB_SC_TVS(RB_UART_SPEED_9600, "9600"),
RB_SC_TVS(RB_UART_SPEED_19200, "19200"),
RB_SC_TVS(RB_UART_SPEED_38400, "38400"),
RB_SC_TVS(RB_UART_SPEED_57600, "57600"),
RB_SC_TVS(RB_UART_SPEED_115200, "115200"),
};
/*
* While the defines are carried over from rbcfg, use strings that more clearly
* show the actual setting purpose (especially since the NAND* settings apply
* to both nand- and nor-based devices). "cfcard" was disabled in rbcfg: disable
* it here too.
*/
static struct sc_u32tvs const sc_bootdevices[] = {
RB_SC_TVS(RB_BOOT_DEVICE_ETHER, "eth"),
RB_SC_TVS(RB_BOOT_DEVICE_NANDETH, "flasheth"),
//RB_SC_TVS(RB_BOOT_DEVICE_CFCARD, "cfcard"),
RB_SC_TVS(RB_BOOT_DEVICE_ETHONCE, "ethonce"),
RB_SC_TVS(RB_BOOT_DEVICE_NANDONLY, "flash"),
RB_SC_TVS(RB_BOOT_DEVICE_FLASHCFG, "cfg"),
RB_SC_TVS(RB_BOOT_DEVICE_FLSHONCE, "cfgonce"),
};
static struct sc_boolts const sc_bootkey = {
.strfalse = "any",
.strtrue = "del",
};
static struct sc_boolts const sc_cpumode = {
.strfalse = "powersave",
.strtrue = "regular",
};
static struct sc_boolts const sc_bootproto = {
.strfalse = "bootp",
.strtrue = "dhcp",
};
static struct sc_boolts const sc_booter = {
.strfalse = "regular",
.strtrue = "backup",
};
static struct sc_boolts const sc_silent_boot = {
.strfalse = "off",
.strtrue = "on",
};
#define SC_TAG_SHOW_STORE_U32TVS_FUNCS(_name) \
static ssize_t sc_tag_show_##_name(const u8 *pld, u16 pld_len, char *buf) \
{ \
return sc_tag_show_u32tvs(pld, pld_len, buf, sc_##_name, ARRAY_SIZE(sc_##_name)); \
} \
static ssize_t sc_tag_store_##_name(const u8 *pld, u16 pld_len, const char *buf, size_t count) \
{ \
return sc_tag_store_u32tvs(pld, pld_len, buf, count, sc_##_name, ARRAY_SIZE(sc_##_name)); \
}
#define SC_TAG_SHOW_STORE_BOOLTS_FUNCS(_name) \
static ssize_t sc_tag_show_##_name(const u8 *pld, u16 pld_len, char *buf) \
{ \
return sc_tag_show_boolts(pld, pld_len, buf, &sc_##_name); \
} \
static ssize_t sc_tag_store_##_name(const u8 *pld, u16 pld_len, const char *buf, size_t count) \
{ \
return sc_tag_store_boolts(pld, pld_len, buf, count, &sc_##_name); \
}
SC_TAG_SHOW_STORE_U32TVS_FUNCS(uartspeeds)
SC_TAG_SHOW_STORE_U32TVS_FUNCS(bootdevices)
SC_TAG_SHOW_STORE_BOOLTS_FUNCS(bootkey)
SC_TAG_SHOW_STORE_BOOLTS_FUNCS(cpumode)
SC_TAG_SHOW_STORE_BOOLTS_FUNCS(bootproto)
SC_TAG_SHOW_STORE_BOOLTS_FUNCS(booter)
SC_TAG_SHOW_STORE_BOOLTS_FUNCS(silent_boot)
static ssize_t sc_tag_show_bootdelays(const u8 *pld, u16 pld_len, char *buf)
{
const char *fmt;
char *out = buf;
u32 data; // cpu-endian
int i;
if (sizeof(data) != pld_len)
return -EINVAL;
read_lock(&sc_bufrwl);
data = *(u32 *)pld; // pld aliases sc_buf
read_unlock(&sc_bufrwl);
for (i = RB_BOOT_DELAY_MIN; i <= RB_BOOT_DELAY_MAX; i++) {
fmt = (i == data) ? "[%d] " : "%d ";
out += sprintf(out, fmt, i);
}
out += sprintf(out, "\n");
return out - buf;
}
static ssize_t sc_tag_store_bootdelays(const u8 *pld, u16 pld_len, const char *buf, size_t count)
{
u32 data; // cpu-endian
int ret;
if (sizeof(data) != pld_len)
return -EINVAL;
ret = kstrtou32(buf, 10, &data);
if (ret)
return ret;
if ((data < RB_BOOT_DELAY_MIN) || (RB_BOOT_DELAY_MAX < data))
return -EINVAL;
write_lock(&sc_bufrwl);
*(u32 *)pld = data; // pld aliases sc_buf
RB_SC_CLRCRC();
write_unlock(&sc_bufrwl);
return count;
}
/* Support CPU frequency accessors only when the tag format has been asserted */
#if defined(CONFIG_ATH79)
/* Use the same letter-based nomenclature as RouterBOOT */
static struct sc_u32tvs const sc_cpufreq_indexes_ath79_9x[] = {
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_9X_A, "a"),
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_9X_B, "b"),
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_9X_C, "c"),
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_9X_D, "d"),
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_9X_E, "e"),
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_9X_F, "f"),
};
static struct sc_u32tvs const sc_cpufreq_indexes_ath79_7x[] = {
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_7X_A, "a"),
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_7X_B, "b"),
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_7X_C, "c"),
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_7X_D, "d"),
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_7X_E, "e"),
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_7X_F, "f"),
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_7X_G, "g"),
RB_SC_TVS(RB_CPU_FREQ_IDX_ATH79_7X_H, "h"),
};
static int sc_tag_cpufreq_ath79_arraysize(void)
{
int idx_max;
if (ATH79_SOC_AR7161 == ath79_soc)
idx_max = RB_CPU_FREQ_IDX_ATH79_7X_AR7161_MAX+1;
else if (soc_is_ar724x())
idx_max = RB_CPU_FREQ_IDX_ATH79_7X_AR724X_MAX+1;
else if (soc_is_ar9344())
idx_max = RB_CPU_FREQ_IDX_ATH79_9X_AR9334_MAX+1;
else if (soc_is_qca953x())
idx_max = RB_CPU_FREQ_IDX_ATH79_9X_QCA953X_MAX+1;
else if (soc_is_qca9556())
idx_max = RB_CPU_FREQ_IDX_ATH79_9X_QCA9556_MAX+1;
else if (soc_is_qca9558())
idx_max = RB_CPU_FREQ_IDX_ATH79_9X_QCA9558_MAX+1;
else
idx_max = -EOPNOTSUPP;
return idx_max;
}
static ssize_t sc_tag_show_cpufreq_indexes(const u8 *pld, u16 pld_len, char *buf)
{
const struct sc_u32tvs *tvs;
if (soc_is_ar71xx() || soc_is_ar724x())
tvs = sc_cpufreq_indexes_ath79_7x;
else
tvs = sc_cpufreq_indexes_ath79_9x;
return sc_tag_show_u32tvs(pld, pld_len, buf, tvs, sc_tag_cpufreq_ath79_arraysize());
}
static ssize_t sc_tag_store_cpufreq_indexes(const u8 *pld, u16 pld_len, const char *buf, size_t count)
{
const struct sc_u32tvs *tvs;
if (soc_is_ar71xx() || soc_is_ar724x())
tvs = sc_cpufreq_indexes_ath79_7x;
else
tvs = sc_cpufreq_indexes_ath79_9x;
return sc_tag_store_u32tvs(pld, pld_len, buf, count, tvs, sc_tag_cpufreq_ath79_arraysize());
}
#else
/* By default we only show the raw value to help with reverse-engineering */
#define sc_tag_show_cpufreq_indexes routerboot_tag_show_u32s
#define sc_tag_store_cpufreq_indexes NULL
#endif
static ssize_t sc_attr_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf);
static ssize_t sc_attr_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count);
/* Array of known tags to publish in sysfs */
static struct sc_attr {
const u16 tag_id;
/* sysfs tag show attribute. Must lock sc_buf when dereferencing pld */
ssize_t (* const tshow)(const u8 *pld, u16 pld_len, char *buf);
/* sysfs tag store attribute. Must lock sc_buf when dereferencing pld */
ssize_t (* const tstore)(const u8 *pld, u16 pld_len, const char *buf, size_t count);
struct kobj_attribute kattr;
u16 pld_ofs;
u16 pld_len;
} sc_attrs[] = {
{
.tag_id = RB_SCID_UART_SPEED,
.tshow = sc_tag_show_uartspeeds,
.tstore = sc_tag_store_uartspeeds,
.kattr = __ATTR(uart_speed, RB_SC_RMODE|RB_SC_WMODE, sc_attr_show, sc_attr_store),
}, {
.tag_id = RB_SCID_BOOT_DELAY,
.tshow = sc_tag_show_bootdelays,
.tstore = sc_tag_store_bootdelays,
.kattr = __ATTR(boot_delay, RB_SC_RMODE|RB_SC_WMODE, sc_attr_show, sc_attr_store),
}, {
.tag_id = RB_SCID_BOOT_DEVICE,
.tshow = sc_tag_show_bootdevices,
.tstore = sc_tag_store_bootdevices,
.kattr = __ATTR(boot_device, RB_SC_RMODE|RB_SC_WMODE, sc_attr_show, sc_attr_store),
}, {
.tag_id = RB_SCID_BOOT_KEY,
.tshow = sc_tag_show_bootkey,
.tstore = sc_tag_store_bootkey,
.kattr = __ATTR(boot_key, RB_SC_RMODE|RB_SC_WMODE, sc_attr_show, sc_attr_store),
}, {
.tag_id = RB_SCID_CPU_MODE,
.tshow = sc_tag_show_cpumode,
.tstore = sc_tag_store_cpumode,
.kattr = __ATTR(cpu_mode, RB_SC_RMODE|RB_SC_WMODE, sc_attr_show, sc_attr_store),
}, {
.tag_id = RB_SCID_BIOS_VERSION,
.tshow = routerboot_tag_show_string,
.tstore = NULL,
.kattr = __ATTR(bios_version, RB_SC_RMODE, sc_attr_show, NULL),
}, {
.tag_id = RB_SCID_BOOT_PROTOCOL,
.tshow = sc_tag_show_bootproto,
.tstore = sc_tag_store_bootproto,
.kattr = __ATTR(boot_proto, RB_SC_RMODE|RB_SC_WMODE, sc_attr_show, sc_attr_store),
}, {
.tag_id = RB_SCID_CPU_FREQ_IDX,
.tshow = sc_tag_show_cpufreq_indexes,
.tstore = sc_tag_store_cpufreq_indexes,
.kattr = __ATTR(cpufreq_index, RB_SC_RMODE|RB_SC_WMODE, sc_attr_show, sc_attr_store),
}, {
.tag_id = RB_SCID_BOOTER,
.tshow = sc_tag_show_booter,
.tstore = sc_tag_store_booter,
.kattr = __ATTR(booter, RB_SC_RMODE|RB_SC_WMODE, sc_attr_show, sc_attr_store),
}, {
.tag_id = RB_SCID_SILENT_BOOT,
.tshow = sc_tag_show_silent_boot,
.tstore = sc_tag_store_silent_boot,
.kattr = __ATTR(silent_boot, RB_SC_RMODE|RB_SC_WMODE, sc_attr_show, sc_attr_store),
},
};
static ssize_t sc_attr_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
const struct sc_attr *sc_attr;
const u8 *pld;
u16 pld_len;
sc_attr = container_of(attr, typeof(*sc_attr), kattr);
if (!sc_attr->pld_len)
return -ENOENT;
pld = sc_buf + sc_attr->pld_ofs; // pld aliases sc_buf -> lock!
pld_len = sc_attr->pld_len;
return sc_attr->tshow(pld, pld_len, buf);
}
static ssize_t sc_attr_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
const struct sc_attr *sc_attr;
const u8 *pld;
u16 pld_len;
if (!RB_SC_HAS_WRITE_SUPPORT)
return -EOPNOTSUPP;
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
sc_attr = container_of(attr, typeof(*sc_attr), kattr);
if (!sc_attr->tstore)
return -EOPNOTSUPP;
if (!sc_attr->pld_len)
return -ENOENT;
pld = sc_buf + sc_attr->pld_ofs; // pld aliases sc_buf -> lock!
pld_len = sc_attr->pld_len;
return sc_attr->tstore(pld, pld_len, buf, count);
}
/*
* Shows the current buffer status:
* "clean": the buffer is in sync with the mtd data
* "dirty": the buffer is out of sync with the mtd data
*/
static ssize_t sc_commit_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
const char *str;
char *out = buf;
u32 crc;
read_lock(&sc_bufrwl);
crc = RB_SC_GETCRC();
read_unlock(&sc_bufrwl);
str = (crc) ? "clean" : "dirty";
out += sprintf(out, "%s\n", str);
return out - buf;
}
/*
* Performs buffer flushing:
* This routine expects an input compatible with kstrtobool().
* - a "false" input discards the current changes and reads data back from mtd.
* - a "true" input commits the current changes to mtd.
* If there is no pending changes, this routine is a no-op.
* Handling failures is left as an exercise to userspace.
*/
static ssize_t sc_commit_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
struct mtd_info *mtd;
struct erase_info ei;
size_t bytes_rw, ret = count;
bool flush;
u32 crc;
if (!RB_SC_HAS_WRITE_SUPPORT)
return -EOPNOTSUPP;
read_lock(&sc_bufrwl);
crc = RB_SC_GETCRC();
read_unlock(&sc_bufrwl);
if (crc)
return count; // NO-OP
ret = kstrtobool(buf, &flush);
if (ret)
return ret;
mtd = get_mtd_device_nm(RB_MTD_SOFT_CONFIG); // TODO allow override
if (IS_ERR(mtd))
return -ENODEV;
write_lock(&sc_bufrwl);
if (!flush) // reread
ret = mtd_read(mtd, 0, mtd->size, &bytes_rw, sc_buf);
else { // crc32 + commit
/*
* CRC32 is computed on the entire buffer, excluding the CRC
* value itself. CRC is already null when we reach this point,
* so we can compute the CRC32 on the buffer as is.
* The expected CRC32 is Ethernet FCS style, meaning the seed is
* ~0 and the final result is also bitflipped.
*/
crc = ~crc32(~0, sc_buf, sc_buflen);
RB_SC_SETCRC(crc);
/*
* The soft_config partition is assumed to be entirely contained
* in a single eraseblock.
*/
ei.addr = 0;
ei.len = mtd->size;
ret = mtd_erase(mtd, &ei);
if (!ret)
ret = mtd_write(mtd, 0, mtd->size, &bytes_rw, sc_buf);
/*
* Handling mtd_write() failure here is a tricky situation. The
* proposed approach is to let userspace deal with retrying,
* with the caveat that it must try to flush the buffer again as
* rereading the mtd contents could potentially read garbage.
* The rationale is: even if we keep a shadow buffer of the
* original content, there is no guarantee that we will ever be
* able to write it anyway.
* Regardless, it appears that RouterBOOT will ignore an invalid
* soft_config (including a completely wiped segment) and will
* write back factory defaults when it happens.
*/
}
write_unlock(&sc_bufrwl);
put_mtd_device(mtd);
if (ret)
goto mtdfail;
if (bytes_rw != sc_buflen) {
ret = -EIO;
goto mtdfail;
}
return count;
mtdfail:
RB_SC_CLRCRC(); // mark buffer content as dirty/invalid
return ret;
}
static struct kobj_attribute sc_kattrcommit = __ATTR(commit, RB_SC_RMODE|RB_SC_WMODE, sc_commit_show, sc_commit_store);
int rb_softconfig_init(struct kobject *rb_kobj, struct mtd_info *mtd)
{
size_t bytes_read, buflen;
const u8 *buf;
int i, ret;
u32 magic;
sc_buf = NULL;
sc_kobj = NULL;
ret = __get_mtd_device(mtd);
if (ret)
return -ENODEV;
sc_buflen = mtd->size;
sc_buf = kmalloc(sc_buflen, GFP_KERNEL);
if (!sc_buf) {
__put_mtd_device(mtd);
return -ENOMEM;
}
ret = mtd_read(mtd, 0, sc_buflen, &bytes_read, sc_buf);
__put_mtd_device(mtd);
if (ret)
goto fail;
if (bytes_read != sc_buflen) {
ret = -EIO;
goto fail;
}
/* Check we have what we expect */
magic = *(const u32 *)sc_buf;
if (RB_MAGIC_SOFT != magic) {
ret = -EINVAL;
goto fail;
}
/* Skip magic and 32bit CRC located immediately after */
buf = sc_buf + (sizeof(magic) + sizeof(u32));
buflen = sc_buflen - (sizeof(magic) + sizeof(u32));
/* Populate sysfs */
ret = -ENOMEM;
sc_kobj = kobject_create_and_add(RB_MTD_SOFT_CONFIG, rb_kobj);
if (!sc_kobj)
goto fail;
rwlock_init(&sc_bufrwl);
/* Locate and publish all known tags */
for (i = 0; i < ARRAY_SIZE(sc_attrs); i++) {
ret = routerboot_tag_find(buf, buflen, sc_attrs[i].tag_id,
&sc_attrs[i].pld_ofs, &sc_attrs[i].pld_len);
if (ret) {
sc_attrs[i].pld_ofs = sc_attrs[i].pld_len = 0;
continue;
}
/* Account for skipped magic and crc32 */
sc_attrs[i].pld_ofs += sizeof(magic) + sizeof(u32);
ret = sysfs_create_file(sc_kobj, &sc_attrs[i].kattr.attr);
if (ret)
pr_warn(RB_SC_PR_PFX "Could not create %s sysfs entry (%d)\n",
sc_attrs[i].kattr.attr.name, ret);
}
/* Finally add the 'commit' attribute */
if (RB_SC_HAS_WRITE_SUPPORT) {
ret = sysfs_create_file(sc_kobj, &sc_kattrcommit.attr);
if (ret) {
pr_err(RB_SC_PR_PFX "Could not create %s sysfs entry (%d), aborting!\n",
sc_kattrcommit.attr.name, ret);
goto sysfsfail; // required attribute
}
}
pr_info("MikroTik RouterBOARD software configuration sysfs driver v" RB_SOFTCONFIG_VER "\n");
return 0;
sysfsfail:
kobject_put(sc_kobj);
sc_kobj = NULL;
fail:
kfree(sc_buf);
sc_buf = NULL;
return ret;
}
void rb_softconfig_exit(void)
{
kobject_put(sc_kobj);
sc_kobj = NULL;
kfree(sc_buf);
sc_buf = NULL;
}

View file

@ -0,0 +1,251 @@
// SPDX-License-Identifier: GPL-2.0-only
/*
* Driver for MikroTik RouterBoot flash data. Common routines.
*
* Copyright (C) 2020 Thibaut VARÈNE <hacks+kernel@slashdirt.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sysfs.h>
#include <linux/mtd/mtd.h>
#include "routerboot.h"
static struct kobject *rb_kobj;
/**
* routerboot_tag_find() - Locate a given tag in routerboot config data.
* @bufhead: the buffer to look into. Must start with a tag node.
* @buflen: size of bufhead
* @tag_id: the tag identifier to look for
* @pld_ofs: will be updated with tag payload offset in bufhead, if tag found
* @pld_len: will be updated with tag payload size, if tag found
*
* This incarnation of tag_find() does only that: it finds a specific routerboot
* tag node in the input buffer. Routerboot tag nodes are u32 values:
* - The low nibble is the tag identification number,
* - The high nibble is the tag payload length (node excluded) in bytes.
* The payload immediately follows the tag node. Tag nodes are 32bit-aligned.
* The returned pld_ofs will always be aligned. pld_len may not end on 32bit
* boundary (the only known case is when parsing ERD data).
* The nodes are cpu-endian on the flash media. The payload is cpu-endian when
* applicable. Tag nodes are not ordered (by ID) on flash.
*
* Return: 0 on success (tag found) or errno
*/
int routerboot_tag_find(const u8 *bufhead, const size_t buflen, const u16 tag_id,
u16 *pld_ofs, u16 *pld_len)
{
const u32 *datum, *bufend;
u32 node;
u16 id, len;
int ret;
if (!bufhead || !tag_id)
return -EINVAL;
ret = -ENOENT;
datum = (const u32 *)bufhead;
bufend = (const u32 *)(bufhead + buflen);
while (datum < bufend) {
node = *datum++;
/* Tag list ends with null node */
if (!node)
break;
id = node & 0xFFFF;
len = node >> 16;
if (tag_id == id) {
if (datum >= bufend)
break;
if (pld_ofs)
*pld_ofs = (u16)((u8 *)datum - bufhead);
if (pld_len)
*pld_len = len;
ret = 0;
break;
}
/*
* The only known situation where len may not end on 32bit
* boundary is within ERD data. Since we're only extracting
* one tag (the first and only one) from that data, we should
* never need to forcefully ALIGN(). Do it anyway, this is not a
* performance path.
*/
len = ALIGN(len, sizeof(*datum));
datum += len / sizeof(*datum);
}
return ret;
}
/**
* routerboot_rle_decode() - Simple RLE (MikroTik variant) decoding routine.
* @in: input buffer to decode
* @inlen: size of in
* @out: output buffer to write decoded data to
* @outlen: pointer to out size when function is called, will be updated with
* size of decoded output on return
*
* MikroTik's variant of RLE operates as follows, considering a signed run byte:
* - positive run => classic RLE
* - negative run => the next -<run> bytes must be copied verbatim
* The API is matched to the lzo1x routines for convenience.
*
* NB: The output buffer cannot overlap with the input buffer.
*
* Return: 0 on success or errno
*/
int routerboot_rle_decode(const u8 *in, size_t inlen, u8 *out, size_t *outlen)
{
int ret, run, nbytes; // use native types for speed
u8 byte;
if (!in || (inlen < 2) || !out)
return -EINVAL;
ret = -ENOSPC;
nbytes = 0;
while (inlen >= 2) {
run = *in++;
inlen--;
/* Verbatim copies */
if (run & 0x80) {
/* Invert run byte sign */
run = ~run & 0xFF;
run++;
if (run > inlen)
goto fail;
inlen -= run;
nbytes += run;
if (nbytes > *outlen)
goto fail;
/* Basic memcpy */
while (run-- > 0)
*out++ = *in++;
}
/* Stream of half-words RLE: <run><byte>. run == 0 is ignored */
else {
byte = *in++;
inlen--;
nbytes += run;
if (nbytes > *outlen)
goto fail;
while (run-- > 0)
*out++ = byte;
}
}
ret = 0;
fail:
*outlen = nbytes;
return ret;
}
static void routerboot_mtd_notifier_add(struct mtd_info *mtd)
{
/* Currently routerboot is only known to live on NOR flash */
if (mtd->type != MTD_NORFLASH)
return;
/*
* We ignore the following return values and always register.
* These init() routines are designed so that their failed state is
* always manageable by the corresponding exit() calls.
* Notifier is called with MTD mutex held: use __get/__put variants.
* TODO: allow partition names override
*/
if (!strcmp(mtd->name, RB_MTD_HARD_CONFIG))
rb_hardconfig_init(rb_kobj, mtd);
else if (!strcmp(mtd->name, RB_MTD_SOFT_CONFIG))
rb_softconfig_init(rb_kobj, mtd);
}
static void routerboot_mtd_notifier_remove(struct mtd_info *mtd)
{
if (mtd->type != MTD_NORFLASH)
return;
if (!strcmp(mtd->name, RB_MTD_HARD_CONFIG))
rb_hardconfig_exit();
else if (!strcmp(mtd->name, RB_MTD_SOFT_CONFIG))
rb_softconfig_exit();
}
/* Note: using a notifier prevents qualifying init()/exit() functions with __init/__exit */
static struct mtd_notifier routerboot_mtd_notifier = {
.add = routerboot_mtd_notifier_add,
.remove = routerboot_mtd_notifier_remove,
};
static int __init routerboot_init(void)
{
rb_kobj = kobject_create_and_add("mikrotik", firmware_kobj);
if (!rb_kobj)
return -ENOMEM;
register_mtd_user(&routerboot_mtd_notifier);
return 0;
}
static void __exit routerboot_exit(void)
{
unregister_mtd_user(&routerboot_mtd_notifier);
/* Exit routines are idempotent */
rb_softconfig_exit();
rb_hardconfig_exit();
kobject_put(rb_kobj); // recursive afaict
}
/* Common routines */
ssize_t routerboot_tag_show_string(const u8 *pld, u16 pld_len, char *buf)
{
return scnprintf(buf, pld_len+1, "%s\n", pld);
}
ssize_t routerboot_tag_show_u32s(const u8 *pld, u16 pld_len, char *buf)
{
char *out = buf;
u32 *data; // cpu-endian
/* Caller ensures pld_len > 0 */
if (pld_len % sizeof(*data))
return -EINVAL;
data = (u32 *)pld;
do {
out += sprintf(out, "0x%08x\n", *data);
data++;
} while ((pld_len -= sizeof(*data)));
return out - buf;
}
module_init(routerboot_init);
module_exit(routerboot_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("MikroTik RouterBoot sysfs support");
MODULE_AUTHOR("Thibaut VARENE");

View file

@ -0,0 +1,38 @@
// SPDX-License-Identifier: GPL-2.0-only
/*
* Common definitions for MikroTik RouterBoot data.
*
* Copyright (C) 2020 Thibaut VARÈNE <hacks+kernel@slashdirt.org>
*/
#ifndef _ROUTERBOOT_H_
#define _ROUTERBOOT_H_
#include <linux/types.h>
// these magic values are stored in cpu-endianness on flash
#define RB_MAGIC_HARD (('H') | ('a' << 8) | ('r' << 16) | ('d' << 24))
#define RB_MAGIC_SOFT (('S') | ('o' << 8) | ('f' << 16) | ('t' << 24))
#define RB_MAGIC_LZOR (('L') | ('Z' << 8) | ('O' << 16) | ('R' << 24))
#define RB_MAGIC_LZ77 (('L' << 24) | ('Z' << 16) | ('7' << 8) | ('7'))
#define RB_MAGIC_ERD (('E' << 16) | ('R' << 8) | ('D'))
#define RB_ART_SIZE 0x10000
#define RB_MTD_HARD_CONFIG "hard_config"
#define RB_MTD_SOFT_CONFIG "soft_config"
int routerboot_tag_find(const u8 *bufhead, const size_t buflen, const u16 tag_id, u16 *pld_ofs, u16 *pld_len);
int routerboot_rle_decode(const u8 *in, size_t inlen, u8 *out, size_t *outlen);
int rb_hardconfig_init(struct kobject *rb_kobj, struct mtd_info *mtd);
void rb_hardconfig_exit(void);
int rb_softconfig_init(struct kobject *rb_kobj, struct mtd_info *mtd);
void rb_softconfig_exit(void);
ssize_t routerboot_tag_show_string(const u8 *pld, u16 pld_len, char *buf);
ssize_t routerboot_tag_show_u32s(const u8 *pld, u16 pld_len, char *buf);
#endif /* _ROUTERBOOT_H_ */