xref: /aosp_15_r20/external/flashrom/sb600spi.c (revision 0d6140be3aa665ecc836e8907834fcd3e3b018fc)
1 /*
2  * This file is part of the flashrom project.
3  *
4  * Copyright (C) 2008 Wang Qingpei <[email protected]>
5  * Copyright (C) 2008 Joe Bao <[email protected]>
6  * Copyright (C) 2008 Advanced Micro Devices, Inc.
7  * Copyright (C) 2009, 2010, 2013 Carl-Daniel Hailfinger
8  * Copyright (C) 2013 Stefan Tauner
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  */
20 
21 #include <stdbool.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include "flash.h"
25 #include "programmer.h"
26 #include "hwaccess_physmap.h"
27 #include "spi.h"
28 #include "platform/pci.h"
29 
30 /* This struct is unused, but helps visualize the SB600 SPI BAR layout.
31  *struct sb600_spi_controller {
32  *	unsigned int spi_cntrl0;	/ * 00h * /
33  *	unsigned int restrictedcmd1;	/ * 04h * /
34  *	unsigned int restrictedcmd2;	/ * 08h * /
35  *	unsigned int spi_cntrl1;	/ * 0ch * /
36  *	unsigned int spi_cmdvalue0;	/ * 10h * /
37  *	unsigned int spi_cmdvalue1;	/ * 14h * /
38  *	unsigned int spi_cmdvalue2;	/ * 18h * /
39  *	unsigned int spi_fakeid;	/ * 1Ch * /
40  *};
41  */
42 
43 enum amd_chipset {
44 	CHIPSET_AMD_UNKNOWN,
45 	CHIPSET_SB6XX,
46 	CHIPSET_SB7XX, /* SP5100 too */
47 	CHIPSET_SB89XX, /* Hudson-1 too */
48 	CHIPSET_HUDSON234,
49 	CHIPSET_BOLTON,
50 	CHIPSET_YANGTZE,
51 	CHIPSET_PROMONTORY,
52 };
53 
54 #define FIFO_SIZE_OLD		8
55 #define FIFO_SIZE_YANGTZE	71
56 
57 #define SPI100_CMD_CODE_REG	0x45
58 #define SPI100_CMD_TRIGGER_REG	0x47
59 #define   SPI100_EXECUTE_CMD	(1 << 7)
60 
61 struct sb600spi_data {
62 	struct flashctx *flash;
63 	uint8_t *spibar;
64 };
65 
find_smbus_dev_rev(uint16_t vendor,uint16_t device)66 static int find_smbus_dev_rev(uint16_t vendor, uint16_t device)
67 {
68 	struct pci_dev *smbus_dev = pcidev_find(vendor, device);
69 	if (!smbus_dev) {
70 		msg_pdbg("No SMBus device with ID %04X:%04X found.\n", vendor, device);
71 		msg_perr("ERROR: SMBus device not found. Not enabling SPI.\n");
72 		return -1;
73 	}
74 	return pci_read_byte(smbus_dev, PCI_REVISION_ID);
75 }
76 
77 /* Determine the chipset's version and identify the respective SMBUS device. */
determine_generation(struct pci_dev * dev)78 static enum amd_chipset determine_generation(struct pci_dev *dev)
79 {
80 	msg_pdbg2("Trying to determine the generation of the SPI interface... ");
81 	if (dev->device_id == 0x438d) {
82 		msg_pdbg("SB6xx detected.\n");
83 		return CHIPSET_SB6XX;
84 	} else if (dev->device_id == 0x439d) {
85 		int rev = find_smbus_dev_rev(0x1002, 0x4385);
86 		if (rev < 0)
87 			return CHIPSET_AMD_UNKNOWN;
88 		if (rev >= 0x39 && rev <= 0x3D) {
89 			msg_pdbg("SB7xx/SP5100 detected.\n");
90 			return CHIPSET_SB7XX;
91 		} else if (rev >= 0x40 && rev <= 0x42) {
92 			msg_pdbg("SB8xx/SB9xx/Hudson-1 detected.\n");
93 			return CHIPSET_SB89XX;
94 		} else {
95 			msg_pwarn("SB device found but SMBus revision 0x%02x does not match known values.\n"
96 				  "Assuming SB8xx/SB9xx/Hudson-1. Please send a log to [email protected]\n",
97 				   rev);
98 			return CHIPSET_SB89XX;
99 		}
100 	} else if (dev->device_id == 0x780e) {
101 		/* The PCI ID of the LPC bridge doesn't change between Hudson-2/3/4 and Yangtze (Kabini/Temash)
102 		 * although they use different SPI interfaces. */
103 		int rev = find_smbus_dev_rev(0x1022, 0x780B);
104 		if (rev < 0)
105 			return CHIPSET_AMD_UNKNOWN;
106 		if (rev >= 0x11 && rev <= 0x15) {
107 			msg_pdbg("Hudson-2/3/4 detected.\n");
108 			return CHIPSET_HUDSON234;
109 		} else if (rev == 0x16) {
110 			msg_pdbg("Bolton detected.\n");
111 			return CHIPSET_BOLTON;
112 		} else if ((rev >= 0x39 && rev <= 0x3A) || rev == 0x42) {
113 			msg_pdbg("Yangtze detected.\n");
114 			return CHIPSET_YANGTZE;
115 		} else {
116 			msg_pwarn("FCH device found but SMBus revision 0x%02x does not match known values.\n"
117 				  "Please report this to [email protected] and include this log and\n"
118 				  "the output of lspci -nnvx, thanks!.\n", rev);
119 		}
120 	} else if (dev->device_id == 0x790e) {
121 		int rev = find_smbus_dev_rev(0x1022, 0x790B);
122 		if (rev < 0)
123 			return CHIPSET_AMD_UNKNOWN;
124 		if (rev == 0x4a) {
125 			msg_pdbg("Yangtze detected.\n");
126 			return CHIPSET_YANGTZE;
127 		/**
128 		 * FCH chipsets called 'Promontory' are one's with the
129 		 * so-called SPI100 ip core that uses memory mapping and
130 		 * not a ring buffer for transactions. Typically this is
131 		 * found on both Stoney Ridge and Zen platforms.
132 		 *
133 		 * The revisions I have found by searching various lspci
134 		 * outputs are as follows: 0x4b, 0x59, 0x61 & 0x71.
135 		 */
136 		} else if (rev == 0x4b || rev == 0x51 || rev == 0x59 || rev == 0x61 || rev == 0x71) {
137 			msg_pdbg("Promontory (rev 0x%02x) detected.\n", rev);
138 			return CHIPSET_PROMONTORY;
139 		} else {
140 			msg_pwarn("FCH device found but SMBus revision 0x%02x does not match known values.\n"
141 				  "Please report this to [email protected] and include this log and\n"
142 				  "the output of lspci -nnvx, thanks!.\n", rev);
143 		}
144 
145 
146 	} else
147 		msg_pwarn("%s: Unknown LPC device %" PRIx16 ":%" PRIx16 ".\n"
148 			  "Please report this to [email protected] and include this log and\n"
149 			  "the output of lspci -nnvx, thanks!\n",
150 			  __func__, dev->vendor_id, dev->device_id);
151 
152 	msg_perr("Could not determine chipset generation.");
153 	return CHIPSET_AMD_UNKNOWN;
154 }
155 
reset_internal_fifo_pointer(uint8_t * sb600_spibar)156 static void reset_internal_fifo_pointer(uint8_t *sb600_spibar)
157 {
158 	mmio_writeb(mmio_readb(sb600_spibar + 2) | 0x10, sb600_spibar + 2);
159 
160 	/* FIXME: This loop needs a timeout and a clearer message. */
161 	while (mmio_readb(sb600_spibar + 0xD) & 0x7)
162 		msg_pspew("reset\n");
163 }
164 
compare_internal_fifo_pointer(uint8_t want,uint8_t * sb600_spibar)165 static int compare_internal_fifo_pointer(uint8_t want, uint8_t *sb600_spibar)
166 {
167 	uint8_t have = mmio_readb(sb600_spibar + 0xd) & 0x07;
168 	want %= FIFO_SIZE_OLD;
169 	if (have != want) {
170 		msg_perr("AMD SPI FIFO pointer corruption! Pointer is %d, wanted %d\n", have, want);
171 		msg_perr("Something else is accessing the flash chip and causes random corruption.\n"
172 			 "Please stop all applications and drivers and IPMI which access the flash chip.\n");
173 		return 1;
174 	} else {
175 		msg_pspew("AMD SPI FIFO pointer is %d, wanted %d\n", have, want);
176 		return 0;
177 	}
178 }
179 
180 /* Check the number of bytes to be transmitted and extract opcode. */
check_readwritecnt(const struct flashctx * flash,unsigned int writecnt,unsigned int readcnt)181 static int check_readwritecnt(const struct flashctx *flash, unsigned int writecnt, unsigned int readcnt)
182 {
183 	unsigned int maxwritecnt = flash->mst->spi.max_data_write + 3;
184 	if (writecnt > maxwritecnt) {
185 		msg_pinfo("%s: SPI controller can not send %d bytes, it is limited to %d bytes\n",
186 			  __func__, writecnt, maxwritecnt);
187 		return SPI_INVALID_LENGTH;
188 	}
189 
190 	unsigned int maxreadcnt = flash->mst->spi.max_data_read;
191 	if (readcnt > maxreadcnt) {
192 		msg_pinfo("%s: SPI controller can not receive %d bytes, it is limited to %d bytes\n",
193 			  __func__, readcnt, maxreadcnt);
194 		return SPI_INVALID_LENGTH;
195 	}
196 	return 0;
197 }
198 
execute_command(uint8_t * sb600_spibar)199 static void execute_command(uint8_t *sb600_spibar)
200 {
201 	msg_pspew("Executing... ");
202 	mmio_writeb(mmio_readb(sb600_spibar + 2) | 1, sb600_spibar + 2);
203 	while (mmio_readb(sb600_spibar + 2) & 1)
204 		;
205 	msg_pspew("done\n");
206 }
207 
execute_spi100_command(uint8_t * sb600_spibar)208 static void execute_spi100_command(uint8_t *sb600_spibar)
209 {
210 	msg_pspew("Executing... ");
211 	mmio_writeb(mmio_readb(sb600_spibar + SPI100_CMD_TRIGGER_REG) | SPI100_EXECUTE_CMD,
212 			sb600_spibar + SPI100_CMD_TRIGGER_REG);
213 	while (mmio_readb(sb600_spibar + SPI100_CMD_TRIGGER_REG) & SPI100_CMD_TRIGGER_REG)
214 		;
215 	msg_pspew("done\n");
216 }
217 
sb600_spi_send_command(const struct flashctx * flash,unsigned int writecnt,unsigned int readcnt,const unsigned char * writearr,unsigned char * readarr)218 static int sb600_spi_send_command(const struct flashctx *flash, unsigned int writecnt,
219 				  unsigned int readcnt,
220 				  const unsigned char *writearr,
221 				  unsigned char *readarr)
222 {
223 	struct sb600spi_data *sb600_data = flash->mst->spi.data;
224 	uint8_t *sb600_spibar = sb600_data->spibar;
225 	/* First byte is cmd which can not be sent through the FIFO. */
226 	unsigned char cmd = *writearr++;
227 	writecnt--;
228 	msg_pspew("%s, cmd=0x%02x, writecnt=%d, readcnt=%d\n", __func__, cmd, writecnt, readcnt);
229 	mmio_writeb(cmd, sb600_spibar + 0);
230 
231 	int ret = check_readwritecnt(flash, writecnt, readcnt);
232 	if (ret != 0)
233 		return ret;
234 
235 	/* This is a workaround for a bug in SPI controller. If we only send
236 	 * an opcode and no additional data/address, the SPI controller will
237 	 * read one byte too few from the chip. Basically, the last byte of
238 	 * the chip response is discarded and will not end up in the FIFO.
239 	 * It is unclear if the CS# line is set high too early as well.
240 	 */
241 	unsigned int readoffby1 = (writecnt > 0) ? 0 : 1;
242 	uint8_t readwrite = (readcnt + readoffby1) << 4 | (writecnt);
243 	mmio_writeb(readwrite, sb600_spibar + 1);
244 
245 	reset_internal_fifo_pointer(sb600_spibar);
246 	msg_pspew("Filling FIFO: ");
247 	unsigned int count;
248 	for (count = 0; count < writecnt; count++) {
249 		msg_pspew("[%02x]", writearr[count]);
250 		mmio_writeb(writearr[count], sb600_spibar + 0xC);
251 	}
252 	msg_pspew("\n");
253 	if (compare_internal_fifo_pointer(writecnt, sb600_spibar))
254 		return SPI_PROGRAMMER_ERROR;
255 
256 	/*
257 	 * We should send the data in sequence, which means we need to reset
258 	 * the FIFO pointer to the first byte we want to send.
259 	 */
260 	reset_internal_fifo_pointer(sb600_spibar);
261 	execute_command(sb600_spibar);
262 	if (compare_internal_fifo_pointer(writecnt + readcnt, sb600_spibar))
263 		return SPI_PROGRAMMER_ERROR;
264 
265 	/*
266 	 * After the command executed, we should find out the index of the
267 	 * received byte. Here we just reset the FIFO pointer and skip the
268 	 * writecnt.
269 	 * It would be possible to increase the FIFO pointer by one instead
270 	 * of reading and discarding one byte from the FIFO.
271 	 * The FIFO is implemented on top of an 8 byte ring buffer and the
272 	 * buffer is never cleared. For every byte that is shifted out after
273 	 * the opcode, the FIFO already stores the response from the chip.
274 	 * Usually, the chip will respond with 0x00 or 0xff.
275 	 */
276 	reset_internal_fifo_pointer(sb600_spibar);
277 
278 	/* Skip the bytes we sent. */
279 	msg_pspew("Skipping: ");
280 	for (count = 0; count < writecnt; count++) {
281 		msg_pspew("[%02x]", mmio_readb(sb600_spibar + 0xC));
282 	}
283 	msg_pspew("\n");
284 	if (compare_internal_fifo_pointer(writecnt, sb600_spibar))
285 		return SPI_PROGRAMMER_ERROR;
286 
287 	msg_pspew("Reading FIFO: ");
288 	for (count = 0; count < readcnt; count++) {
289 		readarr[count] = mmio_readb(sb600_spibar + 0xC);
290 		msg_pspew("[%02x]", readarr[count]);
291 	}
292 	msg_pspew("\n");
293 	if (compare_internal_fifo_pointer(writecnt+readcnt, sb600_spibar))
294 		return SPI_PROGRAMMER_ERROR;
295 
296 	if (mmio_readb(sb600_spibar + 1) != readwrite) {
297 		msg_perr("Unexpected change in AMD SPI read/write count!\n");
298 		msg_perr("Something else is accessing the flash chip and causes random corruption.\n"
299 			 "Please stop all applications and drivers and IPMI which access the flash chip.\n");
300 		return SPI_PROGRAMMER_ERROR;
301 	}
302 
303 	return 0;
304 }
305 
spi100_spi_send_command(const struct flashctx * flash,unsigned int writecnt,unsigned int readcnt,const unsigned char * writearr,unsigned char * readarr)306 static int spi100_spi_send_command(const struct flashctx *flash, unsigned int writecnt,
307 				  unsigned int readcnt,
308 				  const unsigned char *writearr,
309 				  unsigned char *readarr)
310 {
311 	struct sb600spi_data *sb600_data = flash->mst->spi.data;
312 	uint8_t *sb600_spibar = sb600_data->spibar;
313 	/* First byte is cmd which can not be sent through the buffer. */
314 	unsigned char cmd = *writearr++;
315 	writecnt--;
316 	msg_pspew("%s, cmd=0x%02x, writecnt=%d, readcnt=%d\n", __func__, cmd, writecnt, readcnt);
317 	mmio_writeb(cmd, sb600_spibar + SPI100_CMD_CODE_REG);
318 
319 	int ret = check_readwritecnt(flash, writecnt, readcnt);
320 	if (ret != 0)
321 		return ret;
322 
323 	/* Use the extended TxByteCount and RxByteCount registers. */
324 	mmio_writeb(writecnt, sb600_spibar + 0x48);
325 	mmio_writeb(readcnt, sb600_spibar + 0x4b);
326 
327 	msg_pspew("Filling buffer: ");
328 	unsigned int count;
329 	for (count = 0; count < writecnt; count++) {
330 		msg_pspew("[%02x]", writearr[count]);
331 		mmio_writeb(writearr[count], sb600_spibar + 0x80 + count);
332 	}
333 	msg_pspew("\n");
334 
335 	execute_spi100_command(sb600_spibar);
336 
337 	msg_pspew("Reading buffer: ");
338 	for (count = 0; count < readcnt; count++) {
339 		readarr[count] = mmio_readb(sb600_spibar + 0x80 + (writecnt + count) % FIFO_SIZE_YANGTZE);
340 		msg_pspew("[%02x]", readarr[count]);
341 	}
342 	msg_pspew("\n");
343 
344 	return 0;
345 }
346 
347 struct spispeed {
348 	const char *const name;
349 	const uint8_t speed;
350 };
351 
352 static const char* spispeeds[] = {
353 	"66 MHz",
354 	"33 MHz",
355 	"22 MHz",
356 	"16.5 MHz",
357 	"100 MHz",
358 	"Reserved",
359 	"Reserved",
360 	"800 kHz",
361 };
362 
363 static const char* spireadmodes[] = {
364 	"Normal (up to 33 MHz)",
365 	"Reserved",
366 	"Dual IO (1-1-2)",
367 	"Quad IO (1-1-4)",
368 	"Dual IO (1-2-2)",
369 	"Quad IO (1-4-4)",
370 	"Normal (up to 66 MHz)",
371 	"Fast Read",
372 };
373 
set_speed(struct pci_dev * dev,enum amd_chipset amd_gen,uint8_t speed,uint8_t * sb600_spibar)374 static int set_speed(struct pci_dev *dev, enum amd_chipset amd_gen, uint8_t speed, uint8_t *sb600_spibar)
375 {
376 	bool success = false;
377 
378 	msg_pdbg("Setting SPI clock to %s (%i)... ", spispeeds[speed], speed);
379 	if (amd_gen >= CHIPSET_YANGTZE) {
380 		rmmio_writew((speed << 12) | (speed << 8) | (speed << 4) | speed, sb600_spibar + 0x22);
381 		uint16_t tmp = mmio_readw(sb600_spibar + 0x22);
382 		success = (((tmp >> 12) & 0xf) == speed && ((tmp >> 8) & 0xf) == speed &&
383 			   ((tmp >> 4) & 0xf) == speed && ((tmp >> 0) & 0xf) == speed);
384 	} else {
385 		rmmio_writeb((mmio_readb(sb600_spibar + 0xd) & ~(0x3 << 4)) | (speed << 4), sb600_spibar + 0xd);
386 		success = (speed == ((mmio_readb(sb600_spibar + 0xd) >> 4) & 0x3));
387 	}
388 
389 	if (!success) {
390 		msg_perr("FAILED!\n");
391 		return 1;
392 	}
393 	msg_pdbg("succeeded.\n");
394 	return 0;
395 }
396 
set_mode(struct pci_dev * dev,uint8_t mode,uint8_t * sb600_spibar)397 static int set_mode(struct pci_dev *dev, uint8_t mode, uint8_t *sb600_spibar)
398 {
399 	msg_pdbg("Setting SPI read mode to %s (%i)... ", spireadmodes[mode], mode);
400 	uint32_t tmp = mmio_readl(sb600_spibar + 0x00);
401 	tmp &= ~(0x6 << 28 | 0x1 << 18); /* Clear mode bits */
402 	tmp |= ((mode & 0x6) << 28) | ((mode & 0x1) << 18);
403 	rmmio_writel(tmp, sb600_spibar + 0x00);
404 	if (tmp != mmio_readl(sb600_spibar + 0x00)) {
405 		msg_perr("FAILED!\n");
406 		return 1;
407 	}
408 	msg_pdbg("succeeded.\n");
409 	return 0;
410 }
411 
handle_speed(const struct programmer_cfg * cfg,struct pci_dev * dev,enum amd_chipset amd_gen,uint8_t * sb600_spibar)412 static int handle_speed(const struct programmer_cfg *cfg,
413 		struct pci_dev *dev, enum amd_chipset amd_gen, uint8_t *sb600_spibar)
414 {
415 	uint32_t tmp;
416 	int16_t spispeed_idx = -1;
417 	int16_t spireadmode_idx = -1;
418 	char *param_str;
419 
420 	param_str = extract_programmer_param_str(cfg, "spispeed");
421 	if (param_str != NULL) {
422 		unsigned int i;
423 		for (i = 0; i < ARRAY_SIZE(spispeeds); i++) {
424 			if (strcasecmp(spispeeds[i], param_str) == 0) {
425 				spispeed_idx = i;
426 				break;
427 			}
428 		}
429 		/* "reserved" is not a valid speed.
430 		 * Error out on speeds not present in the spispeeds array.
431 		 * Only Yangtze supports the second half of indices.
432 		 * No 66 MHz before SB8xx. */
433 		if ((strcasecmp(param_str, "reserved") == 0) ||
434 		    (i == ARRAY_SIZE(spispeeds)) ||
435 		    (amd_gen < CHIPSET_YANGTZE && spispeed_idx > 3) ||
436 		    (amd_gen < CHIPSET_SB89XX && spispeed_idx == 0)) {
437 			msg_perr("Error: Invalid spispeed value: '%s'.\n", param_str);
438 			free(param_str);
439 			return 1;
440 		}
441 		free(param_str);
442 	}
443 
444 	param_str = extract_programmer_param_str(cfg, "spireadmode");
445 	if (param_str != NULL) {
446 		unsigned int i;
447 		for (i = 0; i < ARRAY_SIZE(spireadmodes); i++) {
448 			if (strcasecmp(spireadmodes[i], param_str) == 0) {
449 				spireadmode_idx = i;
450 				break;
451 			}
452 		}
453 		if ((strcasecmp(param_str, "reserved") == 0) ||
454 		    (i == ARRAY_SIZE(spireadmodes))) {
455 			msg_perr("Error: Invalid spireadmode value: '%s'.\n", param_str);
456 			free(param_str);
457 			return 1;
458 		}
459 		if (amd_gen < CHIPSET_BOLTON) {
460 			msg_perr("Warning: spireadmode not supported for this chipset.");
461 		}
462 		free(param_str);
463 	}
464 
465 	/* See the chipset support matrix for SPI Base_Addr below for an explanation of the symbols used.
466 	 * bit   6xx   7xx/SP5100  8xx             9xx  hudson1  hudson234  bolton/yangtze
467 	 * 18    rsvd  <-          fastReadEnable  ?    <-       ?          SpiReadMode[0]
468 	 * 29:30 rsvd  <-          <-              ?    <-       ?          SpiReadMode[2:1]
469 	 */
470 	if (amd_gen >= CHIPSET_BOLTON) {
471 
472 		tmp = mmio_readl(sb600_spibar + 0x00);
473 		uint8_t read_mode = ((tmp >> 28) & 0x6) | ((tmp >> 18) & 0x1);
474 		msg_pdbg("SPI read mode is %s (%i)\n",
475 			spireadmodes[read_mode], read_mode);
476 		if (spireadmode_idx < 0) {
477 			msg_pdbg("spireadmode is not set, "
478 				 "leaving SPI read mode unchanged.\n");
479 		}
480 		else if (set_mode(dev, spireadmode_idx, sb600_spibar) != 0) {
481 			return 1;
482 		}
483 
484 		if (amd_gen >= CHIPSET_YANGTZE) {
485 			tmp = mmio_readb(sb600_spibar + 0x20);
486 			msg_pdbg("UseSpi100 is %sabled\n", (tmp & 0x1) ? "en" : "dis");
487 			if ((tmp & 0x1) == 0) {
488 				rmmio_writeb(tmp | 0x1, sb600_spibar + 0x20);
489 				tmp = mmio_readb(sb600_spibar + 0x20) & 0x1;
490 				if (tmp == 0) {
491 					msg_perr("Enabling Spi100 failed.\n");
492 					return 1;
493 				}
494 				msg_pdbg("Enabling Spi100 succeeded.\n");
495 			}
496 
497 			tmp = mmio_readw(sb600_spibar + 0x22); /* SPI 100 Speed Config */
498 			msg_pdbg("NormSpeedNew is %s\n", spispeeds[(tmp >> 12) & 0xf]);
499 			msg_pdbg("FastSpeedNew is %s\n", spispeeds[(tmp >> 8) & 0xf]);
500 			msg_pdbg("AltSpeedNew is %s\n", spispeeds[(tmp >> 4) & 0xf]);
501 			msg_pdbg("TpmSpeedNew is %s\n", spispeeds[(tmp >> 0) & 0xf]);
502 		}
503 	} else {
504 		if (amd_gen >= CHIPSET_SB89XX && amd_gen <= CHIPSET_HUDSON234) {
505 			bool fast_read = (mmio_readl(sb600_spibar + 0x00) >> 18) & 0x1;
506 			msg_pdbg("Fast Reads are %sabled\n", fast_read ? "en" : "dis");
507 			if (fast_read) {
508 				msg_pdbg("Disabling them temporarily.\n");
509 				rmmio_writel(mmio_readl(sb600_spibar + 0x00) & ~(0x1 << 18),
510 					     sb600_spibar + 0x00);
511 			}
512 		}
513 		tmp = (mmio_readb(sb600_spibar + 0xd) >> 4) & 0x3;
514 		msg_pdbg("NormSpeed is %s\n", spispeeds[tmp]);
515 		if (spispeed_idx < 0) {
516 			spispeed_idx = 3; /* Default to 16.5 MHz */
517 		}
518 	}
519 	if (spispeed_idx < 0) {
520 		msg_pdbg("spispeed is not set, leaving SPI speed unchanged.\n");
521 		return 0;
522 	}
523 	return set_speed(dev, amd_gen, spispeed_idx, sb600_spibar);
524 }
525 
handle_imc(const struct programmer_cfg * cfg,struct pci_dev * dev,enum amd_chipset amd_gen)526 static int handle_imc(const struct programmer_cfg *cfg, struct pci_dev *dev, enum amd_chipset amd_gen)
527 {
528 	/* Handle IMC everywhere but sb600 which does not have one. */
529 	if (amd_gen == CHIPSET_SB6XX)
530 		return 0;
531 
532 	bool amd_imc_force = false;
533 	char *param_value = extract_programmer_param_str(cfg, "amd_imc_force");
534 	if (param_value && !strcmp(param_value, "yes")) {
535 		amd_imc_force = true;
536 		msg_pspew("amd_imc_force enabled.\n");
537 	} else if (param_value && !strlen(param_value)) {
538 		msg_perr("Missing argument for amd_imc_force.\n");
539 		free(param_value);
540 		return 1;
541 	} else if (param_value) {
542 		msg_perr("Unknown argument for amd_imc_force: \"%s\" (not \"yes\").\n", param_value);
543 		free(param_value);
544 		return 1;
545 	}
546 	free(param_value);
547 
548 	/* TODO: we should not only look at IntegratedImcPresent (LPC Dev 20, Func 3, 40h) but also at
549 	 * IMCEnable(Strap) and Override EcEnable(Strap) (sb8xx, sb9xx?, a50, Bolton: Misc_Reg: 80h-87h;
550 	 * sb7xx, sp5100: PM_Reg: B0h-B1h) etc. */
551 	uint8_t reg = pci_read_byte(dev, 0x40);
552 	if ((reg & (1 << 7)) == 0) {
553 		msg_pdbg("IMC is not active.\n");
554 		return 0;
555 	}
556 
557 	if (!amd_imc_force)
558 		programmer_may_write = false;
559 	msg_pinfo("Writes have been disabled for safety reasons because the presence of the IMC\n"
560 		  "was detected and it could interfere with accessing flash memory. Flashrom will\n"
561 		  "try to disable it temporarily but even then this might not be safe:\n"
562 		  "when it is re-enabled and after a reboot it expects to find working code\n"
563 		  "in the flash and it is unpredictable what happens if there is none.\n"
564 		  "\n"
565 		  "To be safe make sure that there is a working IMC firmware at the right\n"
566 		  "location in the image you intend to write and do not attempt to erase.\n"
567 		  "\n"
568 		  "You can enforce write support with the amd_imc_force programmer option.\n");
569 	if (amd_imc_force)
570 		msg_pinfo("Continuing with write support because the user forced us to!\n");
571 
572 	return amd_imc_shutdown(dev);
573 }
574 
promontory_read_memmapped(struct flashctx * flash,uint8_t * buf,unsigned int start,unsigned int len)575 static int promontory_read_memmapped(struct flashctx *flash, uint8_t *buf,
576 		unsigned int start, unsigned int len)
577 {
578 	struct sb600spi_data * data = (struct sb600spi_data *)flash->mst->spi.data;
579 	if (!data->flash) {
580 		map_flash(flash);
581 		data->flash = flash; /* keep a copy of flashctx for unmap() on tear-down. */
582 	}
583 	mmio_readn((void *)(flash->virtual_memory + start), buf, len);
584 	return 0;
585 }
586 
sb600spi_shutdown(void * data)587 static int sb600spi_shutdown(void *data)
588 {
589 	struct sb600spi_data *sb600_data = data;
590 	struct flashctx *flash = sb600_data->flash;
591 	if (flash)
592 		finalize_flash_access(flash);
593 
594 	free(data);
595 	return 0;
596 }
597 
598 static const struct spi_master spi_master_sb600 = {
599 	.max_data_read	= FIFO_SIZE_OLD,
600 	.max_data_write	= FIFO_SIZE_OLD - 3,
601 	.command	= sb600_spi_send_command,
602 	.map_flash_region	= physmap,
603 	.unmap_flash_region	= physunmap,
604 	.read		= default_spi_read,
605 	.write_256	= default_spi_write_256,
606 	.shutdown	= sb600spi_shutdown,
607 };
608 
609 static const struct spi_master spi_master_yangtze = {
610 	.max_data_read	= FIFO_SIZE_YANGTZE - 3, /* Apparently the big SPI 100 buffer is not a ring buffer. */
611 	.max_data_write	= FIFO_SIZE_YANGTZE - 3,
612 	.command	= spi100_spi_send_command,
613 	.map_flash_region	= physmap,
614 	.unmap_flash_region	= physunmap,
615 	.read		= default_spi_read,
616 	.write_256	= default_spi_write_256,
617 	.shutdown	= sb600spi_shutdown,
618 };
619 
620 static const struct spi_master spi_master_promontory = {
621 	.max_data_read	= MAX_DATA_READ_UNLIMITED,
622 	.max_data_write	= FIFO_SIZE_YANGTZE - 3,
623 	.command	= spi100_spi_send_command,
624 	.map_flash_region	= physmap,
625 	.unmap_flash_region	= physunmap,
626 	.read		= promontory_read_memmapped,
627 	.write_256	= default_spi_write_256,
628 	.shutdown	= sb600spi_shutdown,
629 };
630 
sb600_probe_spi(const struct programmer_cfg * cfg,struct pci_dev * dev)631 int sb600_probe_spi(const struct programmer_cfg *cfg, struct pci_dev *dev)
632 {
633 	struct pci_dev *smbus_dev;
634 	uint32_t tmp;
635 	uint8_t reg;
636 	uint8_t *sb600_spibar = NULL;
637 
638 	/* Read SPI_BaseAddr */
639 	tmp = pci_read_long(dev, 0xa0);
640 	tmp &= 0xffffffe0;	/* remove bits 4-0 (reserved) */
641 	msg_pdbg("SPI base address is at 0x%"PRIx32"\n", tmp);
642 
643 	/* If the BAR has address 0, it is unlikely SPI is used. */
644 	if (!tmp)
645 		return 0;
646 
647 	/* Physical memory has to be mapped at page (4k) boundaries. */
648 	sb600_spibar = rphysmap("SB600 SPI registers", tmp & 0xfffff000, 0x1000);
649 	if (sb600_spibar == ERROR_PTR)
650 		return ERROR_FLASHROM_FATAL;
651 
652 	/* The low bits of the SPI base address are used as offset into
653 	 * the mapped page.
654 	 */
655 	sb600_spibar += tmp & 0xfff;
656 
657 	enum amd_chipset amd_gen = determine_generation(dev);
658 	if (amd_gen == CHIPSET_AMD_UNKNOWN)
659 		return ERROR_FLASHROM_NONFATAL;
660 
661 	/* How to read the following table and similar ones in this file:
662 	 * "?" means we have no datasheet for this chipset generation or it doesn't have any relevant info.
663 	 * "<-" means the bit/register meaning is identical to the next non-"?" chipset to the left. "<-" thus
664 	 *      never refers to another "?".
665 	 * If a "?" chipset is between two chipsets with identical meaning, we assume the meaning didn't change
666 	 * twice in between, i.e. the meaning is unchanged for the "?" chipset. Usually we assume that
667 	 * succeeding hardware supports the same functionality as its predecessor unless proven different by
668 	 * tests or documentation, hence "?" will often be implemented equally to "<-".
669 	 *
670 	 * Chipset support matrix for SPI Base_Addr (LPC PCI reg 0xa0)
671 	 * bit   6xx         7xx/SP5100       8xx       9xx  hudson1  hudson2+  yangtze
672 	 * 3    rsvd         <-               <-        ?    <-       ?         RouteTpm2Spi
673 	 * 2    rsvd         AbortEnable      rsvd      ?    <-       ?         <-
674 	 * 1    rsvd         SpiRomEnable     <-        ?    <-       ?         <-
675 	 * 0    rsvd         AltSpiCSEnable   rsvd      ?    <-       ?         <-
676 	 */
677 	if (amd_gen >= CHIPSET_SB7XX) {
678 		tmp = pci_read_long(dev, 0xa0);
679 		msg_pdbg("SpiRomEnable=%"PRIi32"", (tmp >> 1) & 0x1);
680 		if (amd_gen == CHIPSET_SB7XX)
681 			msg_pdbg(", AltSpiCSEnable=%"PRIi32", AbortEnable=%"PRIi32"", tmp & 0x1, (tmp >> 2) & 0x1);
682 		else if (amd_gen >= CHIPSET_YANGTZE)
683 			msg_pdbg(", RouteTpm2Sp=%"PRIi32"", (tmp >> 3) & 0x1);
684 
685 		tmp = pci_read_byte(dev, 0xba);
686 		msg_pdbg(", PrefetchEnSPIFromIMC=%"PRIi32"", (tmp & 0x4) >> 2);
687 
688 		tmp = pci_read_byte(dev, 0xbb);
689 		/* FIXME: Set bit 3,6,7 if not already set.
690 		 * Set bit 5, otherwise SPI accesses are pointless in LPC mode.
691 		 * See doc 42413 AMD SB700/710/750 RPR.
692 		 */
693 		if (amd_gen == CHIPSET_SB7XX)
694 			msg_pdbg(", SpiOpEnInLpcMode=%"PRIi32"", (tmp >> 5) & 0x1);
695 		msg_pdbg(", PrefetchEnSPIFromHost=%"PRIi32"\n", tmp & 0x1);
696 	}
697 
698 	/* Chipset support matrix for SPI_Cntrl0 (spibar + 0x0)
699 	 * See the chipset support matrix for SPI Base_Addr above for an explanation of the symbols used.
700 	 * bit   6xx                7xx/SP5100      8xx               9xx  hudson1  hudson2+  yangtze
701 	 * 17    rsvd               <-              <-                ?    <-       ?         <-
702 	 * 18    rsvd               <-              fastReadEnable<1> ?    <-       ?         SpiReadMode[0]<1>
703 	 * 19    SpiArbEnable       <-              <-                ?    <-       ?         <-
704 	 * 20    (FifoPtrClr)       <-              <-                ?    <-       ?         <-
705 	 * 21    (FifoPtrInc)       <-              <-                ?    <-       ?         IllegalAccess
706 	 * 22    SpiAccessMacRomEn  <-              <-                ?    <-       ?         <-
707 	 * 23    SpiHostAccessRomEn <-              <-                ?    <-       ?         <-
708 	 * 24:26 ArbWaitCount       <-              <-                ?    <-       ?         <-
709 	 * 27    SpiBridgeDisable   <-              <-                ?    <-       ?         rsvd
710 	 * 28    rsvd               DropOneClkOnRd  = SPIClkGate      ?    <-       ?         <-
711 	 * 29:30 rsvd               <-              <-                ?    <-       ?         SpiReadMode[2:1]<1>
712 	 * 31    rsvd               <-              SpiBusy           ?    <-       ?         <-
713 	 *
714 	 *  <1> see handle_speed
715 	 */
716 	tmp = mmio_readl(sb600_spibar + 0x00);
717 	msg_pdbg("(0x%08" PRIx32 ") SpiArbEnable=%"PRIi32"", tmp, (tmp >> 19) & 0x1);
718 	if (amd_gen >= CHIPSET_YANGTZE)
719 		msg_pdbg(", IllegalAccess=%"PRIi32"", (tmp >> 21) & 0x1);
720 
721 	msg_pdbg(", SpiAccessMacRomEn=%"PRIi32", SpiHostAccessRomEn=%"PRIi32", ArbWaitCount=%"PRIi32"",
722 		 (tmp >> 22) & 0x1, (tmp >> 23) & 0x1, (tmp >> 24) & 0x7);
723 
724 	if (amd_gen < CHIPSET_YANGTZE)
725 		msg_pdbg(", SpiBridgeDisable=%"PRIi32"", (tmp >> 27) & 0x1);
726 
727 	switch (amd_gen) {
728 	case CHIPSET_SB7XX:
729 		msg_pdbg(", DropOneClkOnRd/SpiClkGate=%"PRIi32"", (tmp >> 28) & 0x1);
730 		/* Fall through. */
731 	case CHIPSET_SB89XX:
732 	case CHIPSET_HUDSON234:
733 	case CHIPSET_YANGTZE:
734 	case CHIPSET_PROMONTORY:
735 		msg_pdbg(", SpiBusy=%"PRIi32"", (tmp >> 31) & 0x1);
736 	default: break;
737 	}
738 	msg_pdbg("\n");
739 
740 	if (((tmp >> 22) & 0x1) == 0 || ((tmp >> 23) & 0x1) == 0) {
741 		msg_perr("ERROR: State of SpiAccessMacRomEn or SpiHostAccessRomEn prohibits full access.\n");
742 		return ERROR_FLASHROM_NONFATAL;
743 	}
744 
745 	if (amd_gen >= CHIPSET_SB89XX) {
746 		tmp = mmio_readb(sb600_spibar + 0x1D);
747 		msg_pdbg("Using SPI_CS%"PRId32"\n", tmp & 0x3);
748 		/* FIXME: Handle SpiProtect* configuration on Yangtze. */
749 	}
750 
751 	/* Look for the SMBus device. */
752 	smbus_dev = pcidev_find(0x1002, 0x4385);
753 	if (!smbus_dev)
754 		smbus_dev = pcidev_find(0x1022, 0x780b); /* AMD FCH */
755 	if (!smbus_dev)
756 		smbus_dev = pcidev_find(0x1022, 0x790b); /* AMD FP4 */
757 	if (!smbus_dev) {
758 		msg_perr("ERROR: SMBus device not found. Not enabling SPI.\n");
759 		return ERROR_FLASHROM_NONFATAL;
760 	}
761 
762 	/* Note about the bit tests below: If a bit is zero, the GPIO is SPI. */
763 	/* GPIO11/SPI_DO and GPIO12/SPI_DI status */
764 	reg = pci_read_byte(smbus_dev, 0xAB);
765 	reg &= 0xC0;
766 	msg_pdbg("GPIO11 used for %s\n", (reg & (1 << 6)) ? "GPIO" : "SPI_DO");
767 	msg_pdbg("GPIO12 used for %s\n", (reg & (1 << 7)) ? "GPIO" : "SPI_DI");
768 	if (reg != 0x00) {
769 		msg_pdbg("Not enabling SPI");
770 		return 0;
771 	}
772 	/* GPIO31/SPI_HOLD and GPIO32/SPI_CS status */
773 	reg = pci_read_byte(smbus_dev, 0x83);
774 	reg &= 0xC0;
775 	msg_pdbg("GPIO31 used for %s\n", (reg & (1 << 6)) ? "GPIO" : "SPI_HOLD");
776 	msg_pdbg("GPIO32 used for %s\n", (reg & (1 << 7)) ? "GPIO" : "SPI_CS");
777 	/* SPI_HOLD is not used on all boards, filter it out. */
778 	if ((reg & 0x80) != 0x00) {
779 		msg_pdbg("Not enabling SPI");
780 		return 0;
781 	}
782 	/* GPIO47/SPI_CLK status */
783 	reg = pci_read_byte(smbus_dev, 0xA7);
784 	reg &= 0x40;
785 	msg_pdbg("GPIO47 used for %s\n", (reg & (1 << 6)) ? "GPIO" : "SPI_CLK");
786 	if (reg != 0x00) {
787 		msg_pdbg("Not enabling SPI");
788 		return 0;
789 	}
790 
791 	if (handle_speed(cfg, dev, amd_gen, sb600_spibar) != 0)
792 		return ERROR_FLASHROM_FATAL;
793 
794 	if (handle_imc(cfg, dev, amd_gen) != 0)
795 		return ERROR_FLASHROM_FATAL;
796 
797 	struct sb600spi_data *data = calloc(1, sizeof(*data));
798 	if (!data) {
799 		msg_perr("Unable to allocate space for extra SPI master data.\n");
800 		return SPI_GENERIC_ERROR;
801 	}
802 
803 	data->flash = NULL;
804 	data->spibar = sb600_spibar;
805 
806 	/* Starting with Yangtze the SPI controller got a different interface with a much bigger buffer. */
807 	if (amd_gen < CHIPSET_YANGTZE)
808 		register_spi_master(&spi_master_sb600, data);
809 	else if (amd_gen == CHIPSET_YANGTZE)
810 		register_spi_master(&spi_master_yangtze, data);
811 	else
812 		register_spi_master(&spi_master_promontory, data);
813 
814 	return 0;
815 }
816