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