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