i2c_tools: suppress "'blen' may be used uninitialized in this function"
[oweals/busybox.git] / miscutils / i2c_tools.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Minimal i2c-tools implementation for busybox.
4  * Parts of code ported from i2c-tools:
5  *              http://www.lm-sensors.org/wiki/I2CTools.
6  *
7  * Copyright (C) 2014 by Bartosz Golaszewski <bartekgola@gmail.com>
8  *
9  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
10  */
11
12 //config:config I2CGET
13 //config:       bool "i2cget"
14 //config:       default y
15 //config:       select PLATFORM_LINUX
16 //config:       help
17 //config:         Read from I2C/SMBus chip registers.
18 //config:
19 //config:config I2CSET
20 //config:       bool "i2cset"
21 //config:       default y
22 //config:       select PLATFORM_LINUX
23 //config:       help
24 //config:         Set I2C registers.
25 //config:
26 //config:config I2CDUMP
27 //config:       bool "i2cdump"
28 //config:       default y
29 //config:       select PLATFORM_LINUX
30 //config:       help
31 //config:         Examine I2C registers.
32 //config:
33 //config:config I2CDETECT
34 //config:       bool "i2cdetect"
35 //config:       default y
36 //config:       select PLATFORM_LINUX
37 //config:       help
38 //config:         Detect I2C chips.
39 //config:
40
41 //applet:IF_I2CGET(APPLET(i2cget, BB_DIR_USR_SBIN, BB_SUID_DROP))
42 //applet:IF_I2CSET(APPLET(i2cset, BB_DIR_USR_SBIN, BB_SUID_DROP))
43 //applet:IF_I2CDUMP(APPLET(i2cdump, BB_DIR_USR_SBIN, BB_SUID_DROP))
44 //applet:IF_I2CDETECT(APPLET(i2cdetect, BB_DIR_USR_SBIN, BB_SUID_DROP))
45
46 //kbuild:lib-$(CONFIG_I2CGET) += i2c_tools.o
47 //kbuild:lib-$(CONFIG_I2CSET) += i2c_tools.o
48 //kbuild:lib-$(CONFIG_I2CDUMP) += i2c_tools.o
49 //kbuild:lib-$(CONFIG_I2CDETECT) += i2c_tools.o
50
51 /*
52  * Unsupported stuff:
53  *
54  * - upstream i2c-tools can also look-up i2c busses by name, we only accept
55  *   numbers,
56  * - bank and bankreg parameters for i2cdump are not supported because of
57  *   their limited usefulness (see i2cdump manual entry for more info),
58  * - i2cdetect doesn't look for bus info in /proc as it does in upstream, but
59  *   it shouldn't be a problem in modern kernels.
60  */
61
62 #include "libbb.h"
63
64 #include <linux/i2c.h>
65 #include <linux/i2c-dev.h>
66
67 #define I2CDUMP_NUM_REGS                256
68
69 #define I2CDETECT_MODE_AUTO             0
70 #define I2CDETECT_MODE_QUICK            1
71 #define I2CDETECT_MODE_READ             2
72
73 /*
74  * This is needed for ioctl_or_perror_and_die() since it only accepts pointers.
75  */
76 static ALWAYS_INLINE void *itoptr(int i)
77 {
78         return (void*)(intptr_t)i;
79 }
80
81 static int32_t i2c_smbus_access(int fd, char read_write, uint8_t cmd,
82                                 int size, union i2c_smbus_data *data)
83 {
84         struct i2c_smbus_ioctl_data args;
85
86         args.read_write = read_write;
87         args.command = cmd;
88         args.size = size;
89         args.data = data;
90
91         return ioctl(fd, I2C_SMBUS, &args);
92 }
93
94 static int32_t i2c_smbus_read_byte(int fd)
95 {
96         union i2c_smbus_data data;
97         int err;
98
99         err = i2c_smbus_access(fd, I2C_SMBUS_READ, 0, I2C_SMBUS_BYTE, &data);
100         if (err < 0)
101                 return err;
102
103         return data.byte;
104 }
105
106 #if ENABLE_I2CGET || ENABLE_I2CSET || ENABLE_I2CDUMP
107 static int32_t i2c_smbus_write_byte(int fd, uint8_t val)
108 {
109         return i2c_smbus_access(fd, I2C_SMBUS_WRITE,
110                                 val, I2C_SMBUS_BYTE, NULL);
111 }
112
113 static int32_t i2c_smbus_read_byte_data(int fd, uint8_t cmd)
114 {
115         union i2c_smbus_data data;
116         int err;
117
118         err = i2c_smbus_access(fd, I2C_SMBUS_READ, cmd,
119                                I2C_SMBUS_BYTE_DATA, &data);
120         if (err < 0)
121                 return err;
122
123         return data.byte;
124 }
125
126 static int32_t i2c_smbus_read_word_data(int fd, uint8_t cmd)
127 {
128         union i2c_smbus_data data;
129         int err;
130
131         err = i2c_smbus_access(fd, I2C_SMBUS_READ, cmd,
132                                I2C_SMBUS_WORD_DATA, &data);
133         if (err < 0)
134                 return err;
135
136         return data.word;
137 }
138 #endif /* ENABLE_I2CGET || ENABLE_I2CSET || ENABLE_I2CDUMP */
139
140 #if ENABLE_I2CSET
141 static int32_t i2c_smbus_write_byte_data(int file,
142                                          uint8_t cmd, uint8_t value)
143 {
144         union i2c_smbus_data data;
145
146         data.byte = value;
147
148         return i2c_smbus_access(file, I2C_SMBUS_WRITE, cmd,
149                                 I2C_SMBUS_BYTE_DATA, &data);
150 }
151
152 static int32_t i2c_smbus_write_word_data(int file, uint8_t cmd, uint16_t value)
153 {
154         union i2c_smbus_data data;
155
156         data.word = value;
157
158         return i2c_smbus_access(file, I2C_SMBUS_WRITE, cmd,
159                                 I2C_SMBUS_WORD_DATA, &data);
160 }
161
162 static int32_t i2c_smbus_write_block_data(int file, uint8_t cmd,
163                                    uint8_t length, const uint8_t *values)
164 {
165         union i2c_smbus_data data;
166
167         if (length > I2C_SMBUS_BLOCK_MAX)
168                 length = I2C_SMBUS_BLOCK_MAX;
169
170         memcpy(data.block+1, values, length);
171         data.block[0] = length;
172
173         return i2c_smbus_access(file, I2C_SMBUS_WRITE, cmd,
174                                 I2C_SMBUS_BLOCK_DATA, &data);
175 }
176
177 static int32_t i2c_smbus_write_i2c_block_data(int file, uint8_t cmd,
178                                        uint8_t length, const uint8_t *values)
179 {
180         union i2c_smbus_data data;
181
182         if (length > I2C_SMBUS_BLOCK_MAX)
183                 length = I2C_SMBUS_BLOCK_MAX;
184
185         memcpy(data.block+1, values, length);
186         data.block[0] = length;
187
188         return i2c_smbus_access(file, I2C_SMBUS_WRITE, cmd,
189                                 I2C_SMBUS_I2C_BLOCK_BROKEN, &data);
190 }
191 #endif /* ENABLE_I2CSET */
192
193 #if ENABLE_I2CDUMP
194 /*
195  * Returns the number of bytes read, vals must hold at
196  * least I2C_SMBUS_BLOCK_MAX bytes.
197  */
198 static int32_t i2c_smbus_read_block_data(int fd, uint8_t cmd, uint8_t *vals)
199 {
200         union i2c_smbus_data data;
201         int i, err;
202
203         err = i2c_smbus_access(fd, I2C_SMBUS_READ, cmd,
204                                I2C_SMBUS_BLOCK_DATA, &data);
205         if (err < 0)
206                 return err;
207
208         for (i = 1; i <= data.block[0]; i++)
209                 *vals++ = data.block[i];
210         return data.block[0];
211 }
212
213 static int32_t i2c_smbus_read_i2c_block_data(int fd, uint8_t cmd,
214                                              uint8_t len, uint8_t *vals)
215 {
216         union i2c_smbus_data data;
217         int i, err;
218
219         if (len > I2C_SMBUS_BLOCK_MAX)
220                 len = I2C_SMBUS_BLOCK_MAX;
221         data.block[0] = len;
222
223         err = i2c_smbus_access(fd, I2C_SMBUS_READ, cmd,
224                                len == 32 ? I2C_SMBUS_I2C_BLOCK_BROKEN :
225                                            I2C_SMBUS_I2C_BLOCK_DATA, &data);
226         if (err < 0)
227                 return err;
228
229         for (i = 1; i <= data.block[0]; i++)
230                 *vals++ = data.block[i];
231         return data.block[0];
232 }
233 #endif /* ENABLE_I2CDUMP */
234
235 #if ENABLE_I2CDETECT
236 static int32_t i2c_smbus_write_quick(int fd, uint8_t val)
237 {
238         return i2c_smbus_access(fd, val, 0, I2C_SMBUS_QUICK, NULL);
239 }
240 #endif /* ENABLE_I2CDETECT */
241
242 static int i2c_bus_lookup(const char *bus_str)
243 {
244         return xstrtou_range(bus_str, 10, 0, 0xfffff);
245 }
246
247 #if ENABLE_I2CGET || ENABLE_I2CSET || ENABLE_I2CDUMP
248 static int i2c_parse_bus_addr(const char *addr_str)
249 {
250         /* Slave address must be in range 0x03 - 0x77. */
251         return xstrtou_range(addr_str, 16, 0x03, 0x77);
252 }
253
254 static void i2c_set_pec(int fd, int pec)
255 {
256         ioctl_or_perror_and_die(fd, I2C_PEC,
257                                 itoptr(pec ? 1 : 0),
258                                 "can't set PEC");
259 }
260
261 static void i2c_set_slave_addr(int fd, int addr, int force)
262 {
263         ioctl_or_perror_and_die(fd, force ? I2C_SLAVE_FORCE : I2C_SLAVE,
264                                 itoptr(addr),
265                                 "can't set address to 0x%02x", addr);
266 }
267 #endif /* ENABLE_I2CGET || ENABLE_I2CSET || ENABLE_I2CDUMP */
268
269 #if ENABLE_I2CGET || ENABLE_I2CSET
270 static int i2c_parse_data_addr(const char *data_addr)
271 {
272         /* Data address must be an 8 bit integer. */
273         return xstrtou_range(data_addr, 16, 0, 0xff);
274 }
275 #endif /* ENABLE_I2CGET || ENABLE_I2CSET */
276
277 /*
278  * Opens the device file associated with given i2c bus.
279  *
280  * Upstream i2c-tools also support opening devices by i2c bus name
281  * but we drop it here for size reduction.
282  */
283 static int i2c_dev_open(int i2cbus)
284 {
285         char filename[sizeof("/dev/i2c-%d") + sizeof(int)*3];
286         int fd;
287
288         sprintf(filename, "/dev/i2c-%d", i2cbus);
289         fd = open(filename, O_RDWR);
290         if (fd < 0) {
291                 if (errno == ENOENT) {
292                         filename[8] = '/'; /* change to "/dev/i2c/%d" */
293                         fd = xopen(filename, O_RDWR);
294                 } else {
295                         bb_perror_msg_and_die("can't open '%s'", filename);
296                 }
297         }
298
299         return fd;
300 }
301
302 /* Size reducing helpers for xxx_check_funcs(). */
303 static void get_funcs_matrix(int fd, unsigned long *funcs)
304 {
305         ioctl_or_perror_and_die(fd, I2C_FUNCS, funcs,
306                         "can't get adapter functionality matrix");
307 }
308
309 #if ENABLE_I2CGET || ENABLE_I2CSET || ENABLE_I2CDUMP
310 static void check_funcs_test_end(int funcs, int pec, const char *err)
311 {
312         if (pec && !(funcs & (I2C_FUNC_SMBUS_PEC | I2C_FUNC_I2C)))
313                 bb_error_msg("warning: adapter does not support PEC");
314
315         if (err)
316                 bb_error_msg_and_die(
317                         "adapter has no %s capability", err);
318 }
319 #endif /* ENABLE_I2CGET || ENABLE_I2CSET || ENABLE_I2CDUMP */
320
321 /*
322  * The below functions emit an error message and exit if the adapter doesn't
323  * support desired functionalities.
324  */
325 #if ENABLE_I2CGET || ENABLE_I2CDUMP
326 static void check_read_funcs(int fd, int mode, int data_addr, int pec)
327 {
328         unsigned long funcs;
329         const char *err = NULL;
330
331         get_funcs_matrix(fd, &funcs);
332         switch (mode) {
333         case I2C_SMBUS_BYTE:
334                 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE)) {
335                         err = "SMBus receive byte";
336                         break;
337                 }
338                 if (data_addr >= 0 && !(funcs & I2C_FUNC_SMBUS_WRITE_BYTE))
339                         err = "SMBus send byte";
340                 break;
341         case I2C_SMBUS_BYTE_DATA:
342                 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE_DATA))
343                         err = "SMBus read byte";
344                 break;
345         case I2C_SMBUS_WORD_DATA:
346                 if (!(funcs & I2C_FUNC_SMBUS_READ_WORD_DATA))
347                         err = "SMBus read word";
348                 break;
349 #if ENABLE_I2CDUMP
350         case I2C_SMBUS_BLOCK_DATA:
351                 if (!(funcs & I2C_FUNC_SMBUS_READ_BLOCK_DATA))
352                         err = "SMBus block read";
353                 break;
354
355         case I2C_SMBUS_I2C_BLOCK_DATA:
356                 if (!(funcs & I2C_FUNC_SMBUS_READ_I2C_BLOCK))
357                         err = "I2C block read";
358                 break;
359 #endif /* ENABLE_I2CDUMP */
360         default:
361                 bb_error_msg_and_die("internal error");
362         }
363         check_funcs_test_end(funcs, pec, err);
364 }
365 #endif /* ENABLE_I2CGET || ENABLE_I2CDUMP */
366
367 #if ENABLE_I2CSET
368 static void check_write_funcs(int fd, int mode, int pec)
369 {
370         unsigned long funcs;
371         const char *err = NULL;
372
373         get_funcs_matrix(fd, &funcs);
374         switch (mode) {
375         case I2C_SMBUS_BYTE:
376                 if (!(funcs & I2C_FUNC_SMBUS_WRITE_BYTE))
377                         err = "SMBus send byte";
378                 break;
379
380         case I2C_SMBUS_BYTE_DATA:
381                 if (!(funcs & I2C_FUNC_SMBUS_WRITE_BYTE_DATA))
382                         err = "SMBus write byte";
383                 break;
384
385         case I2C_SMBUS_WORD_DATA:
386                 if (!(funcs & I2C_FUNC_SMBUS_WRITE_WORD_DATA))
387                         err = "SMBus write word";
388                 break;
389
390         case I2C_SMBUS_BLOCK_DATA:
391                 if (!(funcs & I2C_FUNC_SMBUS_WRITE_BLOCK_DATA))
392                         err = "SMBus block write";
393                 break;
394         case I2C_SMBUS_I2C_BLOCK_DATA:
395                 if (!(funcs & I2C_FUNC_SMBUS_WRITE_I2C_BLOCK))
396                         err = "I2C block write";
397                 break;
398         }
399         check_funcs_test_end(funcs, pec, err);
400 }
401 #endif /* ENABLE_I2CSET */
402
403 static void confirm_or_abort(void)
404 {
405         fprintf(stderr, "Continue? [y/N] ");
406         fflush_all();
407         if (!bb_ask_confirmation())
408                 bb_error_msg_and_die("aborting");
409 }
410
411 /*
412  * Return only if user confirms the action, abort otherwise.
413  *
414  * The messages displayed here are much less elaborate than their i2c-tools
415  * counterparts - this is done for size reduction.
416  */
417 static void confirm_action(int bus_addr, int mode, int data_addr, int pec)
418 {
419         bb_error_msg("WARNING! This program can confuse your I2C bus");
420
421         /* Don't let the user break his/her EEPROMs */
422         if (bus_addr >= 0x50 && bus_addr <= 0x57 && pec) {
423                 bb_error_msg_and_die("this is I2C not smbus - using PEC on I2C "
424                         "devices may result in data loss, aborting");
425         }
426
427         if (mode == I2C_SMBUS_BYTE && data_addr >= 0 && pec)
428                 bb_error_msg("WARNING! May interpret a write byte command "
429                         "with PEC as a write byte data command");
430
431         if (pec)
432                 bb_error_msg("PEC checking enabled");
433
434         confirm_or_abort();
435 }
436
437 #if ENABLE_I2CGET
438 //usage:#define i2cget_trivial_usage
439 //usage:       "[-f] [-y] BUS CHIP-ADDRESS [DATA-ADDRESS [MODE]]"
440 //usage:#define i2cget_full_usage "\n\n"
441 //usage:       "Read from I2C/SMBus chip registers\n"
442 //usage:     "\n        I2CBUS  i2c bus number"
443 //usage:     "\n        ADDRESS 0x03 - 0x77"
444 //usage:     "\nMODE is:"
445 //usage:     "\n        b       read byte data (default)"
446 //usage:     "\n        w       read word data"
447 //usage:     "\n        c       write byte/read byte"
448 //usage:     "\n        Append p for SMBus PEC"
449 //usage:     "\n"
450 //usage:     "\n        -f      force access"
451 //usage:     "\n        -y      disable interactive mode"
452 int i2cget_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
453 int i2cget_main(int argc UNUSED_PARAM, char **argv)
454 {
455         const unsigned opt_f = (1 << 0), opt_y = (1 << 1);
456         const char *const optstr = "fy";
457
458         int bus_num, bus_addr, data_addr = -1, status;
459         int mode = I2C_SMBUS_BYTE, pec = 0, fd;
460         unsigned opts;
461
462         opt_complementary = "-2:?4"; /* from 2 to 4 args */
463         opts = getopt32(argv, optstr);
464         argv += optind;
465
466         bus_num = i2c_bus_lookup(argv[0]);
467         bus_addr = i2c_parse_bus_addr(argv[1]);
468
469         if (argv[2]) {
470                 data_addr = i2c_parse_data_addr(argv[2]);
471                 mode = I2C_SMBUS_BYTE_DATA;
472                 if (argv[3]) {
473                         switch (argv[3][0]) {
474                         case 'b':       /* Already set */               break;
475                         case 'w':       mode = I2C_SMBUS_WORD_DATA;     break;
476                         case 'c':       mode = I2C_SMBUS_BYTE;          break;
477                         default:
478                                 bb_error_msg("invalid mode");
479                                 bb_show_usage();
480                         }
481                         pec = argv[3][1] == 'p';
482                 }
483         }
484
485         fd = i2c_dev_open(bus_num);
486         check_read_funcs(fd, mode, data_addr, pec);
487         i2c_set_slave_addr(fd, bus_addr, opts & opt_f);
488
489         if (!(opts & opt_y))
490                 confirm_action(bus_addr, mode, data_addr, pec);
491
492         if (pec)
493                 i2c_set_pec(fd, 1);
494
495         switch (mode) {
496         case I2C_SMBUS_BYTE:
497                 if (data_addr >= 0) {
498                         status = i2c_smbus_write_byte(fd, data_addr);
499                         if (status < 0)
500                                 bb_error_msg("warning - write failed");
501                 }
502                 status = i2c_smbus_read_byte(fd);
503                 break;
504         case I2C_SMBUS_WORD_DATA:
505                 status = i2c_smbus_read_word_data(fd, data_addr);
506                 break;
507         default: /* I2C_SMBUS_BYTE_DATA */
508                 status = i2c_smbus_read_byte_data(fd, data_addr);
509         }
510         close(fd);
511
512         if (status < 0)
513                 bb_perror_msg_and_die("read failed");
514
515         printf("0x%0*x\n", mode == I2C_SMBUS_WORD_DATA ? 4 : 2, status);
516
517         return 0;
518 }
519 #endif /* ENABLE_I2CGET */
520
521 #if ENABLE_I2CSET
522 //usage:#define i2cset_trivial_usage
523 //usage:       "[-f] [-y] [-m MASK] BUS CHIP-ADDR DATA-ADDR [VALUE] ... [MODE]"
524 //usage:#define i2cset_full_usage "\n\n"
525 //usage:       "Set I2C registers\n"
526 //usage:     "\n        I2CBUS  i2c bus number"
527 //usage:     "\n        ADDRESS 0x03 - 0x77"
528 //usage:     "\nMODE is:"
529 //usage:     "\n        c       byte, no value"
530 //usage:     "\n        b       byte data (default)"
531 //usage:     "\n        w       word data"
532 //usage:     "\n        i       I2C block data"
533 //usage:     "\n        s       SMBus block data"
534 //usage:     "\n        Append p for SMBus PEC"
535 //usage:     "\n"
536 //usage:     "\n        -f      force access"
537 //usage:     "\n        -y      disable interactive mode"
538 //usage:     "\n        -r      read back and compare the result"
539 //usage:     "\n        -m MASK mask specifying which bits to write"
540 int i2cset_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
541 int i2cset_main(int argc, char **argv)
542 {
543         const unsigned opt_f = (1 << 0), opt_y = (1 << 1),
544                               opt_m = (1 << 2), opt_r = (1 << 3);
545         const char *const optstr = "fym:r";
546
547         int bus_num, bus_addr, data_addr, mode = I2C_SMBUS_BYTE, pec = 0;
548         int val, blen = 0, mask = 0, fd, status;
549         unsigned char block[I2C_SMBUS_BLOCK_MAX];
550         char *opt_m_arg = NULL;
551         unsigned opts;
552
553         opt_complementary = "-3"; /* from 3 to ? args */
554         opts = getopt32(argv, optstr, &opt_m_arg);
555         argv += optind;
556         argc -= optind;
557
558         bus_num = i2c_bus_lookup(argv[0]);
559         bus_addr = i2c_parse_bus_addr(argv[1]);
560         data_addr = i2c_parse_data_addr(argv[2]);
561
562         if (argv[3]) {
563                 if (!argv[4] && argv[3][0] != 'c') {
564                         mode = I2C_SMBUS_BYTE_DATA; /* Implicit b */
565                 } else {
566                         switch (argv[argc-1][0]) {
567                         case 'c': /* Already set */                     break;
568                         case 'b': mode = I2C_SMBUS_BYTE_DATA;           break;
569                         case 'w': mode = I2C_SMBUS_WORD_DATA;           break;
570                         case 's': mode = I2C_SMBUS_BLOCK_DATA;          break;
571                         case 'i': mode = I2C_SMBUS_I2C_BLOCK_DATA;      break;
572                         default:
573                                 bb_error_msg("invalid mode");
574                                 bb_show_usage();
575                         }
576
577                         pec = argv[argc-1][1] == 'p';
578                         if (mode == I2C_SMBUS_BLOCK_DATA ||
579                                         mode == I2C_SMBUS_I2C_BLOCK_DATA) {
580                                 if (pec && mode == I2C_SMBUS_I2C_BLOCK_DATA)
581                                         bb_error_msg_and_die(
582                                                 "PEC not supported for I2C "
583                                                 "block writes");
584                                 if (opts & opt_m)
585                                         bb_error_msg_and_die(
586                                                 "mask not supported for block "
587                                                 "writes");
588                         }
589                 }
590         }
591
592         /* Prepare the value(s) to be written according to current mode. */
593         switch (mode) {
594         case I2C_SMBUS_BYTE_DATA:
595                 val = xstrtou_range(argv[3], 0, 0, 0xff);
596                 break;
597         case I2C_SMBUS_WORD_DATA:
598                 val = xstrtou_range(argv[3], 0, 0, 0xffff);
599                 break;
600         case I2C_SMBUS_BLOCK_DATA:
601         case I2C_SMBUS_I2C_BLOCK_DATA:
602                 for (blen = 3; blen < (argc - 1); blen++)
603                         block[blen] = xstrtou_range(argv[blen], 0, 0, 0xff);
604                 val = -1;
605                 break;
606         default:
607                 val = -1;
608                 break;
609         }
610
611         if (opts & opt_m) {
612                 mask = xstrtou_range(opt_m_arg, 0, 0,
613                                 (mode == I2C_SMBUS_BYTE ||
614                                  mode == I2C_SMBUS_BYTE_DATA) ? 0xff : 0xffff);
615         }
616
617         fd = i2c_dev_open(bus_num);
618         check_write_funcs(fd, mode, pec);
619         i2c_set_slave_addr(fd, bus_addr, opts & opt_f);
620
621         if (!(opts & opt_y))
622                 confirm_action(bus_addr, mode, data_addr, pec);
623
624         /*
625          * If we're using mask - read the current value here and adjust the
626          * value to be written.
627          */
628         if (opts & opt_m) {
629                 int tmpval;
630
631                 switch (mode) {
632                 case I2C_SMBUS_BYTE:
633                         tmpval = i2c_smbus_read_byte(fd);
634                         break;
635                 case I2C_SMBUS_WORD_DATA:
636                         tmpval = i2c_smbus_read_word_data(fd, data_addr);
637                         break;
638                 default:
639                         tmpval = i2c_smbus_read_byte_data(fd, data_addr);
640                 }
641
642                 if (tmpval < 0)
643                         bb_perror_msg_and_die("can't read old value");
644
645                 val = (val & mask) | (tmpval & ~mask);
646
647                 if (!(opts & opt_y)) {
648                         bb_error_msg("old value 0x%0*x, write mask "
649                                 "0x%0*x, will write 0x%0*x to register "
650                                 "0x%02x",
651                                 mode == I2C_SMBUS_WORD_DATA ? 4 : 2, tmpval,
652                                 mode == I2C_SMBUS_WORD_DATA ? 4 : 2, mask,
653                                 mode == I2C_SMBUS_WORD_DATA ? 4 : 2, val,
654                                 data_addr);
655                         confirm_or_abort();
656                 }
657         }
658
659         if (pec)
660                 i2c_set_pec(fd, 1);
661
662         switch (mode) {
663         case I2C_SMBUS_BYTE:
664                 status = i2c_smbus_write_byte(fd, data_addr);
665                 break;
666         case I2C_SMBUS_WORD_DATA:
667                 status = i2c_smbus_write_word_data(fd, data_addr, val);
668                 break;
669         case I2C_SMBUS_BLOCK_DATA:
670                 status = i2c_smbus_write_block_data(fd, data_addr,
671                                                     blen, block);
672                 break;
673         case I2C_SMBUS_I2C_BLOCK_DATA:
674                 status = i2c_smbus_write_i2c_block_data(fd, data_addr,
675                                                         blen, block);
676                 break;
677         default: /* I2C_SMBUS_BYTE_DATA */
678                 status = i2c_smbus_write_byte_data(fd, data_addr, val);
679                 break;
680         }
681         if (status < 0)
682                 bb_perror_msg_and_die("write failed");
683
684         if (pec)
685                 i2c_set_pec(fd, 0); /* Clear PEC. */
686
687         /* No readback required - we're done. */
688         if (!(opts & opt_r))
689                 return 0;
690
691         switch (mode) {
692         case I2C_SMBUS_BYTE:
693                 status = i2c_smbus_read_byte(fd);
694                 val = data_addr;
695                 break;
696         case I2C_SMBUS_WORD_DATA:
697                 status = i2c_smbus_read_word_data(fd, data_addr);
698                 break;
699         default: /* I2C_SMBUS_BYTE_DATA */
700                 status = i2c_smbus_read_byte_data(fd, data_addr);
701         }
702
703         if (status < 0) {
704                 puts("Warning - readback failed");
705         } else
706         if (status != val) {
707                 printf("Warning - data mismatch - wrote "
708                        "0x%0*x, read back 0x%0*x\n",
709                        mode == I2C_SMBUS_WORD_DATA ? 4 : 2, val,
710                        mode == I2C_SMBUS_WORD_DATA ? 4 : 2, status);
711         } else {
712                 printf("Value 0x%0*x written, readback matched\n",
713                        mode == I2C_SMBUS_WORD_DATA ? 4 : 2, val);
714         }
715
716         return 0;
717 }
718 #endif /* ENABLE_I2CSET */
719
720 #if ENABLE_I2CDUMP
721 static int read_block_data(int buf_fd, int mode, int *block)
722 {
723         uint8_t cblock[I2C_SMBUS_BLOCK_MAX + I2CDUMP_NUM_REGS];
724         int res, blen = 0, tmp, i;
725
726         if (mode == I2C_SMBUS_BLOCK_DATA) {
727                 blen = i2c_smbus_read_block_data(buf_fd, 0, cblock);
728                 if (blen <= 0)
729                         goto fail;
730         } else {
731                 for (res = 0; res < I2CDUMP_NUM_REGS; res += tmp) {
732                         tmp = i2c_smbus_read_i2c_block_data(
733                                         buf_fd, res, I2C_SMBUS_BLOCK_MAX,
734                                         cblock + res);
735                         if (tmp <= 0) {
736                                 blen = tmp;
737                                 goto fail;
738                         }
739                 }
740
741                 if (res >= I2CDUMP_NUM_REGS)
742                         res = I2CDUMP_NUM_REGS;
743
744                 for (i = 0; i < res; i++)
745                         block[i] = cblock[i];
746
747                 if (mode != I2C_SMBUS_BLOCK_DATA)
748                         for (i = res; i < I2CDUMP_NUM_REGS; i++)
749                                 block[i] = -1;
750         }
751
752         return blen;
753
754  fail:
755         bb_error_msg_and_die("block read failed: %d", blen);
756 }
757
758 /* Dump all but word data. */
759 static void dump_data(int bus_fd, int mode, unsigned first,
760                       unsigned last, int *block, int blen)
761 {
762         int i, j, res;
763
764         puts("     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f"
765              "    0123456789abcdef");
766
767         for (i = 0; i < I2CDUMP_NUM_REGS; i += 0x10) {
768                 if (mode == I2C_SMBUS_BLOCK_DATA && i >= blen)
769                         break;
770                 if (i/16 < first/16)
771                         continue;
772                 if (i/16 > last/16)
773                         break;
774
775                 printf("%02x: ", i);
776                 for (j = 0; j < 16; j++) {
777                         fflush_all();
778                         /* Skip unwanted registers */
779                         if (i+j < first || i+j > last) {
780                                 printf("   ");
781                                 if (mode == I2C_SMBUS_WORD_DATA) {
782                                         printf("   ");
783                                         j++;
784                                 }
785                                 continue;
786                         }
787
788                         switch (mode) {
789                         case I2C_SMBUS_BYTE_DATA:
790                                 res = i2c_smbus_read_byte_data(bus_fd, i+j);
791                                 block[i+j] = res;
792                                 break;
793                         case I2C_SMBUS_WORD_DATA:
794                                 res = i2c_smbus_read_word_data(bus_fd, i+j);
795                                 if (res < 0) {
796                                         block[i+j] = res;
797                                         block[i+j+1] = res;
798                                 } else {
799                                         block[i+j] = res & 0xff;
800                                         block[i+j+1] = res >> 8;
801                                 }
802                                 break;
803                         case I2C_SMBUS_BYTE:
804                                 res = i2c_smbus_read_byte(bus_fd);
805                                 block[i+j] = res;
806                                 break;
807                         default:
808                                 res = block[i+j];
809                         }
810
811                         if (mode == I2C_SMBUS_BLOCK_DATA &&
812                             i+j >= blen) {
813                                 printf("   ");
814                         } else if (res < 0) {
815                                 printf("XX ");
816                                 if (mode == I2C_SMBUS_WORD_DATA)
817                                         printf("XX ");
818                         } else {
819                                 printf("%02x ", block[i+j]);
820                                 if (mode == I2C_SMBUS_WORD_DATA)
821                                         printf("%02x ", block[i+j+1]);
822                         }
823
824                         if (mode == I2C_SMBUS_WORD_DATA)
825                                 j++;
826                 }
827                 printf("   ");
828
829                 for (j = 0; j < 16; j++) {
830                         if (mode == I2C_SMBUS_BLOCK_DATA && i+j >= blen)
831                                 break;
832                         /* Skip unwanted registers */
833                         if (i+j < first || i+j > last) {
834                                 bb_putchar(' ');
835                                 continue;
836                         }
837
838                         res = block[i+j];
839                         if (res < 0) {
840                                 bb_putchar('X');
841                         } else if (res == 0x00 || res == 0xff) {
842                                 bb_putchar('.');
843                         } else if (res < 32 || res >= 127) {
844                                 bb_putchar('?');
845                         } else {
846                                 bb_putchar(res);
847                         }
848                 }
849                 bb_putchar('\n');
850         }
851 }
852
853 static void dump_word_data(int bus_fd, unsigned first, unsigned last)
854 {
855         int i, j, rv;
856
857         /* Word data. */
858         puts("     0,8  1,9  2,a  3,b  4,c  5,d  6,e  7,f");
859         for (i = 0; i < 256; i += 8) {
860                 if (i/8 < first/8)
861                         continue;
862                 if (i/8 > last/8)
863                         break;
864
865                 printf("%02x: ", i);
866                 for (j = 0; j < 8; j++) {
867                         /* Skip unwanted registers. */
868                         if (i+j < first || i+j > last) {
869                                 printf("     ");
870                                 continue;
871                         }
872
873                         rv = i2c_smbus_read_word_data(bus_fd, i+j);
874                         if (rv < 0)
875                                 printf("XXXX ");
876                         else
877                                 printf("%04x ", rv & 0xffff);
878                 }
879                 bb_putchar('\n');
880         }
881 }
882
883 //usage:#define i2cdump_trivial_usage
884 //usage:       "[-f] [-r FIRST-LAST] [-y] BUS ADDR [MODE]"
885 //usage:#define i2cdump_full_usage "\n\n"
886 //usage:       "Examine I2C registers\n"
887 //usage:     "\n        I2CBUS  i2c bus number"
888 //usage:     "\n        ADDRESS 0x03 - 0x77"
889 //usage:     "\nMODE is:"
890 //usage:     "\n        b       byte (default)"
891 //usage:     "\n        w       word"
892 //usage:     "\n        W       word on even register addresses"
893 //usage:     "\n        i       I2C block"
894 //usage:     "\n        s       SMBus block"
895 //usage:     "\n        c       consecutive byte"
896 //usage:     "\n        Append p for SMBus PEC"
897 //usage:     "\n"
898 //usage:     "\n        -f      force access"
899 //usage:     "\n        -y      disable interactive mode"
900 //usage:     "\n        -r      limit the number of registers being accessed"
901 int i2cdump_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
902 int i2cdump_main(int argc UNUSED_PARAM, char **argv)
903 {
904         const unsigned opt_f = (1 << 0), opt_y = (1 << 1),
905                               opt_r = (1 << 2);
906         const char *const optstr = "fyr:";
907
908         int bus_num, bus_addr, mode = I2C_SMBUS_BYTE_DATA, even = 0, pec = 0;
909         unsigned first = 0x00, last = 0xff, opts;
910         int *block = (int *)bb_common_bufsiz1;
911         char *opt_r_str, *dash;
912         int fd, res;
913
914         opt_complementary = "-2:?3"; /* from 2 to 3 args */
915         opts = getopt32(argv, optstr, &opt_r_str);
916         argv += optind;
917
918         bus_num = i2c_bus_lookup(argv[0]);
919         bus_addr = i2c_parse_bus_addr(argv[1]);
920
921         if (argv[2]) {
922                 switch (argv[2][0]) {
923                 case 'b': /* Already set. */                    break;
924                 case 'c': mode = I2C_SMBUS_BYTE;                break;
925                 case 'w': mode = I2C_SMBUS_WORD_DATA;           break;
926                 case 'W':
927                         mode = I2C_SMBUS_WORD_DATA;
928                         even = 1;
929                         break;
930                 case 's': mode = I2C_SMBUS_BLOCK_DATA;          break;
931                 case 'i': mode = I2C_SMBUS_I2C_BLOCK_DATA;      break;
932                 default:
933                         bb_error_msg_and_die("invalid mode");
934                 }
935
936                 if (argv[2][1] == 'p') {
937                         if (argv[2][0] == 'W' || argv[2][0] == 'i') {
938                                 bb_error_msg_and_die(
939                                         "pec not supported for -W and -i");
940                         } else {
941                                 pec = 1;
942                         }
943                 }
944         }
945
946         if (opts & opt_r) {
947                 first = strtol(opt_r_str, &dash, 0);
948                 if (dash == opt_r_str || *dash != '-' || first > 0xff)
949                         bb_error_msg_and_die("invalid range");
950                 last = xstrtou_range(++dash, 0, first, 0xff);
951
952                 /* Range is not available for every mode. */
953                 switch (mode) {
954                 case I2C_SMBUS_BYTE:
955                 case I2C_SMBUS_BYTE_DATA:
956                         break;
957                 case I2C_SMBUS_WORD_DATA:
958                         if (!even || (!(first % 2) && last % 2))
959                                 break;
960                         /* Fall through */
961                 default:
962                         bb_error_msg_and_die(
963                                 "range not compatible with selected mode");
964                 }
965         }
966
967         fd = i2c_dev_open(bus_num);
968         check_read_funcs(fd, mode, -1 /* data_addr */, pec);
969         i2c_set_slave_addr(fd, bus_addr, opts & opt_f);
970
971         if (pec)
972                 i2c_set_pec(fd, 1);
973
974         if (!(opts & opt_y))
975                 confirm_action(bus_addr, mode, -1 /* data_addr */, pec);
976
977         /* All but word data. */
978         if (mode != I2C_SMBUS_WORD_DATA || even) {
979                 int blen = 0;
980
981                 if (mode == I2C_SMBUS_BLOCK_DATA || mode == I2C_SMBUS_I2C_BLOCK_DATA)
982                         blen = read_block_data(fd, mode, block);
983
984                 if (mode == I2C_SMBUS_BYTE) {
985                         res = i2c_smbus_write_byte(fd, first);
986                         if (res < 0)
987                                 bb_perror_msg_and_die("write start address");
988                 }
989
990                 dump_data(fd, mode, first, last, block, blen);
991         } else {
992                 dump_word_data(fd, first, last);
993         }
994
995         return 0;
996 }
997 #endif /* ENABLE_I2CDUMP */
998
999 #if ENABLE_I2CDETECT
1000 enum adapter_type {
1001         ADT_DUMMY = 0,
1002         ADT_ISA,
1003         ADT_I2C,
1004         ADT_SMBUS,
1005 };
1006
1007 struct adap_desc {
1008         const char *funcs;
1009         const char *algo;
1010 };
1011
1012 static const struct adap_desc adap_descs[] = {
1013         { .funcs        = "dummy",
1014           .algo         = "Dummy bus", },
1015         { .funcs        = "isa",
1016           .algo         = "ISA bus", },
1017         { .funcs        = "i2c",
1018           .algo         = "I2C adapter", },
1019         { .funcs        = "smbus",
1020           .algo         = "SMBus adapter", },
1021 };
1022
1023 struct i2c_func
1024 {
1025         long value;
1026         const char* name;
1027 };
1028
1029 static const struct i2c_func i2c_funcs_tab[] = {
1030         { .value = I2C_FUNC_I2C,
1031           .name = "I2C" },
1032         { .value = I2C_FUNC_SMBUS_QUICK,
1033           .name = "SMBus quick command" },
1034         { .value = I2C_FUNC_SMBUS_WRITE_BYTE,
1035           .name = "SMBus send byte" },
1036         { .value = I2C_FUNC_SMBUS_READ_BYTE,
1037           .name = "SMBus receive byte" },
1038         { .value = I2C_FUNC_SMBUS_WRITE_BYTE_DATA,
1039           .name = "SMBus write byte" },
1040         { .value = I2C_FUNC_SMBUS_READ_BYTE_DATA,
1041           .name = "SMBus read byte" },
1042         { .value = I2C_FUNC_SMBUS_WRITE_WORD_DATA,
1043           .name = "SMBus write word" },
1044         { .value = I2C_FUNC_SMBUS_READ_WORD_DATA,
1045           .name = "SMBus read word" },
1046         { .value = I2C_FUNC_SMBUS_PROC_CALL,
1047           .name = "SMBus process call" },
1048         { .value = I2C_FUNC_SMBUS_WRITE_BLOCK_DATA,
1049           .name = "SMBus block write" },
1050         { .value = I2C_FUNC_SMBUS_READ_BLOCK_DATA,
1051           .name = "SMBus block read" },
1052         { .value = I2C_FUNC_SMBUS_BLOCK_PROC_CALL,
1053           .name = "SMBus block process call" },
1054         { .value = I2C_FUNC_SMBUS_PEC,
1055           .name = "SMBus PEC" },
1056         { .value = I2C_FUNC_SMBUS_WRITE_I2C_BLOCK,
1057           .name = "I2C block write" },
1058         { .value = I2C_FUNC_SMBUS_READ_I2C_BLOCK,
1059           .name = "I2C block read" },
1060         { .value = 0, .name = NULL }
1061 };
1062
1063 static enum adapter_type i2cdetect_get_funcs(int bus)
1064 {
1065         enum adapter_type ret;
1066         unsigned long funcs;
1067         int fd;
1068
1069         fd = i2c_dev_open(bus);
1070
1071         get_funcs_matrix(fd, &funcs);
1072         if (funcs & I2C_FUNC_I2C)
1073                 ret = ADT_I2C;
1074         else if (funcs & (I2C_FUNC_SMBUS_BYTE |
1075                           I2C_FUNC_SMBUS_BYTE_DATA |
1076                           I2C_FUNC_SMBUS_WORD_DATA))
1077                 ret = ADT_SMBUS;
1078         else
1079                 ret = ADT_DUMMY;
1080
1081         close(fd);
1082
1083         return ret;
1084 }
1085
1086 static void NORETURN list_i2c_busses_and_exit(void)
1087 {
1088         const char *const i2cdev_path = "/sys/class/i2c-dev";
1089
1090         char path[NAME_MAX], name[128];
1091         struct dirent *de, *subde;
1092         enum adapter_type adt;
1093         DIR *dir, *subdir;
1094         int rv, bus;
1095         char *pos;
1096         FILE *fp;
1097
1098         /*
1099          * XXX Upstream i2cdetect also looks for i2c bus info in /proc/bus/i2c,
1100          * but we won't bother since it's only useful on older kernels (before
1101          * 2.6.5). We expect sysfs to be present and mounted at /sys/.
1102          */
1103
1104         dir = xopendir(i2cdev_path);
1105         while ((de = readdir(dir))) {
1106                 if (de->d_name[0] == '.')
1107                         continue;
1108
1109                 /* Simple version for ISA chips. */
1110                 snprintf(path, NAME_MAX, "%s/%s/name",
1111                          i2cdev_path, de->d_name);
1112                 fp = fopen(path, "r");
1113                 if (fp == NULL) {
1114                         snprintf(path, NAME_MAX,
1115                                  "%s/%s/device/name",
1116                                  i2cdev_path, de->d_name);
1117                         fp = fopen(path, "r");
1118                 }
1119
1120                 /* Non-ISA chips require the hard-way. */
1121                 if (fp == NULL) {
1122                         snprintf(path, NAME_MAX,
1123                                  "%s/%s/device/name",
1124                                  i2cdev_path, de->d_name);
1125                         subdir = opendir(path);
1126                         if (subdir == NULL)
1127                                 continue;
1128
1129                         while ((subde = readdir(subdir))) {
1130                                 if (subde->d_name[0] == '.')
1131                                         continue;
1132
1133                                 if (is_prefixed_with(subde->d_name, "i2c-")) {
1134                                         snprintf(path, NAME_MAX,
1135                                                  "%s/%s/device/%s/name",
1136                                                  i2cdev_path, de->d_name,
1137                                                  subde->d_name);
1138                                         fp = fopen(path, "r");
1139                                         break;
1140                                 }
1141                         }
1142                 }
1143
1144                 if (fp != NULL) {
1145                         /*
1146                          * Get the rest of the info and display a line
1147                          * for a single bus.
1148                          */
1149                         memset(name, 0, sizeof(name));
1150                         pos = fgets(name, sizeof(name), fp);
1151                         fclose(fp);
1152                         if (pos == NULL)
1153                                 continue;
1154
1155                         pos = strchr(name, '\n');
1156                         if (pos != NULL)
1157                                 *pos = '\0';
1158
1159                         rv = sscanf(de->d_name, "i2c-%d", &bus);
1160                         if (rv != 1)
1161                                 continue;
1162
1163                         if (is_prefixed_with(name, "ISA"))
1164                                 adt = ADT_ISA;
1165                         else
1166                                 adt = i2cdetect_get_funcs(bus);
1167
1168                         printf(
1169                                 "i2c-%d\t%-10s\t%-32s\t%s\n",
1170                                 bus, adap_descs[adt].funcs,
1171                                 name, adap_descs[adt].algo);
1172                 }
1173         }
1174
1175         exit(EXIT_SUCCESS);
1176 }
1177
1178 static void NORETURN no_support(const char *cmd)
1179 {
1180         bb_error_msg_and_die("bus doesn't support %s", cmd);
1181 }
1182
1183 static void will_skip(const char *cmd)
1184 {
1185         bb_error_msg(
1186                 "warning: can't use %s command, "
1187                 "will skip some addresses", cmd);
1188 }
1189
1190 //usage:#define i2cdetect_trivial_usage
1191 //usage:       "[-F I2CBUS] [-l] [-y] [-a] [-q|-r] I2CBUS [FIRST LAST]"
1192 //usage:#define i2cdetect_full_usage "\n\n"
1193 //usage:       "Detect I2C chips.\n"
1194 //usage:     "\n        I2CBUS  i2c bus number"
1195 //usage:     "\n        FIRST and LAST limit the probing range"
1196 //usage:     "\n"
1197 //usage:     "\n        -l      output list of installed busses"
1198 //usage:     "\n        -y      disable interactive mode"
1199 //usage:     "\n        -a      force scanning of non-regular addresses"
1200 //usage:     "\n        -q      use smbus quick write commands for probing (default)"
1201 //usage:     "\n        -r      use smbus read byte commands for probing"
1202 //usage:     "\n        -F      display list of functionalities"
1203 int i2cdetect_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1204 int i2cdetect_main(int argc UNUSED_PARAM, char **argv)
1205 {
1206         const unsigned opt_y = (1 << 0), opt_a = (1 << 1),
1207                               opt_q = (1 << 2), opt_r = (1 << 3),
1208                               opt_F = (1 << 4), opt_l = (1 << 5);
1209         const char *const optstr = "yaqrFl";
1210
1211         int fd, bus_num, i, j, mode = I2CDETECT_MODE_AUTO, status, cmd;
1212         unsigned first = 0x03, last = 0x77, opts;
1213         unsigned long funcs;
1214
1215         opt_complementary = "q--r:r--q:" /* mutually exclusive */
1216                         "?3"; /* up to 3 args */
1217         opts = getopt32(argv, optstr);
1218         argv += optind;
1219
1220         if (opts & opt_l)
1221                 list_i2c_busses_and_exit();
1222
1223         if (!argv[0])
1224                 bb_show_usage();
1225
1226         bus_num = i2c_bus_lookup(argv[0]);
1227         fd = i2c_dev_open(bus_num);
1228         get_funcs_matrix(fd, &funcs);
1229
1230         if (opts & opt_F) {
1231                 /* Only list the functionalities. */
1232                 printf("Functionalities implemented by bus #%d\n", bus_num);
1233                 for (i = 0; i2c_funcs_tab[i].value; i++) {
1234                         printf("%-32s %s\n", i2c_funcs_tab[i].name,
1235                                funcs & i2c_funcs_tab[i].value ? "yes" : "no");
1236                 }
1237
1238                 return EXIT_SUCCESS;
1239         }
1240
1241         if (opts & opt_r)
1242                 mode = I2CDETECT_MODE_READ;
1243         else if (opts & opt_q)
1244                 mode = I2CDETECT_MODE_QUICK;
1245
1246         if (opts & opt_a) {
1247                 first = 0x00;
1248                 last = 0x7f;
1249         }
1250
1251         /* Read address range. */
1252         if (argv[1]) {
1253                 first = xstrtou_range(argv[1], 16, first, last);
1254                 if (argv[2])
1255                         last = xstrtou_range(argv[2], 16, first, last);
1256         }
1257
1258         if (!(funcs & (I2C_FUNC_SMBUS_QUICK | I2C_FUNC_SMBUS_READ_BYTE))) {
1259                 no_support("detection commands");
1260         } else
1261         if (mode == I2CDETECT_MODE_QUICK && !(funcs & I2C_FUNC_SMBUS_QUICK)) {
1262                 no_support("SMBus quick write");
1263         } else
1264         if (mode == I2CDETECT_MODE_READ && !(funcs & I2C_FUNC_SMBUS_READ_BYTE)) {
1265                 no_support("SMBus receive byte");
1266         }
1267
1268         if (mode == I2CDETECT_MODE_AUTO) {
1269                 if (!(funcs & I2C_FUNC_SMBUS_QUICK))
1270                         will_skip("SMBus quick write");
1271                 if (!(funcs & I2C_FUNC_SMBUS_READ_BYTE))
1272                         will_skip("SMBus receive byte");
1273         }
1274
1275         if (!(opts & opt_y))
1276                 confirm_action(-1, -1, -1, 0);
1277
1278         puts("     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f");
1279         for (i = 0; i < 128; i += 16) {
1280                 printf("%02x: ", i);
1281                 for (j = 0; j < 16; j++) {
1282                         fflush_all();
1283
1284                         cmd = mode;
1285                         if (mode == I2CDETECT_MODE_AUTO) {
1286                                 if ((i+j >= 0x30 && i+j <= 0x37) ||
1287                                     (i+j >= 0x50 && i+j <= 0x5F))
1288                                         cmd = I2CDETECT_MODE_READ;
1289                                 else
1290                                         cmd = I2CDETECT_MODE_QUICK;
1291                         }
1292
1293                         /* Skip unwanted addresses. */
1294                         if (i+j < first
1295                          || i+j > last
1296                          || (cmd == I2CDETECT_MODE_READ && !(funcs & I2C_FUNC_SMBUS_READ_BYTE))
1297                          || (cmd == I2CDETECT_MODE_QUICK && !(funcs & I2C_FUNC_SMBUS_QUICK)))
1298                         {
1299                                 printf("   ");
1300                                 continue;
1301                         }
1302
1303                         status = ioctl(fd, I2C_SLAVE, itoptr(i + j));
1304                         if (status < 0) {
1305                                 if (errno == EBUSY) {
1306                                         printf("UU ");
1307                                         continue;
1308                                 }
1309
1310                                 bb_perror_msg_and_die(
1311                                         "can't set address to 0x%02x", i + j);
1312                         }
1313
1314                         switch (cmd) {
1315                         case I2CDETECT_MODE_READ:
1316                                 /*
1317                                  * This is known to lock SMBus on various
1318                                  * write-only chips (mainly clock chips).
1319                                  */
1320                                 status = i2c_smbus_read_byte(fd);
1321                                 break;
1322                         default: /* I2CDETECT_MODE_QUICK: */
1323                                 /*
1324                                  * This is known to corrupt the Atmel
1325                                  * AT24RF08 EEPROM.
1326                                  */
1327                                 status = i2c_smbus_write_quick(fd,
1328                                                                I2C_SMBUS_WRITE);
1329                                 break;
1330                         }
1331
1332                         if (status < 0)
1333                                 printf("-- ");
1334                         else
1335                                 printf("%02x ", i+j);
1336                 }
1337                 bb_putchar('\n');
1338         }
1339
1340         return 0;
1341 }
1342 #endif /* ENABLE_I2CDETECT */