1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * (C) Copyright 2002
4 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
5 */
6
7/*
8 * I2C test
9 *
10 * For verifying the I2C bus, a full I2C bus scanning is performed.
11 *
12 * #ifdef CFG_SYS_POST_I2C_ADDRS
13 *   The test is considered as passed if all the devices and only the devices
14 *   in the list are found.
15 *   #ifdef CFG_SYS_POST_I2C_IGNORES
16 *     Ignore devices listed in CFG_SYS_POST_I2C_IGNORES.  These devices
17 *     are optional or not vital to board functionality.
18 *   #endif
19 * #else [ ! CFG_SYS_POST_I2C_ADDRS ]
20 *   The test is considered as passed if any I2C device is found.
21 * #endif
22 */
23
24#include <common.h>
25#include <log.h>
26#include <post.h>
27#include <i2c.h>
28
29#if CFG_POST & CFG_SYS_POST_I2C
30
31static int i2c_ignore_device(unsigned int chip)
32{
33#ifdef CFG_SYS_POST_I2C_IGNORES
34	const unsigned char i2c_ignore_list[] = CFG_SYS_POST_I2C_IGNORES;
35	int i;
36
37	for (i = 0; i < sizeof(i2c_ignore_list); i++)
38		if (i2c_ignore_list[i] == chip)
39			return 1;
40#endif
41
42	return 0;
43}
44
45int i2c_post_test (int flags)
46{
47	unsigned int i;
48#ifndef CFG_SYS_POST_I2C_ADDRS
49	/* Start at address 1, address 0 is the general call address */
50	for (i = 1; i < 128; i++) {
51		if (i2c_ignore_device(i))
52			continue;
53		if (i2c_probe (i) == 0)
54			return 0;
55	}
56
57	/* No devices found */
58	return -1;
59#else
60	unsigned int ret  = 0;
61	int j;
62	unsigned char i2c_addr_list[] = CFG_SYS_POST_I2C_ADDRS;
63
64	/* Start at address 1, address 0 is the general call address */
65	for (i = 1; i < 128; i++) {
66		if (i2c_ignore_device(i))
67			continue;
68		if (i2c_probe(i) != 0)
69			continue;
70
71		for (j = 0; j < sizeof(i2c_addr_list); ++j) {
72			if (i == i2c_addr_list[j]) {
73				i2c_addr_list[j] = 0xff;
74				break;
75			}
76		}
77
78		if (j == sizeof(i2c_addr_list)) {
79			ret = -1;
80			post_log("I2C: addr %02x not expected\n", i);
81		}
82	}
83
84	for (i = 0; i < sizeof(i2c_addr_list); ++i) {
85		if (i2c_addr_list[i] == 0xff)
86			continue;
87		if (i2c_ignore_device(i2c_addr_list[i]))
88			continue;
89		post_log("I2C: addr %02x did not respond\n", i2c_addr_list[i]);
90		ret = -1;
91	}
92
93	return ret;
94#endif
95}
96
97#endif /* CFG_POST & CFG_SYS_POST_I2C */
98