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