diff options
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/Makefile | 15 | ||||
| -rw-r--r-- | lib/fdtdec.c | 3 | ||||
| -rw-r--r-- | lib/libfdt/fdt_wip.c | 129 | ||||
| -rw-r--r-- | lib/rsa/Makefile | 48 | ||||
| -rw-r--r-- | lib/rsa/rsa-sign.c | 459 | ||||
| -rw-r--r-- | lib/rsa/rsa-verify.c | 385 | ||||
| -rw-r--r-- | lib/string.c | 59 | ||||
| -rw-r--r-- | lib/trace.c | 379 | ||||
| -rw-r--r-- | lib/vsprintf.c | 16 | 
9 files changed, 1483 insertions, 10 deletions
| diff --git a/lib/Makefile b/lib/Makefile index 5d586098d..f5a8819f3 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -26,7 +26,6 @@ include $(TOPDIR)/config.mk  LIB	= $(obj)libgeneric.o  ifndef CONFIG_SPL_BUILD -COBJS-$(CONFIG_ADDR_MAP) += addr_map.o  COBJS-$(CONFIG_AES) += aes.o  COBJS-$(CONFIG_BZIP2) += bzlib.o  COBJS-$(CONFIG_BZIP2) += bzlib_crctable.o @@ -36,13 +35,10 @@ COBJS-$(CONFIG_BZIP2) += bzlib_huffman.o  COBJS-$(CONFIG_USB_TTY) += circbuf.o  COBJS-y += crc7.o  COBJS-y += crc16.o -COBJS-y += display_options.o -COBJS-y += errno.o  COBJS-$(CONFIG_OF_CONTROL) += fdtdec.o  COBJS-$(CONFIG_TEST_FDTDEC) += fdtdec_test.o  COBJS-$(CONFIG_GZIP) += gunzip.o  COBJS-$(CONFIG_GZIP_COMPRESSED) += gzip.o -COBJS-y += hashtable.o  COBJS-y += initcall.o  COBJS-$(CONFIG_LMB) += lmb.o  COBJS-y += ldiv.o @@ -60,14 +56,12 @@ endif  ifdef CONFIG_SPL_BUILD  COBJS-$(CONFIG_SPL_YMODEM_SUPPORT) += crc16.o -COBJS-$(CONFIG_SPL_NET_SUPPORT) += crc32.o -ifneq ($(CONFIG_SPL_SPI_FLASH_SUPPORT)$(CONFIG_SPL_NET_SUPPORT),) -COBJS-y += display_options.o -endif -COBJS-$(CONFIG_SPL_NET_SUPPORT) += errno.o -COBJS-$(CONFIG_SPL_NET_SUPPORT) += hashtable.o  COBJS-$(CONFIG_SPL_NET_SUPPORT) += net_utils.o  endif +COBJS-$(CONFIG_ADDR_MAP) += addr_map.o +COBJS-y += hashtable.o +COBJS-y += errno.o +COBJS-y += display_options.o  COBJS-$(CONFIG_BCH) += bch.o  COBJS-y += crc32.o  COBJS-y += ctype.o @@ -77,6 +71,7 @@ COBJS-y += linux_string.o  COBJS-$(CONFIG_REGEX) += slre.o  COBJS-y += string.o  COBJS-y += time.o +COBJS-$(CONFIG_TRACE) += trace.o  COBJS-$(CONFIG_BOOTP_PXE) += uuid.o  COBJS-y += vsprintf.o  COBJS-$(CONFIG_RANDOM_MACADDR) += rand.o diff --git a/lib/fdtdec.c b/lib/fdtdec.c index 24ccd0af1..1b3c81058 100644 --- a/lib/fdtdec.c +++ b/lib/fdtdec.c @@ -59,6 +59,8 @@ static const char * const compat_names[COMPAT_COUNT] = {  	COMPAT(SAMSUNG_EXYNOS5_SOUND, "samsung,exynos-sound"),  	COMPAT(WOLFSON_WM8994_CODEC, "wolfson,wm8994-codec"),  	COMPAT(SAMSUNG_EXYNOS_SPI, "samsung,exynos-spi"), +	COMPAT(GOOGLE_CROS_EC, "google,cros-ec"), +	COMPAT(GOOGLE_CROS_EC_KEYB, "google,cros-ec-keyb"),  	COMPAT(SAMSUNG_EXYNOS_EHCI, "samsung,exynos-ehci"),  	COMPAT(SAMSUNG_EXYNOS_USB_PHY, "samsung,exynos-usb-phy"),  	COMPAT(SAMSUNG_EXYNOS_TMU, "samsung,exynos-tmu"), @@ -70,6 +72,7 @@ static const char * const compat_names[COMPAT_COUNT] = {  	COMPAT(GENERIC_SPI_FLASH, "spi-flash"),  	COMPAT(MAXIM_98095_CODEC, "maxim,max98095-codec"),  	COMPAT(INFINEON_SLB9635_TPM, "infineon,slb9635-tpm"), +	COMPAT(INFINEON_SLB9645_TPM, "infineon,slb9645-tpm"),  };  const char *fdtdec_get_compatible(enum fdt_compat_id id) diff --git a/lib/libfdt/fdt_wip.c b/lib/libfdt/fdt_wip.c index 63e67b78c..b9e3c4a74 100644 --- a/lib/libfdt/fdt_wip.c +++ b/lib/libfdt/fdt_wip.c @@ -120,3 +120,132 @@ int fdt_nop_node(void *fdt, int nodeoffset)  			endoffset - nodeoffset);  	return 0;  } + +#define FDT_MAX_DEPTH	32 + +static int str_in_list(const char *str, char * const list[], int count) +{ +	int i; + +	for (i = 0; i < count; i++) +		if (!strcmp(list[i], str)) +			return 1; + +	return 0; +} + +int fdt_find_regions(const void *fdt, char * const inc[], int inc_count, +		     char * const exc_prop[], int exc_prop_count, +		     struct fdt_region region[], int max_regions, +		     char *path, int path_len, int add_string_tab) +{ +	int stack[FDT_MAX_DEPTH]; +	char *end; +	int nextoffset = 0; +	uint32_t tag; +	int count = 0; +	int start = -1; +	int depth = -1; +	int want = 0; +	int base = fdt_off_dt_struct(fdt); + +	end = path; +	*end = '\0'; +	do { +		const struct fdt_property *prop; +		const char *name; +		const char *str; +		int include = 0; +		int stop_at = 0; +		int offset; +		int len; + +		offset = nextoffset; +		tag = fdt_next_tag(fdt, offset, &nextoffset); +		stop_at = nextoffset; + +		switch (tag) { +		case FDT_PROP: +			include = want >= 2; +			stop_at = offset; +			prop = fdt_get_property_by_offset(fdt, offset, NULL); +			str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff)); +			if (str_in_list(str, exc_prop, exc_prop_count)) +				include = 0; +			break; + +		case FDT_NOP: +			include = want >= 2; +			stop_at = offset; +			break; + +		case FDT_BEGIN_NODE: +			depth++; +			if (depth == FDT_MAX_DEPTH) +				return -FDT_ERR_BADSTRUCTURE; +			name = fdt_get_name(fdt, offset, &len); +			if (end - path + 2 + len >= path_len) +				return -FDT_ERR_NOSPACE; +			if (end != path + 1) +				*end++ = '/'; +			strcpy(end, name); +			end += len; +			stack[depth] = want; +			if (want == 1) +				stop_at = offset; +			if (str_in_list(path, inc, inc_count)) +				want = 2; +			else if (want) +				want--; +			else +				stop_at = offset; +			include = want; +			break; + +		case FDT_END_NODE: +			include = want; +			want = stack[depth--]; +			while (end > path && *--end != '/') +				; +			*end = '\0'; +			break; + +		case FDT_END: +			include = 1; +			break; +		} + +		if (include && start == -1) { +			/* Should we merge with previous? */ +			if (count && count <= max_regions && +			    offset == region[count - 1].offset + +					region[count - 1].size - base) +				start = region[--count].offset - base; +			else +				start = offset; +		} + +		if (!include && start != -1) { +			if (count < max_regions) { +				region[count].offset = base + start; +				region[count].size = stop_at - start; +			} +			count++; +			start = -1; +		} +	} while (tag != FDT_END); + +	if (nextoffset != fdt_size_dt_struct(fdt)) +		return -FDT_ERR_BADLAYOUT; + +	/* Add a region for the END tag and the string table */ +	if (count < max_regions) { +		region[count].offset = base + start; +		region[count].size = nextoffset - start; +		if (add_string_tab) +			region[count].size += fdt_size_dt_strings(fdt); +	} +	count++; + +	return count; +} diff --git a/lib/rsa/Makefile b/lib/rsa/Makefile new file mode 100644 index 000000000..9eb3e40f5 --- /dev/null +++ b/lib/rsa/Makefile @@ -0,0 +1,48 @@ +# +# Copyright (c) 2013, Google Inc. +# +# (C) Copyright 2000-2007 +# Wolfgang Denk, DENX Software Engineering, wd@denx.de. +# +# See file CREDITS for list of people who contributed to this +# project. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 2 of +# the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, +# MA 02111-1307 USA +# + +include $(TOPDIR)/config.mk + +LIB	= $(obj)librsa.o + +ifdef CONFIG_FIT_SIGNATURE +COBJS-$(CONFIG_RSA) += rsa-verify.o +endif + +COBJS	:= $(sort $(COBJS-y)) +SRCS	:= $(COBJS:.o=.c) +OBJS	:= $(addprefix $(obj),$(COBJS)) + +$(LIB):	$(obj).depend $(OBJS) +	$(call cmd_link_o_target, $(OBJS)) + +######################################################################### + +# defines $(obj).depend target +include $(SRCTREE)/rules.mk + +sinclude $(obj).depend + +######################################################################### diff --git a/lib/rsa/rsa-sign.c b/lib/rsa/rsa-sign.c new file mode 100644 index 000000000..e30d8ca84 --- /dev/null +++ b/lib/rsa/rsa-sign.c @@ -0,0 +1,459 @@ +/* + * Copyright (c) 2013, Google Inc. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +#include "mkimage.h" +#include <stdio.h> +#include <string.h> +#include <image.h> +#include <time.h> +#include <openssl/rsa.h> +#include <openssl/pem.h> +#include <openssl/err.h> +#include <openssl/ssl.h> +#include <openssl/evp.h> + +#if OPENSSL_VERSION_NUMBER >= 0x10000000L +#define HAVE_ERR_REMOVE_THREAD_STATE +#endif + +static int rsa_err(const char *msg) +{ +	unsigned long sslErr = ERR_get_error(); + +	fprintf(stderr, "%s", msg); +	fprintf(stderr, ": %s\n", +		ERR_error_string(sslErr, 0)); + +	return -1; +} + +/** + * rsa_get_pub_key() - read a public key from a .crt file + * + * @keydir:	Directory containins the key + * @name	Name of key file (will have a .crt extension) + * @rsap	Returns RSA object, or NULL on failure + * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL) + */ +static int rsa_get_pub_key(const char *keydir, const char *name, RSA **rsap) +{ +	char path[1024]; +	EVP_PKEY *key; +	X509 *cert; +	RSA *rsa; +	FILE *f; +	int ret; + +	*rsap = NULL; +	snprintf(path, sizeof(path), "%s/%s.crt", keydir, name); +	f = fopen(path, "r"); +	if (!f) { +		fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n", +			path, strerror(errno)); +		return -EACCES; +	} + +	/* Read the certificate */ +	cert = NULL; +	if (!PEM_read_X509(f, &cert, NULL, NULL)) { +		rsa_err("Couldn't read certificate"); +		ret = -EINVAL; +		goto err_cert; +	} + +	/* Get the public key from the certificate. */ +	key = X509_get_pubkey(cert); +	if (!key) { +		rsa_err("Couldn't read public key\n"); +		ret = -EINVAL; +		goto err_pubkey; +	} + +	/* Convert to a RSA_style key. */ +	rsa = EVP_PKEY_get1_RSA(key); +	if (!rsa) { +		rsa_err("Couldn't convert to a RSA style key"); +		goto err_rsa; +	} +	fclose(f); +	EVP_PKEY_free(key); +	X509_free(cert); +	*rsap = rsa; + +	return 0; + +err_rsa: +	EVP_PKEY_free(key); +err_pubkey: +	X509_free(cert); +err_cert: +	fclose(f); +	return ret; +} + +/** + * rsa_get_priv_key() - read a private key from a .key file + * + * @keydir:	Directory containins the key + * @name	Name of key file (will have a .key extension) + * @rsap	Returns RSA object, or NULL on failure + * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL) + */ +static int rsa_get_priv_key(const char *keydir, const char *name, RSA **rsap) +{ +	char path[1024]; +	RSA *rsa; +	FILE *f; + +	*rsap = NULL; +	snprintf(path, sizeof(path), "%s/%s.key", keydir, name); +	f = fopen(path, "r"); +	if (!f) { +		fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n", +			path, strerror(errno)); +		return -ENOENT; +	} + +	rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path); +	if (!rsa) { +		rsa_err("Failure reading private key"); +		fclose(f); +		return -EPROTO; +	} +	fclose(f); +	*rsap = rsa; + +	return 0; +} + +static int rsa_init(void) +{ +	int ret; + +	ret = SSL_library_init(); +	if (!ret) { +		fprintf(stderr, "Failure to init SSL library\n"); +		return -1; +	} +	SSL_load_error_strings(); + +	OpenSSL_add_all_algorithms(); +	OpenSSL_add_all_digests(); +	OpenSSL_add_all_ciphers(); + +	return 0; +} + +static void rsa_remove(void) +{ +	CRYPTO_cleanup_all_ex_data(); +	ERR_free_strings(); +#ifdef HAVE_ERR_REMOVE_THREAD_STATE +	ERR_remove_thread_state(NULL); +#else +	ERR_remove_state(0); +#endif +	EVP_cleanup(); +} + +static int rsa_sign_with_key(RSA *rsa, const struct image_region region[], +		int region_count, uint8_t **sigp, uint *sig_size) +{ +	EVP_PKEY *key; +	EVP_MD_CTX *context; +	int size, ret = 0; +	uint8_t *sig; +	int i; + +	key = EVP_PKEY_new(); +	if (!key) +		return rsa_err("EVP_PKEY object creation failed"); + +	if (!EVP_PKEY_set1_RSA(key, rsa)) { +		ret = rsa_err("EVP key setup failed"); +		goto err_set; +	} + +	size = EVP_PKEY_size(key); +	sig = malloc(size); +	if (!sig) { +		fprintf(stderr, "Out of memory for signature (%d bytes)\n", +			size); +		ret = -ENOMEM; +		goto err_alloc; +	} + +	context = EVP_MD_CTX_create(); +	if (!context) { +		ret = rsa_err("EVP context creation failed"); +		goto err_create; +	} +	EVP_MD_CTX_init(context); +	if (!EVP_SignInit(context, EVP_sha1())) { +		ret = rsa_err("Signer setup failed"); +		goto err_sign; +	} + +	for (i = 0; i < region_count; i++) { +		if (!EVP_SignUpdate(context, region[i].data, region[i].size)) { +			ret = rsa_err("Signing data failed"); +			goto err_sign; +		} +	} + +	if (!EVP_SignFinal(context, sig, sig_size, key)) { +		ret = rsa_err("Could not obtain signature"); +		goto err_sign; +	} +	EVP_MD_CTX_cleanup(context); +	EVP_MD_CTX_destroy(context); +	EVP_PKEY_free(key); + +	debug("Got signature: %d bytes, expected %d\n", *sig_size, size); +	*sigp = sig; +	*sig_size = size; + +	return 0; + +err_sign: +	EVP_MD_CTX_destroy(context); +err_create: +	free(sig); +err_alloc: +err_set: +	EVP_PKEY_free(key); +	return ret; +} + +int rsa_sign(struct image_sign_info *info, +	     const struct image_region region[], int region_count, +	     uint8_t **sigp, uint *sig_len) +{ +	RSA *rsa; +	int ret; + +	ret = rsa_init(); +	if (ret) +		return ret; + +	ret = rsa_get_priv_key(info->keydir, info->keyname, &rsa); +	if (ret) +		goto err_priv; +	ret = rsa_sign_with_key(rsa, region, region_count, sigp, sig_len); +	if (ret) +		goto err_sign; + +	RSA_free(rsa); +	rsa_remove(); + +	return ret; + +err_sign: +	RSA_free(rsa); +err_priv: +	rsa_remove(); +	return ret; +} + +/* + * rsa_get_params(): - Get the important parameters of an RSA public key + */ +int rsa_get_params(RSA *key, uint32_t *n0_invp, BIGNUM **modulusp, +		   BIGNUM **r_squaredp) +{ +	BIGNUM *big1, *big2, *big32, *big2_32; +	BIGNUM *n, *r, *r_squared, *tmp; +	BN_CTX *bn_ctx = BN_CTX_new(); +	int ret = 0; + +	/* Initialize BIGNUMs */ +	big1 = BN_new(); +	big2 = BN_new(); +	big32 = BN_new(); +	r = BN_new(); +	r_squared = BN_new(); +	tmp = BN_new(); +	big2_32 = BN_new(); +	n = BN_new(); +	if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 || +	    !n) { +		fprintf(stderr, "Out of memory (bignum)\n"); +		return -ENOMEM; +	} + +	if (!BN_copy(n, key->n) || !BN_set_word(big1, 1L) || +	    !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L)) +		ret = -1; + +	/* big2_32 = 2^32 */ +	if (!BN_exp(big2_32, big2, big32, bn_ctx)) +		ret = -1; + +	/* Calculate n0_inv = -1 / n[0] mod 2^32 */ +	if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) || +	    !BN_sub(tmp, big2_32, tmp)) +		ret = -1; +	*n0_invp = BN_get_word(tmp); + +	/* Calculate R = 2^(# of key bits) */ +	if (!BN_set_word(tmp, BN_num_bits(n)) || +	    !BN_exp(r, big2, tmp, bn_ctx)) +		ret = -1; + +	/* Calculate r_squared = R^2 mod n */ +	if (!BN_copy(r_squared, r) || +	    !BN_mul(tmp, r_squared, r, bn_ctx) || +	    !BN_mod(r_squared, tmp, n, bn_ctx)) +		ret = -1; + +	*modulusp = n; +	*r_squaredp = r_squared; + +	BN_free(big1); +	BN_free(big2); +	BN_free(big32); +	BN_free(r); +	BN_free(tmp); +	BN_free(big2_32); +	if (ret) { +		fprintf(stderr, "Bignum operations failed\n"); +		return -ENOMEM; +	} + +	return ret; +} + +static int fdt_add_bignum(void *blob, int noffset, const char *prop_name, +			  BIGNUM *num, int num_bits) +{ +	int nwords = num_bits / 32; +	int size; +	uint32_t *buf, *ptr; +	BIGNUM *tmp, *big2, *big32, *big2_32; +	BN_CTX *ctx; +	int ret; + +	tmp = BN_new(); +	big2 = BN_new(); +	big32 = BN_new(); +	big2_32 = BN_new(); +	if (!tmp || !big2 || !big32 || !big2_32) { +		fprintf(stderr, "Out of memory (bignum)\n"); +		return -ENOMEM; +	} +	ctx = BN_CTX_new(); +	if (!tmp) { +		fprintf(stderr, "Out of memory (bignum context)\n"); +		return -ENOMEM; +	} +	BN_set_word(big2, 2L); +	BN_set_word(big32, 32L); +	BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */ + +	size = nwords * sizeof(uint32_t); +	buf = malloc(size); +	if (!buf) { +		fprintf(stderr, "Out of memory (%d bytes)\n", size); +		return -ENOMEM; +	} + +	/* Write out modulus as big endian array of integers */ +	for (ptr = buf + nwords - 1; ptr >= buf; ptr--) { +		BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */ +		*ptr = cpu_to_fdt32(BN_get_word(tmp)); +		BN_rshift(num, num, 32); /*  N = N/B */ +	} + +	ret = fdt_setprop(blob, noffset, prop_name, buf, size); +	if (ret) { +		fprintf(stderr, "Failed to write public key to FIT\n"); +		return -ENOSPC; +	} +	free(buf); +	BN_free(tmp); +	BN_free(big2); +	BN_free(big32); +	BN_free(big2_32); + +	return ret; +} + +int rsa_add_verify_data(struct image_sign_info *info, void *keydest) +{ +	BIGNUM *modulus, *r_squared; +	uint32_t n0_inv; +	int parent, node; +	char name[100]; +	int ret; +	int bits; +	RSA *rsa; + +	debug("%s: Getting verification data\n", __func__); +	ret = rsa_get_pub_key(info->keydir, info->keyname, &rsa); +	if (ret) +		return ret; +	ret = rsa_get_params(rsa, &n0_inv, &modulus, &r_squared); +	if (ret) +		return ret; +	bits = BN_num_bits(modulus); +	parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME); +	if (parent == -FDT_ERR_NOTFOUND) { +		parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME); +		if (parent < 0) { +			fprintf(stderr, "Couldn't create signature node: %s\n", +				fdt_strerror(parent)); +			return -EINVAL; +		} +	} + +	/* Either create or overwrite the named key node */ +	snprintf(name, sizeof(name), "key-%s", info->keyname); +	node = fdt_subnode_offset(keydest, parent, name); +	if (node == -FDT_ERR_NOTFOUND) { +		node = fdt_add_subnode(keydest, parent, name); +		if (node < 0) { +			fprintf(stderr, "Could not create key subnode: %s\n", +				fdt_strerror(node)); +			return -EINVAL; +		} +	} else if (node < 0) { +		fprintf(stderr, "Cannot select keys parent: %s\n", +			fdt_strerror(node)); +		return -ENOSPC; +	} + +	ret = fdt_setprop_string(keydest, node, "key-name-hint", +				 info->keyname); +	ret |= fdt_setprop_u32(keydest, node, "rsa,num-bits", bits); +	ret |= fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv); +	ret |= fdt_add_bignum(keydest, node, "rsa,modulus", modulus, bits); +	ret |= fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared, bits); +	ret |= fdt_setprop_string(keydest, node, FIT_ALGO_PROP, +				  info->algo->name); +	if (info->require_keys) { +		fdt_setprop_string(keydest, node, "required", +				   info->require_keys); +	} +	BN_free(modulus); +	BN_free(r_squared); +	if (ret) +		return -EIO; + +	return 0; +} diff --git a/lib/rsa/rsa-verify.c b/lib/rsa/rsa-verify.c new file mode 100644 index 000000000..6a0268919 --- /dev/null +++ b/lib/rsa/rsa-verify.c @@ -0,0 +1,385 @@ +/* + * Copyright (c) 2013, Google Inc. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +#include <common.h> +#include <fdtdec.h> +#include <rsa.h> +#include <sha1.h> +#include <asm/byteorder.h> +#include <asm/errno.h> +#include <asm/unaligned.h> + +/** + * struct rsa_public_key - holder for a public key + * + * An RSA public key consists of a modulus (typically called N), the inverse + * and R^2, where R is 2^(# key bits). + */ +struct rsa_public_key { +	uint len;		/* Length of modulus[] in number of uint32_t */ +	uint32_t n0inv;		/* -1 / modulus[0] mod 2^32 */ +	uint32_t *modulus;	/* modulus as little endian array */ +	uint32_t *rr;		/* R^2 as little endian array */ +}; + +#define UINT64_MULT32(v, multby)  (((uint64_t)(v)) * ((uint32_t)(multby))) + +#define RSA2048_BYTES	(2048 / 8) + +/* This is the minimum/maximum key size we support, in bits */ +#define RSA_MIN_KEY_BITS	2048 +#define RSA_MAX_KEY_BITS	2048 + +/* This is the maximum signature length that we support, in bits */ +#define RSA_MAX_SIG_BITS	2048 + +static const uint8_t padding_sha1_rsa2048[RSA2048_BYTES - SHA1_SUM_LEN] = { +	0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	0xff, 0xff, 0xff, 0xff, 0x00, 0x30, 0x21, 0x30, +	0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, +	0x05, 0x00, 0x04, 0x14 +}; + +/** + * subtract_modulus() - subtract modulus from the given value + * + * @key:	Key containing modulus to subtract + * @num:	Number to subtract modulus from, as little endian word array + */ +static void subtract_modulus(const struct rsa_public_key *key, uint32_t num[]) +{ +	int64_t acc = 0; +	uint i; + +	for (i = 0; i < key->len; i++) { +		acc += (uint64_t)num[i] - key->modulus[i]; +		num[i] = (uint32_t)acc; +		acc >>= 32; +	} +} + +/** + * greater_equal_modulus() - check if a value is >= modulus + * + * @key:	Key containing modulus to check + * @num:	Number to check against modulus, as little endian word array + * @return 0 if num < modulus, 1 if num >= modulus + */ +static int greater_equal_modulus(const struct rsa_public_key *key, +				 uint32_t num[]) +{ +	uint32_t i; + +	for (i = key->len - 1; i >= 0; i--) { +		if (num[i] < key->modulus[i]) +			return 0; +		if (num[i] > key->modulus[i]) +			return 1; +	} + +	return 1;  /* equal */ +} + +/** + * montgomery_mul_add_step() - Perform montgomery multiply-add step + * + * Operation: montgomery result[] += a * b[] / n0inv % modulus + * + * @key:	RSA key + * @result:	Place to put result, as little endian word array + * @a:		Multiplier + * @b:		Multiplicand, as little endian word array + */ +static void montgomery_mul_add_step(const struct rsa_public_key *key, +		uint32_t result[], const uint32_t a, const uint32_t b[]) +{ +	uint64_t acc_a, acc_b; +	uint32_t d0; +	uint i; + +	acc_a = (uint64_t)a * b[0] + result[0]; +	d0 = (uint32_t)acc_a * key->n0inv; +	acc_b = (uint64_t)d0 * key->modulus[0] + (uint32_t)acc_a; +	for (i = 1; i < key->len; i++) { +		acc_a = (acc_a >> 32) + (uint64_t)a * b[i] + result[i]; +		acc_b = (acc_b >> 32) + (uint64_t)d0 * key->modulus[i] + +				(uint32_t)acc_a; +		result[i - 1] = (uint32_t)acc_b; +	} + +	acc_a = (acc_a >> 32) + (acc_b >> 32); + +	result[i - 1] = (uint32_t)acc_a; + +	if (acc_a >> 32) +		subtract_modulus(key, result); +} + +/** + * montgomery_mul() - Perform montgomery mutitply + * + * Operation: montgomery result[] = a[] * b[] / n0inv % modulus + * + * @key:	RSA key + * @result:	Place to put result, as little endian word array + * @a:		Multiplier, as little endian word array + * @b:		Multiplicand, as little endian word array + */ +static void montgomery_mul(const struct rsa_public_key *key, +		uint32_t result[], uint32_t a[], const uint32_t b[]) +{ +	uint i; + +	for (i = 0; i < key->len; ++i) +		result[i] = 0; +	for (i = 0; i < key->len; ++i) +		montgomery_mul_add_step(key, result, a[i], b); +} + +/** + * pow_mod() - in-place public exponentiation + * + * @key:	RSA key + * @inout:	Big-endian word array containing value and result + */ +static int pow_mod(const struct rsa_public_key *key, uint32_t *inout) +{ +	uint32_t *result, *ptr; +	uint i; + +	/* Sanity check for stack size - key->len is in 32-bit words */ +	if (key->len > RSA_MAX_KEY_BITS / 32) { +		debug("RSA key words %u exceeds maximum %d\n", key->len, +		      RSA_MAX_KEY_BITS / 32); +		return -EINVAL; +	} + +	uint32_t val[key->len], acc[key->len], tmp[key->len]; +	result = tmp;  /* Re-use location. */ + +	/* Convert from big endian byte array to little endian word array. */ +	for (i = 0, ptr = inout + key->len - 1; i < key->len; i++, ptr--) +		val[i] = get_unaligned_be32(ptr); + +	montgomery_mul(key, acc, val, key->rr);  /* axx = a * RR / R mod M */ +	for (i = 0; i < 16; i += 2) { +		montgomery_mul(key, tmp, acc, acc); /* tmp = acc^2 / R mod M */ +		montgomery_mul(key, acc, tmp, tmp); /* acc = tmp^2 / R mod M */ +	} +	montgomery_mul(key, result, acc, val);  /* result = XX * a / R mod M */ + +	/* Make sure result < mod; result is at most 1x mod too large. */ +	if (greater_equal_modulus(key, result)) +		subtract_modulus(key, result); + +	/* Convert to bigendian byte array */ +	for (i = key->len - 1, ptr = inout; (int)i >= 0; i--, ptr++) +		put_unaligned_be32(result[i], ptr); + +	return 0; +} + +static int rsa_verify_key(const struct rsa_public_key *key, const uint8_t *sig, +		const uint32_t sig_len, const uint8_t *hash) +{ +	const uint8_t *padding; +	int pad_len; +	int ret; + +	if (!key || !sig || !hash) +		return -EIO; + +	if (sig_len != (key->len * sizeof(uint32_t))) { +		debug("Signature is of incorrect length %d\n", sig_len); +		return -EINVAL; +	} + +	/* Sanity check for stack size */ +	if (sig_len > RSA_MAX_SIG_BITS / 8) { +		debug("Signature length %u exceeds maximum %d\n", sig_len, +		      RSA_MAX_SIG_BITS / 8); +		return -EINVAL; +	} + +	uint32_t buf[sig_len / sizeof(uint32_t)]; + +	memcpy(buf, sig, sig_len); + +	ret = pow_mod(key, buf); +	if (ret) +		return ret; + +	/* Determine padding to use depending on the signature type. */ +	padding = padding_sha1_rsa2048; +	pad_len = RSA2048_BYTES - SHA1_SUM_LEN; + +	/* Check pkcs1.5 padding bytes. */ +	if (memcmp(buf, padding, pad_len)) { +		debug("In RSAVerify(): Padding check failed!\n"); +		return -EINVAL; +	} + +	/* Check hash. */ +	if (memcmp((uint8_t *)buf + pad_len, hash, sig_len - pad_len)) { +		debug("In RSAVerify(): Hash check failed!\n"); +		return -EACCES; +	} + +	return 0; +} + +static void rsa_convert_big_endian(uint32_t *dst, const uint32_t *src, int len) +{ +	int i; + +	for (i = 0; i < len; i++) +		dst[i] = fdt32_to_cpu(src[len - 1 - i]); +} + +static int rsa_verify_with_keynode(struct image_sign_info *info, +		const void *hash, uint8_t *sig, uint sig_len, int node) +{ +	const void *blob = info->fdt_blob; +	struct rsa_public_key key; +	const void *modulus, *rr; +	int ret; + +	if (node < 0) { +		debug("%s: Skipping invalid node", __func__); +		return -EBADF; +	} +	if (!fdt_getprop(blob, node, "rsa,n0-inverse", NULL)) { +		debug("%s: Missing rsa,n0-inverse", __func__); +		return -EFAULT; +	} +	key.len = fdtdec_get_int(blob, node, "rsa,num-bits", 0); +	key.n0inv = fdtdec_get_int(blob, node, "rsa,n0-inverse", 0); +	modulus = fdt_getprop(blob, node, "rsa,modulus", NULL); +	rr = fdt_getprop(blob, node, "rsa,r-squared", NULL); +	if (!key.len || !modulus || !rr) { +		debug("%s: Missing RSA key info", __func__); +		return -EFAULT; +	} + +	/* Sanity check for stack size */ +	if (key.len > RSA_MAX_KEY_BITS || key.len < RSA_MIN_KEY_BITS) { +		debug("RSA key bits %u outside allowed range %d..%d\n", +		      key.len, RSA_MIN_KEY_BITS, RSA_MAX_KEY_BITS); +		return -EFAULT; +	} +	key.len /= sizeof(uint32_t) * 8; +	uint32_t key1[key.len], key2[key.len]; + +	key.modulus = key1; +	key.rr = key2; +	rsa_convert_big_endian(key.modulus, modulus, key.len); +	rsa_convert_big_endian(key.rr, rr, key.len); +	if (!key.modulus || !key.rr) { +		debug("%s: Out of memory", __func__); +		return -ENOMEM; +	} + +	debug("key length %d\n", key.len); +	ret = rsa_verify_key(&key, sig, sig_len, hash); +	if (ret) { +		printf("%s: RSA failed to verify: %d\n", __func__, ret); +		return ret; +	} + +	return 0; +} + +int rsa_verify(struct image_sign_info *info, +	       const struct image_region region[], int region_count, +	       uint8_t *sig, uint sig_len) +{ +	const void *blob = info->fdt_blob; +	uint8_t hash[SHA1_SUM_LEN]; +	int ndepth, noffset; +	int sig_node, node; +	char name[100]; +	sha1_context ctx; +	int ret, i; + +	sig_node = fdt_subnode_offset(blob, 0, FIT_SIG_NODENAME); +	if (sig_node < 0) { +		debug("%s: No signature node found\n", __func__); +		return -ENOENT; +	} + +	sha1_starts(&ctx); +	for (i = 0; i < region_count; i++) +		sha1_update(&ctx, region[i].data, region[i].size); +	sha1_finish(&ctx, hash); + +	/* See if we must use a particular key */ +	if (info->required_keynode != -1) { +		ret = rsa_verify_with_keynode(info, hash, sig, sig_len, +			info->required_keynode); +		if (!ret) +			return ret; +	} + +	/* Look for a key that matches our hint */ +	snprintf(name, sizeof(name), "key-%s", info->keyname); +	node = fdt_subnode_offset(blob, sig_node, name); +	ret = rsa_verify_with_keynode(info, hash, sig, sig_len, node); +	if (!ret) +		return ret; + +	/* No luck, so try each of the keys in turn */ +	for (ndepth = 0, noffset = fdt_next_node(info->fit, sig_node, &ndepth); +			(noffset >= 0) && (ndepth > 0); +			noffset = fdt_next_node(info->fit, noffset, &ndepth)) { +		if (ndepth == 1 && noffset != node) { +			ret = rsa_verify_with_keynode(info, hash, sig, sig_len, +						      noffset); +			if (!ret) +				break; +		} +	} + +	return ret; +} diff --git a/lib/string.c b/lib/string.c index 09dfae03c..3a82efab6 100644 --- a/lib/string.c +++ b/lib/string.c @@ -617,3 +617,62 @@ void *memchr(const void *s, int c, size_t n)  }  #endif +#ifndef __HAVE_ARCH_MEMCHR_INV +static void *check_bytes8(const u8 *start, u8 value, unsigned int bytes) +{ +	while (bytes) { +		if (*start != value) +			return (void *)start; +		start++; +		bytes--; +	} +	return NULL; +} +/** + * memchr_inv - Find an unmatching character in an area of memory. + * @start: The memory area + * @c: Find a character other than c + * @bytes: The size of the area. + * + * returns the address of the first character other than @c, or %NULL + * if the whole buffer contains just @c. + */ +void *memchr_inv(const void *start, int c, size_t bytes) +{ +	u8 value = c; +	u64 value64; +	unsigned int words, prefix; + +	if (bytes <= 16) +		return check_bytes8(start, value, bytes); + +	value64 = value; +	value64 |= value64 << 8; +	value64 |= value64 << 16; +	value64 |= value64 << 32; + +	prefix = (unsigned long)start % 8; +	if (prefix) { +		u8 *r; + +		prefix = 8 - prefix; +		r = check_bytes8(start, value, prefix); +		if (r) +			return r; +		start += prefix; +		bytes -= prefix; +	} + +	words = bytes / 8; + +	while (words) { +		if (*(u64 *)start != value64) +			return check_bytes8(start, value, 8); +		start += 8; +		words--; +	} + +	return check_bytes8(start, value, bytes % 8); +} +#endif + diff --git a/lib/trace.c b/lib/trace.c new file mode 100644 index 000000000..e7455bcfe --- /dev/null +++ b/lib/trace.c @@ -0,0 +1,379 @@ +/* + * Copyright (c) 2012 The Chromium OS Authors. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +#include <common.h> +#include <trace.h> +#include <asm/io.h> +#include <asm/sections.h> + +DECLARE_GLOBAL_DATA_PTR; + +static char trace_enabled __attribute__((section(".data"))); +static char trace_inited __attribute__((section(".data"))); + +/* The header block at the start of the trace memory area */ +struct trace_hdr { +	int func_count;		/* Total number of function call sites */ +	u64 call_count;		/* Total number of tracked function calls */ +	u64 untracked_count;	/* Total number of untracked function calls */ +	int funcs_used;		/* Total number of functions used */ + +	/* +	 * Call count for each function. This is indexed by the word offset +	 * of the function from gd->relocaddr +	 */ +	uintptr_t *call_accum; + +	/* Function trace list */ +	struct trace_call *ftrace;	/* The function call records */ +	ulong ftrace_size;	/* Num. of ftrace records we have space for */ +	ulong ftrace_count;	/* Num. of ftrace records written */ +	ulong ftrace_too_deep_count;	/* Functions that were too deep */ + +	int depth; +	int depth_limit; +	int max_depth; +}; + +static struct trace_hdr *hdr;	/* Pointer to start of trace buffer */ + +static inline uintptr_t __attribute__((no_instrument_function)) +		func_ptr_to_num(void *func_ptr) +{ +	uintptr_t offset = (uintptr_t)func_ptr; + +#ifdef CONFIG_SANDBOX +	offset -= (uintptr_t)&_init; +#else +	if (gd->flags & GD_FLG_RELOC) +		offset -= gd->relocaddr; +	else +		offset -= CONFIG_SYS_TEXT_BASE; +#endif +	return offset / FUNC_SITE_SIZE; +} + +static void __attribute__((no_instrument_function)) add_ftrace(void *func_ptr, +				void *caller, ulong flags) +{ +	if (hdr->depth > hdr->depth_limit) { +		hdr->ftrace_too_deep_count++; +		return; +	} +	if (hdr->ftrace_count < hdr->ftrace_size) { +		struct trace_call *rec = &hdr->ftrace[hdr->ftrace_count]; + +		rec->func = func_ptr_to_num(func_ptr); +		rec->caller = func_ptr_to_num(caller); +		rec->flags = flags | (timer_get_us() & FUNCF_TIMESTAMP_MASK); +	} +	hdr->ftrace_count++; +} + +static void __attribute__((no_instrument_function)) add_textbase(void) +{ +	if (hdr->ftrace_count < hdr->ftrace_size) { +		struct trace_call *rec = &hdr->ftrace[hdr->ftrace_count]; + +		rec->func = CONFIG_SYS_TEXT_BASE; +		rec->caller = 0; +		rec->flags = FUNCF_TEXTBASE; +	} +	hdr->ftrace_count++; +} + +/** + * This is called on every function entry + * + * We add to our tally for this function and add to the list of called + * functions. + * + * @param func_ptr	Pointer to function being entered + * @param caller	Pointer to function which called this function + */ +void __attribute__((no_instrument_function)) __cyg_profile_func_enter( +		void *func_ptr, void *caller) +{ +	if (trace_enabled) { +		int func; + +		add_ftrace(func_ptr, caller, FUNCF_ENTRY); +		func = func_ptr_to_num(func_ptr); +		if (func < hdr->func_count) { +			hdr->call_accum[func]++; +			hdr->call_count++; +		} else { +			hdr->untracked_count++; +		} +		hdr->depth++; +		if (hdr->depth > hdr->depth_limit) +			hdr->max_depth = hdr->depth; +	} +} + +/** + * This is called on every function exit + * + * We do nothing here. + * + * @param func_ptr	Pointer to function being entered + * @param caller	Pointer to function which called this function + */ +void __attribute__((no_instrument_function)) __cyg_profile_func_exit( +		void *func_ptr, void *caller) +{ +	if (trace_enabled) { +		add_ftrace(func_ptr, caller, FUNCF_EXIT); +		hdr->depth--; +	} +} + +/** + * Produce a list of called functions + * + * The information is written into the supplied buffer - a header followed + * by a list of function records. + * + * @param buff		Buffer to place list into + * @param buff_size	Size of buffer + * @param needed	Returns size of buffer needed, which may be + *			greater than buff_size if we ran out of space. + * @return 0 if ok, -1 if space was exhausted + */ +int trace_list_functions(void *buff, int buff_size, unsigned int *needed) +{ +	struct trace_output_hdr *output_hdr = NULL; +	void *end, *ptr = buff; +	int func; +	int upto; + +	end = buff ? buff + buff_size : NULL; + +	/* Place some header information */ +	if (ptr + sizeof(struct trace_output_hdr) < end) +		output_hdr = ptr; +	ptr += sizeof(struct trace_output_hdr); + +	/* Add information about each function */ +	for (func = upto = 0; func < hdr->func_count; func++) { +		int calls = hdr->call_accum[func]; + +		if (!calls) +			continue; + +		if (ptr + sizeof(struct trace_output_func) < end) { +			struct trace_output_func *stats = ptr; + +			stats->offset = func * FUNC_SITE_SIZE; +			stats->call_count = calls; +			upto++; +		} +		ptr += sizeof(struct trace_output_func); +	} + +	/* Update the header */ +	if (output_hdr) { +		output_hdr->rec_count = upto; +		output_hdr->type = TRACE_CHUNK_FUNCS; +	} + +	/* Work out how must of the buffer we used */ +	*needed = ptr - buff; +	if (ptr > end) +		return -1; +	return 0; +} + +int trace_list_calls(void *buff, int buff_size, unsigned *needed) +{ +	struct trace_output_hdr *output_hdr = NULL; +	void *end, *ptr = buff; +	int rec, upto; +	int count; + +	end = buff ? buff + buff_size : NULL; + +	/* Place some header information */ +	if (ptr + sizeof(struct trace_output_hdr) < end) +		output_hdr = ptr; +	ptr += sizeof(struct trace_output_hdr); + +	/* Add information about each call */ +	count = hdr->ftrace_count; +	if (count > hdr->ftrace_size) +		count = hdr->ftrace_size; +	for (rec = upto = 0; rec < count; rec++) { +		if (ptr + sizeof(struct trace_call) < end) { +			struct trace_call *call = &hdr->ftrace[rec]; +			struct trace_call *out = ptr; + +			out->func = call->func * FUNC_SITE_SIZE; +			out->caller = call->caller * FUNC_SITE_SIZE; +			out->flags = call->flags; +			upto++; +		} +		ptr += sizeof(struct trace_call); +	} + +	/* Update the header */ +	if (output_hdr) { +		output_hdr->rec_count = upto; +		output_hdr->type = TRACE_CHUNK_CALLS; +	} + +	/* Work out how must of the buffer we used */ +	*needed = ptr - buff; +	if (ptr > end) +		return -1; +	return 0; +} + +/* Print basic information about tracing */ +void trace_print_stats(void) +{ +	ulong count; + +#ifndef FTRACE +	puts("Warning: make U-Boot with FTRACE to enable function instrumenting.\n"); +	puts("You will likely get zeroed data here\n"); +#endif +	if (!trace_inited) { +		printf("Trace is disabled\n"); +		return; +	} +	print_grouped_ull(hdr->func_count, 10); +	puts(" function sites\n"); +	print_grouped_ull(hdr->call_count, 10); +	puts(" function calls\n"); +	print_grouped_ull(hdr->untracked_count, 10); +	puts(" untracked function calls\n"); +	count = min(hdr->ftrace_count, hdr->ftrace_size); +	print_grouped_ull(count, 10); +	puts(" traced function calls"); +	if (hdr->ftrace_count > hdr->ftrace_size) { +		printf(" (%lu dropped due to overflow)", +		       hdr->ftrace_count - hdr->ftrace_size); +	} +	puts("\n"); +	printf("%15d maximum observed call depth\n", hdr->max_depth); +	printf("%15d call depth limit\n", hdr->depth_limit); +	print_grouped_ull(hdr->ftrace_too_deep_count, 10); +	puts(" calls not traced due to depth\n"); +} + +void __attribute__((no_instrument_function)) trace_set_enabled(int enabled) +{ +	trace_enabled = enabled != 0; +} + +/** + * Init the tracing system ready for used, and enable it + * + * @param buff		Pointer to trace buffer + * @param buff_size	Size of trace buffer + */ +int __attribute__((no_instrument_function)) trace_init(void *buff, +		size_t buff_size) +{ +	ulong func_count = gd->mon_len / FUNC_SITE_SIZE; +	size_t needed; +	int was_disabled = !trace_enabled; + +	if (!was_disabled) { +#ifdef CONFIG_TRACE_EARLY +		char *end; +		ulong used; + +		/* +		 * Copy over the early trace data if we have it. Disable +		 * tracing while we are doing this. +		 */ +		trace_enabled = 0; +		hdr = map_sysmem(CONFIG_TRACE_EARLY_ADDR, +				 CONFIG_TRACE_EARLY_SIZE); +		end = (char *)&hdr->ftrace[hdr->ftrace_count]; +		used = end - (char *)hdr; +		printf("trace: copying %08lx bytes of early data from %x to %08lx\n", +		       used, CONFIG_TRACE_EARLY_ADDR, +		       (ulong)map_to_sysmem(buff)); +		memcpy(buff, hdr, used); +#else +		puts("trace: already enabled\n"); +		return -1; +#endif +	} +	hdr = (struct trace_hdr *)buff; +	needed = sizeof(*hdr) + func_count * sizeof(uintptr_t); +	if (needed > buff_size) { +		printf("trace: buffer size %zd bytes: at least %zd needed\n", +		       buff_size, needed); +		return -1; +	} + +	if (was_disabled) +		memset(hdr, '\0', needed); +	hdr->func_count = func_count; +	hdr->call_accum = (uintptr_t *)(hdr + 1); + +	/* Use any remaining space for the timed function trace */ +	hdr->ftrace = (struct trace_call *)(buff + needed); +	hdr->ftrace_size = (buff_size - needed) / sizeof(*hdr->ftrace); +	add_textbase(); + +	puts("trace: enabled\n"); +	hdr->depth_limit = 15; +	trace_enabled = 1; +	trace_inited = 1; +	return 0; +} + +#ifdef CONFIG_TRACE_EARLY +int __attribute__((no_instrument_function)) trace_early_init(void) +{ +	ulong func_count = gd->mon_len / FUNC_SITE_SIZE; +	size_t buff_size = CONFIG_TRACE_EARLY_SIZE; +	size_t needed; + +	/* We can ignore additional calls to this function */ +	if (trace_enabled) +		return 0; + +	hdr = map_sysmem(CONFIG_TRACE_EARLY_ADDR, CONFIG_TRACE_EARLY_SIZE); +	needed = sizeof(*hdr) + func_count * sizeof(uintptr_t); +	if (needed > buff_size) { +		printf("trace: buffer size is %zd bytes, at least %zd needed\n", +		       buff_size, needed); +		return -1; +	} + +	memset(hdr, '\0', needed); +	hdr->call_accum = (uintptr_t *)(hdr + 1); +	hdr->func_count = func_count; + +	/* Use any remaining space for the timed function trace */ +	hdr->ftrace = (struct trace_call *)((char *)hdr + needed); +	hdr->ftrace_size = (buff_size - needed) / sizeof(*hdr->ftrace); +	add_textbase(); +	hdr->depth_limit = 200; +	printf("trace: early enable at %08x\n", CONFIG_TRACE_EARLY_ADDR); + +	trace_enabled = 1; +	return 0; +} +#endif diff --git a/lib/vsprintf.c b/lib/vsprintf.c index 533a96b85..82e5c1365 100644 --- a/lib/vsprintf.c +++ b/lib/vsprintf.c @@ -870,3 +870,19 @@ char *simple_itoa(ulong i)  	} while (i > 0);  	return p + 1;  } + +/* We don't seem to have %'d in U-Boot */ +void print_grouped_ull(unsigned long long int_val, int digits) +{ +	char str[21], *s; +	int grab = 3; + +	digits = (digits + 2) / 3; +	sprintf(str, "%*llu", digits * 3, int_val); +	for (s = str; *s; s += grab) { +		if (s != str) +			putc(s[-1] != ' ' ? ',' : ' '); +		printf("%.*s", grab, s); +		grab = 3; +	} +} |