xref: /freebsd/usr.sbin/i2c/i2c.c (revision 1f0a49e86350d036ee4d68dce934b7da3f8ba46e)
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 				error = -1;
146 				goto out;
147 			}
148 			index = skip_get_tokens(skip_addr, tokens,
149 			    len / 2 + 1);
150 		}
151 
152 		if (!no_range && (addr_range.start > addr_range.end)) {
153 			fprintf(stderr, "Skip address out of range\n");
154 			error = -1;
155 			goto out;
156 		}
157 	}
158 
159 	printf("Scanning I2C devices on %s: ", dev);
160 	for (i = 1; i < 127; i++) {
161 
162 		if (skip && ( addr_range.start < addr_range.end)) {
163 			if (i >= addr_range.start && i <= addr_range.end)
164 				continue;
165 
166 		} else if (skip && no_range)
167 			for (j = 0; j < index; j++) {
168 				if (tokens[j] == i) {
169 					do_skip = 1;
170 					break;
171 				}
172 			}
173 
174 		if (do_skip) {
175 			do_skip = 0;
176 			continue;
177 		}
178 
179 		cmd.slave = i << 1;
180 		cmd.last = 1;
181 		cmd.count = 0;
182 		error = ioctl(fd, I2CRSTCARD, &cmd);
183 		if (error)
184 			goto out;
185 
186 		cmd.slave = i << 1;
187 		cmd.last = 1;
188 		error = ioctl(fd, I2CSTART, &cmd);
189 		if (!error)
190 			printf("%x ", i);
191 		cmd.slave = i << 1;
192 		cmd.last = 1;
193 		error = ioctl(fd, I2CSTOP, &cmd);
194 	}
195 	printf("\n");
196 
197 	error = ioctl(fd, I2CRSTCARD, &cmd);
198 out:
199 	close(fd);
200 	if (skip && no_range)
201 		free(tokens);
202 
203 	if (error) {
204 		fprintf(stderr, "Error scanning I2C controller (%s): %s\n",
205 		    dev, strerror(errno));
206 		return (EX_NOINPUT);
207 	} else
208 		return (EX_OK);
209 }
210 
211 static int
212 reset_bus(struct iiccmd cmd, char *dev)
213 {
214 	int fd, error;
215 
216 	fd = open(dev, O_RDWR);
217 	if (fd == -1) {
218 		fprintf(stderr, "Error opening I2C controller (%s) for "
219 		    "resetting: %s\n", dev, strerror(errno));
220 		return (EX_NOINPUT);
221 	}
222 
223 	printf("Resetting I2C controller on %s: ", dev);
224 	error = ioctl(fd, I2CRSTCARD, &cmd);
225 	close (fd);
226 
227 	if (error) {
228 		printf("error: %s\n", strerror(errno));
229 		return (EX_IOERR);
230 	} else {
231 		printf("OK\n");
232 		return (EX_OK);
233 	}
234 }
235 
236 static char *
237 prepare_buf(int size, uint32_t off)
238 {
239 	char *buf;
240 
241 	buf = malloc(size);
242 	if (buf == NULL)
243 		return (buf);
244 
245 	if (size == 1)
246 		buf[0] = off & 0xff;
247 	else if (size == 2) {
248 		buf[0] = (off >> 8) & 0xff;
249 		buf[1] = off & 0xff;
250 	}
251 
252 	return (buf);
253 }
254 
255 static int
256 i2c_write(char *dev, struct options i2c_opt, char *i2c_buf)
257 {
258 	struct iiccmd cmd;
259 	int ch, i, error, fd, bufsize;
260 	char *err_msg, *buf;
261 
262 	/*
263 	 * Read data to be written to the chip from stdin
264 	 */
265 	if (i2c_opt.verbose && !i2c_opt.binary)
266 		fprintf(stderr, "Enter %u bytes of data: ", i2c_opt.count);
267 
268 	for (i = 0; i < i2c_opt.count; i++) {
269 		ch = getchar();
270 		if (ch == EOF) {
271 			free(i2c_buf);
272 			err(1, "not enough data, exiting\n");
273 		}
274 		i2c_buf[i] = ch;
275 	}
276 
277 	fd = open(dev, O_RDWR);
278 	if (fd == -1) {
279 		free(i2c_buf);
280 		err(1, "open failed");
281 	}
282 
283 	cmd.slave = i2c_opt.addr;
284 	error = ioctl(fd, I2CSTART, &cmd);
285 	if (error == -1) {
286 		err_msg = "ioctl: error sending start condition";
287 		goto err1;
288 	}
289 
290 	if (i2c_opt.width) {
291 		bufsize = i2c_opt.width / 8;
292 		buf = prepare_buf(bufsize, i2c_opt.off);
293 		if (buf == NULL) {
294 			err_msg = "error: offset malloc";
295 			goto err1;
296 		}
297 	} else
298 		bufsize = 0;
299 
300 	switch(i2c_opt.mode) {
301 	case I2C_MODE_STOP_START:
302 		/*
303 		 * Write offset where the data will go
304 		 */
305 		if (i2c_opt.width) {
306 			cmd.count = bufsize;
307 			cmd.buf = buf;
308 			error = ioctl(fd, I2CWRITE, &cmd);
309 			free(buf);
310 			if (error == -1) {
311 				err_msg = "ioctl: error when write offset";
312 				goto err1;
313 			}
314 		}
315 
316 		error = ioctl(fd, I2CSTOP, &cmd);
317 		if (error == -1) {
318 			err_msg = "ioctl: error sending stop condition";
319 			goto err2;
320 		}
321 		cmd.slave = i2c_opt.addr;
322 		error = ioctl(fd, I2CSTART, &cmd);
323 		if (error == -1) {
324 			err_msg = "ioctl: error sending start condition";
325 			goto err1;
326 		}
327 
328 		/*
329 		 * Write the data
330 		 */
331 		cmd.count = i2c_opt.count;
332 		cmd.buf = i2c_buf;
333 		cmd.last = 0;
334 		error = ioctl(fd, I2CWRITE, &cmd);
335 		if (error == -1) {
336 			err_msg = "ioctl: error when write";
337 			goto err1;
338 		}
339 		break;
340 
341 	case I2C_MODE_REPEATED_START:
342 		/*
343 		 * Write offset where the data will go
344 		 */
345 		if (i2c_opt.width) {
346 			cmd.count = bufsize;
347 			cmd.buf = buf;
348 			error = ioctl(fd, I2CWRITE, &cmd);
349 			free(buf);
350 			if (error == -1) {
351 				err_msg = "ioctl: error when write offset";
352 				goto err1;
353 			}
354 		}
355 
356 		cmd.slave = i2c_opt.addr;
357 		error = ioctl(fd, I2CRPTSTART, &cmd);
358 		if (error == -1) {
359 			err_msg = "ioctl: error sending repeated start "
360 			    "condition";
361 			goto err1;
362 		}
363 
364 		/*
365 		 * Write the data
366 		 */
367 		cmd.count = i2c_opt.count;
368 		cmd.buf = i2c_buf;
369 		cmd.last = 0;
370 		error = ioctl(fd, I2CWRITE, &cmd);
371 		if (error == -1) {
372 			err_msg = "ioctl: error when write";
373 			goto err1;
374 		}
375 		break;
376 
377 	case I2C_MODE_NONE: /* fall through */
378 	default:
379 		buf = realloc(buf, bufsize + i2c_opt.count);
380 		if (buf == NULL) {
381 			err_msg = "error: data malloc";
382 			goto err1;
383 		}
384 
385 		memcpy(buf + bufsize, i2c_buf, i2c_opt.count);
386 		/*
387 		 * Write offset and data
388 		 */
389 		cmd.count = bufsize + i2c_opt.count;
390 		cmd.buf = buf;
391 		cmd.last = 0;
392 		error = ioctl(fd, I2CWRITE, &cmd);
393 		free(buf);
394 		if (error == -1) {
395 			err_msg = "ioctl: error when write";
396 			goto err1;
397 		}
398 		break;
399 	}
400 	cmd.slave = i2c_opt.addr;
401 	error = ioctl(fd, I2CSTOP, &cmd);
402 	if (error == -1) {
403 		err_msg = "ioctl: error sending stop condition";
404 		goto err2;
405 	}
406 
407 	close(fd);
408 	return (0);
409 
410 err1:
411 	cmd.slave = i2c_opt.addr;
412 	error = ioctl(fd, I2CSTOP, &cmd);
413 	if (error == -1)
414 		fprintf(stderr, "error sending stop condtion\n");
415 err2:
416 	if (err_msg)
417 		fprintf(stderr, "%s", err_msg);
418 
419 	close(fd);
420 	return (1);
421 }
422 
423 static int
424 i2c_read(char *dev, struct options i2c_opt, char *i2c_buf)
425 {
426 	struct iiccmd cmd;
427 	int i, fd, error, bufsize;
428 	char *err_msg, data = 0, *buf;
429 
430 	fd = open(dev, O_RDWR);
431 	if (fd == -1)
432 		err(1, "open failed");
433 
434 	bzero(&cmd, sizeof(cmd));
435 
436 	if (i2c_opt.width) {
437 		cmd.slave = i2c_opt.addr;
438 		cmd.count = 1;
439 		cmd.last = 0;
440 		cmd.buf = &data;
441 		error = ioctl(fd, I2CSTART, &cmd);
442 		if (error == -1) {
443 			err_msg = "ioctl: error sending start condition";
444 			goto err1;
445 		}
446 		bufsize = i2c_opt.width / 8;
447 		buf = prepare_buf(bufsize, i2c_opt.off);
448 		if (buf == NULL) {
449 			err_msg = "error: offset malloc";
450 			goto err1;
451 		}
452 
453 		cmd.count = bufsize;
454 		cmd.buf = buf;
455 		cmd.last = 0;
456 		error = ioctl(fd, I2CWRITE, &cmd);
457 		free(buf);
458 		if (error == -1) {
459 			err_msg = "ioctl: error when write offset";
460 			goto err1;
461 		}
462 
463 		if (i2c_opt.mode == I2C_MODE_STOP_START) {
464 			cmd.slave = i2c_opt.addr;
465 			error = ioctl(fd, I2CSTOP, &cmd);
466 			if (error == -1) {
467 				err_msg = "error sending stop condtion\n";
468 				goto err2;
469 			}
470 		}
471 	}
472 	cmd.slave = i2c_opt.addr;
473 	cmd.count = 1;
474 	cmd.last = 0;
475 	cmd.buf = &data;
476 	if (i2c_opt.mode == I2C_MODE_STOP_START) {
477 		error = ioctl(fd, I2CSTART, &cmd);
478 		if (error == -1) {
479 			err_msg = "ioctl: error sending start condition";
480 			goto err1;
481 		}
482 	} else if (i2c_opt.mode == I2C_MODE_REPEATED_START) {
483 		error = ioctl(fd, I2CRPTSTART, &cmd);
484 		if (error == -1) {
485 			err_msg = "ioctl: error sending repeated start "
486 			    "condition";
487 			goto err1;
488 		}
489 	}
490 	error = ioctl(fd, I2CSTOP, &cmd);
491 	if (error == -1) {
492 		err_msg = "error sending stop condtion\n";
493 		goto err2;
494 	}
495 
496 	for (i = 0; i < i2c_opt.count; i++) {
497 		error = read(fd, &i2c_buf[i], 1);
498 		if (error == -1) {
499 			err_msg = "ioctl: error while reading";
500 			goto err1;
501 		}
502 	}
503 
504 	close(fd);
505 	return (0);
506 
507 err1:
508 	cmd.slave = i2c_opt.addr;
509 	error = ioctl(fd, I2CSTOP, &cmd);
510 	if (error == -1)
511 		fprintf(stderr, "error sending stop condtion\n");
512 err2:
513 	if (err_msg)
514 		fprintf(stderr, "%s", err_msg);
515 
516 	close(fd);
517 	return (1);
518 }
519 
520 int
521 main(int argc, char** argv)
522 {
523 	struct iiccmd cmd;
524 	struct options i2c_opt;
525 	char *dev, *skip_addr, *i2c_buf;
526 	int error, chunk_size, i, j, ch;
527 
528 	errno = 0;
529 	error = 0;
530 
531 	/* Line-break the output every chunk_size bytes */
532 	chunk_size = 16;
533 
534 	dev = I2C_DEV;
535 
536 	/* Default values */
537 	i2c_opt.addr_set = 0;
538 	i2c_opt.off = 0;
539 	i2c_opt.verbose = 0;
540 	i2c_opt.dir = 'r';	/* direction = read */
541 	i2c_opt.width = 8;
542 	i2c_opt.count = 1;
543 	i2c_opt.binary = 0;	/* ASCII text output */
544 	i2c_opt.scan = 0;	/* no bus scan */
545 	i2c_opt.skip = 0;	/* scan all addresses */
546 	i2c_opt.reset = 0;	/* no bus reset */
547 	i2c_opt.mode = I2C_MODE_NOTSET;
548 
549 	while ((ch = getopt(argc, argv, "a:f:d:o:w:c:m:n:sbvrh")) != -1) {
550 		switch(ch) {
551 		case 'a':
552 			i2c_opt.addr = (strtoul(optarg, 0, 16) << 1);
553 			if (i2c_opt.addr == 0 && errno == EINVAL)
554 				i2c_opt.addr_set = 0;
555 			else
556 				i2c_opt.addr_set = 1;
557 			break;
558 		case 'f':
559 			dev = optarg;
560 			break;
561 		case 'd':
562 			i2c_opt.dir = optarg[0];
563 			break;
564 		case 'o':
565 			i2c_opt.off = strtoul(optarg, 0, 16);
566 			if (i2c_opt.off == 0 && errno == EINVAL)
567 				error = 1;
568 			break;
569 		case 'w':
570 			i2c_opt.width = atoi(optarg);
571 			break;
572 		case 'c':
573 			i2c_opt.count = atoi(optarg);
574 			break;
575 		case 'm':
576 			if (!strcmp(optarg, "no"))
577 				i2c_opt.mode = I2C_MODE_NONE;
578 			else if (!strcmp(optarg, "ss"))
579 				i2c_opt.mode = I2C_MODE_STOP_START;
580 			else if (!strcmp(optarg, "rs"))
581 				i2c_opt.mode = I2C_MODE_REPEATED_START;
582 			else
583 				usage();
584 			break;
585 		case 'n':
586 			i2c_opt.skip = 1;
587 			skip_addr = optarg;
588 			break;
589 		case 's':
590 			i2c_opt.scan = 1;
591 			break;
592 		case 'b':
593 			i2c_opt.binary = 1;
594 			break;
595 		case 'v':
596 			i2c_opt.verbose = 1;
597 			break;
598 		case 'r':
599 			i2c_opt.reset = 1;
600 			break;
601 		case 'h':
602 		default:
603 			usage();
604 		}
605 	}
606 	argc -= optind;
607 	argv += optind;
608 
609 	/* Set default mode if option -m is not specified */
610 	if (i2c_opt.mode == I2C_MODE_NOTSET) {
611 		if (i2c_opt.dir == 'r')
612 			i2c_opt.mode = I2C_MODE_STOP_START;
613 		else if (i2c_opt.dir == 'w')
614 			i2c_opt.mode = I2C_MODE_NONE;
615 	}
616 
617 	/* Basic sanity check of command line arguments */
618 	if (i2c_opt.scan) {
619 		if (i2c_opt.addr_set)
620 			usage();
621 	} else if (i2c_opt.reset) {
622 		if (i2c_opt.addr_set)
623 			usage();
624 	} else if (error) {
625 		usage();
626 	} else if ((i2c_opt.dir == 'r' || i2c_opt.dir == 'w')) {
627 		if ((i2c_opt.addr_set == 0) ||
628 		    !(i2c_opt.width == 0 || i2c_opt.width == 8 ||
629 		    i2c_opt.width == 16))
630 		usage();
631 	}
632 
633 	if (i2c_opt.verbose)
634 		fprintf(stderr, "dev: %s, addr: 0x%x, r/w: %c, "
635 		    "offset: 0x%02x, width: %u, count: %u\n", dev,
636 		    i2c_opt.addr >> 1, i2c_opt.dir, i2c_opt.off,
637 		    i2c_opt.width, i2c_opt.count);
638 
639 	if (i2c_opt.scan)
640 		exit(scan_bus(cmd, dev, i2c_opt.skip, skip_addr));
641 
642 	if (i2c_opt.reset)
643 		exit(reset_bus(cmd, dev));
644 
645 	i2c_buf = malloc(i2c_opt.count);
646 	if (i2c_buf == NULL)
647 		err(1, "data malloc");
648 
649 	if (i2c_opt.dir == 'w') {
650 		error = i2c_write(dev, i2c_opt, i2c_buf);
651 		if (error) {
652 			free(i2c_buf);
653 			return (1);
654 		}
655 	}
656 	if (i2c_opt.dir == 'r') {
657 		error = i2c_read(dev, i2c_opt, i2c_buf);
658 		if (error) {
659 			free(i2c_buf);
660 			return (1);
661 		}
662 	}
663 
664 	if (i2c_opt.verbose)
665 		fprintf(stderr, "\nData %s (hex):\n", i2c_opt.dir == 'r' ?
666 		    "read" : "written");
667 
668 	i = 0;
669 	j = 0;
670 	while (i < i2c_opt.count) {
671 		if (i2c_opt.verbose || (i2c_opt.dir == 'r' &&
672 		    !i2c_opt.binary))
673 			fprintf (stderr, "%02hhx ", i2c_buf[i++]);
674 
675 		if (i2c_opt.dir == 'r' && i2c_opt.binary) {
676 			fprintf(stdout, "%c", i2c_buf[j++]);
677 			if(!i2c_opt.verbose)
678 				i++;
679 		}
680 		if (!i2c_opt.verbose && (i2c_opt.dir == 'w'))
681 			break;
682 		if ((i % chunk_size) == 0)
683 			fprintf(stderr, "\n");
684 	}
685 	if ((i % chunk_size) != 0)
686 		fprintf(stderr, "\n");
687 
688 	free(i2c_buf);
689 	return (0);
690 }
691