1/*
2 * at25.c -- support most SPI EEPROMs, such as Atmel AT25 models
3 *
4 * Copyright (C) 2006 David Brownell
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 */
11
12#include <linux/kernel.h>
13#include <linux/module.h>
14#include <linux/slab.h>
15#include <linux/delay.h>
16#include <linux/device.h>
17#include <linux/sched.h>
18
19#include <linux/spi/spi.h>
20#include <linux/spi/eeprom.h>
21#include <linux/property.h>
22
23/*
24 * NOTE: this is an *EEPROM* driver.  The vagaries of product naming
25 * mean that some AT25 products are EEPROMs, and others are FLASH.
26 * Handle FLASH chips with the drivers/mtd/devices/m25p80.c driver,
27 * not this one!
28 */
29
30struct at25_data {
31	struct spi_device	*spi;
32	struct memory_accessor	mem;
33	struct mutex		lock;
34	struct spi_eeprom	chip;
35	struct bin_attribute	bin;
36	unsigned		addrlen;
37};
38
39#define	AT25_WREN	0x06		/* latch the write enable */
40#define	AT25_WRDI	0x04		/* reset the write enable */
41#define	AT25_RDSR	0x05		/* read status register */
42#define	AT25_WRSR	0x01		/* write status register */
43#define	AT25_READ	0x03		/* read byte(s) */
44#define	AT25_WRITE	0x02		/* write byte(s)/sector */
45
46#define	AT25_SR_nRDY	0x01		/* nRDY = write-in-progress */
47#define	AT25_SR_WEN	0x02		/* write enable (latched) */
48#define	AT25_SR_BP0	0x04		/* BP for software writeprotect */
49#define	AT25_SR_BP1	0x08
50#define	AT25_SR_WPEN	0x80		/* writeprotect enable */
51
52#define	AT25_INSTR_BIT3	0x08		/* Additional address bit in instr */
53
54#define EE_MAXADDRLEN	3		/* 24 bit addresses, up to 2 MBytes */
55
56/* Specs often allow 5 msec for a page write, sometimes 20 msec;
57 * it's important to recover from write timeouts.
58 */
59#define	EE_TIMEOUT	25
60
61/*-------------------------------------------------------------------------*/
62
63#define	io_limit	PAGE_SIZE	/* bytes */
64
65static ssize_t
66at25_ee_read(
67	struct at25_data	*at25,
68	char			*buf,
69	unsigned		offset,
70	size_t			count
71)
72{
73	u8			command[EE_MAXADDRLEN + 1];
74	u8			*cp;
75	ssize_t			status;
76	struct spi_transfer	t[2];
77	struct spi_message	m;
78	u8			instr;
79
80	if (unlikely(offset >= at25->bin.size))
81		return 0;
82	if ((offset + count) > at25->bin.size)
83		count = at25->bin.size - offset;
84	if (unlikely(!count))
85		return count;
86
87	cp = command;
88
89	instr = AT25_READ;
90	if (at25->chip.flags & EE_INSTR_BIT3_IS_ADDR)
91		if (offset >= (1U << (at25->addrlen * 8)))
92			instr |= AT25_INSTR_BIT3;
93	*cp++ = instr;
94
95	/* 8/16/24-bit address is written MSB first */
96	switch (at25->addrlen) {
97	default:	/* case 3 */
98		*cp++ = offset >> 16;
99	case 2:
100		*cp++ = offset >> 8;
101	case 1:
102	case 0:	/* can't happen: for better codegen */
103		*cp++ = offset >> 0;
104	}
105
106	spi_message_init(&m);
107	memset(t, 0, sizeof t);
108
109	t[0].tx_buf = command;
110	t[0].len = at25->addrlen + 1;
111	spi_message_add_tail(&t[0], &m);
112
113	t[1].rx_buf = buf;
114	t[1].len = count;
115	spi_message_add_tail(&t[1], &m);
116
117	mutex_lock(&at25->lock);
118
119	/* Read it all at once.
120	 *
121	 * REVISIT that's potentially a problem with large chips, if
122	 * other devices on the bus need to be accessed regularly or
123	 * this chip is clocked very slowly
124	 */
125	status = spi_sync(at25->spi, &m);
126	dev_dbg(&at25->spi->dev,
127		"read %Zd bytes at %d --> %d\n",
128		count, offset, (int) status);
129
130	mutex_unlock(&at25->lock);
131	return status ? status : count;
132}
133
134static ssize_t
135at25_bin_read(struct file *filp, struct kobject *kobj,
136	      struct bin_attribute *bin_attr,
137	      char *buf, loff_t off, size_t count)
138{
139	struct device		*dev;
140	struct at25_data	*at25;
141
142	dev = container_of(kobj, struct device, kobj);
143	at25 = dev_get_drvdata(dev);
144
145	return at25_ee_read(at25, buf, off, count);
146}
147
148
149static ssize_t
150at25_ee_write(struct at25_data *at25, const char *buf, loff_t off,
151	      size_t count)
152{
153	ssize_t			status = 0;
154	unsigned		written = 0;
155	unsigned		buf_size;
156	u8			*bounce;
157
158	if (unlikely(off >= at25->bin.size))
159		return -EFBIG;
160	if ((off + count) > at25->bin.size)
161		count = at25->bin.size - off;
162	if (unlikely(!count))
163		return count;
164
165	/* Temp buffer starts with command and address */
166	buf_size = at25->chip.page_size;
167	if (buf_size > io_limit)
168		buf_size = io_limit;
169	bounce = kmalloc(buf_size + at25->addrlen + 1, GFP_KERNEL);
170	if (!bounce)
171		return -ENOMEM;
172
173	/* For write, rollover is within the page ... so we write at
174	 * most one page, then manually roll over to the next page.
175	 */
176	mutex_lock(&at25->lock);
177	do {
178		unsigned long	timeout, retries;
179		unsigned	segment;
180		unsigned	offset = (unsigned) off;
181		u8		*cp = bounce;
182		int		sr;
183		u8		instr;
184
185		*cp = AT25_WREN;
186		status = spi_write(at25->spi, cp, 1);
187		if (status < 0) {
188			dev_dbg(&at25->spi->dev, "WREN --> %d\n",
189					(int) status);
190			break;
191		}
192
193		instr = AT25_WRITE;
194		if (at25->chip.flags & EE_INSTR_BIT3_IS_ADDR)
195			if (offset >= (1U << (at25->addrlen * 8)))
196				instr |= AT25_INSTR_BIT3;
197		*cp++ = instr;
198
199		/* 8/16/24-bit address is written MSB first */
200		switch (at25->addrlen) {
201		default:	/* case 3 */
202			*cp++ = offset >> 16;
203		case 2:
204			*cp++ = offset >> 8;
205		case 1:
206		case 0:	/* can't happen: for better codegen */
207			*cp++ = offset >> 0;
208		}
209
210		/* Write as much of a page as we can */
211		segment = buf_size - (offset % buf_size);
212		if (segment > count)
213			segment = count;
214		memcpy(cp, buf, segment);
215		status = spi_write(at25->spi, bounce,
216				segment + at25->addrlen + 1);
217		dev_dbg(&at25->spi->dev,
218				"write %u bytes at %u --> %d\n",
219				segment, offset, (int) status);
220		if (status < 0)
221			break;
222
223		/* REVISIT this should detect (or prevent) failed writes
224		 * to readonly sections of the EEPROM...
225		 */
226
227		/* Wait for non-busy status */
228		timeout = jiffies + msecs_to_jiffies(EE_TIMEOUT);
229		retries = 0;
230		do {
231
232			sr = spi_w8r8(at25->spi, AT25_RDSR);
233			if (sr < 0 || (sr & AT25_SR_nRDY)) {
234				dev_dbg(&at25->spi->dev,
235					"rdsr --> %d (%02x)\n", sr, sr);
236				/* at HZ=100, this is sloooow */
237				msleep(1);
238				continue;
239			}
240			if (!(sr & AT25_SR_nRDY))
241				break;
242		} while (retries++ < 3 || time_before_eq(jiffies, timeout));
243
244		if ((sr < 0) || (sr & AT25_SR_nRDY)) {
245			dev_err(&at25->spi->dev,
246				"write %d bytes offset %d, "
247				"timeout after %u msecs\n",
248				segment, offset,
249				jiffies_to_msecs(jiffies -
250					(timeout - EE_TIMEOUT)));
251			status = -ETIMEDOUT;
252			break;
253		}
254
255		off += segment;
256		buf += segment;
257		count -= segment;
258		written += segment;
259
260	} while (count > 0);
261
262	mutex_unlock(&at25->lock);
263
264	kfree(bounce);
265	return written ? written : status;
266}
267
268static ssize_t
269at25_bin_write(struct file *filp, struct kobject *kobj,
270	       struct bin_attribute *bin_attr,
271	       char *buf, loff_t off, size_t count)
272{
273	struct device		*dev;
274	struct at25_data	*at25;
275
276	dev = container_of(kobj, struct device, kobj);
277	at25 = dev_get_drvdata(dev);
278
279	return at25_ee_write(at25, buf, off, count);
280}
281
282/*-------------------------------------------------------------------------*/
283
284/* Let in-kernel code access the eeprom data. */
285
286static ssize_t at25_mem_read(struct memory_accessor *mem, char *buf,
287			 off_t offset, size_t count)
288{
289	struct at25_data *at25 = container_of(mem, struct at25_data, mem);
290
291	return at25_ee_read(at25, buf, offset, count);
292}
293
294static ssize_t at25_mem_write(struct memory_accessor *mem, const char *buf,
295			  off_t offset, size_t count)
296{
297	struct at25_data *at25 = container_of(mem, struct at25_data, mem);
298
299	return at25_ee_write(at25, buf, offset, count);
300}
301
302/*-------------------------------------------------------------------------*/
303
304static int at25_fw_to_chip(struct device *dev, struct spi_eeprom *chip)
305{
306	u32 val;
307
308	memset(chip, 0, sizeof(*chip));
309	strncpy(chip->name, "at25", sizeof(chip->name));
310
311	if (device_property_read_u32(dev, "size", &val) == 0 ||
312	    device_property_read_u32(dev, "at25,byte-len", &val) == 0) {
313		chip->byte_len = val;
314	} else {
315		dev_err(dev, "Error: missing \"size\" property\n");
316		return -ENODEV;
317	}
318
319	if (device_property_read_u32(dev, "pagesize", &val) == 0 ||
320	    device_property_read_u32(dev, "at25,page-size", &val) == 0) {
321		chip->page_size = (u16)val;
322	} else {
323		dev_err(dev, "Error: missing \"pagesize\" property\n");
324		return -ENODEV;
325	}
326
327	if (device_property_read_u32(dev, "at25,addr-mode", &val) == 0) {
328		chip->flags = (u16)val;
329	} else {
330		if (device_property_read_u32(dev, "address-width", &val)) {
331			dev_err(dev,
332				"Error: missing \"address-width\" property\n");
333			return -ENODEV;
334		}
335		switch (val) {
336		case 8:
337			chip->flags |= EE_ADDR1;
338			break;
339		case 16:
340			chip->flags |= EE_ADDR2;
341			break;
342		case 24:
343			chip->flags |= EE_ADDR3;
344			break;
345		default:
346			dev_err(dev,
347				"Error: bad \"address-width\" property: %u\n",
348				val);
349			return -ENODEV;
350		}
351		if (device_property_present(dev, "read-only"))
352			chip->flags |= EE_READONLY;
353	}
354	return 0;
355}
356
357static int at25_probe(struct spi_device *spi)
358{
359	struct at25_data	*at25 = NULL;
360	struct spi_eeprom	chip;
361	int			err;
362	int			sr;
363	int			addrlen;
364
365	/* Chip description */
366	if (!spi->dev.platform_data) {
367		err = at25_fw_to_chip(&spi->dev, &chip);
368		if (err)
369			return err;
370	} else
371		chip = *(struct spi_eeprom *)spi->dev.platform_data;
372
373	/* For now we only support 8/16/24 bit addressing */
374	if (chip.flags & EE_ADDR1)
375		addrlen = 1;
376	else if (chip.flags & EE_ADDR2)
377		addrlen = 2;
378	else if (chip.flags & EE_ADDR3)
379		addrlen = 3;
380	else {
381		dev_dbg(&spi->dev, "unsupported address type\n");
382		return -EINVAL;
383	}
384
385	/* Ping the chip ... the status register is pretty portable,
386	 * unlike probing manufacturer IDs.  We do expect that system
387	 * firmware didn't write it in the past few milliseconds!
388	 */
389	sr = spi_w8r8(spi, AT25_RDSR);
390	if (sr < 0 || sr & AT25_SR_nRDY) {
391		dev_dbg(&spi->dev, "rdsr --> %d (%02x)\n", sr, sr);
392		return -ENXIO;
393	}
394
395	at25 = devm_kzalloc(&spi->dev, sizeof(struct at25_data), GFP_KERNEL);
396	if (!at25)
397		return -ENOMEM;
398
399	mutex_init(&at25->lock);
400	at25->chip = chip;
401	at25->spi = spi_dev_get(spi);
402	spi_set_drvdata(spi, at25);
403	at25->addrlen = addrlen;
404
405	/* Export the EEPROM bytes through sysfs, since that's convenient.
406	 * And maybe to other kernel code; it might hold a board's Ethernet
407	 * address, or board-specific calibration data generated on the
408	 * manufacturing floor.
409	 *
410	 * Default to root-only access to the data; EEPROMs often hold data
411	 * that's sensitive for read and/or write, like ethernet addresses,
412	 * security codes, board-specific manufacturing calibrations, etc.
413	 */
414	sysfs_bin_attr_init(&at25->bin);
415	at25->bin.attr.name = "eeprom";
416	at25->bin.attr.mode = S_IRUSR;
417	at25->bin.read = at25_bin_read;
418	at25->mem.read = at25_mem_read;
419
420	at25->bin.size = at25->chip.byte_len;
421	if (!(chip.flags & EE_READONLY)) {
422		at25->bin.write = at25_bin_write;
423		at25->bin.attr.mode |= S_IWUSR;
424		at25->mem.write = at25_mem_write;
425	}
426
427	err = sysfs_create_bin_file(&spi->dev.kobj, &at25->bin);
428	if (err)
429		return err;
430
431	if (chip.setup)
432		chip.setup(&at25->mem, chip.context);
433
434	dev_info(&spi->dev, "%Zd %s %s eeprom%s, pagesize %u\n",
435		(at25->bin.size < 1024)
436			? at25->bin.size
437			: (at25->bin.size / 1024),
438		(at25->bin.size < 1024) ? "Byte" : "KByte",
439		at25->chip.name,
440		(chip.flags & EE_READONLY) ? " (readonly)" : "",
441		at25->chip.page_size);
442	return 0;
443}
444
445static int at25_remove(struct spi_device *spi)
446{
447	struct at25_data	*at25;
448
449	at25 = spi_get_drvdata(spi);
450	sysfs_remove_bin_file(&spi->dev.kobj, &at25->bin);
451	return 0;
452}
453
454/*-------------------------------------------------------------------------*/
455
456static const struct of_device_id at25_of_match[] = {
457	{ .compatible = "atmel,at25", },
458	{ }
459};
460MODULE_DEVICE_TABLE(of, at25_of_match);
461
462static struct spi_driver at25_driver = {
463	.driver = {
464		.name		= "at25",
465		.owner		= THIS_MODULE,
466		.of_match_table = at25_of_match,
467	},
468	.probe		= at25_probe,
469	.remove		= at25_remove,
470};
471
472module_spi_driver(at25_driver);
473
474MODULE_DESCRIPTION("Driver for most SPI EEPROMs");
475MODULE_AUTHOR("David Brownell");
476MODULE_LICENSE("GPL");
477MODULE_ALIAS("spi:at25");
478