xref: /rk3399_rockchip-uboot/arch/arm/mach-rockchip/resource_img.c (revision f1fc975dacf3d9cf751d82fdb6f9d48b37aa9c65)
1 /*
2  * (C) Copyright 2017 Rockchip Electronics Co., Ltd
3  *
4  * SPDX-License-Identifier:     GPL-2.0+
5  */
6 #include <common.h>
7 #include <adc.h>
8 #include <asm/io.h>
9 #include <malloc.h>
10 #include <linux/list.h>
11 #include <asm/arch/resource_img.h>
12 #include <boot_rkimg.h>
13 #include <dm/ofnode.h>
14 #ifdef CONFIG_ANDROID_AB
15 #include <android_avb/libavb_ab.h>
16 #include <android_avb/rk_avb_ops_user.h>
17 #endif
18 #ifdef CONFIG_ANDROID_BOOT_IMAGE
19 #include <android_bootloader.h>
20 #include <android_image.h>
21 #endif
22 
23 DECLARE_GLOBAL_DATA_PTR;
24 
25 #define PART_RESOURCE			"resource"
26 #define RESOURCE_MAGIC			"RSCE"
27 #define RESOURCE_MAGIC_SIZE		4
28 #define RESOURCE_VERSION		0
29 #define CONTENT_VERSION			0
30 #define ENTRY_TAG			"ENTR"
31 #define ENTRY_TAG_SIZE			4
32 #define MAX_FILE_NAME_LEN		256
33 
34 /*
35  *         resource image structure
36  * ----------------------------------------------
37  * |                                            |
38  * |    header  (1 block)                       |
39  * |                                            |
40  * ---------------------------------------------|
41  * |                      |                     |
42  * |    entry0  (1 block) |                     |
43  * |                      |                     |
44  * ------------------------                     |
45  * |                      |                     |
46  * |    entry1  (1 block) | contents (n blocks) |
47  * |                      |                     |
48  * ------------------------                     |
49  * |    ......            |                     |
50  * ------------------------                     |
51  * |                      |                     |
52  * |    entryn  (1 block) |                     |
53  * |                      |                     |
54  * ----------------------------------------------
55  * |                                            |
56  * |    file0  (x blocks)                       |
57  * |                                            |
58  * ----------------------------------------------
59  * |                                            |
60  * |    file1  (y blocks)                       |
61  * |                                            |
62  * ----------------------------------------------
63  * |                   ......                   |
64  * |---------------------------------------------
65  * |                                            |
66  * |    filen  (z blocks)                       |
67  * |                                            |
68  * ----------------------------------------------
69  */
70 
71 /**
72  * struct resource_image_header
73  *
74  * @magic: should be "RSCE"
75  * @version: resource image version, current is 0
76  * @c_version: content version, current is 0
77  * @blks: the size of the header ( 1 block = 512 bytes)
78  * @c_offset: contents offset(by block) in the image
79  * @e_blks: the size(by block) of the entry in the contents
80  * @e_num: numbers of the entrys.
81  */
82 
83 struct resource_img_hdr {
84 	char		magic[4];
85 	uint16_t	version;
86 	uint16_t	c_version;
87 	uint8_t		blks;
88 	uint8_t		c_offset;
89 	uint8_t		e_blks;
90 	uint32_t	e_nums;
91 };
92 
93 struct resource_entry {
94 	char		tag[4];
95 	char		name[MAX_FILE_NAME_LEN];
96 	uint32_t	f_offset;
97 	uint32_t	f_size;
98 };
99 
100 struct resource_file {
101 	char		name[MAX_FILE_NAME_LEN];
102 	uint32_t	f_offset;
103 	uint32_t	f_size;
104 	struct list_head link;
105 	uint32_t 	rsce_base;	/* Base addr of resource */
106 };
107 
108 static LIST_HEAD(entrys_head);
109 
110 static int resource_image_check_header(const struct resource_img_hdr *hdr)
111 {
112 	int ret;
113 
114 	ret = memcmp(RESOURCE_MAGIC, hdr->magic, RESOURCE_MAGIC_SIZE);
115 	if (ret) {
116 		printf("bad resource image magic: %s\n",
117 		       hdr->magic ? hdr->magic : "none");
118 		ret = -EINVAL;
119 	}
120 	debug("resource image header:\n");
121 	debug("magic:%s\n", hdr->magic);
122 	debug("version:%d\n", hdr->version);
123 	debug("c_version:%d\n", hdr->c_version);
124 	debug("blks:%d\n", hdr->blks);
125 	debug("c_offset:%d\n", hdr->c_offset);
126 	debug("e_blks:%d\n", hdr->e_blks);
127 	debug("e_num:%d\n", hdr->e_nums);
128 
129 	return ret;
130 }
131 
132 static int add_file_to_list(struct resource_entry *entry, int rsce_base)
133 {
134 	struct resource_file *file;
135 
136 	if (memcmp(entry->tag, ENTRY_TAG, ENTRY_TAG_SIZE)) {
137 		printf("invalid entry tag\n");
138 		return -ENOENT;
139 	}
140 	file = malloc(sizeof(*file));
141 	if (!file) {
142 		printf("out of memory\n");
143 		return -ENOMEM;
144 	}
145 	strcpy(file->name, entry->name);
146 	file->rsce_base = rsce_base;
147 	file->f_offset = entry->f_offset;
148 	file->f_size = entry->f_size;
149 	list_add_tail(&file->link, &entrys_head);
150 	debug("entry:%p  %s offset:%d size:%d\n",
151 	      entry, file->name, file->f_offset, file->f_size);
152 
153 	return 0;
154 }
155 
156 static int init_resource_list(struct resource_img_hdr *hdr)
157 {
158 	struct resource_entry *entry;
159 	void *content;
160 	int size;
161 	int ret;
162 	int e_num;
163 	int offset = 0;
164 	int resource_found = 0;
165 	struct blk_desc *dev_desc;
166 	disk_partition_t part_info;
167 
168 /*
169  * Primary detect AOSP format image, try to get resource image from
170  * boot/recovery partition. If not, it's an RK format image and try
171  * to get from resource partition.
172  */
173 #ifdef CONFIG_ANDROID_BOOT_IMAGE
174 	struct andr_img_hdr *andr_hdr;
175 	char *boot_partname = PART_BOOT;
176 #endif
177 
178 	if (hdr) {
179 		content = (void *)((char *)hdr
180 				   + (hdr->c_offset) * RK_BLK_SIZE);
181 		for (e_num = 0; e_num < hdr->e_nums; e_num++) {
182 			size = e_num * hdr->e_blks * RK_BLK_SIZE;
183 			entry = (struct resource_entry *)(content + size);
184 			add_file_to_list(entry, offset);
185 		}
186 		return 0;
187 	}
188 
189 	dev_desc = rockchip_get_bootdev();
190 	if (!dev_desc) {
191 		printf("%s: dev_desc is NULL!\n", __func__);
192 		return -ENODEV;
193 	}
194 	hdr = memalign(ARCH_DMA_MINALIGN, RK_BLK_SIZE);
195 	if (!hdr) {
196 		printf("%s: out of memory!\n", __func__);
197 		return -ENOMEM;
198 	}
199 
200 #ifdef CONFIG_ANDROID_BOOT_IMAGE
201 	/* Get boot mode from misc */
202 #ifndef CONFIG_ANDROID_AB
203 	if (rockchip_get_boot_mode() == BOOT_MODE_RECOVERY)
204 		boot_partname = PART_RECOVERY;
205 #endif
206 
207 	/* Read boot/recovery and chenc if this is an AOSP img */
208 #ifdef CONFIG_ANDROID_AB
209 	char slot_suffix[3] = {0};
210 
211 	if (rk_avb_get_current_slot(slot_suffix))
212 		goto out;
213 	boot_partname = android_str_append(boot_partname, slot_suffix);
214 	if (boot_partname == NULL)
215 		goto out;
216 #endif
217 	ret = part_get_info_by_name(dev_desc, boot_partname, &part_info);
218 	if (ret < 0) {
219 		printf("%s: failed to get %s part, ret=%d\n",
220 		       __func__, boot_partname, ret);
221 		/* RKIMG can support part table without 'boot' */
222 		goto next;
223 	}
224 
225 	/*
226 	 * Only read header and check magic, is a AOSP format image?
227 	 * If so, get resource image from second part.
228 	 */
229 	andr_hdr = (void *)hdr;
230 	ret = blk_dread(dev_desc, part_info.start, 1, andr_hdr);
231 	if (ret != 1) {
232 		printf("%s: failed to read %s hdr, ret=%d\n",
233 		       __func__, part_info.name, ret);
234 		goto out;
235 	}
236 	ret = android_image_check_header(andr_hdr);
237 	if (!ret) {
238 		debug("%s: Load resource from %s second pos\n",
239 		      __func__, part_info.name);
240 		/* Read resource from second offset */
241 		offset = part_info.start * RK_BLK_SIZE;
242 		offset += andr_hdr->page_size;
243 		offset += ALIGN(andr_hdr->kernel_size, andr_hdr->page_size);
244 		offset += ALIGN(andr_hdr->ramdisk_size, andr_hdr->page_size);
245 		offset = offset / RK_BLK_SIZE;
246 
247 		resource_found = 1;
248 	}
249 next:
250 #endif
251 	/*
252 	 * If not found resource image in AOSP format images(boot/recovery part),
253 	 * try to read RK format images(resource part).
254 	 */
255 	if (!resource_found) {
256 		debug("%s: Load resource from resource part\n", __func__);
257 		/* Read resource from Rockchip Resource partition */
258 		ret = part_get_info_by_name(dev_desc, PART_RESOURCE, &part_info);
259 		if (ret < 0) {
260 			printf("%s: failed to get resource part, ret=%d\n",
261 			       __func__, ret);
262 			goto out;
263 		}
264 		offset = part_info.start;
265 	}
266 
267 	/* Only read header and check magic */
268 	ret = blk_dread(dev_desc, offset, 1, hdr);
269 	if (ret != 1) {
270 		printf("%s: failed to read resource hdr, ret=%d\n",
271 		       __func__, ret);
272 		goto out;
273 	}
274 
275 	ret = resource_image_check_header(hdr);
276 	if (ret < 0)
277 		goto out;
278 
279 	content = memalign(ARCH_DMA_MINALIGN,
280 			   hdr->e_blks * hdr->e_nums * RK_BLK_SIZE);
281 	if (!content) {
282 		printf("%s: failed to alloc memory for content\n", __func__);
283 		goto out;
284 	}
285 
286 	/* Read all entries from resource image */
287 	ret = blk_dread(dev_desc, offset + hdr->c_offset,
288 			hdr->e_blks * hdr->e_nums, content);
289 	if (ret != (hdr->e_blks * hdr->e_nums)) {
290 		printf("%s: failed to read resource entries, ret=%d\n",
291 		       __func__, ret);
292 		goto err;
293 	}
294 
295 	for (e_num = 0; e_num < hdr->e_nums; e_num++) {
296 		size = e_num * hdr->e_blks * RK_BLK_SIZE;
297 		entry = (struct resource_entry *)(content + size);
298 		add_file_to_list(entry, offset);
299 	}
300 
301 err:
302 	free(content);
303 out:
304 	free(hdr);
305 
306 	return 0;
307 }
308 
309 static struct resource_file *get_file_info(struct resource_img_hdr *hdr,
310 					   const char *name)
311 {
312 	struct resource_file *file;
313 	struct list_head *node;
314 
315 	if (list_empty(&entrys_head))
316 		init_resource_list(hdr);
317 
318 	list_for_each(node, &entrys_head) {
319 		file = list_entry(node, struct resource_file, link);
320 		if (!strcmp(file->name, name))
321 			return file;
322 	}
323 
324 	return NULL;
325 }
326 
327 int rockchip_get_resource_file(void *buf, const char *name)
328 {
329 	struct resource_file *file;
330 
331 	file = get_file_info(buf, name);
332 
333 	return file->f_offset;
334 }
335 
336 /*
337  * read file from resource partition
338  * @buf: destination buf to store file data;
339  * @name: file name
340  * @offset: blocks offset in the file, 1 block = 512 bytes
341  * @len: the size(by bytes) of file to read.
342  */
343 int rockchip_read_resource_file(void *buf, const char *name,
344 				int offset, int len)
345 {
346 	struct resource_file *file;
347 	int ret = 0;
348 	int blks;
349 	struct blk_desc *dev_desc;
350 
351 	file = get_file_info(NULL, name);
352 	if (!file) {
353 		printf("Can't find file:%s\n", name);
354 		return -ENOENT;
355 	}
356 
357 	if (len <= 0 || len > file->f_size)
358 		len = file->f_size;
359 	blks = DIV_ROUND_UP(len, RK_BLK_SIZE);
360 	dev_desc = rockchip_get_bootdev();
361 	if (!dev_desc) {
362 		printf("%s: dev_desc is NULL!\n", __func__);
363 		return -ENODEV;
364 	}
365 	ret = blk_dread(dev_desc, file->rsce_base + file->f_offset + offset,
366 			blks, buf);
367 	if (ret != blks)
368 		ret = -EIO;
369 	else
370 		ret = len;
371 
372 	return ret;
373 }
374 
375 #define is_digit(c)		((c) >= '0' && (c) <= '9')
376 #define is_abcd(c)		((c) >= 'a' && (c) <= 'd')
377 #define is_equal(c)		((c) == '=')
378 
379 #define DTB_FILE		"rk-kernel.dtb"
380 #define KEY_WORDS_ADC_CTRL	"#_"
381 #define KEY_WORDS_ADC_CH	"_ch"
382 #define KEY_WORDS_GPIO		"#gpio"
383 #define GPIO_EXT_PORT		0x50
384 #define MAX_ADC_CH_NR		10
385 #define MAX_GPIO_NR		10
386 
387 #ifdef CONFIG_ADC
388 /*
389  * How to make it works ?
390  *
391  * 1. pack dtb into rockchip resource.img, require:
392  *    (1) file name end with ".dtb";
393  *    (2) file name contains key words, like: ...#_[controller]_ch[channel]=[value]...dtb
394  *	  @controller: adc controller name in dts, eg. "saradc", ...;
395  *	  @channel: adc channel;
396  *	  @value: adc value;
397  *    eg: ...#_saradc_ch1=223#_saradc_ch2=650....dtb
398  *
399  * 2. U-Boot dtsi about adc controller node:
400  *    (1) enable "u-boot,dm-pre-reloc;";
401  *    (2) must set status "okay";
402  */
403 static int rockchip_read_dtb_by_adc(const char *file_name)
404 {
405 	static int cached_v[MAX_ADC_CH_NR];
406 	int offset_ctrl = strlen(KEY_WORDS_ADC_CTRL);
407 	int offset_ch = strlen(KEY_WORDS_ADC_CH);
408 	int ret, channel, len = 0, found = 0, margin = 30;
409 	uint32_t raw_adc;
410 	unsigned long dtb_adc;
411 	char *stradc, *strch, *p;
412 	char adc_v_string[10];
413 	char dev_name[32];
414 
415 	debug("%s: %s\n", __func__, file_name);
416 
417 	/* Invalid format ? */
418 	stradc = strstr(file_name, KEY_WORDS_ADC_CTRL);
419 	while (stradc) {
420 		debug("   - substr: %s\n", stradc);
421 
422 		/* Parse controller name */
423 		strch = strstr(stradc, KEY_WORDS_ADC_CH);
424 		len = strch - (stradc + offset_ctrl);
425 		strlcpy(dev_name, stradc + offset_ctrl, len + 1);
426 
427 		/* Parse adc channel */
428 		p = strch + offset_ch;
429 		if (is_digit(*p) && is_equal(*(p + 1))) {
430 			channel = *p - '0';
431 		} else {
432 			debug("   - invalid format: %s\n", stradc);
433 			return -EINVAL;
434 		}
435 
436 		/*
437 		 * Read raw adc value
438 		 *
439 		 * It doesn't need to read adc value every loop, reading once
440 		 * is enough. We use cached_v[] to save what we have read, zero
441 		 * means not read before.
442 		 */
443 		if (cached_v[channel] == 0) {
444 			ret = adc_channel_single_shot(dev_name,
445 						      channel, &raw_adc);
446 			if (ret) {
447 				debug("   - failed to read adc, ret=%d\n", ret);
448 				return ret;
449 			}
450 			cached_v[channel] = raw_adc;
451 		}
452 
453 		/* Parse dtb adc value */
454 		p = strch + offset_ch + 2;	/* 2: channel and '=' */
455 		while (*p && is_digit(*p)) {
456 			len++;
457 			p++;
458 		}
459 		strlcpy(adc_v_string, strch + offset_ch + 2, len + 1);
460 		dtb_adc = simple_strtoul(adc_v_string, NULL, 10);
461 
462 		if (abs(dtb_adc - cached_v[channel]) <= margin) {
463 			found = 1;
464 			stradc = strstr(p, KEY_WORDS_ADC_CTRL);
465 		} else {
466 			found = 0;
467 			break;
468 		}
469 
470 		debug("   - parse: controller=%s, channel=%d, dtb_adc=%ld, read=%d %s\n",
471 		      dev_name, channel, dtb_adc, cached_v[channel], found ? "(Y)" : "");
472 	}
473 
474 	return found ? 0 : -ENOENT;
475 }
476 #else
477 static int rockchip_read_dtb_by_adc(const char *file_name)
478 {
479 	return  -ENOENT;
480 }
481 #endif
482 
483 static int gpio_parse_base_address(fdt_addr_t *gpio_base_addr)
484 {
485 	static int initial;
486 	ofnode parent, node;
487 	int i = 0;
488 
489 	if (initial)
490 		return 0;
491 
492 	parent = ofnode_path("/pinctrl");
493 	if (!ofnode_valid(parent)) {
494 		debug("   - Can't find pinctrl node\n");
495 		return -EINVAL;
496 	}
497 
498 	ofnode_for_each_subnode(node, parent) {
499 		if (!ofnode_get_property(node, "gpio-controller", NULL)) {
500 			debug("   - Can't find gpio-controller\n");
501 			continue;
502 		}
503 
504 		gpio_base_addr[i++] = ofnode_get_addr(node);
505 		debug("   - gpio%d: 0x%x\n", i - 1, (uint32_t)gpio_base_addr[i - 1]);
506 	}
507 
508 	if (i == 0) {
509 		debug("   - parse gpio address failed\n");
510 		return -EINVAL;
511 	}
512 
513 	initial = 1;
514 
515 	return 0;
516 }
517 
518 /*
519  * How to make it works ?
520  *
521  * 1. pack dtb into rockchip resource.img, require:
522  *    (1) file name end with ".dtb";
523  *    (2) file name contains key words, like: ...#gpio[pin]=[value]...dtb
524  *	  @pin: gpio name, eg. 0a2 means GPIO0A2;
525  *	  @value: gpio level, 0 or 1;
526  *    eg: ...#gpio0a6=1#gpio1c2=0....dtb
527  *
528  * 2. U-Boot dtsi about gpio node:
529  *    (1) enable "u-boot,dm-pre-reloc;" for all gpio node;
530  *    (2) set all gpio status "disabled"(Because we just want their property);
531  */
532 static int rockchip_read_dtb_by_gpio(const char *file_name)
533 {
534 	static uint32_t cached_v[MAX_GPIO_NR];
535 	fdt_addr_t gpio_base_addr[MAX_GPIO_NR];
536 	int ret, found = 0, offset = strlen(KEY_WORDS_GPIO);
537 	uint8_t port, pin, bank, lvl, val;
538 	char *strgpio, *p;
539 	uint32_t bit;
540 
541 	debug("%s\n", file_name);
542 
543 	strgpio = strstr(file_name, KEY_WORDS_GPIO);
544 	while (strgpio) {
545 		debug("   - substr: %s\n", strgpio);
546 
547 		p = strgpio + offset;
548 
549 		/* Invalid format ? */
550 		if (!(is_digit(*(p + 0)) && is_abcd(*(p + 1)) &&
551 		      is_digit(*(p + 2)) && is_equal(*(p + 3)) &&
552 		      is_digit(*(p + 4)))) {
553 			debug("   - invalid format: %s\n", strgpio);
554 			return -EINVAL;
555 		}
556 
557 		/* Parse gpio address */
558 		ret = gpio_parse_base_address(gpio_base_addr);
559 		if (ret) {
560 			debug("   - Can't parse gpio base address: %d\n", ret);
561 			return ret;
562 		}
563 
564 		/* Read gpio value */
565 		port = *(p + 0) - '0';
566 		bank = *(p + 1) - 'a';
567 		pin  = *(p + 2) - '0';
568 		lvl  = *(p + 4) - '0';
569 
570 		/*
571 		 * It doesn't need to read gpio value every loop, reading once
572 		 * is enough. We use cached_v[] to save what we have read, zero
573 		 * means not read before.
574 		 */
575 		if (cached_v[port] == 0)
576 			cached_v[port] =
577 				readl(gpio_base_addr[port] + GPIO_EXT_PORT);
578 
579 		/* Verify result */
580 		bit = bank * 8 + pin;
581 		val = cached_v[port] & (1 << bit) ? 1 : 0;
582 
583 		if (val == !!lvl) {
584 			found = 1;
585 			strgpio = strstr(p, KEY_WORDS_GPIO);
586 		} else {
587 			found = 0;
588 			break;
589 		}
590 
591 		debug("   - parse: gpio%d%c%d=%d, read=%d %s\n",
592 		      port, bank + 'a', pin, lvl, val, found ? "(Y)" : "");
593 	}
594 
595 	return found ? 0 : -ENOENT;
596 }
597 
598 int rockchip_read_dtb_file(void *fdt_addr)
599 {
600 	struct resource_file *file;
601 	struct list_head *node;
602 	char *dtb_name = DTB_FILE;
603 	int ret;
604 
605 	if (list_empty(&entrys_head))
606 		init_resource_list(NULL);
607 
608 	list_for_each(node, &entrys_head) {
609 		file = list_entry(node, struct resource_file, link);
610 		if (!strstr(file->name, ".dtb"))
611 			continue;
612 
613 		if (strstr(file->name, KEY_WORDS_ADC_CTRL) &&
614 		    strstr(file->name, KEY_WORDS_ADC_CH) &&
615 		    !rockchip_read_dtb_by_adc(file->name)) {
616 			dtb_name = file->name;
617 			break;
618 		} else if (strstr(file->name, KEY_WORDS_GPIO) &&
619 			   !rockchip_read_dtb_by_gpio(file->name)) {
620 			dtb_name = file->name;
621 			break;
622 		}
623 	}
624 
625 	printf("DTB: %s\n", dtb_name);
626 
627 	ret = rockchip_read_resource_file((void *)fdt_addr, dtb_name, 0, 0);
628 	if (ret < 0)
629 		return ret;
630 
631 #if defined(CONFIG_CMD_DTIMG) && \
632     defined(CONFIG_OF_LIBFDT_OVERLAY) && defined(CONFIG_USING_KERNEL_DTB)
633 	android_fdt_overlay_apply((void *)fdt_addr);
634 #endif
635 
636 	return ret;
637 }
638