1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Driver for the Diolan u2c-12 USB-I2C adapter
4  *
5  * Copyright (c) 2010-2011 Ericsson AB
6  *
7  * Derived from:
8  *  i2c-tiny-usb.c
9  *  Copyright (C) 2006-2007 Till Harbaum (Till@Harbaum.org)
10  */
11 
12 #include <linux/kernel.h>
13 #include <linux/errno.h>
14 #include <linux/module.h>
15 #include <linux/types.h>
16 #include <linux/slab.h>
17 #include <linux/usb.h>
18 #include <linux/i2c.h>
19 
20 #define DRIVER_NAME		"i2c-diolan-u2c"
21 
22 #define USB_VENDOR_ID_DIOLAN		0x0abf
23 #define USB_DEVICE_ID_DIOLAN_U2C	0x3370
24 
25 
26 /* commands via USB, must match command ids in the firmware */
27 #define CMD_I2C_READ		0x01
28 #define CMD_I2C_WRITE		0x02
29 #define CMD_I2C_SCAN		0x03	/* Returns list of detected devices */
30 #define CMD_I2C_RELEASE_SDA	0x04
31 #define CMD_I2C_RELEASE_SCL	0x05
32 #define CMD_I2C_DROP_SDA	0x06
33 #define CMD_I2C_DROP_SCL	0x07
34 #define CMD_I2C_READ_SDA	0x08
35 #define CMD_I2C_READ_SCL	0x09
36 #define CMD_GET_FW_VERSION	0x0a
37 #define CMD_GET_SERIAL		0x0b
38 #define CMD_I2C_START		0x0c
39 #define CMD_I2C_STOP		0x0d
40 #define CMD_I2C_REPEATED_START	0x0e
41 #define CMD_I2C_PUT_BYTE	0x0f
42 #define CMD_I2C_GET_BYTE	0x10
43 #define CMD_I2C_PUT_ACK		0x11
44 #define CMD_I2C_GET_ACK		0x12
45 #define CMD_I2C_PUT_BYTE_ACK	0x13
46 #define CMD_I2C_GET_BYTE_ACK	0x14
47 #define CMD_I2C_SET_SPEED	0x1b
48 #define CMD_I2C_GET_SPEED	0x1c
49 #define CMD_I2C_SET_CLK_SYNC	0x24
50 #define CMD_I2C_GET_CLK_SYNC	0x25
51 #define CMD_I2C_SET_CLK_SYNC_TO	0x26
52 #define CMD_I2C_GET_CLK_SYNC_TO	0x27
53 
54 #define RESP_OK			0x00
55 #define RESP_FAILED		0x01
56 #define RESP_BAD_MEMADDR	0x04
57 #define RESP_DATA_ERR		0x05
58 #define RESP_NOT_IMPLEMENTED	0x06
59 #define RESP_NACK		0x07
60 #define RESP_TIMEOUT		0x09
61 
62 #define U2C_I2C_SPEED_FAST	0	/* 400 kHz */
63 #define U2C_I2C_SPEED_STD	1	/* 100 kHz */
64 #define U2C_I2C_SPEED_2KHZ	242	/* 2 kHz, minimum speed */
65 #define U2C_I2C_SPEED(f)	((DIV_ROUND_UP(1000000, (f)) - 10) / 2 + 1)
66 
67 #define U2C_I2C_FREQ_FAST	400000
68 #define U2C_I2C_FREQ_STD	100000
69 #define U2C_I2C_FREQ(s)		(1000000 / (2 * (s - 1) + 10))
70 
71 #define DIOLAN_USB_TIMEOUT	100	/* in ms */
72 #define DIOLAN_SYNC_TIMEOUT	20	/* in ms */
73 
74 #define DIOLAN_OUTBUF_LEN	128
75 #define DIOLAN_FLUSH_LEN	(DIOLAN_OUTBUF_LEN - 4)
76 #define DIOLAN_INBUF_LEN	256	/* Maximum supported receive length */
77 
78 /* Structure to hold all of our device specific stuff */
79 struct i2c_diolan_u2c {
80 	u8 obuffer[DIOLAN_OUTBUF_LEN];	/* output buffer */
81 	u8 ibuffer[DIOLAN_INBUF_LEN];	/* input buffer */
82 	int ep_in, ep_out;              /* Endpoints    */
83 	struct usb_device *usb_dev;	/* the usb device for this device */
84 	struct usb_interface *interface;/* the interface for this device */
85 	struct i2c_adapter adapter;	/* i2c related things */
86 	int olen;			/* Output buffer length */
87 	int ocount;			/* Number of enqueued messages */
88 };
89 
90 static uint frequency = U2C_I2C_FREQ_STD;	/* I2C clock frequency in Hz */
91 
92 module_param(frequency, uint, S_IRUGO | S_IWUSR);
93 MODULE_PARM_DESC(frequency, "I2C clock frequency in hertz");
94 
95 /* usb layer */
96 
97 /* Send command to device, and get response. */
98 static int diolan_usb_transfer(struct i2c_diolan_u2c *dev)
99 {
100 	int ret = 0;
101 	int actual;
102 	int i;
103 
104 	if (!dev->olen || !dev->ocount)
105 		return -EINVAL;
106 
107 	ret = usb_bulk_msg(dev->usb_dev,
108 			   usb_sndbulkpipe(dev->usb_dev, dev->ep_out),
109 			   dev->obuffer, dev->olen, &actual,
110 			   DIOLAN_USB_TIMEOUT);
111 	if (!ret) {
112 		for (i = 0; i < dev->ocount; i++) {
113 			int tmpret;
114 
115 			tmpret = usb_bulk_msg(dev->usb_dev,
116 					      usb_rcvbulkpipe(dev->usb_dev,
117 							      dev->ep_in),
118 					      dev->ibuffer,
119 					      sizeof(dev->ibuffer), &actual,
120 					      DIOLAN_USB_TIMEOUT);
121 			/*
122 			 * Stop command processing if a previous command
123 			 * returned an error.
124 			 * Note that we still need to retrieve all messages.
125 			 */
126 			if (ret < 0)
127 				continue;
128 			ret = tmpret;
129 			if (ret == 0 && actual > 0) {
130 				switch (dev->ibuffer[actual - 1]) {
131 				case RESP_NACK:
132 					/*
133 					 * Return ENXIO if NACK was received as
134 					 * response to the address phase,
135 					 * EIO otherwise
136 					 */
137 					ret = i == 1 ? -ENXIO : -EIO;
138 					break;
139 				case RESP_TIMEOUT:
140 					ret = -ETIMEDOUT;
141 					break;
142 				case RESP_OK:
143 					/* strip off return code */
144 					ret = actual - 1;
145 					break;
146 				default:
147 					ret = -EIO;
148 					break;
149 				}
150 			}
151 		}
152 	}
153 	dev->olen = 0;
154 	dev->ocount = 0;
155 	return ret;
156 }
157 
158 static int diolan_write_cmd(struct i2c_diolan_u2c *dev, bool flush)
159 {
160 	if (flush || dev->olen >= DIOLAN_FLUSH_LEN)
161 		return diolan_usb_transfer(dev);
162 	return 0;
163 }
164 
165 /* Send command (no data) */
166 static int diolan_usb_cmd(struct i2c_diolan_u2c *dev, u8 command, bool flush)
167 {
168 	dev->obuffer[dev->olen++] = command;
169 	dev->ocount++;
170 	return diolan_write_cmd(dev, flush);
171 }
172 
173 /* Send command with one byte of data */
174 static int diolan_usb_cmd_data(struct i2c_diolan_u2c *dev, u8 command, u8 data,
175 			       bool flush)
176 {
177 	dev->obuffer[dev->olen++] = command;
178 	dev->obuffer[dev->olen++] = data;
179 	dev->ocount++;
180 	return diolan_write_cmd(dev, flush);
181 }
182 
183 /* Send command with two bytes of data */
184 static int diolan_usb_cmd_data2(struct i2c_diolan_u2c *dev, u8 command, u8 d1,
185 				u8 d2, bool flush)
186 {
187 	dev->obuffer[dev->olen++] = command;
188 	dev->obuffer[dev->olen++] = d1;
189 	dev->obuffer[dev->olen++] = d2;
190 	dev->ocount++;
191 	return diolan_write_cmd(dev, flush);
192 }
193 
194 /*
195  * Flush input queue.
196  * If we don't do this at startup and the controller has queued up
197  * messages which were not retrieved, it will stop responding
198  * at some point.
199  */
200 static void diolan_flush_input(struct i2c_diolan_u2c *dev)
201 {
202 	int i;
203 
204 	for (i = 0; i < 10; i++) {
205 		int actual = 0;
206 		int ret;
207 
208 		ret = usb_bulk_msg(dev->usb_dev,
209 				   usb_rcvbulkpipe(dev->usb_dev, dev->ep_in),
210 				   dev->ibuffer, sizeof(dev->ibuffer), &actual,
211 				   DIOLAN_USB_TIMEOUT);
212 		if (ret < 0 || actual == 0)
213 			break;
214 	}
215 	if (i == 10)
216 		dev_err(&dev->interface->dev, "Failed to flush input buffer\n");
217 }
218 
219 static int diolan_i2c_start(struct i2c_diolan_u2c *dev)
220 {
221 	return diolan_usb_cmd(dev, CMD_I2C_START, false);
222 }
223 
224 static int diolan_i2c_repeated_start(struct i2c_diolan_u2c *dev)
225 {
226 	return diolan_usb_cmd(dev, CMD_I2C_REPEATED_START, false);
227 }
228 
229 static int diolan_i2c_stop(struct i2c_diolan_u2c *dev)
230 {
231 	return diolan_usb_cmd(dev, CMD_I2C_STOP, true);
232 }
233 
234 static int diolan_i2c_get_byte_ack(struct i2c_diolan_u2c *dev, bool ack,
235 				   u8 *byte)
236 {
237 	int ret;
238 
239 	ret = diolan_usb_cmd_data(dev, CMD_I2C_GET_BYTE_ACK, ack, true);
240 	if (ret > 0)
241 		*byte = dev->ibuffer[0];
242 	else if (ret == 0)
243 		ret = -EIO;
244 
245 	return ret;
246 }
247 
248 static int diolan_i2c_put_byte_ack(struct i2c_diolan_u2c *dev, u8 byte)
249 {
250 	return diolan_usb_cmd_data(dev, CMD_I2C_PUT_BYTE_ACK, byte, false);
251 }
252 
253 static int diolan_set_speed(struct i2c_diolan_u2c *dev, u8 speed)
254 {
255 	return diolan_usb_cmd_data(dev, CMD_I2C_SET_SPEED, speed, true);
256 }
257 
258 /* Enable or disable clock synchronization (stretching) */
259 static int diolan_set_clock_synch(struct i2c_diolan_u2c *dev, bool enable)
260 {
261 	return diolan_usb_cmd_data(dev, CMD_I2C_SET_CLK_SYNC, enable, true);
262 }
263 
264 /* Set clock synchronization timeout in ms */
265 static int diolan_set_clock_synch_timeout(struct i2c_diolan_u2c *dev, int ms)
266 {
267 	int to_val = ms * 10;
268 
269 	return diolan_usb_cmd_data2(dev, CMD_I2C_SET_CLK_SYNC_TO,
270 				    to_val & 0xff, (to_val >> 8) & 0xff, true);
271 }
272 
273 static void diolan_fw_version(struct i2c_diolan_u2c *dev)
274 {
275 	int ret;
276 
277 	ret = diolan_usb_cmd(dev, CMD_GET_FW_VERSION, true);
278 	if (ret >= 2)
279 		dev_info(&dev->interface->dev,
280 			 "Diolan U2C firmware version %u.%u\n",
281 			 (unsigned int)dev->ibuffer[0],
282 			 (unsigned int)dev->ibuffer[1]);
283 }
284 
285 static void diolan_get_serial(struct i2c_diolan_u2c *dev)
286 {
287 	int ret;
288 	u32 serial;
289 
290 	ret = diolan_usb_cmd(dev, CMD_GET_SERIAL, true);
291 	if (ret >= 4) {
292 		serial = le32_to_cpu(*(u32 *)dev->ibuffer);
293 		dev_info(&dev->interface->dev,
294 			 "Diolan U2C serial number %u\n", serial);
295 	}
296 }
297 
298 static int diolan_init(struct i2c_diolan_u2c *dev)
299 {
300 	int speed, ret;
301 
302 	if (frequency >= 200000) {
303 		speed = U2C_I2C_SPEED_FAST;
304 		frequency = U2C_I2C_FREQ_FAST;
305 	} else if (frequency >= 100000 || frequency == 0) {
306 		speed = U2C_I2C_SPEED_STD;
307 		frequency = U2C_I2C_FREQ_STD;
308 	} else {
309 		speed = U2C_I2C_SPEED(frequency);
310 		if (speed > U2C_I2C_SPEED_2KHZ)
311 			speed = U2C_I2C_SPEED_2KHZ;
312 		frequency = U2C_I2C_FREQ(speed);
313 	}
314 
315 	dev_info(&dev->interface->dev,
316 		 "Diolan U2C at USB bus %03d address %03d speed %d Hz\n",
317 		 dev->usb_dev->bus->busnum, dev->usb_dev->devnum, frequency);
318 
319 	diolan_flush_input(dev);
320 	diolan_fw_version(dev);
321 	diolan_get_serial(dev);
322 
323 	/* Set I2C speed */
324 	ret = diolan_set_speed(dev, speed);
325 	if (ret < 0)
326 		return ret;
327 
328 	/* Configure I2C clock synchronization */
329 	ret = diolan_set_clock_synch(dev, speed != U2C_I2C_SPEED_FAST);
330 	if (ret < 0)
331 		return ret;
332 
333 	if (speed != U2C_I2C_SPEED_FAST)
334 		ret = diolan_set_clock_synch_timeout(dev, DIOLAN_SYNC_TIMEOUT);
335 
336 	return ret;
337 }
338 
339 /* i2c layer */
340 
341 static int diolan_usb_xfer(struct i2c_adapter *adapter, struct i2c_msg *msgs,
342 			   int num)
343 {
344 	struct i2c_diolan_u2c *dev = i2c_get_adapdata(adapter);
345 	struct i2c_msg *pmsg;
346 	int i, j;
347 	int ret, sret;
348 
349 	ret = diolan_i2c_start(dev);
350 	if (ret < 0)
351 		return ret;
352 
353 	for (i = 0; i < num; i++) {
354 		pmsg = &msgs[i];
355 		if (i) {
356 			ret = diolan_i2c_repeated_start(dev);
357 			if (ret < 0)
358 				goto abort;
359 		}
360 		ret = diolan_i2c_put_byte_ack(dev,
361 					      i2c_8bit_addr_from_msg(pmsg));
362 		if (ret < 0)
363 			goto abort;
364 		if (pmsg->flags & I2C_M_RD) {
365 			for (j = 0; j < pmsg->len; j++) {
366 				u8 byte;
367 				bool ack = j < pmsg->len - 1;
368 
369 				/*
370 				 * Don't send NACK if this is the first byte
371 				 * of a SMBUS_BLOCK message.
372 				 */
373 				if (j == 0 && (pmsg->flags & I2C_M_RECV_LEN))
374 					ack = true;
375 
376 				ret = diolan_i2c_get_byte_ack(dev, ack, &byte);
377 				if (ret < 0)
378 					goto abort;
379 				/*
380 				 * Adjust count if first received byte is length
381 				 */
382 				if (j == 0 && (pmsg->flags & I2C_M_RECV_LEN)) {
383 					if (byte == 0
384 					    || byte > I2C_SMBUS_BLOCK_MAX) {
385 						ret = -EPROTO;
386 						goto abort;
387 					}
388 					pmsg->len += byte;
389 				}
390 				pmsg->buf[j] = byte;
391 			}
392 		} else {
393 			for (j = 0; j < pmsg->len; j++) {
394 				ret = diolan_i2c_put_byte_ack(dev,
395 							      pmsg->buf[j]);
396 				if (ret < 0)
397 					goto abort;
398 			}
399 		}
400 	}
401 	ret = num;
402 abort:
403 	sret = diolan_i2c_stop(dev);
404 	if (sret < 0 && ret >= 0)
405 		ret = sret;
406 	return ret;
407 }
408 
409 /*
410  * Return list of supported functionality.
411  */
412 static u32 diolan_usb_func(struct i2c_adapter *a)
413 {
414 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
415 	       I2C_FUNC_SMBUS_READ_BLOCK_DATA | I2C_FUNC_SMBUS_BLOCK_PROC_CALL;
416 }
417 
418 static const struct i2c_algorithm diolan_usb_algorithm = {
419 	.master_xfer = diolan_usb_xfer,
420 	.functionality = diolan_usb_func,
421 };
422 
423 /* device layer */
424 
425 static const struct usb_device_id diolan_u2c_table[] = {
426 	{ USB_DEVICE(USB_VENDOR_ID_DIOLAN, USB_DEVICE_ID_DIOLAN_U2C) },
427 	{ }
428 };
429 
430 MODULE_DEVICE_TABLE(usb, diolan_u2c_table);
431 
432 static void diolan_u2c_free(struct i2c_diolan_u2c *dev)
433 {
434 	usb_put_dev(dev->usb_dev);
435 	kfree(dev);
436 }
437 
438 static int diolan_u2c_probe(struct usb_interface *interface,
439 			    const struct usb_device_id *id)
440 {
441 	struct usb_host_interface *hostif = interface->cur_altsetting;
442 	struct i2c_diolan_u2c *dev;
443 	int ret;
444 
445 	if (hostif->desc.bInterfaceNumber != 0
446 	    || hostif->desc.bNumEndpoints < 2)
447 		return -ENODEV;
448 
449 	/* allocate memory for our device state and initialize it */
450 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
451 	if (dev == NULL) {
452 		ret = -ENOMEM;
453 		goto error;
454 	}
455 	dev->ep_out = hostif->endpoint[0].desc.bEndpointAddress;
456 	dev->ep_in = hostif->endpoint[1].desc.bEndpointAddress;
457 
458 	dev->usb_dev = usb_get_dev(interface_to_usbdev(interface));
459 	dev->interface = interface;
460 
461 	/* save our data pointer in this interface device */
462 	usb_set_intfdata(interface, dev);
463 
464 	/* setup i2c adapter description */
465 	dev->adapter.owner = THIS_MODULE;
466 	dev->adapter.class = I2C_CLASS_HWMON;
467 	dev->adapter.algo = &diolan_usb_algorithm;
468 	i2c_set_adapdata(&dev->adapter, dev);
469 	snprintf(dev->adapter.name, sizeof(dev->adapter.name),
470 		 DRIVER_NAME " at bus %03d device %03d",
471 		 dev->usb_dev->bus->busnum, dev->usb_dev->devnum);
472 
473 	dev->adapter.dev.parent = &dev->interface->dev;
474 
475 	/* initialize diolan i2c interface */
476 	ret = diolan_init(dev);
477 	if (ret < 0) {
478 		dev_err(&interface->dev, "failed to initialize adapter\n");
479 		goto error_free;
480 	}
481 
482 	/* and finally attach to i2c layer */
483 	ret = i2c_add_adapter(&dev->adapter);
484 	if (ret < 0)
485 		goto error_free;
486 
487 	dev_dbg(&interface->dev, "connected " DRIVER_NAME "\n");
488 
489 	return 0;
490 
491 error_free:
492 	usb_set_intfdata(interface, NULL);
493 	diolan_u2c_free(dev);
494 error:
495 	return ret;
496 }
497 
498 static void diolan_u2c_disconnect(struct usb_interface *interface)
499 {
500 	struct i2c_diolan_u2c *dev = usb_get_intfdata(interface);
501 
502 	i2c_del_adapter(&dev->adapter);
503 	usb_set_intfdata(interface, NULL);
504 	diolan_u2c_free(dev);
505 
506 	dev_dbg(&interface->dev, "disconnected\n");
507 }
508 
509 static struct usb_driver diolan_u2c_driver = {
510 	.name = DRIVER_NAME,
511 	.probe = diolan_u2c_probe,
512 	.disconnect = diolan_u2c_disconnect,
513 	.id_table = diolan_u2c_table,
514 };
515 
516 module_usb_driver(diolan_u2c_driver);
517 
518 MODULE_AUTHOR("Guenter Roeck <linux@roeck-us.net>");
519 MODULE_DESCRIPTION(DRIVER_NAME " driver");
520 MODULE_LICENSE("GPL");
521