1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * i2c-smbus.c - SMBus extensions to the I2C protocol
4  *
5  * Copyright (C) 2008 David Brownell
6  * Copyright (C) 2010-2019 Jean Delvare <jdelvare@suse.de>
7  */
8 
9 #include <linux/device.h>
10 #include <linux/dmi.h>
11 #include <linux/gpio/consumer.h>
12 #include <linux/i2c.h>
13 #include <linux/i2c-smbus.h>
14 #include <linux/interrupt.h>
15 #include <linux/kernel.h>
16 #include <linux/module.h>
17 #include <linux/property.h>
18 #include <linux/slab.h>
19 #include <linux/workqueue.h>
20 
21 struct i2c_smbus_alert {
22 	struct work_struct	alert;
23 	struct i2c_client	*ara;		/* Alert response address */
24 };
25 
26 struct alert_data {
27 	unsigned short		addr;
28 	enum i2c_alert_protocol	type;
29 	unsigned int		data;
30 };
31 
32 /* If this is the alerting device, notify its driver */
33 static int smbus_do_alert(struct device *dev, void *addrp)
34 {
35 	struct i2c_client *client = i2c_verify_client(dev);
36 	struct alert_data *data = addrp;
37 	struct i2c_driver *driver;
38 	int ret;
39 
40 	if (!client || client->addr != data->addr)
41 		return 0;
42 	if (client->flags & I2C_CLIENT_TEN)
43 		return 0;
44 
45 	/*
46 	 * Drivers should either disable alerts, or provide at least
47 	 * a minimal handler.  Lock so the driver won't change.
48 	 */
49 	device_lock(dev);
50 	if (client->dev.driver) {
51 		driver = to_i2c_driver(client->dev.driver);
52 		if (driver->alert) {
53 			/* Stop iterating after we find the device */
54 			driver->alert(client, data->type, data->data);
55 			ret = -EBUSY;
56 		} else {
57 			dev_warn(&client->dev, "no driver alert()!\n");
58 			ret = -EOPNOTSUPP;
59 		}
60 	} else {
61 		dev_dbg(&client->dev, "alert with no driver\n");
62 		ret = -ENODEV;
63 	}
64 	device_unlock(dev);
65 
66 	return ret;
67 }
68 
69 /* Same as above, but call back all drivers with alert handler */
70 
71 static int smbus_do_alert_force(struct device *dev, void *addrp)
72 {
73 	struct i2c_client *client = i2c_verify_client(dev);
74 	struct alert_data *data = addrp;
75 	struct i2c_driver *driver;
76 
77 	if (!client || (client->flags & I2C_CLIENT_TEN))
78 		return 0;
79 
80 	/*
81 	 * Drivers should either disable alerts, or provide at least
82 	 * a minimal handler. Lock so the driver won't change.
83 	 */
84 	device_lock(dev);
85 	if (client->dev.driver) {
86 		driver = to_i2c_driver(client->dev.driver);
87 		if (driver->alert)
88 			driver->alert(client, data->type, data->data);
89 	}
90 	device_unlock(dev);
91 
92 	return 0;
93 }
94 
95 /*
96  * The alert IRQ handler needs to hand work off to a task which can issue
97  * SMBus calls, because those sleeping calls can't be made in IRQ context.
98  */
99 static irqreturn_t smbus_alert(int irq, void *d)
100 {
101 	struct i2c_smbus_alert *alert = d;
102 	struct i2c_client *ara;
103 	unsigned short prev_addr = I2C_CLIENT_END; /* Not a valid address */
104 
105 	ara = alert->ara;
106 
107 	for (;;) {
108 		s32 status;
109 		struct alert_data data;
110 
111 		/*
112 		 * Devices with pending alerts reply in address order, low
113 		 * to high, because of slave transmit arbitration.  After
114 		 * responding, an SMBus device stops asserting SMBALERT#.
115 		 *
116 		 * Note that SMBus 2.0 reserves 10-bit addresses for future
117 		 * use.  We neither handle them, nor try to use PEC here.
118 		 */
119 		status = i2c_smbus_read_byte(ara);
120 		if (status < 0)
121 			break;
122 
123 		data.data = status & 1;
124 		data.addr = status >> 1;
125 		data.type = I2C_PROTOCOL_SMBUS_ALERT;
126 
127 		dev_dbg(&ara->dev, "SMBALERT# from dev 0x%02x, flag %d\n",
128 			data.addr, data.data);
129 
130 		/* Notify driver for the device which issued the alert */
131 		status = device_for_each_child(&ara->adapter->dev, &data,
132 					       smbus_do_alert);
133 		/*
134 		 * If we read the same address more than once, and the alert
135 		 * was not handled by a driver, it won't do any good to repeat
136 		 * the loop because it will never terminate. Try again, this
137 		 * time calling the alert handlers of all devices connected to
138 		 * the bus, and abort the loop afterwards. If this helps, we
139 		 * are all set. If it doesn't, there is nothing else we can do,
140 		 * so we might as well abort the loop.
141 		 * Note: This assumes that a driver with alert handler handles
142 		 * the alert properly and clears it if necessary.
143 		 */
144 		if (data.addr == prev_addr && status != -EBUSY) {
145 			device_for_each_child(&ara->adapter->dev, &data,
146 					      smbus_do_alert_force);
147 			break;
148 		}
149 		prev_addr = data.addr;
150 	}
151 
152 	return IRQ_HANDLED;
153 }
154 
155 static void smbalert_work(struct work_struct *work)
156 {
157 	struct i2c_smbus_alert *alert;
158 
159 	alert = container_of(work, struct i2c_smbus_alert, alert);
160 
161 	smbus_alert(0, alert);
162 
163 }
164 
165 /* Setup SMBALERT# infrastructure */
166 static int smbalert_probe(struct i2c_client *ara)
167 {
168 	struct i2c_smbus_alert_setup *setup = dev_get_platdata(&ara->dev);
169 	struct i2c_smbus_alert *alert;
170 	struct i2c_adapter *adapter = ara->adapter;
171 	unsigned long irqflags = IRQF_SHARED | IRQF_ONESHOT;
172 	struct gpio_desc *gpiod;
173 	int res, irq;
174 
175 	alert = devm_kzalloc(&ara->dev, sizeof(struct i2c_smbus_alert),
176 			     GFP_KERNEL);
177 	if (!alert)
178 		return -ENOMEM;
179 
180 	if (setup) {
181 		irq = setup->irq;
182 	} else {
183 		irq = fwnode_irq_get_byname(dev_fwnode(adapter->dev.parent),
184 					    "smbus_alert");
185 		if (irq <= 0) {
186 			gpiod = devm_gpiod_get(adapter->dev.parent, "smbalert", GPIOD_IN);
187 			if (IS_ERR(gpiod))
188 				return PTR_ERR(gpiod);
189 
190 			irq = gpiod_to_irq(gpiod);
191 			if (irq <= 0)
192 				return irq;
193 
194 			irqflags |= IRQF_TRIGGER_FALLING;
195 		}
196 	}
197 
198 	INIT_WORK(&alert->alert, smbalert_work);
199 	alert->ara = ara;
200 
201 	if (irq > 0) {
202 		res = devm_request_threaded_irq(&ara->dev, irq, NULL, smbus_alert,
203 						irqflags, "smbus_alert", alert);
204 		if (res)
205 			return res;
206 	}
207 
208 	i2c_set_clientdata(ara, alert);
209 	dev_info(&adapter->dev, "supports SMBALERT#\n");
210 
211 	return 0;
212 }
213 
214 /* IRQ and memory resources are managed so they are freed automatically */
215 static void smbalert_remove(struct i2c_client *ara)
216 {
217 	struct i2c_smbus_alert *alert = i2c_get_clientdata(ara);
218 
219 	cancel_work_sync(&alert->alert);
220 }
221 
222 static const struct i2c_device_id smbalert_ids[] = {
223 	{ "smbus_alert" },
224 	{ /* LIST END */ }
225 };
226 MODULE_DEVICE_TABLE(i2c, smbalert_ids);
227 
228 static struct i2c_driver smbalert_driver = {
229 	.driver = {
230 		.name	= "smbus_alert",
231 	},
232 	.probe		= smbalert_probe,
233 	.remove		= smbalert_remove,
234 	.id_table	= smbalert_ids,
235 };
236 
237 /**
238  * i2c_handle_smbus_alert - Handle an SMBus alert
239  * @ara: the ARA client on the relevant adapter
240  * Context: can't sleep
241  *
242  * Helper function to be called from an I2C bus driver's interrupt
243  * handler. It will schedule the alert work, in turn calling the
244  * corresponding I2C device driver's alert function.
245  *
246  * It is assumed that ara is a valid i2c client previously returned by
247  * i2c_new_smbus_alert_device().
248  */
249 int i2c_handle_smbus_alert(struct i2c_client *ara)
250 {
251 	struct i2c_smbus_alert *alert = i2c_get_clientdata(ara);
252 
253 	return schedule_work(&alert->alert);
254 }
255 EXPORT_SYMBOL_GPL(i2c_handle_smbus_alert);
256 
257 module_i2c_driver(smbalert_driver);
258 
259 #if IS_ENABLED(CONFIG_I2C_SLAVE)
260 #define SMBUS_HOST_NOTIFY_LEN	3
261 struct i2c_slave_host_notify_status {
262 	u8 index;
263 	u8 addr;
264 };
265 
266 static int i2c_slave_host_notify_cb(struct i2c_client *client,
267 				    enum i2c_slave_event event, u8 *val)
268 {
269 	struct i2c_slave_host_notify_status *status = client->dev.platform_data;
270 
271 	switch (event) {
272 	case I2C_SLAVE_WRITE_RECEIVED:
273 		/* We only retrieve the first byte received (addr)
274 		 * since there is currently no support to retrieve the data
275 		 * parameter from the client.
276 		 */
277 		if (status->index == 0)
278 			status->addr = *val;
279 		if (status->index < U8_MAX)
280 			status->index++;
281 		break;
282 	case I2C_SLAVE_STOP:
283 		if (status->index == SMBUS_HOST_NOTIFY_LEN)
284 			i2c_handle_smbus_host_notify(client->adapter,
285 						     status->addr);
286 		fallthrough;
287 	case I2C_SLAVE_WRITE_REQUESTED:
288 		status->index = 0;
289 		break;
290 	case I2C_SLAVE_READ_REQUESTED:
291 	case I2C_SLAVE_READ_PROCESSED:
292 		*val = 0xff;
293 		break;
294 	}
295 
296 	return 0;
297 }
298 
299 /**
300  * i2c_new_slave_host_notify_device - get a client for SMBus host-notify support
301  * @adapter: the target adapter
302  * Context: can sleep
303  *
304  * Setup handling of the SMBus host-notify protocol on a given I2C bus segment.
305  *
306  * Handling is done by creating a device and its callback and handling data
307  * received via the SMBus host-notify address (0x8)
308  *
309  * This returns the client, which should be ultimately freed using
310  * i2c_free_slave_host_notify_device(); or an ERRPTR to indicate an error.
311  */
312 struct i2c_client *i2c_new_slave_host_notify_device(struct i2c_adapter *adapter)
313 {
314 	struct i2c_board_info host_notify_board_info = {
315 		I2C_BOARD_INFO("smbus_host_notify", 0x08),
316 		.flags  = I2C_CLIENT_SLAVE,
317 	};
318 	struct i2c_slave_host_notify_status *status;
319 	struct i2c_client *client;
320 	int ret;
321 
322 	status = kzalloc(sizeof(struct i2c_slave_host_notify_status),
323 			 GFP_KERNEL);
324 	if (!status)
325 		return ERR_PTR(-ENOMEM);
326 
327 	host_notify_board_info.platform_data = status;
328 
329 	client = i2c_new_client_device(adapter, &host_notify_board_info);
330 	if (IS_ERR(client)) {
331 		kfree(status);
332 		return client;
333 	}
334 
335 	ret = i2c_slave_register(client, i2c_slave_host_notify_cb);
336 	if (ret) {
337 		i2c_unregister_device(client);
338 		kfree(status);
339 		return ERR_PTR(ret);
340 	}
341 
342 	return client;
343 }
344 EXPORT_SYMBOL_GPL(i2c_new_slave_host_notify_device);
345 
346 /**
347  * i2c_free_slave_host_notify_device - free the client for SMBus host-notify
348  * support
349  * @client: the client to free
350  * Context: can sleep
351  *
352  * Free the i2c_client allocated via i2c_new_slave_host_notify_device
353  */
354 void i2c_free_slave_host_notify_device(struct i2c_client *client)
355 {
356 	if (IS_ERR_OR_NULL(client))
357 		return;
358 
359 	i2c_slave_unregister(client);
360 	kfree(client->dev.platform_data);
361 	i2c_unregister_device(client);
362 }
363 EXPORT_SYMBOL_GPL(i2c_free_slave_host_notify_device);
364 #endif
365 
366 /*
367  * SPD is not part of SMBus but we include it here for convenience as the
368  * target systems are the same.
369  * Restrictions to automatic SPD instantiation:
370  *  - Only works if all filled slots have the same memory type
371  *  - Only works for (LP)DDR memory types up to DDR5
372  *  - Only works on systems with 1 to 8 memory slots
373  */
374 #if IS_ENABLED(CONFIG_DMI)
375 static void i2c_register_spd(struct i2c_adapter *adap, bool write_disabled)
376 {
377 	int n, slot_count = 0, dimm_count = 0;
378 	u16 handle;
379 	u8 common_mem_type = 0x0, mem_type;
380 	u64 mem_size;
381 	bool instantiate = true;
382 	const char *name;
383 
384 	while ((handle = dmi_memdev_handle(slot_count)) != 0xffff) {
385 		slot_count++;
386 
387 		/* Skip empty slots */
388 		mem_size = dmi_memdev_size(handle);
389 		if (!mem_size)
390 			continue;
391 
392 		/* Skip undefined memory type */
393 		mem_type = dmi_memdev_type(handle);
394 		if (mem_type <= 0x02)		/* Invalid, Other, Unknown */
395 			continue;
396 
397 		if (!common_mem_type) {
398 			/* First filled slot */
399 			common_mem_type = mem_type;
400 		} else {
401 			/* Check that all filled slots have the same type */
402 			if (mem_type != common_mem_type) {
403 				dev_warn(&adap->dev,
404 					 "Different memory types mixed, not instantiating SPD\n");
405 				return;
406 			}
407 		}
408 		dimm_count++;
409 	}
410 
411 	/* No useful DMI data, bail out */
412 	if (!dimm_count)
413 		return;
414 
415 	/*
416 	 * The max number of SPD EEPROMs that can be addressed per bus is 8.
417 	 * If more slots are present either muxed or multiple busses are
418 	 * necessary or the additional slots are ignored.
419 	 */
420 	slot_count = min(slot_count, 8);
421 
422 	/*
423 	 * Memory types could be found at section 7.18.2 (Memory Device — Type), table 78
424 	 * https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.6.0.pdf
425 	 */
426 	switch (common_mem_type) {
427 	case 0x12:	/* DDR */
428 	case 0x13:	/* DDR2 */
429 	case 0x18:	/* DDR3 */
430 	case 0x1B:	/* LPDDR */
431 	case 0x1C:	/* LPDDR2 */
432 	case 0x1D:	/* LPDDR3 */
433 		name = "spd";
434 		break;
435 	case 0x1A:	/* DDR4 */
436 	case 0x1E:	/* LPDDR4 */
437 		name = "ee1004";
438 		break;
439 	case 0x22:	/* DDR5 */
440 	case 0x23:	/* LPDDR5 */
441 		name = "spd5118";
442 		instantiate = !write_disabled;
443 		break;
444 	default:
445 		dev_info(&adap->dev,
446 			 "Memory type 0x%02x not supported yet, not instantiating SPD\n",
447 			 common_mem_type);
448 		return;
449 	}
450 
451 	/*
452 	 * We don't know in which slots the memory modules are. We could
453 	 * try to guess from the slot names, but that would be rather complex
454 	 * and unreliable, so better probe all possible addresses until we
455 	 * have found all memory modules.
456 	 */
457 	for (n = 0; n < slot_count && dimm_count; n++) {
458 		struct i2c_board_info info;
459 		unsigned short addr_list[2];
460 
461 		memset(&info, 0, sizeof(struct i2c_board_info));
462 		strscpy(info.type, name, I2C_NAME_SIZE);
463 		addr_list[0] = 0x50 + n;
464 		addr_list[1] = I2C_CLIENT_END;
465 
466 		if (!instantiate)
467 			continue;
468 
469 		if (!IS_ERR(i2c_new_scanned_device(adap, &info, addr_list, NULL))) {
470 			dev_info(&adap->dev,
471 				 "Successfully instantiated SPD at 0x%hx\n",
472 				 addr_list[0]);
473 			dimm_count--;
474 		}
475 	}
476 }
477 
478 void i2c_register_spd_write_disable(struct i2c_adapter *adap)
479 {
480 	i2c_register_spd(adap, true);
481 }
482 EXPORT_SYMBOL_GPL(i2c_register_spd_write_disable);
483 
484 void i2c_register_spd_write_enable(struct i2c_adapter *adap)
485 {
486 	i2c_register_spd(adap, false);
487 }
488 EXPORT_SYMBOL_GPL(i2c_register_spd_write_enable);
489 
490 #endif
491 
492 MODULE_AUTHOR("Jean Delvare <jdelvare@suse.de>");
493 MODULE_DESCRIPTION("SMBus protocol extensions support");
494 MODULE_LICENSE("GPL");
495