eeprom: at24: move at24_read() below at24_eeprom_write()
[cascardo/linux.git] / drivers / misc / eeprom / at24.c
1 /*
2  * at24.c - handle most I2C EEPROMs
3  *
4  * Copyright (C) 2005-2007 David Brownell
5  * Copyright (C) 2008 Wolfram Sang, Pengutronix
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  */
12 #include <linux/kernel.h>
13 #include <linux/init.h>
14 #include <linux/module.h>
15 #include <linux/slab.h>
16 #include <linux/delay.h>
17 #include <linux/mutex.h>
18 #include <linux/mod_devicetable.h>
19 #include <linux/log2.h>
20 #include <linux/bitops.h>
21 #include <linux/jiffies.h>
22 #include <linux/of.h>
23 #include <linux/acpi.h>
24 #include <linux/i2c.h>
25 #include <linux/nvmem-provider.h>
26 #include <linux/platform_data/at24.h>
27
28 /*
29  * I2C EEPROMs from most vendors are inexpensive and mostly interchangeable.
30  * Differences between different vendor product lines (like Atmel AT24C or
31  * MicroChip 24LC, etc) won't much matter for typical read/write access.
32  * There are also I2C RAM chips, likewise interchangeable. One example
33  * would be the PCF8570, which acts like a 24c02 EEPROM (256 bytes).
34  *
35  * However, misconfiguration can lose data. "Set 16-bit memory address"
36  * to a part with 8-bit addressing will overwrite data. Writing with too
37  * big a page size also loses data. And it's not safe to assume that the
38  * conventional addresses 0x50..0x57 only hold eeproms; a PCF8563 RTC
39  * uses 0x51, for just one example.
40  *
41  * Accordingly, explicit board-specific configuration data should be used
42  * in almost all cases. (One partial exception is an SMBus used to access
43  * "SPD" data for DRAM sticks. Those only use 24c02 EEPROMs.)
44  *
45  * So this driver uses "new style" I2C driver binding, expecting to be
46  * told what devices exist. That may be in arch/X/mach-Y/board-Z.c or
47  * similar kernel-resident tables; or, configuration data coming from
48  * a bootloader.
49  *
50  * Other than binding model, current differences from "eeprom" driver are
51  * that this one handles write access and isn't restricted to 24c02 devices.
52  * It also handles larger devices (32 kbit and up) with two-byte addresses,
53  * which won't work on pure SMBus systems.
54  */
55
56 struct at24_data {
57         struct at24_platform_data chip;
58         int use_smbus;
59         int use_smbus_write;
60
61         /*
62          * Lock protects against activities from other Linux tasks,
63          * but not from changes by other I2C masters.
64          */
65         struct mutex lock;
66
67         u8 *writebuf;
68         unsigned write_max;
69         unsigned num_addresses;
70
71         struct nvmem_config nvmem_config;
72         struct nvmem_device *nvmem;
73
74         /*
75          * Some chips tie up multiple I2C addresses; dummy devices reserve
76          * them for us, and we'll use them with SMBus calls.
77          */
78         struct i2c_client *client[];
79 };
80
81 /*
82  * This parameter is to help this driver avoid blocking other drivers out
83  * of I2C for potentially troublesome amounts of time. With a 100 kHz I2C
84  * clock, one 256 byte read takes about 1/43 second which is excessive;
85  * but the 1/170 second it takes at 400 kHz may be quite reasonable; and
86  * at 1 MHz (Fm+) a 1/430 second delay could easily be invisible.
87  *
88  * This value is forced to be a power of two so that writes align on pages.
89  */
90 static unsigned io_limit = 128;
91 module_param(io_limit, uint, 0);
92 MODULE_PARM_DESC(io_limit, "Maximum bytes per I/O (default 128)");
93
94 /*
95  * Specs often allow 5 msec for a page write, sometimes 20 msec;
96  * it's important to recover from write timeouts.
97  */
98 static unsigned write_timeout = 25;
99 module_param(write_timeout, uint, 0);
100 MODULE_PARM_DESC(write_timeout, "Time (in ms) to try writes (default 25)");
101
102 #define AT24_SIZE_BYTELEN 5
103 #define AT24_SIZE_FLAGS 8
104
105 #define AT24_BITMASK(x) (BIT(x) - 1)
106
107 /* create non-zero magic value for given eeprom parameters */
108 #define AT24_DEVICE_MAGIC(_len, _flags)                 \
109         ((1 << AT24_SIZE_FLAGS | (_flags))              \
110             << AT24_SIZE_BYTELEN | ilog2(_len))
111
112 static const struct i2c_device_id at24_ids[] = {
113         /* needs 8 addresses as A0-A2 are ignored */
114         { "24c00",      AT24_DEVICE_MAGIC(128 / 8,      AT24_FLAG_TAKE8ADDR) },
115         /* old variants can't be handled with this generic entry! */
116         { "24c01",      AT24_DEVICE_MAGIC(1024 / 8,     0) },
117         { "24c02",      AT24_DEVICE_MAGIC(2048 / 8,     0) },
118         /* spd is a 24c02 in memory DIMMs */
119         { "spd",        AT24_DEVICE_MAGIC(2048 / 8,
120                                 AT24_FLAG_READONLY | AT24_FLAG_IRUGO) },
121         { "24c04",      AT24_DEVICE_MAGIC(4096 / 8,     0) },
122         /* 24rf08 quirk is handled at i2c-core */
123         { "24c08",      AT24_DEVICE_MAGIC(8192 / 8,     0) },
124         { "24c16",      AT24_DEVICE_MAGIC(16384 / 8,    0) },
125         { "24c32",      AT24_DEVICE_MAGIC(32768 / 8,    AT24_FLAG_ADDR16) },
126         { "24c64",      AT24_DEVICE_MAGIC(65536 / 8,    AT24_FLAG_ADDR16) },
127         { "24c128",     AT24_DEVICE_MAGIC(131072 / 8,   AT24_FLAG_ADDR16) },
128         { "24c256",     AT24_DEVICE_MAGIC(262144 / 8,   AT24_FLAG_ADDR16) },
129         { "24c512",     AT24_DEVICE_MAGIC(524288 / 8,   AT24_FLAG_ADDR16) },
130         { "24c1024",    AT24_DEVICE_MAGIC(1048576 / 8,  AT24_FLAG_ADDR16) },
131         { "at24", 0 },
132         { /* END OF LIST */ }
133 };
134 MODULE_DEVICE_TABLE(i2c, at24_ids);
135
136 static const struct acpi_device_id at24_acpi_ids[] = {
137         { "INT3499", AT24_DEVICE_MAGIC(8192 / 8, 0) },
138         { }
139 };
140 MODULE_DEVICE_TABLE(acpi, at24_acpi_ids);
141
142 /*-------------------------------------------------------------------------*/
143
144 /*
145  * This routine supports chips which consume multiple I2C addresses. It
146  * computes the addressing information to be used for a given r/w request.
147  * Assumes that sanity checks for offset happened at sysfs-layer.
148  */
149 static struct i2c_client *at24_translate_offset(struct at24_data *at24,
150                 unsigned *offset)
151 {
152         unsigned i;
153
154         if (at24->chip.flags & AT24_FLAG_ADDR16) {
155                 i = *offset >> 16;
156                 *offset &= 0xffff;
157         } else {
158                 i = *offset >> 8;
159                 *offset &= 0xff;
160         }
161
162         return at24->client[i];
163 }
164
165 static ssize_t at24_eeprom_read(struct at24_data *at24, char *buf,
166                 unsigned offset, size_t count)
167 {
168         struct i2c_msg msg[2];
169         u8 msgbuf[2];
170         struct i2c_client *client;
171         unsigned long timeout, read_time;
172         int status, i;
173
174         memset(msg, 0, sizeof(msg));
175
176         /*
177          * REVISIT some multi-address chips don't rollover page reads to
178          * the next slave address, so we may need to truncate the count.
179          * Those chips might need another quirk flag.
180          *
181          * If the real hardware used four adjacent 24c02 chips and that
182          * were misconfigured as one 24c08, that would be a similar effect:
183          * one "eeprom" file not four, but larger reads would fail when
184          * they crossed certain pages.
185          */
186
187         /*
188          * Slave address and byte offset derive from the offset. Always
189          * set the byte address; on a multi-master board, another master
190          * may have changed the chip's "current" address pointer.
191          */
192         client = at24_translate_offset(at24, &offset);
193
194         if (count > io_limit)
195                 count = io_limit;
196
197         if (at24->use_smbus) {
198                 /* Smaller eeproms can work given some SMBus extension calls */
199                 if (count > I2C_SMBUS_BLOCK_MAX)
200                         count = I2C_SMBUS_BLOCK_MAX;
201         } else {
202                 /*
203                  * When we have a better choice than SMBus calls, use a
204                  * combined I2C message. Write address; then read up to
205                  * io_limit data bytes. Note that read page rollover helps us
206                  * here (unlike writes). msgbuf is u8 and will cast to our
207                  * needs.
208                  */
209                 i = 0;
210                 if (at24->chip.flags & AT24_FLAG_ADDR16)
211                         msgbuf[i++] = offset >> 8;
212                 msgbuf[i++] = offset;
213
214                 msg[0].addr = client->addr;
215                 msg[0].buf = msgbuf;
216                 msg[0].len = i;
217
218                 msg[1].addr = client->addr;
219                 msg[1].flags = I2C_M_RD;
220                 msg[1].buf = buf;
221                 msg[1].len = count;
222         }
223
224         /*
225          * Reads fail if the previous write didn't complete yet. We may
226          * loop a few times until this one succeeds, waiting at least
227          * long enough for one entire page write to work.
228          */
229         timeout = jiffies + msecs_to_jiffies(write_timeout);
230         do {
231                 read_time = jiffies;
232                 if (at24->use_smbus) {
233                         status = i2c_smbus_read_i2c_block_data_or_emulated(client, offset,
234                                                                            count, buf);
235                 } else {
236                         status = i2c_transfer(client->adapter, msg, 2);
237                         if (status == 2)
238                                 status = count;
239                 }
240                 dev_dbg(&client->dev, "read %zu@%d --> %d (%ld)\n",
241                                 count, offset, status, jiffies);
242
243                 if (status == count)
244                         return count;
245
246                 usleep_range(1000, 1500);
247         } while (time_before(read_time, timeout));
248
249         return -ETIMEDOUT;
250 }
251
252 /*
253  * Note that if the hardware write-protect pin is pulled high, the whole
254  * chip is normally write protected. But there are plenty of product
255  * variants here, including OTP fuses and partial chip protect.
256  *
257  * We only use page mode writes; the alternative is sloooow. This routine
258  * writes at most one page.
259  */
260 static ssize_t at24_eeprom_write(struct at24_data *at24, const char *buf,
261                 unsigned offset, size_t count)
262 {
263         struct i2c_client *client;
264         struct i2c_msg msg;
265         ssize_t status = 0;
266         unsigned long timeout, write_time;
267         unsigned next_page;
268
269         /* Get corresponding I2C address and adjust offset */
270         client = at24_translate_offset(at24, &offset);
271
272         /* write_max is at most a page */
273         if (count > at24->write_max)
274                 count = at24->write_max;
275
276         /* Never roll over backwards, to the start of this page */
277         next_page = roundup(offset + 1, at24->chip.page_size);
278         if (offset + count > next_page)
279                 count = next_page - offset;
280
281         /* If we'll use I2C calls for I/O, set up the message */
282         if (!at24->use_smbus) {
283                 int i = 0;
284
285                 msg.addr = client->addr;
286                 msg.flags = 0;
287
288                 /* msg.buf is u8 and casts will mask the values */
289                 msg.buf = at24->writebuf;
290                 if (at24->chip.flags & AT24_FLAG_ADDR16)
291                         msg.buf[i++] = offset >> 8;
292
293                 msg.buf[i++] = offset;
294                 memcpy(&msg.buf[i], buf, count);
295                 msg.len = i + count;
296         }
297
298         /*
299          * Writes fail if the previous one didn't complete yet. We may
300          * loop a few times until this one succeeds, waiting at least
301          * long enough for one entire page write to work.
302          */
303         timeout = jiffies + msecs_to_jiffies(write_timeout);
304         do {
305                 write_time = jiffies;
306                 if (at24->use_smbus_write) {
307                         switch (at24->use_smbus_write) {
308                         case I2C_SMBUS_I2C_BLOCK_DATA:
309                                 status = i2c_smbus_write_i2c_block_data(client,
310                                                 offset, count, buf);
311                                 break;
312                         case I2C_SMBUS_BYTE_DATA:
313                                 status = i2c_smbus_write_byte_data(client,
314                                                 offset, buf[0]);
315                                 break;
316                         }
317
318                         if (status == 0)
319                                 status = count;
320                 } else {
321                         status = i2c_transfer(client->adapter, &msg, 1);
322                         if (status == 1)
323                                 status = count;
324                 }
325                 dev_dbg(&client->dev, "write %zu@%d --> %zd (%ld)\n",
326                                 count, offset, status, jiffies);
327
328                 if (status == count)
329                         return count;
330
331                 usleep_range(1000, 1500);
332         } while (time_before(write_time, timeout));
333
334         return -ETIMEDOUT;
335 }
336
337 static int at24_read(void *priv, unsigned int off, void *val, size_t count)
338 {
339         struct at24_data *at24 = priv;
340         char *buf = val;
341
342         if (unlikely(!count))
343                 return count;
344
345         /*
346          * Read data from chip, protecting against concurrent updates
347          * from this host, but not from other I2C masters.
348          */
349         mutex_lock(&at24->lock);
350
351         while (count) {
352                 int     status;
353
354                 status = at24_eeprom_read(at24, buf, off, count);
355                 if (status < 0) {
356                         mutex_unlock(&at24->lock);
357                         return status;
358                 }
359                 buf += status;
360                 off += status;
361                 count -= status;
362         }
363
364         mutex_unlock(&at24->lock);
365
366         return 0;
367 }
368
369 static int at24_write(void *priv, unsigned int off, void *val, size_t count)
370 {
371         struct at24_data *at24 = priv;
372         char *buf = val;
373
374         if (unlikely(!count))
375                 return -EINVAL;
376
377         /*
378          * Write data to chip, protecting against concurrent updates
379          * from this host, but not from other I2C masters.
380          */
381         mutex_lock(&at24->lock);
382
383         while (count) {
384                 int status;
385
386                 status = at24_eeprom_write(at24, buf, off, count);
387                 if (status < 0) {
388                         mutex_unlock(&at24->lock);
389                         return status;
390                 }
391                 buf += status;
392                 off += status;
393                 count -= status;
394         }
395
396         mutex_unlock(&at24->lock);
397
398         return 0;
399 }
400
401 #ifdef CONFIG_OF
402 static void at24_get_ofdata(struct i2c_client *client,
403                 struct at24_platform_data *chip)
404 {
405         const __be32 *val;
406         struct device_node *node = client->dev.of_node;
407
408         if (node) {
409                 if (of_get_property(node, "read-only", NULL))
410                         chip->flags |= AT24_FLAG_READONLY;
411                 val = of_get_property(node, "pagesize", NULL);
412                 if (val)
413                         chip->page_size = be32_to_cpup(val);
414         }
415 }
416 #else
417 static void at24_get_ofdata(struct i2c_client *client,
418                 struct at24_platform_data *chip)
419 { }
420 #endif /* CONFIG_OF */
421
422 static int at24_probe(struct i2c_client *client, const struct i2c_device_id *id)
423 {
424         struct at24_platform_data chip;
425         kernel_ulong_t magic = 0;
426         bool writable;
427         int use_smbus = 0;
428         int use_smbus_write = 0;
429         struct at24_data *at24;
430         int err;
431         unsigned i, num_addresses;
432
433         if (client->dev.platform_data) {
434                 chip = *(struct at24_platform_data *)client->dev.platform_data;
435         } else {
436                 if (id) {
437                         magic = id->driver_data;
438                 } else {
439                         const struct acpi_device_id *aid;
440
441                         aid = acpi_match_device(at24_acpi_ids, &client->dev);
442                         if (aid)
443                                 magic = aid->driver_data;
444                 }
445                 if (!magic)
446                         return -ENODEV;
447
448                 chip.byte_len = BIT(magic & AT24_BITMASK(AT24_SIZE_BYTELEN));
449                 magic >>= AT24_SIZE_BYTELEN;
450                 chip.flags = magic & AT24_BITMASK(AT24_SIZE_FLAGS);
451                 /*
452                  * This is slow, but we can't know all eeproms, so we better
453                  * play safe. Specifying custom eeprom-types via platform_data
454                  * is recommended anyhow.
455                  */
456                 chip.page_size = 1;
457
458                 /* update chipdata if OF is present */
459                 at24_get_ofdata(client, &chip);
460
461                 chip.setup = NULL;
462                 chip.context = NULL;
463         }
464
465         if (!is_power_of_2(chip.byte_len))
466                 dev_warn(&client->dev,
467                         "byte_len looks suspicious (no power of 2)!\n");
468         if (!chip.page_size) {
469                 dev_err(&client->dev, "page_size must not be 0!\n");
470                 return -EINVAL;
471         }
472         if (!is_power_of_2(chip.page_size))
473                 dev_warn(&client->dev,
474                         "page_size looks suspicious (no power of 2)!\n");
475
476         /* Use I2C operations unless we're stuck with SMBus extensions. */
477         if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
478                 if (chip.flags & AT24_FLAG_ADDR16)
479                         return -EPFNOSUPPORT;
480
481                 if (i2c_check_functionality(client->adapter,
482                                 I2C_FUNC_SMBUS_READ_I2C_BLOCK)) {
483                         use_smbus = I2C_SMBUS_I2C_BLOCK_DATA;
484                 } else if (i2c_check_functionality(client->adapter,
485                                 I2C_FUNC_SMBUS_READ_WORD_DATA)) {
486                         use_smbus = I2C_SMBUS_WORD_DATA;
487                 } else if (i2c_check_functionality(client->adapter,
488                                 I2C_FUNC_SMBUS_READ_BYTE_DATA)) {
489                         use_smbus = I2C_SMBUS_BYTE_DATA;
490                 } else {
491                         return -EPFNOSUPPORT;
492                 }
493
494                 if (i2c_check_functionality(client->adapter,
495                                 I2C_FUNC_SMBUS_WRITE_I2C_BLOCK)) {
496                         use_smbus_write = I2C_SMBUS_I2C_BLOCK_DATA;
497                 } else if (i2c_check_functionality(client->adapter,
498                                 I2C_FUNC_SMBUS_WRITE_BYTE_DATA)) {
499                         use_smbus_write = I2C_SMBUS_BYTE_DATA;
500                         chip.page_size = 1;
501                 }
502         }
503
504         if (chip.flags & AT24_FLAG_TAKE8ADDR)
505                 num_addresses = 8;
506         else
507                 num_addresses = DIV_ROUND_UP(chip.byte_len,
508                         (chip.flags & AT24_FLAG_ADDR16) ? 65536 : 256);
509
510         at24 = devm_kzalloc(&client->dev, sizeof(struct at24_data) +
511                 num_addresses * sizeof(struct i2c_client *), GFP_KERNEL);
512         if (!at24)
513                 return -ENOMEM;
514
515         mutex_init(&at24->lock);
516         at24->use_smbus = use_smbus;
517         at24->use_smbus_write = use_smbus_write;
518         at24->chip = chip;
519         at24->num_addresses = num_addresses;
520
521         writable = !(chip.flags & AT24_FLAG_READONLY);
522         if (writable) {
523                 if (!use_smbus || use_smbus_write) {
524
525                         unsigned write_max = chip.page_size;
526
527                         if (write_max > io_limit)
528                                 write_max = io_limit;
529                         if (use_smbus && write_max > I2C_SMBUS_BLOCK_MAX)
530                                 write_max = I2C_SMBUS_BLOCK_MAX;
531                         at24->write_max = write_max;
532
533                         /* buffer (data + address at the beginning) */
534                         at24->writebuf = devm_kzalloc(&client->dev,
535                                 write_max + 2, GFP_KERNEL);
536                         if (!at24->writebuf)
537                                 return -ENOMEM;
538                 } else {
539                         dev_warn(&client->dev,
540                                 "cannot write due to controller restrictions.");
541                 }
542         }
543
544         at24->client[0] = client;
545
546         /* use dummy devices for multiple-address chips */
547         for (i = 1; i < num_addresses; i++) {
548                 at24->client[i] = i2c_new_dummy(client->adapter,
549                                         client->addr + i);
550                 if (!at24->client[i]) {
551                         dev_err(&client->dev, "address 0x%02x unavailable\n",
552                                         client->addr + i);
553                         err = -EADDRINUSE;
554                         goto err_clients;
555                 }
556         }
557
558         at24->nvmem_config.name = dev_name(&client->dev);
559         at24->nvmem_config.dev = &client->dev;
560         at24->nvmem_config.read_only = !writable;
561         at24->nvmem_config.root_only = true;
562         at24->nvmem_config.owner = THIS_MODULE;
563         at24->nvmem_config.compat = true;
564         at24->nvmem_config.base_dev = &client->dev;
565         at24->nvmem_config.reg_read = at24_read;
566         at24->nvmem_config.reg_write = at24_write;
567         at24->nvmem_config.priv = at24;
568         at24->nvmem_config.stride = 4;
569         at24->nvmem_config.word_size = 1;
570         at24->nvmem_config.size = chip.byte_len;
571
572         at24->nvmem = nvmem_register(&at24->nvmem_config);
573
574         if (IS_ERR(at24->nvmem)) {
575                 err = PTR_ERR(at24->nvmem);
576                 goto err_clients;
577         }
578
579         i2c_set_clientdata(client, at24);
580
581         dev_info(&client->dev, "%u byte %s EEPROM, %s, %u bytes/write\n",
582                 chip.byte_len, client->name,
583                 writable ? "writable" : "read-only", at24->write_max);
584         if (use_smbus == I2C_SMBUS_WORD_DATA ||
585             use_smbus == I2C_SMBUS_BYTE_DATA) {
586                 dev_notice(&client->dev, "Falling back to %s reads, "
587                            "performance will suffer\n", use_smbus ==
588                            I2C_SMBUS_WORD_DATA ? "word" : "byte");
589         }
590
591         /* export data to kernel code */
592         if (chip.setup)
593                 chip.setup(at24->nvmem, chip.context);
594
595         return 0;
596
597 err_clients:
598         for (i = 1; i < num_addresses; i++)
599                 if (at24->client[i])
600                         i2c_unregister_device(at24->client[i]);
601
602         return err;
603 }
604
605 static int at24_remove(struct i2c_client *client)
606 {
607         struct at24_data *at24;
608         int i;
609
610         at24 = i2c_get_clientdata(client);
611
612         nvmem_unregister(at24->nvmem);
613
614         for (i = 1; i < at24->num_addresses; i++)
615                 i2c_unregister_device(at24->client[i]);
616
617         return 0;
618 }
619
620 /*-------------------------------------------------------------------------*/
621
622 static struct i2c_driver at24_driver = {
623         .driver = {
624                 .name = "at24",
625                 .acpi_match_table = ACPI_PTR(at24_acpi_ids),
626         },
627         .probe = at24_probe,
628         .remove = at24_remove,
629         .id_table = at24_ids,
630 };
631
632 static int __init at24_init(void)
633 {
634         if (!io_limit) {
635                 pr_err("at24: io_limit must not be 0!\n");
636                 return -EINVAL;
637         }
638
639         io_limit = rounddown_pow_of_two(io_limit);
640         return i2c_add_driver(&at24_driver);
641 }
642 module_init(at24_init);
643
644 static void __exit at24_exit(void)
645 {
646         i2c_del_driver(&at24_driver);
647 }
648 module_exit(at24_exit);
649
650 MODULE_DESCRIPTION("Driver for most I2C EEPROMs");
651 MODULE_AUTHOR("David Brownell and Wolfram Sang");
652 MODULE_LICENSE("GPL");