1 /*
2  * (C) Copyright 2013
3  * Reinhard Pfau, Guntermann & Drunck GmbH, reinhard.pfau@gdsys.cc
4  *
5  * SPDX-License-Identifier:	GPL-2.0+
6  */
7 
8 /* TODO: some more #ifdef's to avoid unneeded code for stage 1 / stage 2 */
9 
10 #ifdef CCDM_ID_DEBUG
11 #define DEBUG
12 #endif
13 
14 #include <common.h>
15 #include <malloc.h>
16 #include <fs.h>
17 #include <i2c.h>
18 #include <mmc.h>
19 #include <tpm.h>
20 #include <u-boot/sha1.h>
21 #include <asm/byteorder.h>
22 #include <asm/unaligned.h>
23 #include <pca9698.h>
24 
25 #undef CCDM_FIRST_STAGE
26 #undef CCDM_SECOND_STAGE
27 #undef CCDM_AUTO_FIRST_STAGE
28 
29 #ifdef CONFIG_DEVELOP
30 #define CCDM_DEVELOP
31 #endif
32 
33 #ifdef CONFIG_TRAILBLAZER
34 #define CCDM_FIRST_STAGE
35 #undef CCDM_SECOND_STAGE
36 #else
37 #undef CCDM_FIRST_STAGE
38 #define CCDM_SECOND_STAGE
39 #endif
40 
41 #if defined(CCDM_DEVELOP) && defined(CCDM_SECOND_STAGE) && \
42 	!defined(CCCM_FIRST_STAGE)
43 #define CCDM_AUTO_FIRST_STAGE
44 #endif
45 
46 /* CCDM specific contants */
47 enum {
48 	/* NV indices */
49 	NV_COMMON_DATA_INDEX	= 0x40000001,
50 	/* magics for key blob chains */
51 	MAGIC_KEY_PROGRAM	= 0x68726500,
52 	MAGIC_HMAC		= 0x68616300,
53 	MAGIC_END_OF_CHAIN	= 0x00000000,
54 	/* sizes */
55 	NV_COMMON_DATA_MIN_SIZE	= 3 * sizeof(uint64_t) + 2 * sizeof(uint16_t),
56 };
57 
58 /* other constants */
59 enum {
60 	ESDHC_BOOT_IMAGE_SIG_OFS	= 0x40,
61 	ESDHC_BOOT_IMAGE_SIZE_OFS	= 0x48,
62 	ESDHC_BOOT_IMAGE_ADDR_OFS	= 0x50,
63 	ESDHC_BOOT_IMAGE_TARGET_OFS	= 0x58,
64 	ESDHC_BOOT_IMAGE_ENTRY_OFS	= 0x60,
65 };
66 
67 enum {
68 	I2C_SOC_0 = 0,
69 	I2C_SOC_1 = 1,
70 };
71 
72 struct key_program {
73 	uint32_t magic;
74 	uint32_t code_crc;
75 	uint32_t code_size;
76 	uint8_t code[];
77 };
78 
79 struct h_reg {
80 	bool valid;
81 	uint8_t digest[20];
82 };
83 
84 
85 enum access_mode {
86 	HREG_NONE	= 0,
87 	HREG_RD		= 1,
88 	HREG_WR		= 2,
89 	HREG_RDWR	= 3,
90 };
91 
92 /* register constants */
93 enum {
94 	FIX_HREG_DEVICE_ID_HASH	= 0,
95 	FIX_HREG_SELF_HASH	= 1,
96 	FIX_HREG_STAGE2_HASH	= 2,
97 	FIX_HREG_VENDOR		= 3,
98 	COUNT_FIX_HREGS
99 };
100 
101 
102 /* hre opcodes */
103 enum {
104 	/* opcodes w/o data */
105 	HRE_NOP		= 0x00,
106 	HRE_SYNC	= HRE_NOP,
107 	HRE_CHECK0	= 0x01,
108 	/* opcodes w/o data, w/ sync dst */
109 	/* opcodes w/ data */
110 	HRE_LOAD	= 0x81,
111 	/* opcodes w/data, w/sync dst */
112 	HRE_XOR		= 0xC1,
113 	HRE_AND		= 0xC2,
114 	HRE_OR		= 0xC3,
115 	HRE_EXTEND	= 0xC4,
116 	HRE_LOADKEY	= 0xC5,
117 };
118 
119 /* hre errors */
120 enum {
121 	HRE_E_OK	= 0,
122 	HRE_E_TPM_FAILURE,
123 	HRE_E_INVALID_HREG,
124 };
125 
126 static uint64_t device_id;
127 static uint64_t device_cl;
128 static uint64_t device_type;
129 
130 static uint32_t platform_key_handle;
131 
132 static void(*bl2_entry)(void);
133 
134 static struct h_reg pcr_hregs[24];
135 static struct h_reg fix_hregs[COUNT_FIX_HREGS];
136 static struct h_reg var_hregs[8];
137 static uint32_t hre_tpm_err;
138 static int hre_err = HRE_E_OK;
139 
140 #define IS_PCR_HREG(spec) ((spec) & 0x20)
141 #define IS_FIX_HREG(spec) (((spec) & 0x38) == 0x08)
142 #define IS_VAR_HREG(spec) (((spec) & 0x38) == 0x10)
143 #define HREG_IDX(spec) ((spec) & (IS_PCR_HREG(spec) ? 0x1f : 0x7))
144 
145 
146 static const uint8_t prg_stage1_prepare[] = {
147 	0x00, 0x20, 0x00, 0x00, /* opcode: SYNC f0 */
148 	0x00, 0x24, 0x00, 0x00, /* opcode: SYNC f1 */
149 	0x01, 0x80, 0x00, 0x00, /* opcode: CHECK0 PCR0 */
150 	0x81, 0x22, 0x00, 0x00, /* opcode: LOAD PCR0, f0 */
151 	0x01, 0x84, 0x00, 0x00, /* opcode: CHECK0 PCR1 */
152 	0x81, 0x26, 0x10, 0x00, /* opcode: LOAD PCR1, f1 */
153 	0x01, 0x88, 0x00, 0x00, /* opcode: CHECK0 PCR2 */
154 	0x81, 0x2a, 0x20, 0x00, /* opcode: LOAD PCR2, f2 */
155 	0x01, 0x8c, 0x00, 0x00, /* opcode: CHECK0 PCR3 */
156 	0x81, 0x2e, 0x30, 0x00, /* opcode: LOAD PCR3, f3 */
157 };
158 
159 static const uint8_t vendor[] = "Guntermann & Drunck";
160 
161 /**
162  * @brief read a bunch of data from MMC into memory.
163  *
164  * @param mmc	pointer to the mmc structure to use.
165  * @param src	offset where the data starts on MMC/SD device (in bytes).
166  * @param dst	pointer to the location where the read data should be stored.
167  * @param size	number of bytes to read from the MMC/SD device.
168  * @return number of bytes read or -1 on error.
169  */
170 static int ccdm_mmc_read(struct mmc *mmc, u64 src, u8 *dst, int size)
171 {
172 	int result = 0;
173 	u32 blk_len, ofs;
174 	ulong block_no, n, cnt;
175 	u8 *tmp_buf = NULL;
176 
177 	if (size <= 0)
178 		goto end;
179 
180 	blk_len = mmc->read_bl_len;
181 	tmp_buf = malloc(blk_len);
182 	if (!tmp_buf)
183 		goto failure;
184 	block_no = src / blk_len;
185 	ofs = src % blk_len;
186 
187 	if (ofs) {
188 		n = mmc->block_dev.block_read(&mmc->block_dev, block_no++, 1,
189 			tmp_buf);
190 		if (!n)
191 			goto failure;
192 		result = min(size, (int)(blk_len - ofs));
193 		memcpy(dst, tmp_buf + ofs, result);
194 		dst += result;
195 		size -= result;
196 	}
197 	cnt = size / blk_len;
198 	if (cnt) {
199 		n = mmc->block_dev.block_read(&mmc->block_dev, block_no, cnt,
200 			dst);
201 		if (n != cnt)
202 			goto failure;
203 		size -= cnt * blk_len;
204 		result += cnt * blk_len;
205 		dst += cnt * blk_len;
206 		block_no += cnt;
207 	}
208 	if (size) {
209 		n = mmc->block_dev.block_read(&mmc->block_dev, block_no++, 1,
210 			tmp_buf);
211 		if (!n)
212 			goto failure;
213 		memcpy(dst, tmp_buf, size);
214 		result += size;
215 	}
216 	goto end;
217 failure:
218 	result = -1;
219 end:
220 	if (tmp_buf)
221 		free(tmp_buf);
222 	return result;
223 }
224 
225 /**
226  * @brief returns a location where the 2nd stage bootloader can be(/ is) placed.
227  *
228  * @return pointer to the location for/of the 2nd stage bootloader
229  */
230 static u8 *get_2nd_stage_bl_location(ulong target_addr)
231 {
232 	ulong addr;
233 #ifdef CCDM_SECOND_STAGE
234 	addr = getenv_ulong("loadaddr", 16, CONFIG_LOADADDR);
235 #else
236 	addr = target_addr;
237 #endif
238 	return (u8 *)(addr);
239 }
240 
241 
242 #ifdef CCDM_SECOND_STAGE
243 /**
244  * @brief returns a location where the image can be(/ is) placed.
245  *
246  * @return pointer to the location for/of the image
247  */
248 static u8 *get_image_location(void)
249 {
250 	ulong addr;
251 	/* TODO use other area? */
252 	addr = getenv_ulong("loadaddr", 16, CONFIG_LOADADDR);
253 	return (u8 *)(addr);
254 }
255 #endif
256 
257 /**
258  * @brief get the size of a given (TPM) NV area
259  * @param index	NV index of the area to get size for
260  * @param size	pointer to the size
261  * @return 0 on success, != 0 on error
262  */
263 static int get_tpm_nv_size(uint32_t index, uint32_t *size)
264 {
265 	uint32_t err;
266 	uint8_t info[72];
267 	uint8_t *ptr;
268 	uint16_t v16;
269 
270 	err = tpm_get_capability(TPM_CAP_NV_INDEX, index,
271 		info, sizeof(info));
272 	if (err) {
273 		printf("tpm_get_capability(CAP_NV_INDEX, %08x) failed: %u\n",
274 		       index, err);
275 		return 1;
276 	}
277 
278 	/* skip tag and nvIndex */
279 	ptr = info + 6;
280 	/* skip 2 pcr info fields */
281 	v16 = get_unaligned_be16(ptr);
282 	ptr += 2 + v16 + 1 + 20;
283 	v16 = get_unaligned_be16(ptr);
284 	ptr += 2 + v16 + 1 + 20;
285 	/* skip permission and flags */
286 	ptr += 6 + 3;
287 
288 	*size = get_unaligned_be32(ptr);
289 	return 0;
290 }
291 
292 /**
293  * @brief search for a key by usage auth and pub key hash.
294  * @param auth	usage auth of the key to search for
295  * @param pubkey_digest	(SHA1) hash of the pub key structure of the key
296  * @param[out] handle	the handle of the key iff found
297  * @return 0 if key was found in TPM; != 0 if not.
298  */
299 static int find_key(const uint8_t auth[20], const uint8_t pubkey_digest[20],
300 		uint32_t *handle)
301 {
302 	uint16_t key_count;
303 	uint32_t key_handles[10];
304 	uint8_t buf[288];
305 	uint8_t *ptr;
306 	uint32_t err;
307 	uint8_t digest[20];
308 	size_t buf_len;
309 	unsigned int i;
310 
311 	/* fetch list of already loaded keys in the TPM */
312 	err = tpm_get_capability(TPM_CAP_HANDLE, TPM_RT_KEY, buf, sizeof(buf));
313 	if (err)
314 		return -1;
315 	key_count = get_unaligned_be16(buf);
316 	ptr = buf + 2;
317 	for (i = 0; i < key_count; ++i, ptr += 4)
318 		key_handles[i] = get_unaligned_be32(ptr);
319 
320 	/* now search a(/ the) key which we can access with the given auth */
321 	for (i = 0; i < key_count; ++i) {
322 		buf_len = sizeof(buf);
323 		err = tpm_get_pub_key_oiap(key_handles[i], auth, buf, &buf_len);
324 		if (err && err != TPM_AUTHFAIL)
325 			return -1;
326 		if (err)
327 			continue;
328 		sha1_csum(buf, buf_len, digest);
329 		if (!memcmp(digest, pubkey_digest, 20)) {
330 			*handle = key_handles[i];
331 			return 0;
332 		}
333 	}
334 	return 1;
335 }
336 
337 /**
338  * @brief read CCDM common data from TPM NV
339  * @return 0 if CCDM common data was found and read, !=0 if something failed.
340  */
341 static int read_common_data(void)
342 {
343 	uint32_t size;
344 	uint32_t err;
345 	uint8_t buf[256];
346 	sha1_context ctx;
347 
348 	if (get_tpm_nv_size(NV_COMMON_DATA_INDEX, &size) ||
349 	    size < NV_COMMON_DATA_MIN_SIZE)
350 		return 1;
351 	err = tpm_nv_read_value(NV_COMMON_DATA_INDEX,
352 		buf, min(sizeof(buf), size));
353 	if (err) {
354 		printf("tpm_nv_read_value() failed: %u\n", err);
355 		return 1;
356 	}
357 
358 	device_id = get_unaligned_be64(buf);
359 	device_cl = get_unaligned_be64(buf + 8);
360 	device_type = get_unaligned_be64(buf + 16);
361 
362 	sha1_starts(&ctx);
363 	sha1_update(&ctx, buf, 24);
364 	sha1_finish(&ctx, fix_hregs[FIX_HREG_DEVICE_ID_HASH].digest);
365 	fix_hregs[FIX_HREG_DEVICE_ID_HASH].valid = true;
366 
367 	platform_key_handle = get_unaligned_be32(buf + 24);
368 
369 	return 0;
370 }
371 
372 /**
373  * @brief compute hash of bootloader itself.
374  * @param[out] dst	hash register where the hash should be stored
375  * @return 0 on success, != 0 on failure.
376  *
377  * @note MUST be called at a time where the boot loader is accessible at the
378  * configured location (; so take care when code is reallocated).
379  */
380 static int compute_self_hash(struct h_reg *dst)
381 {
382 	sha1_csum((const uint8_t *)CONFIG_SYS_MONITOR_BASE,
383 		  CONFIG_SYS_MONITOR_LEN, dst->digest);
384 	dst->valid = true;
385 	return 0;
386 }
387 
388 int ccdm_compute_self_hash(void)
389 {
390 	if (!fix_hregs[FIX_HREG_SELF_HASH].valid)
391 		compute_self_hash(&fix_hregs[FIX_HREG_SELF_HASH]);
392 	return 0;
393 }
394 
395 /**
396  * @brief compute the hash of the 2nd stage boot loader (on SD card)
397  * @param[out] dst	hash register to store the computed hash
398  * @return 0 on success, != 0 on failure
399  *
400  * Determines the size and location of the 2nd stage boot loader on SD card,
401  * loads the 2nd stage boot loader and computes the (SHA1) hash value.
402  * Within the 1st stage boot loader, the 2nd stage boot loader is loaded at
403  * the desired memory location and the variable @a bl2_entry is set.
404  *
405  * @note This sets the variable @a bl2_entry to the entry point when the
406  * 2nd stage boot loader is loaded at its configured memory location.
407  */
408 static int compute_second_stage_hash(struct h_reg *dst)
409 {
410 	int result = 0;
411 	u32 code_len, code_offset, target_addr, exec_entry;
412 	struct mmc *mmc;
413 	u8 *load_addr = NULL;
414 	u8 buf[128];
415 
416 	mmc = find_mmc_device(0);
417 	if (!mmc)
418 		goto failure;
419 	mmc_init(mmc);
420 
421 	if (ccdm_mmc_read(mmc, 0, buf, sizeof(buf)) < 0)
422 		goto failure;
423 
424 	code_offset = *(u32 *)(buf + ESDHC_BOOT_IMAGE_ADDR_OFS);
425 	code_len = *(u32 *)(buf + ESDHC_BOOT_IMAGE_SIZE_OFS);
426 	target_addr = *(u32 *)(buf + ESDHC_BOOT_IMAGE_TARGET_OFS);
427 	exec_entry =  *(u32 *)(buf + ESDHC_BOOT_IMAGE_ENTRY_OFS);
428 
429 	load_addr = get_2nd_stage_bl_location(target_addr);
430 	if (load_addr == (u8 *)target_addr)
431 		bl2_entry = (void(*)(void))exec_entry;
432 
433 	if (ccdm_mmc_read(mmc, code_offset, load_addr, code_len) < 0)
434 		goto failure;
435 
436 	sha1_csum(load_addr, code_len, dst->digest);
437 	dst->valid = true;
438 
439 	goto end;
440 failure:
441 	result = 1;
442 	bl2_entry = NULL;
443 end:
444 	return result;
445 }
446 
447 /**
448  * @brief get pointer to  hash register by specification
449  * @param spec	specification of a hash register
450  * @return pointer to hash register or NULL if @a spec does not qualify a
451  * valid hash register; NULL else.
452  */
453 static struct h_reg *get_hreg(uint8_t spec)
454 {
455 	uint8_t idx;
456 
457 	idx = HREG_IDX(spec);
458 	if (IS_FIX_HREG(spec)) {
459 		if (idx < ARRAY_SIZE(fix_hregs))
460 			return fix_hregs + idx;
461 		hre_err = HRE_E_INVALID_HREG;
462 	} else if (IS_PCR_HREG(spec)) {
463 		if (idx < ARRAY_SIZE(pcr_hregs))
464 			return pcr_hregs + idx;
465 		hre_err = HRE_E_INVALID_HREG;
466 	} else if (IS_VAR_HREG(spec)) {
467 		if (idx < ARRAY_SIZE(var_hregs))
468 			return var_hregs + idx;
469 		hre_err = HRE_E_INVALID_HREG;
470 	}
471 	return NULL;
472 }
473 
474 /**
475  * @brief get pointer of a hash register by specification and usage.
476  * @param spec	specification of a hash register
477  * @param mode	access mode (read or write or read/write)
478  * @return pointer to hash register if found and valid; NULL else.
479  *
480  * This func uses @a get_reg() to determine the hash register for a given spec.
481  * If a register is found it is validated according to the desired access mode.
482  * The value of automatic registers (PCR register and fixed registers) is
483  * loaded or computed on read access.
484  */
485 static struct h_reg *access_hreg(uint8_t spec, enum access_mode mode)
486 {
487 	struct h_reg *result;
488 
489 	result = get_hreg(spec);
490 	if (!result)
491 		return NULL;
492 
493 	if (mode & HREG_WR) {
494 		if (IS_FIX_HREG(spec)) {
495 			hre_err = HRE_E_INVALID_HREG;
496 			return NULL;
497 		}
498 	}
499 	if (mode & HREG_RD) {
500 		if (!result->valid) {
501 			if (IS_PCR_HREG(spec)) {
502 				hre_tpm_err = tpm_pcr_read(HREG_IDX(spec),
503 					result->digest, 20);
504 				result->valid = (hre_tpm_err == TPM_SUCCESS);
505 			} else if (IS_FIX_HREG(spec)) {
506 				switch (HREG_IDX(spec)) {
507 				case FIX_HREG_DEVICE_ID_HASH:
508 					read_common_data();
509 					break;
510 				case FIX_HREG_SELF_HASH:
511 					ccdm_compute_self_hash();
512 					break;
513 				case FIX_HREG_STAGE2_HASH:
514 					compute_second_stage_hash(result);
515 					break;
516 				case FIX_HREG_VENDOR:
517 					memcpy(result->digest, vendor, 20);
518 					result->valid = true;
519 					break;
520 				}
521 			} else {
522 				result->valid = true;
523 			}
524 		}
525 		if (!result->valid) {
526 			hre_err = HRE_E_INVALID_HREG;
527 			return NULL;
528 		}
529 	}
530 
531 	return result;
532 }
533 
534 static void *compute_and(void *_dst, const void *_src, size_t n)
535 {
536 	uint8_t *dst = _dst;
537 	const uint8_t *src = _src;
538 	size_t i;
539 
540 	for (i = n; i-- > 0; )
541 		*dst++ &= *src++;
542 
543 	return _dst;
544 }
545 
546 static void *compute_or(void *_dst, const void *_src, size_t n)
547 {
548 	uint8_t *dst = _dst;
549 	const uint8_t *src = _src;
550 	size_t i;
551 
552 	for (i = n; i-- > 0; )
553 		*dst++ |= *src++;
554 
555 	return _dst;
556 }
557 
558 static void *compute_xor(void *_dst, const void *_src, size_t n)
559 {
560 	uint8_t *dst = _dst;
561 	const uint8_t *src = _src;
562 	size_t i;
563 
564 	for (i = n; i-- > 0; )
565 		*dst++ ^= *src++;
566 
567 	return _dst;
568 }
569 
570 static void *compute_extend(void *_dst, const void *_src, size_t n)
571 {
572 	uint8_t digest[20];
573 	sha1_context ctx;
574 
575 	sha1_starts(&ctx);
576 	sha1_update(&ctx, _dst, n);
577 	sha1_update(&ctx, _src, n);
578 	sha1_finish(&ctx, digest);
579 	memcpy(_dst, digest, min(n, sizeof(digest)));
580 
581 	return _dst;
582 }
583 
584 static int hre_op_loadkey(struct h_reg *src_reg, struct h_reg *dst_reg,
585 		const void *key, size_t key_size)
586 {
587 	uint32_t parent_handle;
588 	uint32_t key_handle;
589 
590 	if (!src_reg || !dst_reg || !src_reg->valid || !dst_reg->valid)
591 		return -1;
592 	if (find_key(src_reg->digest, dst_reg->digest, &parent_handle))
593 		return -1;
594 	hre_tpm_err = tpm_load_key2_oiap(parent_handle, key, key_size,
595 		src_reg->digest, &key_handle);
596 	if (hre_tpm_err) {
597 		hre_err = HRE_E_TPM_FAILURE;
598 		return -1;
599 	}
600 	/* TODO remember key handle somehow? */
601 
602 	return 0;
603 }
604 
605 /**
606  * @brief executes the next opcode on the hash register engine.
607  * @param[in,out] ip	pointer to the opcode (instruction pointer)
608  * @param[in,out] code_size	(remaining) size of the code
609  * @return new instruction pointer on success, NULL on error.
610  */
611 static const uint8_t *hre_execute_op(const uint8_t **ip, size_t *code_size)
612 {
613 	bool dst_modified = false;
614 	uint32_t ins;
615 	uint8_t opcode;
616 	uint8_t src_spec;
617 	uint8_t dst_spec;
618 	uint16_t data_size;
619 	struct h_reg *src_reg, *dst_reg;
620 	uint8_t buf[20];
621 	const uint8_t *src_buf, *data;
622 	uint8_t *ptr;
623 	int i;
624 	void * (*bin_func)(void *, const void *, size_t);
625 
626 	if (*code_size < 4)
627 		return NULL;
628 
629 	ins = get_unaligned_be32(*ip);
630 	opcode = **ip;
631 	data = *ip + 4;
632 	src_spec = (ins >> 18) & 0x3f;
633 	dst_spec = (ins >> 12) & 0x3f;
634 	data_size = (ins & 0x7ff);
635 
636 	debug("HRE: ins=%08x (op=%02x, s=%02x, d=%02x, L=%d)\n", ins,
637 	      opcode, src_spec, dst_spec, data_size);
638 
639 	if ((opcode & 0x80) && (data_size + 4) > *code_size)
640 		return NULL;
641 
642 	src_reg = access_hreg(src_spec, HREG_RD);
643 	if (hre_err || hre_tpm_err)
644 		return NULL;
645 	dst_reg = access_hreg(dst_spec, (opcode & 0x40) ? HREG_RDWR : HREG_WR);
646 	if (hre_err || hre_tpm_err)
647 		return NULL;
648 
649 	switch (opcode) {
650 	case HRE_NOP:
651 		goto end;
652 	case HRE_CHECK0:
653 		if (src_reg) {
654 			for (i = 0; i < 20; ++i) {
655 				if (src_reg->digest[i])
656 					return NULL;
657 			}
658 		}
659 		break;
660 	case HRE_LOAD:
661 		bin_func = memcpy;
662 		goto do_bin_func;
663 	case HRE_XOR:
664 		bin_func = compute_xor;
665 		goto do_bin_func;
666 	case HRE_AND:
667 		bin_func = compute_and;
668 		goto do_bin_func;
669 	case HRE_OR:
670 		bin_func = compute_or;
671 		goto do_bin_func;
672 	case HRE_EXTEND:
673 		bin_func = compute_extend;
674 do_bin_func:
675 		if (!dst_reg)
676 			return NULL;
677 		if (src_reg) {
678 			src_buf = src_reg->digest;
679 		} else {
680 			if (!data_size) {
681 				memset(buf, 0, 20);
682 				src_buf = buf;
683 			} else if (data_size == 1) {
684 				memset(buf, *data, 20);
685 				src_buf = buf;
686 			} else if (data_size >= 20) {
687 				src_buf = data;
688 			} else {
689 				src_buf = buf;
690 				for (ptr = (uint8_t *)src_buf, i = 20; i > 0;
691 					i -= data_size, ptr += data_size)
692 					memcpy(ptr, data,
693 					       min_t(size_t, i, data_size));
694 			}
695 		}
696 		bin_func(dst_reg->digest, src_buf, 20);
697 		dst_reg->valid = true;
698 		dst_modified = true;
699 		break;
700 	case HRE_LOADKEY:
701 		if (hre_op_loadkey(src_reg, dst_reg, data, data_size))
702 			return NULL;
703 		break;
704 	default:
705 		return NULL;
706 	}
707 
708 	if (dst_reg && dst_modified && IS_PCR_HREG(dst_spec)) {
709 		hre_tpm_err = tpm_extend(HREG_IDX(dst_spec), dst_reg->digest,
710 			dst_reg->digest);
711 		if (hre_tpm_err) {
712 			hre_err = HRE_E_TPM_FAILURE;
713 			return NULL;
714 		}
715 	}
716 end:
717 	*ip += 4;
718 	*code_size -= 4;
719 	if (opcode & 0x80) {
720 		*ip += data_size;
721 		*code_size -= data_size;
722 	}
723 
724 	return *ip;
725 }
726 
727 /**
728  * @brief runs a program on the hash register engine.
729  * @param code		pointer to the (HRE) code.
730  * @param code_size	size of the code (in bytes).
731  * @return 0 on success, != 0 on failure.
732  */
733 static int hre_run_program(const uint8_t *code, size_t code_size)
734 {
735 	size_t code_left;
736 	const uint8_t *ip = code;
737 
738 	code_left = code_size;
739 	hre_tpm_err = 0;
740 	hre_err = HRE_E_OK;
741 	while (code_left > 0)
742 		if (!hre_execute_op(&ip, &code_left))
743 			return -1;
744 
745 	return hre_err;
746 }
747 
748 static int check_hmac(struct key_program *hmac,
749 	const uint8_t *data, size_t data_size)
750 {
751 	uint8_t key[20], computed_hmac[20];
752 	uint32_t type;
753 
754 	type = get_unaligned_be32(hmac->code);
755 	if (type != 0)
756 		return 1;
757 	memset(key, 0, sizeof(key));
758 	compute_extend(key, pcr_hregs[1].digest, 20);
759 	compute_extend(key, pcr_hregs[2].digest, 20);
760 	compute_extend(key, pcr_hregs[3].digest, 20);
761 	compute_extend(key, pcr_hregs[4].digest, 20);
762 
763 	sha1_hmac(key, sizeof(key), data, data_size, computed_hmac);
764 
765 	return memcmp(computed_hmac, hmac->code + 4, 20);
766 }
767 
768 static int verify_program(struct key_program *prg)
769 {
770 	uint32_t crc;
771 	crc = crc32(0, prg->code, prg->code_size);
772 
773 	if (crc != prg->code_crc) {
774 		printf("HRC crc mismatch: %08x != %08x\n",
775 		       crc, prg->code_crc);
776 		return 1;
777 	}
778 	return 0;
779 }
780 
781 #if defined(CCDM_FIRST_STAGE) || (defined CCDM_AUTO_FIRST_STAGE)
782 static struct key_program *load_sd_key_program(void)
783 {
784 	u32 code_len, code_offset;
785 	struct mmc *mmc;
786 	u8 buf[128];
787 	struct key_program *result = NULL, *hmac = NULL;
788 	struct key_program header;
789 
790 	mmc = find_mmc_device(0);
791 	if (!mmc)
792 		return NULL;
793 	mmc_init(mmc);
794 
795 	if (ccdm_mmc_read(mmc, 0, buf, sizeof(buf)) <= 0)
796 		goto failure;
797 
798 	code_offset = *(u32 *)(buf + ESDHC_BOOT_IMAGE_ADDR_OFS);
799 	code_len = *(u32 *)(buf + ESDHC_BOOT_IMAGE_SIZE_OFS);
800 
801 	code_offset += code_len;
802 	/* TODO: the following needs to be the size of the 2nd stage env */
803 	code_offset += CONFIG_ENV_SIZE;
804 
805 	if (ccdm_mmc_read(mmc, code_offset, buf, 4*3) < 0)
806 		goto failure;
807 
808 	header.magic = get_unaligned_be32(buf);
809 	header.code_crc = get_unaligned_be32(buf + 4);
810 	header.code_size = get_unaligned_be32(buf + 8);
811 
812 	if (header.magic != MAGIC_KEY_PROGRAM)
813 		goto failure;
814 
815 	result = malloc(sizeof(struct key_program) + header.code_size);
816 	if (!result)
817 		goto failure;
818 	*result = header;
819 
820 	printf("load key program chunk from SD card (%u bytes) ",
821 	       header.code_size);
822 	code_offset += 12;
823 	if (ccdm_mmc_read(mmc, code_offset, result->code, header.code_size)
824 		< 0)
825 		goto failure;
826 	code_offset += header.code_size;
827 	puts("\n");
828 
829 	if (verify_program(result))
830 		goto failure;
831 
832 	if (ccdm_mmc_read(mmc, code_offset, buf, 4*3) < 0)
833 		goto failure;
834 
835 	header.magic = get_unaligned_be32(buf);
836 	header.code_crc = get_unaligned_be32(buf + 4);
837 	header.code_size = get_unaligned_be32(buf + 8);
838 
839 	if (header.magic == MAGIC_HMAC) {
840 		puts("check integrity\n");
841 		hmac = malloc(sizeof(struct key_program) + header.code_size);
842 		if (!hmac)
843 			goto failure;
844 		*hmac = header;
845 		code_offset += 12;
846 		if (ccdm_mmc_read(mmc, code_offset, hmac->code,
847 				  hmac->code_size) < 0)
848 			goto failure;
849 		if (verify_program(hmac))
850 			goto failure;
851 		if (check_hmac(hmac, result->code, result->code_size)) {
852 			puts("key program integrity could not be verified\n");
853 			goto failure;
854 		}
855 		puts("key program verified\n");
856 	}
857 
858 	goto end;
859 failure:
860 	if (result)
861 		free(result);
862 	result = NULL;
863 end:
864 	if (hmac)
865 		free(hmac);
866 
867 	return result;
868 }
869 #endif
870 
871 #ifdef CCDM_SECOND_STAGE
872 /**
873  * @brief load a key program from file system.
874  * @param ifname	interface of the file system
875  * @param dev_part_str	device part of the file system
876  * @param fs_type	tyep of the file system
877  * @param path		path of the file to load.
878  * @return the loaded structure or NULL on failure.
879  */
880 static struct key_program *load_key_chunk(const char *ifname,
881 	const char *dev_part_str, int fs_type,
882 	const char *path)
883 {
884 	struct key_program *result = NULL;
885 	struct key_program header;
886 	uint32_t crc;
887 	uint8_t buf[12];
888 	loff_t i;
889 
890 	if (fs_set_blk_dev(ifname, dev_part_str, fs_type))
891 		goto failure;
892 	if (fs_read(path, (ulong)buf, 0, 12, &i) < 0)
893 		goto failure;
894 	if (i < 12)
895 		goto failure;
896 	header.magic = get_unaligned_be32(buf);
897 	header.code_crc = get_unaligned_be32(buf + 4);
898 	header.code_size = get_unaligned_be32(buf + 8);
899 
900 	if (header.magic != MAGIC_HMAC && header.magic != MAGIC_KEY_PROGRAM)
901 		goto failure;
902 
903 	result = malloc(sizeof(struct key_program) + header.code_size);
904 	if (!result)
905 		goto failure;
906 	if (fs_set_blk_dev(ifname, dev_part_str, fs_type))
907 		goto failure;
908 	if (fs_read(path, (ulong)result, 0,
909 		    sizeof(struct key_program) + header.code_size, &i) < 0)
910 		goto failure;
911 	if (i <= 0)
912 		goto failure;
913 	*result = header;
914 
915 	crc = crc32(0, result->code, result->code_size);
916 
917 	if (crc != result->code_crc) {
918 		printf("%s: HRC crc mismatch: %08x != %08x\n",
919 		       path, crc, result->code_crc);
920 		goto failure;
921 	}
922 	goto end;
923 failure:
924 	if (result) {
925 		free(result);
926 		result = NULL;
927 	}
928 end:
929 	return result;
930 }
931 #endif
932 
933 #if defined(CCDM_FIRST_STAGE) || (defined CCDM_AUTO_FIRST_STAGE)
934 static int first_stage_actions(void)
935 {
936 	int result = 0;
937 	struct key_program *sd_prg = NULL;
938 
939 	puts("CCDM S1: start actions\n");
940 #ifndef CCDM_SECOND_STAGE
941 	if (tpm_continue_self_test())
942 		goto failure;
943 #else
944 	tpm_continue_self_test();
945 #endif
946 	mdelay(37);
947 
948 	if (hre_run_program(prg_stage1_prepare, sizeof(prg_stage1_prepare)))
949 		goto failure;
950 
951 	sd_prg = load_sd_key_program();
952 	if (sd_prg) {
953 		if (hre_run_program(sd_prg->code, sd_prg->code_size))
954 			goto failure;
955 		puts("SD code run successfully\n");
956 	} else {
957 		puts("no key program found on SD\n");
958 		goto failure;
959 	}
960 	goto end;
961 failure:
962 	result = 1;
963 end:
964 	if (sd_prg)
965 		free(sd_prg);
966 	printf("CCDM S1: actions done (%d)\n", result);
967 	return result;
968 }
969 #endif
970 
971 #ifdef CCDM_FIRST_STAGE
972 static int first_stage_init(void)
973 {
974 	int res = 0;
975 	puts("CCDM S1\n");
976 	if (tpm_init() || tpm_startup(TPM_ST_CLEAR))
977 		return 1;
978 	res = first_stage_actions();
979 #ifndef CCDM_SECOND_STAGE
980 	if (!res) {
981 		if (bl2_entry)
982 			(*bl2_entry)();
983 		res = 1;
984 	}
985 #endif
986 	return res;
987 }
988 #endif
989 
990 #ifdef CCDM_SECOND_STAGE
991 static const uint8_t prg_stage2_prepare[] = {
992 	0x00, 0x80, 0x00, 0x00, /* opcode: SYNC PCR0 */
993 	0x00, 0x84, 0x00, 0x00, /* opcode: SYNC PCR1 */
994 	0x00, 0x88, 0x00, 0x00, /* opcode: SYNC PCR2 */
995 	0x00, 0x8c, 0x00, 0x00, /* opcode: SYNC PCR3 */
996 	0x00, 0x90, 0x00, 0x00, /* opcode: SYNC PCR4 */
997 };
998 
999 static const uint8_t prg_stage2_success[] = {
1000 	0x81, 0x02, 0x40, 0x14, /* opcode: LOAD PCR4, #<20B data> */
1001 	0x48, 0xfd, 0x95, 0x17, 0xe7, 0x54, 0x6b, 0x68, /* data */
1002 	0x92, 0x31, 0x18, 0x05, 0xf8, 0x58, 0x58, 0x3c, /* data */
1003 	0xe4, 0xd2, 0x81, 0xe0, /* data */
1004 };
1005 
1006 static const uint8_t prg_stage_fail[] = {
1007 	0x81, 0x01, 0x00, 0x14, /* opcode: LOAD v0, #<20B data> */
1008 	0xc0, 0x32, 0xad, 0xc1, 0xff, 0x62, 0x9c, 0x9b, /* data */
1009 	0x66, 0xf2, 0x27, 0x49, 0xad, 0x66, 0x7e, 0x6b, /* data */
1010 	0xea, 0xdf, 0x14, 0x4b, /* data */
1011 	0x81, 0x42, 0x30, 0x00, /* opcode: LOAD PCR3, v0 */
1012 	0x81, 0x42, 0x40, 0x00, /* opcode: LOAD PCR4, v0 */
1013 };
1014 
1015 static int second_stage_init(void)
1016 {
1017 	static const char mac_suffix[] = ".mac";
1018 	bool did_first_stage_run = true;
1019 	int result = 0;
1020 	char *cptr, *mmcdev = NULL;
1021 	struct key_program *hmac_blob = NULL;
1022 	const char *image_path = "/ccdm.itb";
1023 	char *mac_path = NULL;
1024 	ulong image_addr;
1025 	loff_t image_size;
1026 	uint32_t err;
1027 
1028 	printf("CCDM S2\n");
1029 	if (tpm_init())
1030 		return 1;
1031 	err = tpm_startup(TPM_ST_CLEAR);
1032 	if (err != TPM_INVALID_POSTINIT)
1033 		did_first_stage_run = false;
1034 
1035 #ifdef CCDM_AUTO_FIRST_STAGE
1036 	if (!did_first_stage_run && first_stage_actions())
1037 		goto failure;
1038 #else
1039 	if (!did_first_stage_run)
1040 		goto failure;
1041 #endif
1042 
1043 	if (hre_run_program(prg_stage2_prepare, sizeof(prg_stage2_prepare)))
1044 		goto failure;
1045 
1046 	/* run "prepboot" from env to get "mmcdev" set */
1047 	cptr = getenv("prepboot");
1048 	if (cptr && !run_command(cptr, 0))
1049 		mmcdev = getenv("mmcdev");
1050 	if (!mmcdev)
1051 		goto failure;
1052 
1053 	cptr = getenv("ramdiskimage");
1054 	if (cptr)
1055 		image_path = cptr;
1056 
1057 	mac_path = malloc(strlen(image_path) + strlen(mac_suffix) + 1);
1058 	if (mac_path == NULL)
1059 		goto failure;
1060 	strcpy(mac_path, image_path);
1061 	strcat(mac_path, mac_suffix);
1062 
1063 	/* read image from mmcdev (ccdm.itb) */
1064 	image_addr = (ulong)get_image_location();
1065 	if (fs_set_blk_dev("mmc", mmcdev, FS_TYPE_EXT))
1066 		goto failure;
1067 	if (fs_read(image_path, image_addr, 0, 0, &image_size) < 0)
1068 		goto failure;
1069 	if (image_size <= 0)
1070 		goto failure;
1071 	printf("CCDM image found on %s, %lld bytes\n", mmcdev, image_size);
1072 
1073 	hmac_blob = load_key_chunk("mmc", mmcdev, FS_TYPE_EXT, mac_path);
1074 	if (!hmac_blob) {
1075 		puts("failed to load mac file\n");
1076 		goto failure;
1077 	}
1078 	if (verify_program(hmac_blob)) {
1079 		puts("corrupted mac file\n");
1080 		goto failure;
1081 	}
1082 	if (check_hmac(hmac_blob, (u8 *)image_addr, image_size)) {
1083 		puts("image integrity could not be verified\n");
1084 		goto failure;
1085 	}
1086 	puts("CCDM image OK\n");
1087 
1088 	hre_run_program(prg_stage2_success, sizeof(prg_stage2_success));
1089 
1090 	goto end;
1091 failure:
1092 	result = 1;
1093 	hre_run_program(prg_stage_fail, sizeof(prg_stage_fail));
1094 end:
1095 	if (hmac_blob)
1096 		free(hmac_blob);
1097 	if (mac_path)
1098 		free(mac_path);
1099 
1100 	return result;
1101 }
1102 #endif
1103 
1104 int show_self_hash(void)
1105 {
1106 	struct h_reg *hash_ptr;
1107 #ifdef CCDM_SECOND_STAGE
1108 	struct h_reg hash;
1109 
1110 	hash_ptr = &hash;
1111 	if (compute_self_hash(hash_ptr))
1112 		return 1;
1113 #else
1114 	hash_ptr = &fix_hregs[FIX_HREG_SELF_HASH];
1115 #endif
1116 	puts("self hash: ");
1117 	if (hash_ptr && hash_ptr->valid)
1118 		print_buffer(0, hash_ptr->digest, 1, 20, 20);
1119 	else
1120 		puts("INVALID\n");
1121 
1122 	return 0;
1123 }
1124 
1125 /**
1126  * @brief let the system hang.
1127  *
1128  * Called on error.
1129  * Will stop the boot process; display a message and signal the error condition
1130  * by blinking the "status" and the "finder" LED of the controller board.
1131  *
1132  * @note the develop version runs the blink cycle 2 times and then returns.
1133  * The release version never returns.
1134  */
1135 static void ccdm_hang(void)
1136 {
1137 	static const u64 f0 = 0x0ba3bb8ba2e880; /* blink code "finder" LED */
1138 	static const u64 s0 = 0x00f0f0f0f0f0f0; /* blink code "status" LED */
1139 	u64 f, s;
1140 	int i;
1141 #ifdef CCDM_DEVELOP
1142 	int j;
1143 #endif
1144 
1145 	I2C_SET_BUS(I2C_SOC_0);
1146 	pca9698_direction_output(0x22, 0, 0); /* Finder */
1147 	pca9698_direction_output(0x22, 4, 0); /* Status */
1148 
1149 	puts("### ERROR ### Please RESET the board ###\n");
1150 	bootstage_error(BOOTSTAGE_ID_NEED_RESET);
1151 #ifdef CCDM_DEVELOP
1152 	puts("*** ERROR ******** THIS WOULD HANG ******** ERROR ***\n");
1153 	puts("** but we continue since this is a DEVELOP version **\n");
1154 	puts("*** ERROR ******** THIS WOULD HANG ******** ERROR ***\n");
1155 	for (j = 2; j-- > 0;) {
1156 		putc('#');
1157 #else
1158 	for (;;) {
1159 #endif
1160 		f = f0;
1161 		s = s0;
1162 		for (i = 54; i-- > 0;) {
1163 			pca9698_set_value(0x22, 0, !(f & 1));
1164 			pca9698_set_value(0x22, 4, (s & 1));
1165 			f >>= 1;
1166 			s >>= 1;
1167 			mdelay(120);
1168 		}
1169 	}
1170 	puts("\ncontinue...\n");
1171 }
1172 
1173 int startup_ccdm_id_module(void)
1174 {
1175 	int result = 0;
1176 	unsigned int orig_i2c_bus;
1177 
1178 	orig_i2c_bus = i2c_get_bus_num();
1179 	i2c_set_bus_num(I2C_SOC_1);
1180 
1181 	/* goto end; */
1182 
1183 #ifdef CCDM_DEVELOP
1184 	show_self_hash();
1185 #endif
1186 #ifdef CCDM_FIRST_STAGE
1187 	result = first_stage_init();
1188 	if (result) {
1189 		puts("1st stage init failed\n");
1190 		goto failure;
1191 	}
1192 #endif
1193 #ifdef CCDM_SECOND_STAGE
1194 	result = second_stage_init();
1195 	if (result) {
1196 		puts("2nd stage init failed\n");
1197 		goto failure;
1198 	}
1199 #endif
1200 
1201 	goto end;
1202 failure:
1203 	result = 1;
1204 end:
1205 	i2c_set_bus_num(orig_i2c_bus);
1206 	if (result)
1207 		ccdm_hang();
1208 
1209 	return result;
1210 }
1211