2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (C) 2008-2009 Semihalf, Michal Hajduk and Bartlomiej Sieka
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
42 #include <sys/endian.h>
43 #include <sys/ioctl.h>
45 #include <dev/iicbus/iic.h>
47 #define I2C_DEV "/dev/iic0"
48 #define I2C_MODE_NOTSET 0
49 #define I2C_MODE_NONE 1
50 #define I2C_MODE_STOP_START 2
51 #define I2C_MODE_REPEATED_START 3
52 #define I2C_MODE_TRANSFER 4
69 static int fd_cache[N_FDCACHE];
72 usage(const char *msg)
76 fprintf(stderr, "%s\n", msg);
77 fprintf(stderr, "usage: %s -a addr [-f device] [-d [r|w]] [-o offset] "
78 "[-w [0|8|16|16LE|16BE]] [-c count] [-m [tr|ss|rs|no]] [-b] [-v]\n",
80 fprintf(stderr, " %s -s [-f device] [-n skip_addr] -v\n",
82 fprintf(stderr, " %s -r [-f device] -v\n", getprogname());
91 i = ioctl(fd, I2CSTOP);
93 fprintf(stderr, "ioctl: error sending stop condition: %s\n",
99 i2c_do_start(int fd, struct iiccmd *cmd)
103 i = ioctl(fd, I2CSTART, cmd);
105 fprintf(stderr, "ioctl: error sending start condition: %s\n",
111 i2c_do_repeatstart(int fd, struct iiccmd *cmd)
115 i = ioctl(fd, I2CRPTSTART, cmd);
117 fprintf(stderr, "ioctl: error sending repeated start: %s\n",
123 i2c_do_write(int fd, struct iiccmd *cmd)
127 i = ioctl(fd, I2CWRITE, cmd);
129 fprintf(stderr, "ioctl: error writing: %s\n",
135 i2c_do_read(int fd, struct iiccmd *cmd)
139 i = ioctl(fd, I2CREAD, cmd);
141 fprintf(stderr, "ioctl: error reading: %s\n",
152 memset(&cmd, 0, sizeof cmd);
153 i = ioctl(fd, I2CRSTCARD, &cmd);
155 fprintf(stderr, "ioctl: error resetting controller: %s\n",
161 parse_skip(const char *skip, char blacklist[128])
166 for (p = skip; *p != '\0';) {
167 if (*p == '0' && p[1] == 'x')
170 usage("Bad -n argument, expected (first) hex-digit");
171 x = digittoint(*p++) << 4;
173 usage("Bad -n argument, expected (second) hex-digit");
174 x |= digittoint(*p++);
175 if (x == 0 || x > 0x7f)
176 usage("Bad -n argument, (01..7f)");
177 if (*p == ':' || *p == ',' || *p == '\0') {
185 } else if (*p == '.' && p[1] == '.') {
188 usage("Bad -n argument, ([:|,|..|-])");
190 if (*p == '0' && p[1] == 'x')
193 usage("Bad -n argument, expected (first) hex-digit");
194 y = digittoint(*p++) << 4;
196 usage("Bad -n argument, expected (second) hex-digit");
197 y |= digittoint(*p++);
198 if (y == 0 || y > 0x7f)
199 usage("Bad -n argument, (01..7f)");
201 usage("Bad -n argument, (end < start)");
204 if (*p == ':' || *p == ',')
210 scan_bus(const char *dev, int fd, const char *skip, int verbose)
213 struct iic_msg rdmsg;
214 struct iic_rdwr_data rdwrdata;
217 int num_found = 0, use_read_xfer;
220 const char *sep = "";
222 memset(blacklist, 0, sizeof blacklist);
225 parse_skip(skip, blacklist);
227 for (use_read_xfer = 0; use_read_xfer < 2; use_read_xfer++) {
228 for (u = 1; u < 127; u++) {
235 if (i2c_do_reset(fd))
241 rdmsg.flags = IIC_M_RD;
242 rdmsg.slave = u << 1;
243 rdwrdata.msgs = &rdmsg;
245 error = ioctl(fd, I2CRDWR, &rdwrdata);
247 error = ioctl(fd, I2CSTART, &cmd);
248 if (errno == ENODEV || errno == EOPNOTSUPP)
249 break; /* Try reads instead */
250 (void)ioctl(fd, I2CSTOP);
253 if (!num_found++ && verbose) {
255 "Scanning I2C devices on %s:\n",
258 printf("%s%02x", sep, u);
264 if (verbose && !use_read_xfer)
266 "Hardware may not support START/STOP scanning; "
267 "trying less-reliable read method.\n");
269 if (num_found == 0 && verbose)
270 printf("<Nothing Found>");
274 return (i2c_do_reset(fd));
278 reset_bus(const char *dev, int fd, int verbose)
282 fprintf(stderr, "Resetting I2C controller on %s\n", dev);
283 return (i2c_do_reset(fd));
287 encode_offset(const char *width, unsigned offset, uint8_t *dst, size_t *len)
290 if (!strcmp(width, "0")) {
294 if (!strcmp(width, "8")) {
296 return ("Invalid 8-bit offset\n");
302 return ("Invalid 16-bit offset\n");
303 if (!strcmp(width, "16LE") || !strcmp(width, "16")) {
304 le16enc(dst, offset);
308 if (!strcmp(width, "16BE")) {
309 be16enc(dst, offset);
313 return ("Invalid offset width, must be: 0|8|16|16LE|16BE\n");
317 write_offset(int fd, struct options i2c_opt, struct iiccmd *cmd)
320 if (i2c_opt.off_len > 0) {
321 cmd->count = i2c_opt.off_len;
322 cmd->buf = (void*)i2c_opt.off_buf;
323 return (i2c_do_write(fd, cmd));
329 i2c_write(int fd, struct options i2c_opt, uint8_t *i2c_buf)
332 char buf[i2c_opt.off_len + i2c_opt.count];
334 memset(&cmd, 0, sizeof(cmd));
335 cmd.slave = i2c_opt.addr;
337 if (i2c_do_start(fd, &cmd))
338 return (i2c_do_stop(fd) | 1);
340 switch(i2c_opt.mode) {
341 case I2C_MODE_STOP_START:
342 if (write_offset(fd, i2c_opt, &cmd))
343 return (i2c_do_stop(fd) | 1);
348 if (i2c_do_start(fd, &cmd))
349 return (i2c_do_stop(fd) | 1);
354 cmd.count = i2c_opt.count;
355 cmd.buf = (void*)i2c_buf;
357 if (i2c_do_write(fd, &cmd))
358 return (i2c_do_stop(fd) | 1);
361 case I2C_MODE_REPEATED_START:
362 if (write_offset(fd, i2c_opt, &cmd))
363 return (i2c_do_stop(fd) | 1);
365 if (i2c_do_repeatstart(fd, &cmd))
366 return (i2c_do_stop(fd) | 1);
371 cmd.count = i2c_opt.count;
372 cmd.buf = (void*)i2c_buf;
374 if (i2c_do_write(fd, &cmd))
375 return (i2c_do_stop(fd) | 1);
378 case I2C_MODE_NONE: /* fall through */
380 memcpy(buf, i2c_opt.off_buf, i2c_opt.off_len);
381 memcpy(buf + i2c_opt.off_len, i2c_buf, i2c_opt.count);
383 * Write offset and data
385 cmd.count = i2c_opt.off_len + i2c_opt.count;
386 cmd.buf = (void*)buf;
388 if (i2c_do_write(fd, &cmd))
389 return (i2c_do_stop(fd) | 1);
393 return (i2c_do_stop(fd));
397 i2c_read(int fd, struct options i2c_opt, uint8_t *i2c_buf)
402 memset(&cmd, 0, sizeof(cmd));
403 cmd.slave = i2c_opt.addr;
405 if (i2c_opt.off_len) {
409 if (i2c_do_start(fd, &cmd))
410 return (i2c_do_stop(fd) | 1);
412 if (write_offset(fd, i2c_opt, &cmd))
413 return (i2c_do_stop(fd) | 1);
415 if (i2c_opt.mode == I2C_MODE_STOP_START && i2c_do_stop(fd))
418 cmd.slave = i2c_opt.addr | 1;
422 if (i2c_opt.mode == I2C_MODE_STOP_START || i2c_opt.off_len == 0) {
423 if (i2c_do_start(fd, &cmd))
424 return (i2c_do_stop(fd) | 1);
425 } else if (i2c_opt.mode == I2C_MODE_REPEATED_START) {
426 if (i2c_do_repeatstart(fd, &cmd))
427 return (i2c_do_stop(fd) | 1);
430 cmd.count = i2c_opt.count;
431 cmd.buf = (void*)i2c_buf;
433 if (i2c_do_read(fd, &cmd))
434 return (i2c_do_stop(fd) | 1);
436 return (i2c_do_stop(fd));
440 * i2c_rdwr_transfer() - use I2CRDWR to conduct a complete i2c transfer.
442 * Some i2c hardware is unable to provide direct control over START, REPEAT-
443 * START, and STOP operations. Such hardware can only perform a complete
444 * START-<data>-STOP or START-<data>-REPEAT-START-<data>-STOP sequence as a
445 * single operation. The driver framework refers to this sequence as a
446 * "transfer" so we call it "transfer mode". We assemble either one or two
447 * iic_msg structures to describe the IO operations, and hand them off to the
448 * driver to be handled as a single transfer.
451 i2c_rdwr_transfer(int fd, struct options i2c_opt, uint8_t *i2c_buf)
453 struct iic_msg msgs[2], *msgp = msgs;
454 struct iic_rdwr_data xfer;
457 if (i2c_opt.off_len) {
458 msgp->flags = IIC_M_WR | IIC_M_NOSTOP;
459 msgp->slave = i2c_opt.addr;
460 msgp->buf = i2c_opt.off_buf;
461 msgp->len = i2c_opt.off_len;
463 flag = IIC_M_NOSTART;
467 * If the transfer direction is write and we did a write of the offset
468 * above, then we need to elide the start; this transfer is just more
469 * writing that follows the one started above. For a read, we always do
470 * a start; if we did an offset write above it'll be a repeat-start
471 * because of the NOSTOP flag used above.
473 if (i2c_opt.dir == 'w')
474 msgp->flags = IIC_M_WR | flag;
476 msgp->flags = IIC_M_RD;
477 msgp->slave = i2c_opt.addr;
478 msgp->len = i2c_opt.count;
483 xfer.nmsgs = msgp - msgs;
485 if (ioctl(fd, I2CRDWR, &xfer) == -1 )
486 err(1, "ioctl(I2CRDWR) failed");
492 access_bus(int fd, struct options i2c_opt)
494 uint8_t i2c_buf[i2c_opt.count];
496 unsigned u, chunk_size = 16;
499 * For a write, read the data to be written to the chip from stdin.
501 if (i2c_opt.dir == 'w') {
502 if (i2c_opt.verbose && !i2c_opt.binary)
503 fprintf(stderr, "Enter %u bytes of data: ",
505 if (fread(i2c_buf, 1, i2c_opt.count, stdin) != i2c_opt.count)
506 err(1, "not enough data, exiting\n");
509 if (i2c_opt.mode == I2C_MODE_TRANSFER)
510 error = i2c_rdwr_transfer(fd, i2c_opt, i2c_buf);
511 else if (i2c_opt.dir == 'w')
512 error = i2c_write(fd, i2c_opt, i2c_buf);
514 error = i2c_read(fd, i2c_opt, i2c_buf);
517 if (i2c_opt.dir == 'r' && i2c_opt.binary) {
518 (void)fwrite(i2c_buf, 1, i2c_opt.count, stdout);
519 } else if (i2c_opt.verbose || i2c_opt.dir == 'r') {
521 fprintf(stderr, "\nData %s (hex):\n",
522 i2c_opt.dir == 'r' ? "read" : "written");
524 for (u = 0; u < i2c_opt.count; u++) {
525 printf("%02hhx ", i2c_buf[u]);
526 if ((u % chunk_size) == chunk_size - 1)
529 if ((u % chunk_size) != 0)
537 static const char *widths[] = {
547 command_bus(struct options i2c_opt, char *cmd)
551 uint8_t dbuf[BUFSIZ];
553 const char *width = NULL;
559 while (isspace(*cmd))
580 "Did not understand command: 0x%02x ", *cmd);
582 fprintf(stderr, "'%c'", *cmd);
583 fprintf(stderr, "\n");
588 bus = strtoul(cmd, &cmd, 0);
589 if (bus == 0 && errno == EINVAL) {
590 fprintf(stderr, "Could not translate bus number\n");
594 i2c_opt.addr = strtoul(cmd, &cmd, 0);
595 if (i2c_opt.addr == 0 && errno == EINVAL) {
596 fprintf(stderr, "Could not translate device\n");
599 if (i2c_opt.addr < 1 || i2c_opt.addr > 0x7f) {
600 fprintf(stderr, "Invalid device (0x%x)\n", i2c_opt.addr);
608 for(u = 0; widths[u]; u++) {
609 length = strlen(widths[u]);
610 if (memcmp(cmd, widths[u], length))
612 if (!isspace(cmd[length]))
619 fprintf(stderr, "Invalid width\n");
623 offset = strtoul(cmd, &cmd, 0);
624 if (offset == 0 && errno == EINVAL) {
625 fprintf(stderr, "Could not translate offset\n");
629 err_msg = encode_offset(width, offset,
630 i2c_opt.off_buf, &i2c_opt.off_len);
632 fprintf(stderr, "%s", err_msg);
636 if (i2c_opt.dir == 'r') {
637 i2c_opt.count = strtoul(cmd, &cmd, 0);
638 if (i2c_opt.count == 0 && errno == EINVAL) {
639 fprintf(stderr, "Could not translate length\n");
649 if (!isxdigit(*cmd)) {
650 fprintf(stderr, "Not a hex digit.\n");
653 dbuf[i2c_opt.count] = digittoint(*cmd++) << 4;
658 "Uneven number of hex digits.\n");
661 if (!isxdigit(*cmd)) {
662 fprintf(stderr, "Not a hex digit.\n");
665 dbuf[i2c_opt.count++] |= digittoint(*cmd++);
668 assert(bus < N_FDCACHE);
671 (void)sprintf(devbuf, "/dev/iic%u", bus);
672 fd = open(devbuf, O_RDWR);
674 fprintf(stderr, "Error opening I2C controller (%s): %s\n",
675 devbuf, strerror(errno));
681 error = i2c_rdwr_transfer(fd, i2c_opt, dbuf);
685 if (i2c_opt.dir == 'r') {
686 for (u = 0; u < i2c_opt.count; u++)
687 printf("%02x", dbuf[u]);
694 exec_bus(struct options i2c_opt, char *cmd)
698 while (isspace(*cmd))
700 if (*cmd == '#' || *cmd == '\0')
702 error = command_bus(i2c_opt, cmd);
703 if (i2c_opt.verbose) {
704 (void)fflush(stderr);
705 printf(error ? "ERROR\n" : "OK\n");
708 fprintf(stderr, " in: %s", cmd);
710 (void)fflush(stdout);
715 instruct_bus(struct options i2c_opt, int argc, char **argv)
718 int rd_cmds = (argc == 0);
722 if (argc == 0 && !strcmp(*argv, "-")) {
725 error = exec_bus(i2c_opt, *argv);
733 while (fgets(buf, sizeof buf, stdin) != NULL) {
734 error = exec_bus(i2c_opt, buf);
742 main(int argc, char** argv)
744 struct options i2c_opt;
745 const char *dev, *err_msg;
746 int fd, error = 0, ch;
747 const char *optflags = "a:f:d:o:iw:c:m:n:sbvrh";
751 for (ch = 0; ch < N_FDCACHE; ch++)
757 i2c_opt.dir = 'r'; /* direction = read */
760 i2c_opt.binary = 0; /* ASCII text output */
761 i2c_opt.skip = NULL; /* scan all addresses */
762 i2c_opt.mode = I2C_MODE_TRANSFER;
764 /* Find out what we are going to do */
766 while ((ch = getopt(argc, argv, optflags)) != -1) {
773 usage("Only one of [-a|-h|-r|-s]");
784 /* Then handle the legal subset of arguments */
787 case 0: usage("Pick one of [-a|-h|-i|-r|-s]"); break;
788 case 'a': optflags = "a:f:d:w:o:c:m:bv"; break;
789 case 'i': optflags = "iv"; break;
790 case 'r': optflags = "rf:v"; break;
791 case 's': optflags = "sf:n:v"; break;
792 default: assert("Bad do_what");
798 while ((ch = getopt(argc, argv, optflags)) != -1) {
801 i2c_opt.addr = strtoul(optarg, 0, 16);
802 if (i2c_opt.addr == 0 && errno == EINVAL)
803 usage("Bad -a argument (hex)");
804 if (i2c_opt.addr == 0 || i2c_opt.addr > 0x7f)
805 usage("Bad -a argument (01..7f)");
812 i2c_opt.count = (strtoul(optarg, 0, 10));
813 if (i2c_opt.count == 0 && errno == EINVAL)
814 usage("Bad -c argument (decimal)");
817 if (strcmp(optarg, "r") && strcmp(optarg, "w"))
818 usage("Bad -d argument ([r|w])");
819 i2c_opt.dir = optarg[0];
826 if (!strcmp(optarg, "no"))
827 i2c_opt.mode = I2C_MODE_NONE;
828 else if (!strcmp(optarg, "ss"))
829 i2c_opt.mode = I2C_MODE_STOP_START;
830 else if (!strcmp(optarg, "rs"))
831 i2c_opt.mode = I2C_MODE_REPEATED_START;
832 else if (!strcmp(optarg, "tr"))
833 i2c_opt.mode = I2C_MODE_TRANSFER;
835 usage("Bad -m argument ([no|ss|rs|tr])");
838 i2c_opt.skip = optarg;
841 i2c_opt.off = strtoul(optarg, 0, 16);
842 if (i2c_opt.off == 0 && errno == EINVAL)
843 usage("Bad -o argument (hex)");
851 i2c_opt.width = optarg; // checked later.
854 fprintf(stderr, "Illegal -%c option", ch);
861 return(instruct_bus(i2c_opt, argc, argv));
863 usage("Too many arguments");
865 /* Set default mode if option -m is not specified */
866 if (i2c_opt.mode == I2C_MODE_NOTSET) {
867 if (i2c_opt.dir == 'r')
868 i2c_opt.mode = I2C_MODE_STOP_START;
869 else if (i2c_opt.dir == 'w')
870 i2c_opt.mode = I2C_MODE_NONE;
873 err_msg = encode_offset(i2c_opt.width, i2c_opt.off,
874 i2c_opt.off_buf, &i2c_opt.off_len);
875 if (err_msg != NULL) {
876 fprintf(stderr, "%s", err_msg);
881 fprintf(stderr, "dev: %s, addr: 0x%x, r/w: %c, "
882 "offset: 0x%02x, width: %s, count: %u\n", dev,
883 i2c_opt.addr >> 1, i2c_opt.dir, i2c_opt.off,
884 i2c_opt.width, i2c_opt.count);
886 fd = open(dev, O_RDWR);
888 fprintf(stderr, "Error opening I2C controller (%s): %s\n",
889 dev, strerror(errno));
895 error = access_bus(fd, i2c_opt);
898 error = scan_bus(dev, fd, i2c_opt.skip, i2c_opt.verbose);
901 error = reset_bus(dev, fd, i2c_opt.verbose);
904 assert("Bad do_what");