1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * BCM47XX MTD partitioning
4  *
5  * Copyright © 2012 Rafał Miłecki <zajec5@gmail.com>
6  */
7 
8 #include <linux/bcm47xx_nvram.h>
9 #include <linux/module.h>
10 #include <linux/kernel.h>
11 #include <linux/slab.h>
12 #include <linux/mtd/mtd.h>
13 #include <linux/mtd/partitions.h>
14 
15 #include <uapi/linux/magic.h>
16 
17 /*
18  * NAND flash on Netgear R6250 was verified to contain 15 partitions.
19  * This will result in allocating too big array for some old devices, but the
20  * memory will be freed soon anyway (see mtd_device_parse_register).
21  */
22 #define BCM47XXPART_MAX_PARTS		20
23 
24 /*
25  * Amount of bytes we read when analyzing each block of flash memory.
26  * Set it big enough to allow detecting partition and reading important data.
27  */
28 #define BCM47XXPART_BYTES_TO_READ	0x4e8
29 
30 /* Magics */
31 #define BOARD_DATA_MAGIC		0x5246504D	/* MPFR */
32 #define BOARD_DATA_MAGIC2		0xBD0D0BBD
33 #define CFE_MAGIC			0x43464531	/* 1EFC */
34 #define FACTORY_MAGIC			0x59544346	/* FCTY */
35 #define NVRAM_HEADER			0x48534C46	/* FLSH */
36 #define POT_MAGIC1			0x54544f50	/* POTT */
37 #define POT_MAGIC2			0x504f		/* OP */
38 #define ML_MAGIC1			0x39685a42
39 #define ML_MAGIC2			0x26594131
40 #define TRX_MAGIC			0x30524448
41 #define SHSQ_MAGIC			0x71736873	/* shsq (weird ZTE H218N endianness) */
42 
43 static const char * const trx_types[] = { "trx", NULL };
44 
45 struct trx_header {
46 	uint32_t magic;
47 	uint32_t length;
48 	uint32_t crc32;
49 	uint16_t flags;
50 	uint16_t version;
51 	uint32_t offset[3];
52 } __packed;
53 
54 static void bcm47xxpart_add_part(struct mtd_partition *part, const char *name,
55 				 u64 offset, uint32_t mask_flags)
56 {
57 	part->name = name;
58 	part->offset = offset;
59 	part->mask_flags = mask_flags;
60 }
61 
62 /**
63  * bcm47xxpart_bootpartition - gets index of TRX partition used by bootloader
64  *
65  * Some devices may have more than one TRX partition. In such case one of them
66  * is the main one and another a failsafe one. Bootloader may fallback to the
67  * failsafe firmware if it detects corruption of the main image.
68  *
69  * This function provides info about currently used TRX partition. It's the one
70  * containing kernel started by the bootloader.
71  */
72 static int bcm47xxpart_bootpartition(void)
73 {
74 	char buf[4];
75 	int bootpartition;
76 
77 	/* Check CFE environment variable */
78 	if (bcm47xx_nvram_getenv("bootpartition", buf, sizeof(buf)) > 0) {
79 		if (!kstrtoint(buf, 0, &bootpartition))
80 			return bootpartition;
81 	}
82 
83 	return 0;
84 }
85 
86 static int bcm47xxpart_parse(struct mtd_info *master,
87 			     const struct mtd_partition **pparts,
88 			     struct mtd_part_parser_data *data)
89 {
90 	struct mtd_partition *parts;
91 	uint8_t i, curr_part = 0;
92 	uint32_t *buf;
93 	size_t bytes_read;
94 	uint32_t offset;
95 	uint32_t blocksize = master->erasesize;
96 	int trx_parts[2]; /* Array with indexes of TRX partitions */
97 	int trx_num = 0; /* Number of found TRX partitions */
98 	int possible_nvram_sizes[] = { 0x8000, 0xF000, 0x10000, };
99 	int err;
100 
101 	/*
102 	 * Some really old flashes (like AT45DB*) had smaller erasesize-s, but
103 	 * partitions were aligned to at least 0x1000 anyway.
104 	 */
105 	if (blocksize < 0x1000)
106 		blocksize = 0x1000;
107 
108 	/* Alloc */
109 	parts = kcalloc(BCM47XXPART_MAX_PARTS, sizeof(struct mtd_partition),
110 			GFP_KERNEL);
111 	if (!parts)
112 		return -ENOMEM;
113 
114 	buf = kzalloc(BCM47XXPART_BYTES_TO_READ, GFP_KERNEL);
115 	if (!buf) {
116 		kfree(parts);
117 		return -ENOMEM;
118 	}
119 
120 	/* Parse block by block looking for magics */
121 	for (offset = 0; offset <= master->size - blocksize;
122 	     offset += blocksize) {
123 		/* Nothing more in higher memory on BCM47XX (MIPS) */
124 		if (IS_ENABLED(CONFIG_BCM47XX) && offset >= 0x2000000)
125 			break;
126 
127 		if (curr_part >= BCM47XXPART_MAX_PARTS) {
128 			pr_warn("Reached maximum number of partitions, scanning stopped!\n");
129 			break;
130 		}
131 
132 		/* Read beginning of the block */
133 		err = mtd_read(master, offset, BCM47XXPART_BYTES_TO_READ,
134 			       &bytes_read, (uint8_t *)buf);
135 		if (err && !mtd_is_bitflip(err)) {
136 			pr_err("mtd_read error while parsing (offset: 0x%X): %d\n",
137 			       offset, err);
138 			continue;
139 		}
140 
141 		/* Magic or small NVRAM at 0x400 */
142 		if ((buf[0x4e0 / 4] == CFE_MAGIC && buf[0x4e4 / 4] == CFE_MAGIC) ||
143 		    (buf[0x400 / 4] == NVRAM_HEADER)) {
144 			bcm47xxpart_add_part(&parts[curr_part++], "boot",
145 					     offset, MTD_WRITEABLE);
146 			continue;
147 		}
148 
149 		/*
150 		 * board_data starts with board_id which differs across boards,
151 		 * but we can use 'MPFR' (hopefully) magic at 0x100
152 		 */
153 		if (buf[0x100 / 4] == BOARD_DATA_MAGIC) {
154 			bcm47xxpart_add_part(&parts[curr_part++], "board_data",
155 					     offset, MTD_WRITEABLE);
156 			continue;
157 		}
158 
159 		/* Found on Huawei E970 */
160 		if (buf[0x000 / 4] == FACTORY_MAGIC) {
161 			bcm47xxpart_add_part(&parts[curr_part++], "factory",
162 					     offset, MTD_WRITEABLE);
163 			continue;
164 		}
165 
166 		/* POT(TOP) */
167 		if (buf[0x000 / 4] == POT_MAGIC1 &&
168 		    (buf[0x004 / 4] & 0xFFFF) == POT_MAGIC2) {
169 			bcm47xxpart_add_part(&parts[curr_part++], "POT", offset,
170 					     MTD_WRITEABLE);
171 			continue;
172 		}
173 
174 		/* ML */
175 		if (buf[0x010 / 4] == ML_MAGIC1 &&
176 		    buf[0x014 / 4] == ML_MAGIC2) {
177 			bcm47xxpart_add_part(&parts[curr_part++], "ML", offset,
178 					     MTD_WRITEABLE);
179 			continue;
180 		}
181 
182 		/* TRX */
183 		if (buf[0x000 / 4] == TRX_MAGIC) {
184 			struct trx_header *trx;
185 			uint32_t last_subpart;
186 			uint32_t trx_size;
187 
188 			if (trx_num >= ARRAY_SIZE(trx_parts))
189 				pr_warn("No enough space to store another TRX found at 0x%X\n",
190 					offset);
191 			else
192 				trx_parts[trx_num++] = curr_part;
193 			bcm47xxpart_add_part(&parts[curr_part++], "firmware",
194 					     offset, 0);
195 
196 			/*
197 			 * Try to find TRX size. The "length" field isn't fully
198 			 * reliable as it could be decreased to make CRC32 cover
199 			 * only part of TRX data. It's commonly used as checksum
200 			 * can't cover e.g. ever-changing rootfs partition.
201 			 * Use offsets as helpers for assuming min TRX size.
202 			 */
203 			trx = (struct trx_header *)buf;
204 			last_subpart = max3(trx->offset[0], trx->offset[1],
205 					    trx->offset[2]);
206 			trx_size = max(trx->length, last_subpart + blocksize);
207 
208 			/*
209 			 * Skip the TRX data. Decrease offset by block size as
210 			 * the next loop iteration will increase it.
211 			 */
212 			offset += roundup(trx_size, blocksize) - blocksize;
213 			continue;
214 		}
215 
216 		/* Squashfs on devices not using TRX */
217 		if (le32_to_cpu(buf[0x000 / 4]) == SQUASHFS_MAGIC ||
218 		    buf[0x000 / 4] == SHSQ_MAGIC) {
219 			bcm47xxpart_add_part(&parts[curr_part++], "rootfs",
220 					     offset, 0);
221 			continue;
222 		}
223 
224 		/*
225 		 * New (ARM?) devices may have NVRAM in some middle block. Last
226 		 * block will be checked later, so skip it.
227 		 */
228 		if (offset != master->size - blocksize &&
229 		    buf[0x000 / 4] == NVRAM_HEADER) {
230 			bcm47xxpart_add_part(&parts[curr_part++], "nvram",
231 					     offset, 0);
232 			continue;
233 		}
234 
235 		/* Read middle of the block */
236 		err = mtd_read(master, offset + (blocksize / 2), 0x4, &bytes_read,
237 			       (uint8_t *)buf);
238 		if (err && !mtd_is_bitflip(err)) {
239 			pr_err("mtd_read error while parsing (offset: 0x%X): %d\n",
240 			       offset + (blocksize / 2), err);
241 			continue;
242 		}
243 
244 		/* Some devices (ex. WNDR3700v3) don't have a standard 'MPFR' */
245 		if (buf[0x000 / 4] == BOARD_DATA_MAGIC2) {
246 			bcm47xxpart_add_part(&parts[curr_part++], "board_data",
247 					     offset, MTD_WRITEABLE);
248 			continue;
249 		}
250 	}
251 
252 	/* Look for NVRAM at the end of the last block. */
253 	for (i = 0; i < ARRAY_SIZE(possible_nvram_sizes); i++) {
254 		if (curr_part >= BCM47XXPART_MAX_PARTS) {
255 			pr_warn("Reached maximum number of partitions, scanning stopped!\n");
256 			break;
257 		}
258 
259 		offset = master->size - possible_nvram_sizes[i];
260 		err = mtd_read(master, offset, 0x4, &bytes_read,
261 			       (uint8_t *)buf);
262 		if (err && !mtd_is_bitflip(err)) {
263 			pr_err("mtd_read error while reading (offset 0x%X): %d\n",
264 			       offset, err);
265 			continue;
266 		}
267 
268 		/* Standard NVRAM */
269 		if (buf[0] == NVRAM_HEADER) {
270 			bcm47xxpart_add_part(&parts[curr_part++], "nvram",
271 					     master->size - blocksize, 0);
272 			break;
273 		}
274 	}
275 
276 	kfree(buf);
277 
278 	/*
279 	 * Assume that partitions end at the beginning of the one they are
280 	 * followed by.
281 	 */
282 	for (i = 0; i < curr_part; i++) {
283 		u64 next_part_offset = (i < curr_part - 1) ?
284 				       parts[i + 1].offset : master->size;
285 
286 		parts[i].size = next_part_offset - parts[i].offset;
287 	}
288 
289 	/* If there was TRX parse it now */
290 	for (i = 0; i < trx_num; i++) {
291 		struct mtd_partition *trx = &parts[trx_parts[i]];
292 
293 		if (i == bcm47xxpart_bootpartition())
294 			trx->types = trx_types;
295 		else
296 			trx->name = "failsafe";
297 	}
298 
299 	*pparts = parts;
300 	return curr_part;
301 };
302 
303 static const struct of_device_id bcm47xxpart_of_match_table[] = {
304 	{ .compatible = "brcm,bcm947xx-cfe-partitions" },
305 	{},
306 };
307 MODULE_DEVICE_TABLE(of, bcm47xxpart_of_match_table);
308 
309 static struct mtd_part_parser bcm47xxpart_mtd_parser = {
310 	.parse_fn = bcm47xxpart_parse,
311 	.name = "bcm47xxpart",
312 	.of_match_table = bcm47xxpart_of_match_table,
313 };
314 module_mtd_part_parser(bcm47xxpart_mtd_parser);
315 
316 MODULE_LICENSE("GPL");
317 MODULE_DESCRIPTION("MTD partitioning for BCM47XX flash memories");
318