xref: /freebsd/usr.sbin/i2c/i2c.c (revision 830940567b49bb0c08dfaed40418999e76616909)
1 /*-
2  * Copyright (C) 2008-2009 Semihalf, Michal Hajduk and Bartlomiej Sieka
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <err.h>
31 #include <errno.h>
32 #include <sysexits.h>
33 #include <fcntl.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <stdarg.h>
38 #include <unistd.h>
39 #include <sys/ioctl.h>
40 
41 #include <dev/iicbus/iic.h>
42 
43 #define	I2C_DEV			"/dev/iic0"
44 #define	I2C_MODE_NOTSET		0
45 #define	I2C_MODE_NONE		1
46 #define	I2C_MODE_STOP_START	2
47 #define	I2C_MODE_REPEATED_START	3
48 
49 struct options {
50 	int	width;
51 	int	count;
52 	int	verbose;
53 	int	addr_set;
54 	int	binary;
55 	int	scan;
56 	int	skip;
57 	int	reset;
58 	int	mode;
59 	char	dir;
60 	uint32_t	addr;
61 	uint32_t	off;
62 };
63 
64 struct skip_range {
65 	int	start;
66 	int	end;
67 };
68 
69 __dead2 static void
70 usage(void)
71 {
72 
73 	fprintf(stderr, "usage: %s -a addr [-f device] [-d [r|w]] [-o offset] "
74 	    "[-w [0|8|16]] [-c count] [-m [ss|rs|no]] [-b] [-v]\n",
75 	    getprogname());
76 	fprintf(stderr, "       %s -s [-f device] [-n skip_addr] -v\n",
77 	    getprogname());
78 	fprintf(stderr, "       %s -r [-f device] -v\n", getprogname());
79 	exit(EX_USAGE);
80 }
81 
82 static struct skip_range
83 skip_get_range(char *skip_addr)
84 {
85 	struct skip_range addr_range;
86 	char *token;
87 
88 	addr_range.start = 0;
89 	addr_range.end = 0;
90 
91 	token = strsep(&skip_addr, "..");
92 	if (token) {
93 		addr_range.start = strtoul(token, 0, 16);
94 		token = strsep(&skip_addr, "..");
95 		if ((token != NULL) && !atoi(token)) {
96 			token = strsep(&skip_addr, "..");
97 			if (token)
98 				addr_range.end = strtoul(token, 0, 16);
99 		}
100 	}
101 
102 	return (addr_range);
103 }
104 
105 /* Parse the string to get hex 7 bits addresses */
106 static int
107 skip_get_tokens(char *skip_addr, int *sk_addr, int max_index)
108 {
109 	char *token;
110 	int i;
111 
112 	for (i = 0; i < max_index; i++) {
113 		token = strsep(&skip_addr, ":");
114 		if (token == NULL)
115 			break;
116 		sk_addr[i] = strtoul(token, 0, 16);
117 	}
118 	return (i);
119 }
120 
121 static int
122 scan_bus(struct iiccmd cmd, char *dev, int skip, char *skip_addr)
123 {
124 	struct skip_range addr_range = { 0, 0 };
125 	int *tokens, fd, error, i, index, j;
126 	int len = 0, do_skip = 0, no_range = 1;
127 
128 	fd = open(dev, O_RDWR);
129 	if (fd == -1) {
130 		fprintf(stderr, "Error opening I2C controller (%s) for "
131 		    "scanning: %s\n", dev, strerror(errno));
132 		return (EX_NOINPUT);
133 	}
134 
135 	if (skip) {
136 		len = strlen(skip_addr);
137 		if (strstr(skip_addr, "..") != NULL) {
138 			addr_range = skip_get_range(skip_addr);
139 			no_range = 0;
140 		} else {
141 			tokens = (int *)malloc((len / 2 + 1) * sizeof(int));
142 			if (tokens == NULL) {
143 				fprintf(stderr, "Error allocating tokens "
144 				    "buffer\n");
145 				goto out;
146 			}
147 			index = skip_get_tokens(skip_addr, tokens,
148 			    len / 2 + 1);
149 		}
150 
151 		if (!no_range && (addr_range.start > addr_range.end)) {
152 			fprintf(stderr, "Skip address out of range\n");
153 			goto out;
154 		}
155 	}
156 
157 	printf("Scanning I2C devices on %s: ", dev);
158 	for (i = 1; i < 127; i++) {
159 
160 		if (skip && ( addr_range.start < addr_range.end)) {
161 			if (i >= addr_range.start && i <= addr_range.end)
162 				continue;
163 
164 		} else if (skip && no_range)
165 			for (j = 0; j < index; j++) {
166 				if (tokens[j] == i) {
167 					do_skip = 1;
168 					break;
169 				}
170 			}
171 
172 		if (do_skip) {
173 			do_skip = 0;
174 			continue;
175 		}
176 
177 		cmd.slave = i << 1;
178 		cmd.last = 1;
179 		cmd.count = 0;
180 		error = ioctl(fd, I2CRSTCARD, &cmd);
181 		if (error)
182 			goto out;
183 
184 		cmd.slave = i << 1;
185 		cmd.last = 1;
186 		error = ioctl(fd, I2CSTART, &cmd);
187 		if (!error)
188 			printf("%x ", i);
189 		cmd.slave = i << 1;
190 		cmd.last = 1;
191 		error = ioctl(fd, I2CSTOP, &cmd);
192 	}
193 	printf("\n");
194 
195 	error = ioctl(fd, I2CRSTCARD, &cmd);
196 out:
197 	close(fd);
198 	if (skip && no_range)
199 		free(tokens);
200 
201 	if (error) {
202 		fprintf(stderr, "Error scanning I2C controller (%s): %s\n",
203 		    dev, strerror(errno));
204 		return (EX_NOINPUT);
205 	} else
206 		return (EX_OK);
207 }
208 
209 static int
210 reset_bus(struct iiccmd cmd, char *dev)
211 {
212 	int fd, error;
213 
214 	fd = open(dev, O_RDWR);
215 	if (fd == -1) {
216 		fprintf(stderr, "Error opening I2C controller (%s) for "
217 		    "resetting: %s\n", dev, strerror(errno));
218 		return (EX_NOINPUT);
219 	}
220 
221 	printf("Resetting I2C controller on %s: ", dev);
222 	error = ioctl(fd, I2CRSTCARD, &cmd);
223 	close (fd);
224 
225 	if (error) {
226 		printf("error: %s\n", strerror(errno));
227 		return (EX_IOERR);
228 	} else {
229 		printf("OK\n");
230 		return (EX_OK);
231 	}
232 }
233 
234 static char *
235 prepare_buf(int size, uint32_t off)
236 {
237 	char *buf;
238 
239 	buf = malloc(size);
240 	if (buf == NULL)
241 		return (buf);
242 
243 	if (size == 1)
244 		buf[0] = off & 0xff;
245 	else if (size == 2) {
246 		buf[0] = (off >> 8) & 0xff;
247 		buf[1] = off & 0xff;
248 	}
249 
250 	return (buf);
251 }
252 
253 static int
254 i2c_write(char *dev, struct options i2c_opt, char *i2c_buf)
255 {
256 	struct iiccmd cmd;
257 	int ch, i, error, fd, bufsize;
258 	char *err_msg, *buf;
259 
260 	/*
261 	 * Read data to be written to the chip from stdin
262 	 */
263 	if (i2c_opt.verbose && !i2c_opt.binary)
264 		fprintf(stderr, "Enter %u bytes of data: ", i2c_opt.count);
265 
266 	for (i = 0; i < i2c_opt.count; i++) {
267 		ch = getchar();
268 		if (ch == EOF) {
269 			free(i2c_buf);
270 			err(1, "not enough data, exiting\n");
271 		}
272 		i2c_buf[i] = ch;
273 	}
274 
275 	fd = open(dev, O_RDWR);
276 	if (fd == -1) {
277 		free(i2c_buf);
278 		err(1, "open failed");
279 	}
280 
281 	/*
282 	 * Write offset where the data will go
283 	 */
284 	cmd.slave = i2c_opt.addr;
285 	error = ioctl(fd, I2CSTART, &cmd);
286 	if (error == -1) {
287 		err_msg = "ioctl: error sending start condition";
288 		goto err1;
289 	}
290 
291 	if (i2c_opt.width) {
292 		bufsize = i2c_opt.width / 8;
293 		buf = prepare_buf(bufsize, i2c_opt.off);
294 		if (buf == NULL) {
295 			err_msg = "error: offset malloc";
296 			goto err1;
297 		}
298 
299 		cmd.count = bufsize;
300 		cmd.buf = buf;
301 		error = ioctl(fd, I2CWRITE, &cmd);
302 		free(buf);
303 		if (error == -1) {
304 			err_msg = "ioctl: error when write offset";
305 			goto err1;
306 		}
307 	}
308 
309 	/* Mode - stop start */
310 	if (i2c_opt.mode == I2C_MODE_STOP_START) {
311 		cmd.slave = i2c_opt.addr;
312 		error = ioctl(fd, I2CSTOP, &cmd);
313 		if (error == -1) {
314 			err_msg = "ioctl: error sending stop condition";
315 			goto err2;
316 		}
317 		cmd.slave = i2c_opt.addr;
318 		error = ioctl(fd, I2CSTART, &cmd);
319 		if (error == -1) {
320 			err_msg = "ioctl: error sending start condition";
321 			goto err1;
322 		}
323 	}
324 	/* Mode - repeated start */
325 	if (i2c_opt.mode == I2C_MODE_REPEATED_START) {
326 		cmd.slave = i2c_opt.addr;
327 		error = ioctl(fd, I2CRPTSTART, &cmd);
328 		if (error == -1) {
329 			err_msg = "ioctl: error sending repeated start "
330 			    "condition";
331 			goto err1;
332 		}
333 	}
334 
335 	/*
336 	 * Write the data
337 	 */
338 	cmd.count = i2c_opt.count;
339 	cmd.buf = i2c_buf;
340 	cmd.last = 0;
341 	error = ioctl(fd, I2CWRITE, &cmd);
342 	if (error == -1) {
343 		err_msg = "ioctl: error when write";
344 		goto err1;
345 	}
346 	cmd.slave = i2c_opt.addr;
347 	error = ioctl(fd, I2CSTOP, &cmd);
348 	if (error == -1) {
349 		err_msg = "ioctl: error sending stop condition";
350 		goto err2;
351 	}
352 
353 	close(fd);
354 	return (0);
355 
356 err1:
357 	cmd.slave = i2c_opt.addr;
358 	error = ioctl(fd, I2CSTOP, &cmd);
359 	if (error == -1)
360 		fprintf(stderr, "error sending stop condtion\n");
361 err2:
362 	if (err_msg)
363 		fprintf(stderr, err_msg);
364 
365 	close(fd);
366 	return (1);
367 }
368 
369 static int
370 i2c_read(char *dev, struct options i2c_opt, char *i2c_buf)
371 {
372 	struct iiccmd cmd;
373 	int i, fd, error, bufsize;
374 	char *err_msg, data = 0, *buf;
375 
376 	fd = open(dev, O_RDWR);
377 	if (fd == -1)
378 		err(1, "open failed");
379 
380 	bzero(&cmd, sizeof(cmd));
381 
382 	if (i2c_opt.width) {
383 		cmd.slave = i2c_opt.addr;
384 		cmd.count = 1;
385 		cmd.last = 0;
386 		cmd.buf = &data;
387 		error = ioctl(fd, I2CSTART, &cmd);
388 		if (error == -1) {
389 			err_msg = "ioctl: error sending start condition";
390 			goto err1;
391 		}
392 		bufsize = i2c_opt.width / 8;
393 		buf = prepare_buf(bufsize, i2c_opt.off);
394 		if (buf == NULL) {
395 			err_msg = "error: offset malloc";
396 			goto err1;
397 		}
398 
399 		cmd.count = bufsize;
400 		cmd.buf = buf;
401 		cmd.last = 0;
402 		error = ioctl(fd, I2CWRITE, &cmd);
403 		free(buf);
404 		if (error == -1) {
405 			err_msg = "ioctl: error when write offset";
406 			goto err1;
407 		}
408 
409 		if (i2c_opt.mode == I2C_MODE_STOP_START) {
410 			cmd.slave = i2c_opt.addr;
411 			error = ioctl(fd, I2CSTOP, &cmd);
412 			if (error == -1)
413 				goto err2;
414 		}
415 	}
416 	cmd.slave = i2c_opt.addr;
417 	cmd.count = 1;
418 	cmd.last = 0;
419 	cmd.buf = &data;
420 	if (i2c_opt.mode == I2C_MODE_STOP_START) {
421 		error = ioctl(fd, I2CSTART, &cmd);
422 		if (error == -1) {
423 			err_msg = "ioctl: error sending start condition";
424 			goto err1;
425 		}
426 	} else if (i2c_opt.mode == I2C_MODE_REPEATED_START) {
427 		error = ioctl(fd, I2CRPTSTART, &cmd);
428 		if (error == -1) {
429 			err_msg = "ioctl: error sending repeated start "
430 			    "condition";
431 			goto err1;
432 		}
433 	}
434 	error = ioctl(fd, I2CSTOP, &cmd);
435 	if (error == -1)
436 		goto err2;
437 
438 	for (i = 0; i < i2c_opt.count; i++) {
439 		error = read(fd, &i2c_buf[i], 1);
440 		if (error == -1) {
441 			err_msg = "ioctl: error while reading";
442 			goto err1;
443 		}
444 	}
445 
446 	close(fd);
447 	return (0);
448 
449 err1:
450 	cmd.slave = i2c_opt.addr;
451 	error = ioctl(fd, I2CSTOP, &cmd);
452 	if (error == -1)
453 		fprintf(stderr, "error sending stop condtion\n");
454 err2:
455 	if (err_msg)
456 		fprintf(stderr, err_msg);
457 
458 	close(fd);
459 	return (1);
460 }
461 
462 int
463 main(int argc, char** argv)
464 {
465 	struct iiccmd cmd;
466 	struct options i2c_opt;
467 	char *dev, *skip_addr, *err_msg, *i2c_buf;
468 	int error, chunk_size, i, j, ch;
469 
470 	errno = 0;
471 	error = 0;
472 
473 	/* Line-break the output every chunk_size bytes */
474 	chunk_size = 16;
475 
476 	dev = I2C_DEV;
477 	err_msg = NULL;
478 
479 	/* Default values */
480 	i2c_opt.addr_set = 0;
481 	i2c_opt.off = 0;
482 	i2c_opt.verbose = 0;
483 	i2c_opt.dir = 'r';	/* direction = read */
484 	i2c_opt.width = 8;
485 	i2c_opt.count = 1;
486 	i2c_opt.binary = 0;	/* ASCII text output */
487 	i2c_opt.scan = 0;	/* no bus scan */
488 	i2c_opt.skip = 0;	/* scan all addresses */
489 	i2c_opt.reset = 0;	/* no bus reset */
490 	i2c_opt.mode = I2C_MODE_NOTSET;
491 
492 	while ((ch = getopt(argc, argv, "a:f:d:o:w:c:m:n:sbvrh")) != -1) {
493 		switch(ch) {
494 		case 'a':
495 			i2c_opt.addr = (strtoul(optarg, 0, 16) << 1);
496 			if (i2c_opt.addr == 0 && errno == EINVAL)
497 				i2c_opt.addr_set = 0;
498 			else
499 				i2c_opt.addr_set = 1;
500 			break;
501 		case 'f':
502 			dev = optarg;
503 			break;
504 		case 'd':
505 			i2c_opt.dir = optarg[0];
506 			break;
507 		case 'o':
508 			i2c_opt.off = strtoul(optarg, 0, 16);
509 			if (i2c_opt.off == 0 && errno == EINVAL)
510 				error = 1;
511 			break;
512 		case 'w':
513 			i2c_opt.width = atoi(optarg);
514 			break;
515 		case 'c':
516 			i2c_opt.count = atoi(optarg);
517 			break;
518 		case 'm':
519 			if (!strcmp(optarg, "no"))
520 				i2c_opt.mode = I2C_MODE_NONE;
521 			else if (!strcmp(optarg, "ss"))
522 				i2c_opt.mode = I2C_MODE_STOP_START;
523 			else if (!strcmp(optarg, "rs"))
524 				i2c_opt.mode = I2C_MODE_REPEATED_START;
525 			else
526 				usage();
527 			break;
528 		case 'n':
529 			i2c_opt.skip = 1;
530 			skip_addr = optarg;
531 			break;
532 		case 's':
533 			i2c_opt.scan = 1;
534 			break;
535 		case 'b':
536 			i2c_opt.binary = 1;
537 			break;
538 		case 'v':
539 			i2c_opt.verbose = 1;
540 			break;
541 		case 'r':
542 			i2c_opt.reset = 1;
543 			break;
544 		case 'h':
545 		default:
546 			usage();
547 		}
548 	}
549 	argc -= optind;
550 	argv += optind;
551 
552 	/* Set default mode if option -m is not specified */
553 	if (i2c_opt.mode == I2C_MODE_NOTSET) {
554 		if (i2c_opt.dir == 'r')
555 			i2c_opt.mode = I2C_MODE_STOP_START;
556 		else if (i2c_opt.dir == 'w')
557 			i2c_opt.mode = I2C_MODE_NONE;
558 	}
559 
560 	/* Basic sanity check of command line arguments */
561 	if (i2c_opt.scan) {
562 		if (i2c_opt.addr_set)
563 			usage();
564 	} else if (i2c_opt.reset) {
565 		if (i2c_opt.addr_set)
566 			usage();
567 	} else if (error) {
568 		usage();
569 	} else if ((i2c_opt.dir == 'r' || i2c_opt.dir == 'w')) {
570 		if ((i2c_opt.addr_set == 0) ||
571 		    !(i2c_opt.width == 0 || i2c_opt.width == 8 ||
572 		    i2c_opt.width == 16))
573 		usage();
574 	}
575 
576 	if (i2c_opt.verbose)
577 		fprintf(stderr, "dev: %s, addr: 0x%x, r/w: %c, "
578 		    "offset: 0x%02x, width: %u, count: %u\n", dev,
579 		    i2c_opt.addr >> 1, i2c_opt.dir, i2c_opt.off,
580 		    i2c_opt.width, i2c_opt.count);
581 
582 	if (i2c_opt.scan)
583 		exit(scan_bus(cmd, dev, i2c_opt.skip, skip_addr));
584 
585 	if (i2c_opt.reset)
586 		exit(reset_bus(cmd, dev));
587 
588 	i2c_buf = malloc(i2c_opt.count);
589 	if (i2c_buf == NULL)
590 		err(1, "data malloc");
591 
592 	if (i2c_opt.dir == 'w') {
593 		error = i2c_write(dev, i2c_opt, i2c_buf);
594 		if (error) {
595 			free(i2c_buf);
596 			return (1);
597 		}
598 	}
599 	if (i2c_opt.dir == 'r') {
600 		error = i2c_read(dev, i2c_opt, i2c_buf);
601 		if (error) {
602 			free(i2c_buf);
603 			return (1);
604 		}
605 	}
606 
607 	if (i2c_opt.verbose)
608 		fprintf(stderr, "\nData %s (hex):\n", i2c_opt.dir == 'r' ?
609 		    "read" : "written");
610 
611 	i = 0;
612 	j = 0;
613 	while (i < i2c_opt.count) {
614 		if (i2c_opt.verbose || (i2c_opt.dir == 'r' &&
615 		    !i2c_opt.binary))
616 			fprintf (stderr, "%02hhx ", i2c_buf[i++]);
617 
618 		if (i2c_opt.dir == 'r' && i2c_opt.binary) {
619 			fprintf(stdout, "%c", i2c_buf[j++]);
620 			if(!i2c_opt.verbose)
621 				i++;
622 		}
623 		if (!i2c_opt.verbose && (i2c_opt.dir == 'w'))
624 			break;
625 		if ((i % chunk_size) == 0)
626 			fprintf(stderr, "\n");
627 	}
628 	if ((i % chunk_size) != 0)
629 		fprintf(stderr, "\n");
630 
631 	free(i2c_buf);
632 	return (0);
633 }
634