1 /* Copyright 2013-2014 IBM Corp.
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * 	http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12  * implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <inttypes.h>
20 
21 #include "libflash.h"
22 #include "libflash-priv.h"
23 #include "ecc.h"
24 #include "blocklevel.h"
25 
26 static const struct flash_info flash_info[] = {
27 	{ 0xc22018, 0x01000000, FL_ERASE_ALL | FL_CAN_4B, "Macronix MXxxL12835F"},
28 	{ 0xc22019, 0x02000000, FL_ERASE_ALL | FL_CAN_4B, "Macronix MXxxL25635F"},
29 	{ 0xc2201a, 0x04000000, FL_ERASE_ALL | FL_CAN_4B, "Macronix MXxxL51235F"},
30 	{ 0xc2201b, 0x08000000, FL_ERASE_ALL | FL_CAN_4B, "Macronix MX66L1G45G"},
31 	{ 0xef4018, 0x01000000, FL_ERASE_ALL,             "Winbond W25Q128BV"   },
32 	{ 0xef4019, 0x02000000, FL_ERASE_ALL | FL_ERASE_64K | FL_CAN_4B |
33 				FL_ERASE_BULK,
34 							"Winbond W25Q256BV"},
35 	{ 0x20ba20, 0x04000000, FL_ERASE_4K  | FL_ERASE_64K | FL_CAN_4B |
36                                 FL_ERASE_BULK | FL_MICRON_BUGS,
37                                                           "Micron N25Qx512Ax"   },
38 	{ 0x20ba19, 0x02000000, FL_ERASE_4K  | FL_ERASE_64K | FL_CAN_4B |
39                                 FL_ERASE_BULK | FL_MICRON_BUGS,
40                                                           "Micron N25Q256Ax"    },
41 	{ 0x1940ef, 0x02000000, FL_ERASE_4K  | FL_ERASE_64K | FL_CAN_4B |
42 				FL_ERASE_BULK | FL_MICRON_BUGS,
43 							"Micron N25Qx256Ax"   },
44 	{ 0x4d5444, 0x02000000, FL_ERASE_ALL | FL_CAN_4B, "File Abstraction"},
45 	{ 0x55aa55, 0x00100000, FL_ERASE_ALL | FL_CAN_4B, "TEST_FLASH" },
46 	{ 0xaa55aa, 0x02000000, FL_ERASE_ALL | FL_CAN_4B, "EMULATED_FLASH"},
47 };
48 
49 struct flash_chip {
50 	struct spi_flash_ctrl	*ctrl;		/* Controller */
51 	struct flash_info	info;		/* Flash info */
52 	uint32_t		tsize;		/* Corrected flash size */
53 	uint32_t		min_erase_mask;	/* Minimum erase size */
54 	bool			mode_4b;	/* Flash currently in 4b mode */
55 	struct flash_req	*cur_req;	/* Current request */
56 	void			*smart_buf;	/* Buffer for smart writes */
57 	struct blocklevel_device bl;
58 };
59 
60 #ifndef __SKIBOOT__
61 bool libflash_debug;
62 #endif
63 
fl_read_stat(struct spi_flash_ctrl * ct,uint8_t * stat)64 int fl_read_stat(struct spi_flash_ctrl *ct, uint8_t *stat)
65 {
66 	return ct->cmd_rd(ct, CMD_RDSR, false, 0, stat, 1);
67 }
68 
fl_micron_status(struct spi_flash_ctrl * ct)69 static void fl_micron_status(struct spi_flash_ctrl *ct)
70 {
71 	uint8_t flst;
72 
73 	/*
74 	 * After a success status on a write or erase, we
75 	 * need to do that command or some chip variants will
76 	 * lock
77 	 */
78 	ct->cmd_rd(ct, CMD_MIC_RDFLST, false, 0, &flst, 1);
79 }
80 
81 /* Synchronous write completion, probably need a yield hook */
fl_sync_wait_idle(struct spi_flash_ctrl * ct)82 int fl_sync_wait_idle(struct spi_flash_ctrl *ct)
83 {
84 	uint8_t stat;
85 	int rc;
86 
87 	/* XXX Add timeout */
88 	for (;;) {
89 		rc = fl_read_stat(ct, &stat);
90 		if (rc) return rc;
91 		if (!(stat & STAT_WIP)) {
92 			if (ct->finfo->flags & FL_MICRON_BUGS)
93 				fl_micron_status(ct);
94 			return 0;
95 		}
96 	}
97 	/* return FLASH_ERR_WIP_TIMEOUT; */
98 }
99 
100 /* Exported for internal use */
fl_wren(struct spi_flash_ctrl * ct)101 int fl_wren(struct spi_flash_ctrl *ct)
102 {
103 	int i, rc;
104 	uint8_t stat;
105 
106 	/* Some flashes need it to be hammered */
107 	for (i = 0; i < 1000; i++) {
108 		rc = ct->cmd_wr(ct, CMD_WREN, false, 0, NULL, 0);
109 		if (rc) return rc;
110 		rc = fl_read_stat(ct, &stat);
111 		if (rc) return rc;
112 		if (stat & STAT_WIP) {
113 			FL_ERR("LIBFLASH: WREN has WIP status set !\n");
114 			rc = fl_sync_wait_idle(ct);
115 			if (rc)
116 				return rc;
117 			continue;
118 		}
119 		if (stat & STAT_WEN)
120 			return 0;
121 	}
122 	return FLASH_ERR_WREN_TIMEOUT;
123 }
124 
flash_read(struct blocklevel_device * bl,uint64_t pos,void * buf,uint64_t len)125 static int flash_read(struct blocklevel_device *bl, uint64_t pos, void *buf, uint64_t len)
126 {
127 	struct flash_chip *c = container_of(bl, struct flash_chip, bl);
128 	struct spi_flash_ctrl *ct = c->ctrl;
129 
130 	/* XXX Add sanity/bound checking */
131 
132 	/*
133 	 * If the controller supports read and either we are in 3b mode
134 	 * or we are in 4b *and* the controller supports it, then do a
135 	 * high level read.
136 	 */
137 	if ((!c->mode_4b || ct->set_4b) && ct->read)
138 		return ct->read(ct, pos, buf, len);
139 
140 	/* Otherwise, go manual if supported */
141 	if (!ct->cmd_rd)
142 		return FLASH_ERR_CTRL_CMD_UNSUPPORTED;
143 	return ct->cmd_rd(ct, CMD_READ, true, pos, buf, len);
144 }
145 
146 #define COPY_BUFFER_LENGTH 4096
147 
148 /*
149  * This provides a wrapper around flash_read on ECCed data
150  * len is length of data without ECC attached
151  */
flash_read_corrected(struct blocklevel_device * bl,uint32_t pos,void * buf,uint32_t len,bool ecc)152 int flash_read_corrected(struct blocklevel_device *bl, uint32_t pos, void *buf,
153 		uint32_t len, bool ecc)
154 {
155 	struct ecc64 *bufecc;
156 	uint32_t copylen;
157 	int rc;
158 	uint8_t ret;
159 
160 	if (!ecc)
161 		return flash_read(bl, pos, buf, len);
162 
163 	/* Copy the buffer in chunks */
164 	bufecc = malloc(ecc_buffer_size(COPY_BUFFER_LENGTH));
165 	if (!bufecc)
166 		return FLASH_ERR_MALLOC_FAILED;
167 
168 	while (len > 0) {
169 		/* What's left to copy? */
170 		copylen = MIN(len, COPY_BUFFER_LENGTH);
171 
172 		/* Read ECCed data from flash */
173 		rc = flash_read(bl, pos, bufecc, ecc_buffer_size(copylen));
174 		if (rc)
175 			goto err;
176 
177 		/* Extract data from ECCed data */
178 		ret = memcpy_from_ecc(buf, bufecc, copylen);
179 		if (ret) {
180 			rc = FLASH_ERR_ECC_INVALID;
181 			goto err;
182 		}
183 
184 		/* Update for next copy */
185 		len -= copylen;
186 		buf = (uint8_t *)buf + copylen;
187 		pos += ecc_buffer_size(copylen);
188 	}
189 
190 	rc = 0;
191 
192 err:
193 	free(bufecc);
194 	return rc;
195 }
196 
fl_get_best_erase(struct flash_chip * c,uint32_t dst,uint32_t size,uint32_t * chunk,uint8_t * cmd)197 static void fl_get_best_erase(struct flash_chip *c, uint32_t dst, uint32_t size,
198 			      uint32_t *chunk, uint8_t *cmd)
199 {
200 	/* Smaller than 32k, use 4k */
201 	if ((dst & 0x7fff) || (size < 0x8000)) {
202 		*chunk = 0x1000;
203 		*cmd = CMD_SE;
204 		return;
205 	}
206 	/* Smaller than 64k and 32k is supported, use it */
207 	if ((c->info.flags & FL_ERASE_32K) &&
208 	    ((dst & 0xffff) || (size < 0x10000))) {
209 		*chunk = 0x8000;
210 		*cmd = CMD_BE32K;
211 		return;
212 	}
213 	/* If 64K is not supported, use whatever smaller size is */
214 	if (!(c->info.flags & FL_ERASE_64K)) {
215 		if (c->info.flags & FL_ERASE_32K) {
216 			*chunk = 0x8000;
217 			*cmd = CMD_BE32K;
218 		} else {
219 			*chunk = 0x1000;
220 			*cmd = CMD_SE;
221 		}
222 		return;
223 	}
224 	/* Allright, let's go for 64K */
225 	*chunk = 0x10000;
226 	*cmd = CMD_BE;
227 }
228 
flash_erase(struct blocklevel_device * bl,uint64_t dst,uint64_t size)229 static int flash_erase(struct blocklevel_device *bl, uint64_t dst, uint64_t size)
230 {
231 	struct flash_chip *c = container_of(bl, struct flash_chip, bl);
232 	struct spi_flash_ctrl *ct = c->ctrl;
233 	uint32_t chunk;
234 	uint8_t cmd;
235 	int rc;
236 
237 	/* Some sanity checking */
238 	if (((dst + size) <= dst) || !size || (dst + size) > c->tsize)
239 		return FLASH_ERR_PARM_ERROR;
240 
241 	/* Check boundaries fit erase blocks */
242 	if ((dst | size) & c->min_erase_mask)
243 		return FLASH_ERR_ERASE_BOUNDARY;
244 
245 	FL_DBG("LIBFLASH: Erasing 0x%" PRIx64"..0%" PRIx64 "...\n",
246 	       dst, dst + size);
247 
248 	/* Use controller erase if supported */
249 	if (ct->erase)
250 		return ct->erase(ct, dst, size);
251 
252 	/* Allright, loop as long as there's something to erase */
253 	while(size) {
254 		/* How big can we make it based on alignent & size */
255 		fl_get_best_erase(c, dst, size, &chunk, &cmd);
256 
257 		/* Poke write enable */
258 		rc = fl_wren(ct);
259 		if (rc)
260 			return rc;
261 
262 		/* Send erase command */
263 		rc = ct->cmd_wr(ct, cmd, true, dst, NULL, 0);
264 		if (rc)
265 			return rc;
266 
267 		/* Wait for write complete */
268 		rc = fl_sync_wait_idle(ct);
269 		if (rc)
270 			return rc;
271 
272 		size -= chunk;
273 		dst += chunk;
274 	}
275 	return 0;
276 }
277 
flash_erase_chip(struct flash_chip * c)278 int flash_erase_chip(struct flash_chip *c)
279 {
280 	struct spi_flash_ctrl *ct = c->ctrl;
281 	int rc;
282 
283 	/* XXX TODO: Fallback to using normal erases */
284 	if (!(c->info.flags & (FL_ERASE_CHIP|FL_ERASE_BULK)))
285 		return FLASH_ERR_CHIP_ER_NOT_SUPPORTED;
286 
287 	FL_DBG("LIBFLASH: Erasing chip...\n");
288 
289 	/* Use controller erase if supported */
290 	if (ct->erase)
291 		return ct->erase(ct, 0, 0xffffffff);
292 
293 	rc = fl_wren(ct);
294 	if (rc) return rc;
295 
296 	if (c->info.flags & FL_ERASE_CHIP)
297 		rc = ct->cmd_wr(ct, CMD_CE, false, 0, NULL, 0);
298 	else
299 		rc = ct->cmd_wr(ct, CMD_MIC_BULK_ERASE, false, 0, NULL, 0);
300 	if (rc)
301 		return rc;
302 
303 	/* Wait for write complete */
304 	return fl_sync_wait_idle(ct);
305 }
306 
fl_wpage(struct flash_chip * c,uint32_t dst,const void * src,uint32_t size)307 static int fl_wpage(struct flash_chip *c, uint32_t dst, const void *src,
308 		    uint32_t size)
309 {
310 	struct spi_flash_ctrl *ct = c->ctrl;
311 	int rc;
312 
313 	if (size < 1 || size > 0x100)
314 		return FLASH_ERR_BAD_PAGE_SIZE;
315 
316 	rc = fl_wren(ct);
317 	if (rc) return rc;
318 
319 	rc = ct->cmd_wr(ct, CMD_PP, true, dst, src, size);
320 	if (rc)
321 		return rc;
322 
323 	/* Wait for write complete */
324 	return fl_sync_wait_idle(ct);
325 }
326 
flash_write(struct blocklevel_device * bl,uint32_t dst,const void * src,uint32_t size,bool verify)327 static int flash_write(struct blocklevel_device *bl, uint32_t dst, const void *src,
328 		uint32_t size, bool verify)
329 {
330 	struct flash_chip *c = container_of(bl, struct flash_chip, bl);
331 	struct spi_flash_ctrl *ct = c->ctrl;
332 	uint32_t todo = size;
333 	uint32_t d = dst;
334 	const void *s = src;
335 	uint8_t vbuf[0x100];
336 	int rc;
337 
338 	/* Some sanity checking */
339 	if (((dst + size) <= dst) || !size || (dst + size) > c->tsize)
340 		return FLASH_ERR_PARM_ERROR;
341 
342 	FL_DBG("LIBFLASH: Writing to 0x%08x..0%08x...\n", dst, dst + size);
343 
344 	/*
345 	 * If the controller supports write and either we are in 3b mode
346 	 * or we are in 4b *and* the controller supports it, then do a
347 	 * high level write.
348 	 */
349 	if ((!c->mode_4b || ct->set_4b) && ct->write) {
350 		rc = ct->write(ct, dst, src, size);
351 		if (rc)
352 			return rc;
353 		goto writing_done;
354 	}
355 
356 	/* Otherwise, go manual if supported */
357 	if (!ct->cmd_wr)
358 		return FLASH_ERR_CTRL_CMD_UNSUPPORTED;
359 
360 	/* Iterate for each page to write */
361 	while(todo) {
362 		uint32_t chunk;
363 
364 		/* Handle misaligned start */
365 		chunk = 0x100 - (d & 0xff);
366 		if (chunk > todo)
367 			chunk = todo;
368 
369 		rc = fl_wpage(c, d, s, chunk);
370 		if (rc) return rc;
371 		d += chunk;
372 		s += chunk;
373 		todo -= chunk;
374 	}
375 
376  writing_done:
377 	if (!verify)
378 		return 0;
379 
380 	/* Verify */
381 	FL_DBG("LIBFLASH: Verifying...\n");
382 
383 	while(size) {
384 		uint32_t chunk;
385 
386 		chunk = sizeof(vbuf);
387 		if (chunk > size)
388 			chunk = size;
389 		rc = flash_read(bl, dst, vbuf, chunk);
390 		if (rc) return rc;
391 		if (memcmp(vbuf, src, chunk)) {
392 			FL_ERR("LIBFLASH: Miscompare at 0x%08x\n", dst);
393 			return FLASH_ERR_VERIFY_FAILURE;
394 		}
395 		dst += chunk;
396 		src += chunk;
397 		size -= chunk;
398 	}
399 	return 0;
400 }
401 
flash_write_corrected(struct blocklevel_device * bl,uint32_t pos,const void * buf,uint32_t len,bool verify,bool ecc)402 int flash_write_corrected(struct blocklevel_device *bl, uint32_t pos, const void *buf,
403 		uint32_t len, bool verify, bool ecc)
404 {
405 	struct ecc64 *bufecc;
406 	uint32_t copylen, copylen_minus_ecc;
407 	int rc;
408 	uint8_t ret;
409 
410 	if (!ecc)
411 		return flash_write(bl, pos, buf, len, verify);
412 
413 	/* Copy the buffer in chunks */
414 	bufecc = malloc(ecc_buffer_size(COPY_BUFFER_LENGTH));
415 	if (!bufecc)
416 		return FLASH_ERR_MALLOC_FAILED;
417 
418 	while (len > 0) {
419 		/* What's left to copy? */
420 		copylen = MIN(len, COPY_BUFFER_LENGTH);
421 		copylen_minus_ecc = ecc_buffer_size_minus_ecc(copylen);
422 
423 		/* Add the ecc byte to the data */
424 		ret = memcpy_to_ecc(bufecc, buf, copylen_minus_ecc);
425 		if (ret) {
426 			rc = FLASH_ERR_ECC_INVALID;
427 			goto err;
428 		}
429 
430 		/* Write ECCed data to the flash */
431 		rc = flash_write(bl, pos, bufecc, copylen, verify);
432 		if (rc)
433 			goto err;
434 
435 		/* Update for next copy */
436 		len -= copylen_minus_ecc;
437 		buf = (uint8_t *)buf + copylen_minus_ecc;
438 		pos += copylen;
439 	}
440 
441 	rc = 0;
442 
443 err:
444 	free(bufecc);
445 	return rc;
446 }
447 
448 enum sm_comp_res {
449 	sm_no_change,
450 	sm_need_write,
451 	sm_need_erase,
452 };
453 
flash_smart_comp(struct flash_chip * c,const void * src,uint32_t offset,uint32_t size)454 static enum sm_comp_res flash_smart_comp(struct flash_chip *c,
455 					 const void *src,
456 					 uint32_t offset, uint32_t size)
457 {
458 	uint8_t *b = c->smart_buf + offset;
459 	const uint8_t *s = src;
460 	bool is_same = true;
461 	uint32_t i;
462 
463 	/* SRC DEST  NEED_ERASE
464 	 *  0   1       0
465 	 *  1   1       0
466          *  0   0       0
467          *  1   0       1
468          */
469 	for (i = 0; i < size; i++) {
470 		/* Any bit need to be set, need erase */
471 		if (s[i] & ~b[i])
472 			return sm_need_erase;
473 		if (is_same && (b[i] != s[i]))
474 			is_same = false;
475 	}
476 	return is_same ? sm_no_change : sm_need_write;
477 }
478 
flash_smart_write(struct blocklevel_device * bl,uint64_t dst,const void * src,uint64_t size)479 static int flash_smart_write(struct blocklevel_device *bl, uint64_t dst, const void *src, uint64_t size)
480 {
481 	struct flash_chip *c = container_of(bl, struct flash_chip, bl);
482 	uint32_t er_size = c->min_erase_mask + 1;
483 	uint32_t end = dst + size;
484 	int rc;
485 
486 	/* Some sanity checking */
487 	if (end <= dst || !size || end > c->tsize) {
488 		FL_DBG("LIBFLASH: Smart write param error\n");
489 		return FLASH_ERR_PARM_ERROR;
490 	}
491 
492 	FL_DBG("LIBFLASH: Smart writing to 0x%" PRIx64 "..0%" PRIx64 "...\n",
493 	       dst, dst + size);
494 
495 	/* As long as we have something to write ... */
496 	while(dst < end) {
497 		uint32_t page, off, chunk;
498 		enum sm_comp_res sr;
499 
500 		/* Figure out which erase page we are in and read it */
501 		page = dst & ~c->min_erase_mask;
502 		off = dst & c->min_erase_mask;
503 		FL_DBG("LIBFLASH:   reading page 0x%08x..0x%08x...\n",
504 		       page, page + er_size);
505 		rc = flash_read(bl, page, c->smart_buf, er_size);
506 		if (rc) {
507 			FL_DBG("LIBFLASH:    ...error %d!\n", rc);
508 			return rc;
509 		}
510 
511 		/* Locate the chunk of data we are working on */
512 		chunk = er_size - off;
513 		if (size < chunk)
514 			chunk = size;
515 
516 		/* Compare against what we are writing and ff */
517 		sr = flash_smart_comp(c, src, off, chunk);
518 		switch(sr) {
519 		case sm_no_change:
520 			/* Identical, skip it */
521 			FL_DBG("LIBFLASH:    ...same !\n");
522 			break;
523 		case sm_need_write:
524 			/* Just needs writing over */
525 			FL_DBG("LIBFLASH:    ...need write !\n");
526 			rc = flash_write(bl, dst, src, chunk, true);
527 			if (rc) {
528 				FL_DBG("LIBFLASH: Write error %d !\n", rc);
529 				return rc;
530 			}
531 			break;
532 		case sm_need_erase:
533 			FL_DBG("LIBFLASH:    ...need erase !\n");
534 			rc = flash_erase(bl, page, er_size);
535 			if (rc) {
536 				FL_DBG("LIBFLASH: erase error %d !\n", rc);
537 				return rc;
538 			}
539 			/* Then update the portion of the buffer and write the block */
540 			memcpy(c->smart_buf + off, src, chunk);
541 			rc = flash_write(bl, page, c->smart_buf, er_size, true);
542 			if (rc) {
543 				FL_DBG("LIBFLASH: write error %d !\n", rc);
544 				return rc;
545 			}
546 			break;
547 		}
548 		dst += chunk;
549 		src += chunk;
550 		size -= chunk;
551 	}
552 	return 0;
553 }
554 
flash_smart_write_corrected(struct blocklevel_device * bl,uint32_t dst,const void * src,uint32_t size,bool ecc)555 int flash_smart_write_corrected(struct blocklevel_device *bl, uint32_t dst, const void *src,
556 		      uint32_t size, bool ecc)
557 {
558 	struct ecc64 *buf;
559 	int rc;
560 
561 	if (!ecc)
562 		return flash_smart_write(bl, dst, src, size);
563 
564 	buf = malloc(ecc_buffer_size(size));
565 	if (!buf)
566 		return FLASH_ERR_MALLOC_FAILED;
567 
568 	rc = memcpy_to_ecc(buf, src, size);
569 	if (rc) {
570 		rc = FLASH_ERR_ECC_INVALID;
571 		goto out;
572 	}
573 
574 	rc = flash_smart_write(bl, dst, buf, ecc_buffer_size(size));
575 
576 out:
577 	free(buf);
578 	return rc;
579 }
580 
fl_chip_id(struct spi_flash_ctrl * ct,uint8_t * id_buf,uint32_t * id_size)581 static int fl_chip_id(struct spi_flash_ctrl *ct, uint8_t *id_buf,
582 		      uint32_t *id_size)
583 {
584 	int rc;
585 	uint8_t stat;
586 
587 	/* Check initial status */
588 	rc = fl_read_stat(ct, &stat);
589 	if (rc)
590 		return rc;
591 
592 	/* If stuck writing, wait for idle */
593 	if (stat & STAT_WIP) {
594 		FL_ERR("LIBFLASH: Flash in writing state ! Waiting...\n");
595 		rc = fl_sync_wait_idle(ct);
596 		if (rc)
597 			return rc;
598 	} else
599 		FL_DBG("LIBFLASH: Init status: %02x\n", stat);
600 
601 	/* Fallback to get ID manually */
602 	rc = ct->cmd_rd(ct, CMD_RDID, false, 0, id_buf, 3);
603 	if (rc)
604 		return rc;
605 	*id_size = 3;
606 
607 	return 0;
608 }
609 
flash_identify(struct flash_chip * c)610 static int flash_identify(struct flash_chip *c)
611 {
612 	struct spi_flash_ctrl *ct = c->ctrl;
613 	const struct flash_info *info = NULL;
614 	uint32_t iid, id_size;
615 #define MAX_ID_SIZE	16
616 	uint8_t id[MAX_ID_SIZE];
617 	int rc, i;
618 
619 	if (ct->chip_id) {
620 		/* High level controller interface */
621 		id_size = MAX_ID_SIZE;
622 		rc = ct->chip_id(ct, id, &id_size);
623 	} else
624 		rc = fl_chip_id(ct, id, &id_size);
625 	if (rc)
626 		return rc;
627 	if (id_size < 3)
628 		return FLASH_ERR_CHIP_UNKNOWN;
629 
630 	/* Convert to a dword for lookup */
631 	iid = id[0];
632 	iid = (iid << 8) | id[1];
633 	iid = (iid << 8) | id[2];
634 
635 	FL_DBG("LIBFLASH: Flash ID: %02x.%02x.%02x (%06x)\n",
636 	       id[0], id[1], id[2], iid);
637 
638 	/* Lookup in flash_info */
639 	for (i = 0; i < ARRAY_SIZE(flash_info); i++) {
640 		info = &flash_info[i];
641 		if (info->id == iid)
642 			break;
643 	}
644 	if (!info || info->id != iid)
645 		return FLASH_ERR_CHIP_UNKNOWN;
646 
647 	c->info = *info;
648 	c->tsize = info->size;
649 	ct->finfo = &c->info;
650 
651 	/*
652 	 * Let controller know about our settings and possibly
653 	 * override them
654 	 */
655 	if (ct->setup) {
656 		rc = ct->setup(ct, &c->tsize);
657 		if (rc)
658 			return rc;
659 	}
660 
661 	/* Calculate min erase granularity */
662 	if (c->info.flags & FL_ERASE_4K)
663 		c->min_erase_mask = 0xfff;
664 	else if (c->info.flags & FL_ERASE_32K)
665 		c->min_erase_mask = 0x7fff;
666 	else if (c->info.flags & FL_ERASE_64K)
667 		c->min_erase_mask = 0xffff;
668 	else {
669 		/* No erase size ? oops ... */
670 		FL_ERR("LIBFLASH: No erase sizes !\n");
671 		return FLASH_ERR_CTRL_CONFIG_MISMATCH;
672 	}
673 
674 	FL_DBG("LIBFLASH: Found chip %s size %dM erase granule: %dK\n",
675 	       c->info.name, c->tsize >> 20, (c->min_erase_mask + 1) >> 10);
676 
677 	return 0;
678 }
679 
flash_set_4b(struct flash_chip * c,bool enable)680 static int flash_set_4b(struct flash_chip *c, bool enable)
681 {
682 	struct spi_flash_ctrl *ct = c->ctrl;
683 	int rc;
684 
685 	/* Don't have low level interface, assume all is well */
686 	if (!ct->cmd_wr)
687 		return 0;
688 
689 	/* Some flash chips want this */
690 	rc = fl_wren(ct);
691 	if (rc) {
692 		FL_ERR("LIBFLASH: Error %d enabling write for set_4b\n", rc);
693 		/* Ignore the error & move on (could be wrprotect chip) */
694 	}
695 
696 	/* Ignore error in case chip is write protected */
697 	return ct->cmd_wr(ct, enable ? CMD_EN4B : CMD_EX4B, false, 0, NULL, 0);
698 }
699 
flash_force_4b_mode(struct flash_chip * c,bool enable_4b)700 int flash_force_4b_mode(struct flash_chip *c, bool enable_4b)
701 {
702 	struct spi_flash_ctrl *ct = c->ctrl;
703 	int rc = FLASH_ERR_4B_NOT_SUPPORTED;
704 
705 	/*
706 	 * We only allow force 4b if both controller and flash do 4b
707 	 * as this is mainly used if a 3rd party tries to directly
708 	 * access a direct mapped read region
709 	 */
710 	if (enable_4b && !((c->info.flags & FL_CAN_4B) && ct->set_4b))
711 		return rc;
712 
713 	/* Only send to flash directly on controllers that implement
714 	 * the low level callbacks
715 	 */
716 	if (ct->cmd_wr) {
717 		rc = flash_set_4b(c, enable_4b);
718 		if (rc)
719 			return rc;
720 	}
721 
722 	/* Then inform the controller */
723 	if (ct->set_4b)
724 		rc = ct->set_4b(ct, enable_4b);
725 	return rc;
726 }
727 
flash_configure(struct flash_chip * c)728 static int flash_configure(struct flash_chip *c)
729 {
730 	struct spi_flash_ctrl *ct = c->ctrl;
731 	int rc;
732 
733 	/* Crop flash size if necessary */
734 	if (c->tsize > 0x01000000 && !(c->info.flags & FL_CAN_4B)) {
735 		FL_ERR("LIBFLASH: Flash chip cropped to 16M, no 4b mode\n");
736 		c->tsize = 0x01000000;
737 	}
738 
739 	/* If flash chip > 16M, enable 4b mode */
740 	if (c->tsize > 0x01000000) {
741 		FL_DBG("LIBFLASH: Flash >16MB, enabling 4B mode...\n");
742 
743 		/* Set flash to 4b mode if we can */
744 		if (ct->cmd_wr) {
745 			rc = flash_set_4b(c, true);
746 			if (rc) {
747 				FL_ERR("LIBFLASH: Failed to set flash 4b mode\n");
748 				return rc;
749 			}
750 		}
751 
752 
753 		/* Set controller to 4b mode if supported */
754 		if (ct->set_4b) {
755 			FL_DBG("LIBFLASH: Enabling controller 4B mode...\n");
756 			rc = ct->set_4b(ct, true);
757 			if (rc) {
758 				FL_ERR("LIBFLASH: Failed to set controller 4b mode\n");
759 				return rc;
760 			}
761 		}
762 	} else {
763 		FL_DBG("LIBFLASH: Flash <=16MB, disabling 4B mode...\n");
764 
765 		/*
766 		 * If flash chip supports 4b mode, make sure we disable
767 		 * it in case it was left over by the previous user
768 		 */
769 		if (c->info.flags & FL_CAN_4B) {
770 			rc = flash_set_4b(c, false);
771 			if (rc) {
772 				FL_ERR("LIBFLASH: Failed to"
773 				       " clear flash 4b mode\n");
774 				return rc;
775 			}
776 		}
777 		/* Set controller to 3b mode if mode switch is supported */
778 		if (ct->set_4b) {
779 			FL_DBG("LIBFLASH: Disabling controller 4B mode...\n");
780 			rc = ct->set_4b(ct, false);
781 			if (rc) {
782 				FL_ERR("LIBFLASH: Failed to"
783 				       " clear controller 4b mode\n");
784 				return rc;
785 			}
786 		}
787 	}
788 	return 0;
789 }
790 
flash_get_info(struct blocklevel_device * bl,const char ** name,uint64_t * total_size,uint32_t * erase_granule)791 static int flash_get_info(struct blocklevel_device *bl, const char **name,
792 		   uint64_t *total_size, uint32_t *erase_granule)
793 {
794 	struct flash_chip *c = container_of(bl, struct flash_chip, bl);
795 	if (name)
796 		*name = c->info.name;
797 	if (total_size)
798 		*total_size = c->tsize;
799 	if (erase_granule)
800 		*erase_granule = c->min_erase_mask + 1;
801 	return 0;
802 }
803 
flash_init(struct spi_flash_ctrl * ctrl,struct blocklevel_device ** bl,struct flash_chip ** flash_chip)804 int flash_init(struct spi_flash_ctrl *ctrl, struct blocklevel_device **bl,
805 		struct flash_chip **flash_chip)
806 {
807 	struct flash_chip *c;
808 	int rc;
809 
810 	if (!bl)
811 		return FLASH_ERR_PARM_ERROR;
812 
813 	*bl = NULL;
814 
815 	c = malloc(sizeof(struct flash_chip));
816 	if (!c)
817 		return FLASH_ERR_MALLOC_FAILED;
818 	memset(c, 0, sizeof(*c));
819 	c->ctrl = ctrl;
820 
821 	rc = flash_identify(c);
822 	if (rc) {
823 		FL_ERR("LIBFLASH: Flash identification failed\n");
824 		goto bail;
825 	}
826 	c->smart_buf = malloc(c->min_erase_mask + 1);
827 	if (!c->smart_buf) {
828 		FL_ERR("LIBFLASH: Failed to allocate smart buffer !\n");
829 		rc = FLASH_ERR_MALLOC_FAILED;
830 		goto bail;
831 	}
832 	rc = flash_configure(c);
833 	if (rc)
834 		FL_ERR("LIBFLASH: Flash configuration failed\n");
835 bail:
836 	if (rc) {
837 		free(c);
838 		return rc;
839 	}
840 
841 	/* The flash backend doesn't support reiniting it */
842 	c->bl.keep_alive = true;
843 	c->bl.reacquire = NULL;
844 	c->bl.release = NULL;
845 	c->bl.read = &flash_read;
846 	c->bl.write = &flash_smart_write;
847 	c->bl.erase = &flash_erase;
848 	c->bl.get_info = &flash_get_info;
849 	c->bl.erase_mask = c->min_erase_mask;
850 	c->bl.flags = WRITE_NEED_ERASE;
851 
852 	*bl = &(c->bl);
853 	if (flash_chip)
854 		*flash_chip = c;
855 
856 	return 0;
857 }
858 
flash_exit(struct blocklevel_device * bl)859 void flash_exit(struct blocklevel_device *bl)
860 {
861 	/* XXX Make sure we are idle etc... */
862 	if (bl) {
863 		struct flash_chip *c = container_of(bl, struct flash_chip, bl);
864 		free(c->smart_buf);
865 		free(c);
866 	}
867 }
868 
flash_exit_close(struct blocklevel_device * bl,void (* close)(struct spi_flash_ctrl * ctrl))869 void flash_exit_close(struct blocklevel_device *bl, void (*close)(struct spi_flash_ctrl *ctrl))
870 {
871 	if (bl) {
872 		struct flash_chip *c = container_of(bl, struct flash_chip, bl);
873 		close(c->ctrl);
874 		free(c);
875 	}
876 }
877