xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_ras_eeprom.c (revision 07fdad3a93756b872da7b53647715c48d0f4a2d0)
1 /*
2  * Copyright 2019 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  */
23 
24 #include "amdgpu_ras_eeprom.h"
25 #include "amdgpu.h"
26 #include "amdgpu_ras.h"
27 #include <linux/bits.h>
28 #include "atom.h"
29 #include "amdgpu_eeprom.h"
30 #include "amdgpu_atomfirmware.h"
31 #include <linux/debugfs.h>
32 #include <linux/uaccess.h>
33 
34 #include "amdgpu_reset.h"
35 
36 /* These are memory addresses as would be seen by one or more EEPROM
37  * chips strung on the I2C bus, usually by manipulating pins 1-3 of a
38  * set of EEPROM devices. They form a continuous memory space.
39  *
40  * The I2C device address includes the device type identifier, 1010b,
41  * which is a reserved value and indicates that this is an I2C EEPROM
42  * device. It also includes the top 3 bits of the 19 bit EEPROM memory
43  * address, namely bits 18, 17, and 16. This makes up the 7 bit
44  * address sent on the I2C bus with bit 0 being the direction bit,
45  * which is not represented here, and sent by the hardware directly.
46  *
47  * For instance,
48  *   50h = 1010000b => device type identifier 1010b, bits 18:16 = 000b, address 0.
49  *   54h = 1010100b => --"--, bits 18:16 = 100b, address 40000h.
50  *   56h = 1010110b => --"--, bits 18:16 = 110b, address 60000h.
51  * Depending on the size of the I2C EEPROM device(s), bits 18:16 may
52  * address memory in a device or a device on the I2C bus, depending on
53  * the status of pins 1-3. See top of amdgpu_eeprom.c.
54  *
55  * The RAS table lives either at address 0 or address 40000h of EEPROM.
56  */
57 #define EEPROM_I2C_MADDR_0      0x0
58 #define EEPROM_I2C_MADDR_4      0x40000
59 
60 /*
61  * The 2 macros below represent the actual size in bytes that
62  * those entities occupy in the EEPROM memory.
63  * RAS_TABLE_RECORD_SIZE is different than sizeof(eeprom_table_record) which
64  * uses uint64 to store 6b fields such as retired_page.
65  */
66 #define RAS_TABLE_HEADER_SIZE   20
67 #define RAS_TABLE_RECORD_SIZE   24
68 
69 /* Table hdr is 'AMDR' */
70 #define RAS_TABLE_HDR_VAL       0x414d4452
71 
72 /* Bad GPU tag ‘BADG’ */
73 #define RAS_TABLE_HDR_BAD       0x42414447
74 
75 /*
76  * EEPROM Table structure v1
77  * ---------------------------------
78  * |                               |
79  * |     EEPROM TABLE HEADER       |
80  * |      ( size 20 Bytes )        |
81  * |                               |
82  * ---------------------------------
83  * |                               |
84  * |    BAD PAGE RECORD AREA       |
85  * |                               |
86  * ---------------------------------
87  */
88 
89 /* Assume 2-Mbit size EEPROM and take up the whole space. */
90 #define RAS_TBL_SIZE_BYTES      (256 * 1024)
91 #define RAS_TABLE_START         0
92 #define RAS_HDR_START           RAS_TABLE_START
93 #define RAS_RECORD_START        (RAS_HDR_START + RAS_TABLE_HEADER_SIZE)
94 #define RAS_MAX_RECORD_COUNT    ((RAS_TBL_SIZE_BYTES - RAS_TABLE_HEADER_SIZE) \
95 				 / RAS_TABLE_RECORD_SIZE)
96 
97 /*
98  * EEPROM Table structrue v2.1
99  * ---------------------------------
100  * |                               |
101  * |     EEPROM TABLE HEADER       |
102  * |      ( size 20 Bytes )        |
103  * |                               |
104  * ---------------------------------
105  * |                               |
106  * |     EEPROM TABLE RAS INFO     |
107  * | (available info size 4 Bytes) |
108  * |  ( reserved size 252 Bytes )  |
109  * |                               |
110  * ---------------------------------
111  * |                               |
112  * |     BAD PAGE RECORD AREA      |
113  * |                               |
114  * ---------------------------------
115  */
116 
117 /* EEPROM Table V2_1 */
118 #define RAS_TABLE_V2_1_INFO_SIZE       256
119 #define RAS_TABLE_V2_1_INFO_START      RAS_TABLE_HEADER_SIZE
120 #define RAS_RECORD_START_V2_1          (RAS_HDR_START + RAS_TABLE_HEADER_SIZE + \
121 					RAS_TABLE_V2_1_INFO_SIZE)
122 #define RAS_MAX_RECORD_COUNT_V2_1      ((RAS_TBL_SIZE_BYTES - RAS_TABLE_HEADER_SIZE - \
123 					RAS_TABLE_V2_1_INFO_SIZE) \
124 					/ RAS_TABLE_RECORD_SIZE)
125 
126 /* Given a zero-based index of an EEPROM RAS record, yields the EEPROM
127  * offset off of RAS_TABLE_START.  That is, this is something you can
128  * add to control->i2c_address, and then tell I2C layer to read
129  * from/write to there. _N is the so called absolute index,
130  * because it starts right after the table header.
131  */
132 #define RAS_INDEX_TO_OFFSET(_C, _N) ((_C)->ras_record_offset + \
133 				     (_N) * RAS_TABLE_RECORD_SIZE)
134 
135 #define RAS_OFFSET_TO_INDEX(_C, _O) (((_O) - \
136 				      (_C)->ras_record_offset) / RAS_TABLE_RECORD_SIZE)
137 
138 /* Given a 0-based relative record index, 0, 1, 2, ..., etc., off
139  * of "fri", return the absolute record index off of the end of
140  * the table header.
141  */
142 #define RAS_RI_TO_AI(_C, _I) (((_I) + (_C)->ras_fri) % \
143 			      (_C)->ras_max_record_count)
144 
145 #define RAS_NUM_RECS(_tbl_hdr)  (((_tbl_hdr)->tbl_size - \
146 				  RAS_TABLE_HEADER_SIZE) / RAS_TABLE_RECORD_SIZE)
147 
148 #define RAS_NUM_RECS_V2_1(_tbl_hdr)  (((_tbl_hdr)->tbl_size - \
149 				       RAS_TABLE_HEADER_SIZE - \
150 				       RAS_TABLE_V2_1_INFO_SIZE) / RAS_TABLE_RECORD_SIZE)
151 
152 #define to_amdgpu_device(x) ((container_of(x, struct amdgpu_ras, eeprom_control))->adev)
153 
154 static bool __is_ras_eeprom_supported(struct amdgpu_device *adev)
155 {
156 	switch (amdgpu_ip_version(adev, MP1_HWIP, 0)) {
157 	case IP_VERSION(11, 0, 2): /* VEGA20 and ARCTURUS */
158 	case IP_VERSION(11, 0, 7): /* Sienna cichlid */
159 	case IP_VERSION(13, 0, 0):
160 	case IP_VERSION(13, 0, 2): /* Aldebaran */
161 	case IP_VERSION(13, 0, 10):
162 		return true;
163 	case IP_VERSION(13, 0, 6):
164 	case IP_VERSION(13, 0, 12):
165 	case IP_VERSION(13, 0, 14):
166 		return (adev->gmc.is_app_apu) ? false : true;
167 	default:
168 		return false;
169 	}
170 }
171 
172 static bool __get_eeprom_i2c_addr(struct amdgpu_device *adev,
173 				  struct amdgpu_ras_eeprom_control *control)
174 {
175 	struct atom_context *atom_ctx = adev->mode_info.atom_context;
176 	u8 i2c_addr;
177 
178 	if (!control)
179 		return false;
180 
181 	if (adev->bios && amdgpu_atomfirmware_ras_rom_addr(adev, &i2c_addr)) {
182 		/* The address given by VBIOS is an 8-bit, wire-format
183 		 * address, i.e. the most significant byte.
184 		 *
185 		 * Normalize it to a 19-bit EEPROM address. Remove the
186 		 * device type identifier and make it a 7-bit address;
187 		 * then make it a 19-bit EEPROM address. See top of
188 		 * amdgpu_eeprom.c.
189 		 */
190 		i2c_addr = (i2c_addr & 0x0F) >> 1;
191 		control->i2c_address = ((u32) i2c_addr) << 16;
192 
193 		return true;
194 	}
195 
196 	switch (amdgpu_ip_version(adev, MP1_HWIP, 0)) {
197 	case IP_VERSION(11, 0, 2):
198 		/* VEGA20 and ARCTURUS */
199 		if (adev->asic_type == CHIP_VEGA20)
200 			control->i2c_address = EEPROM_I2C_MADDR_0;
201 		else if (strnstr(atom_ctx->vbios_pn,
202 				 "D342",
203 				 sizeof(atom_ctx->vbios_pn)))
204 			control->i2c_address = EEPROM_I2C_MADDR_0;
205 		else
206 			control->i2c_address = EEPROM_I2C_MADDR_4;
207 		return true;
208 	case IP_VERSION(11, 0, 7):
209 		control->i2c_address = EEPROM_I2C_MADDR_0;
210 		return true;
211 	case IP_VERSION(13, 0, 2):
212 		if (strnstr(atom_ctx->vbios_pn, "D673",
213 			    sizeof(atom_ctx->vbios_pn)))
214 			control->i2c_address = EEPROM_I2C_MADDR_4;
215 		else
216 			control->i2c_address = EEPROM_I2C_MADDR_0;
217 		return true;
218 	case IP_VERSION(13, 0, 0):
219 		if (strnstr(atom_ctx->vbios_pn, "D707",
220 			    sizeof(atom_ctx->vbios_pn)))
221 			control->i2c_address = EEPROM_I2C_MADDR_0;
222 		else
223 			control->i2c_address = EEPROM_I2C_MADDR_4;
224 		return true;
225 	case IP_VERSION(13, 0, 6):
226 	case IP_VERSION(13, 0, 10):
227 	case IP_VERSION(13, 0, 12):
228 	case IP_VERSION(13, 0, 14):
229 		control->i2c_address = EEPROM_I2C_MADDR_4;
230 		return true;
231 	default:
232 		return false;
233 	}
234 }
235 
236 static void
237 __encode_table_header_to_buf(struct amdgpu_ras_eeprom_table_header *hdr,
238 			     unsigned char *buf)
239 {
240 	u32 *pp = (uint32_t *)buf;
241 
242 	pp[0] = cpu_to_le32(hdr->header);
243 	pp[1] = cpu_to_le32(hdr->version);
244 	pp[2] = cpu_to_le32(hdr->first_rec_offset);
245 	pp[3] = cpu_to_le32(hdr->tbl_size);
246 	pp[4] = cpu_to_le32(hdr->checksum);
247 }
248 
249 static void
250 __decode_table_header_from_buf(struct amdgpu_ras_eeprom_table_header *hdr,
251 			       unsigned char *buf)
252 {
253 	u32 *pp = (uint32_t *)buf;
254 
255 	hdr->header	      = le32_to_cpu(pp[0]);
256 	hdr->version	      = le32_to_cpu(pp[1]);
257 	hdr->first_rec_offset = le32_to_cpu(pp[2]);
258 	hdr->tbl_size	      = le32_to_cpu(pp[3]);
259 	hdr->checksum	      = le32_to_cpu(pp[4]);
260 }
261 
262 static int __write_table_header(struct amdgpu_ras_eeprom_control *control)
263 {
264 	u8 buf[RAS_TABLE_HEADER_SIZE];
265 	struct amdgpu_device *adev = to_amdgpu_device(control);
266 	int res;
267 
268 	memset(buf, 0, sizeof(buf));
269 	__encode_table_header_to_buf(&control->tbl_hdr, buf);
270 
271 	/* i2c may be unstable in gpu reset */
272 	down_read(&adev->reset_domain->sem);
273 	res = amdgpu_eeprom_write(adev->pm.ras_eeprom_i2c_bus,
274 				  control->i2c_address +
275 				  control->ras_header_offset,
276 				  buf, RAS_TABLE_HEADER_SIZE);
277 	up_read(&adev->reset_domain->sem);
278 
279 	if (res < 0) {
280 		dev_err(adev->dev, "Failed to write EEPROM table header:%d",
281 			res);
282 	} else if (res < RAS_TABLE_HEADER_SIZE) {
283 		dev_err(adev->dev, "Short write:%d out of %d\n", res,
284 			RAS_TABLE_HEADER_SIZE);
285 		res = -EIO;
286 	} else {
287 		res = 0;
288 	}
289 
290 	return res;
291 }
292 
293 static void
294 __encode_table_ras_info_to_buf(struct amdgpu_ras_eeprom_table_ras_info *rai,
295 			       unsigned char *buf)
296 {
297 	u32 *pp = (uint32_t *)buf;
298 	u32 tmp;
299 
300 	tmp = ((uint32_t)(rai->rma_status) & 0xFF) |
301 	      (((uint32_t)(rai->health_percent) << 8) & 0xFF00) |
302 	      (((uint32_t)(rai->ecc_page_threshold) << 16) & 0xFFFF0000);
303 	pp[0] = cpu_to_le32(tmp);
304 }
305 
306 static void
307 __decode_table_ras_info_from_buf(struct amdgpu_ras_eeprom_table_ras_info *rai,
308 				 unsigned char *buf)
309 {
310 	u32 *pp = (uint32_t *)buf;
311 	u32 tmp;
312 
313 	tmp = le32_to_cpu(pp[0]);
314 	rai->rma_status = tmp & 0xFF;
315 	rai->health_percent = (tmp >> 8) & 0xFF;
316 	rai->ecc_page_threshold = (tmp >> 16) & 0xFFFF;
317 }
318 
319 static int __write_table_ras_info(struct amdgpu_ras_eeprom_control *control)
320 {
321 	struct amdgpu_device *adev = to_amdgpu_device(control);
322 	u8 *buf;
323 	int res;
324 
325 	buf = kzalloc(RAS_TABLE_V2_1_INFO_SIZE, GFP_KERNEL);
326 	if (!buf) {
327 		dev_err(adev->dev,
328 			"Failed to alloc buf to write table ras info\n");
329 		return -ENOMEM;
330 	}
331 
332 	__encode_table_ras_info_to_buf(&control->tbl_rai, buf);
333 
334 	/* i2c may be unstable in gpu reset */
335 	down_read(&adev->reset_domain->sem);
336 	res = amdgpu_eeprom_write(adev->pm.ras_eeprom_i2c_bus,
337 				  control->i2c_address +
338 				  control->ras_info_offset,
339 				  buf, RAS_TABLE_V2_1_INFO_SIZE);
340 	up_read(&adev->reset_domain->sem);
341 
342 	if (res < 0) {
343 		dev_err(adev->dev, "Failed to write EEPROM table ras info:%d",
344 			res);
345 	} else if (res < RAS_TABLE_V2_1_INFO_SIZE) {
346 		dev_err(adev->dev, "Short write:%d out of %d\n", res,
347 			RAS_TABLE_V2_1_INFO_SIZE);
348 		res = -EIO;
349 	} else {
350 		res = 0;
351 	}
352 
353 	kfree(buf);
354 
355 	return res;
356 }
357 
358 static u8 __calc_hdr_byte_sum(const struct amdgpu_ras_eeprom_control *control)
359 {
360 	int ii;
361 	u8  *pp, csum;
362 	size_t sz;
363 
364 	/* Header checksum, skip checksum field in the calculation */
365 	sz = sizeof(control->tbl_hdr) - sizeof(control->tbl_hdr.checksum);
366 	pp = (u8 *) &control->tbl_hdr;
367 	csum = 0;
368 	for (ii = 0; ii < sz; ii++, pp++)
369 		csum += *pp;
370 
371 	return csum;
372 }
373 
374 static u8 __calc_ras_info_byte_sum(const struct amdgpu_ras_eeprom_control *control)
375 {
376 	int ii;
377 	u8  *pp, csum;
378 	size_t sz;
379 
380 	sz = sizeof(control->tbl_rai);
381 	pp = (u8 *) &control->tbl_rai;
382 	csum = 0;
383 	for (ii = 0; ii < sz; ii++, pp++)
384 		csum += *pp;
385 
386 	return csum;
387 }
388 
389 static int amdgpu_ras_eeprom_correct_header_tag(
390 	struct amdgpu_ras_eeprom_control *control,
391 	uint32_t header)
392 {
393 	struct amdgpu_ras_eeprom_table_header *hdr = &control->tbl_hdr;
394 	u8 *hh;
395 	int res;
396 	u8 csum;
397 
398 	csum = -hdr->checksum;
399 
400 	hh = (void *) &hdr->header;
401 	csum -= (hh[0] + hh[1] + hh[2] + hh[3]);
402 	hh = (void *) &header;
403 	csum += hh[0] + hh[1] + hh[2] + hh[3];
404 	csum = -csum;
405 	mutex_lock(&control->ras_tbl_mutex);
406 	hdr->header = header;
407 	hdr->checksum = csum;
408 	res = __write_table_header(control);
409 	mutex_unlock(&control->ras_tbl_mutex);
410 
411 	return res;
412 }
413 
414 static void amdgpu_ras_set_eeprom_table_version(struct amdgpu_ras_eeprom_control *control)
415 {
416 	struct amdgpu_device *adev = to_amdgpu_device(control);
417 	struct amdgpu_ras_eeprom_table_header *hdr = &control->tbl_hdr;
418 
419 	switch (amdgpu_ip_version(adev, UMC_HWIP, 0)) {
420 	case IP_VERSION(8, 10, 0):
421 		hdr->version = RAS_TABLE_VER_V2_1;
422 		return;
423 	case IP_VERSION(12, 0, 0):
424 	case IP_VERSION(12, 5, 0):
425 		hdr->version = RAS_TABLE_VER_V3;
426 		return;
427 	default:
428 		hdr->version = RAS_TABLE_VER_V1;
429 		return;
430 	}
431 }
432 
433 /**
434  * amdgpu_ras_eeprom_reset_table -- Reset the RAS EEPROM table
435  * @control: pointer to control structure
436  *
437  * Reset the contents of the header of the RAS EEPROM table.
438  * Return 0 on success, -errno on error.
439  */
440 int amdgpu_ras_eeprom_reset_table(struct amdgpu_ras_eeprom_control *control)
441 {
442 	struct amdgpu_device *adev = to_amdgpu_device(control);
443 	struct amdgpu_ras_eeprom_table_header *hdr = &control->tbl_hdr;
444 	struct amdgpu_ras_eeprom_table_ras_info *rai = &control->tbl_rai;
445 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
446 	u8 csum;
447 	int res;
448 
449 	mutex_lock(&control->ras_tbl_mutex);
450 
451 	hdr->header = RAS_TABLE_HDR_VAL;
452 	amdgpu_ras_set_eeprom_table_version(control);
453 
454 	if (hdr->version >= RAS_TABLE_VER_V2_1) {
455 		hdr->first_rec_offset = RAS_RECORD_START_V2_1;
456 		hdr->tbl_size = RAS_TABLE_HEADER_SIZE +
457 				RAS_TABLE_V2_1_INFO_SIZE;
458 		rai->rma_status = GPU_HEALTH_USABLE;
459 		/**
460 		 * GPU health represented as a percentage.
461 		 * 0 means worst health, 100 means fully health.
462 		 */
463 		rai->health_percent = 100;
464 		/* ecc_page_threshold = 0 means disable bad page retirement */
465 		rai->ecc_page_threshold = con->bad_page_cnt_threshold;
466 	} else {
467 		hdr->first_rec_offset = RAS_RECORD_START;
468 		hdr->tbl_size = RAS_TABLE_HEADER_SIZE;
469 	}
470 
471 	csum = __calc_hdr_byte_sum(control);
472 	if (hdr->version >= RAS_TABLE_VER_V2_1)
473 		csum += __calc_ras_info_byte_sum(control);
474 	csum = -csum;
475 	hdr->checksum = csum;
476 	res = __write_table_header(control);
477 	if (!res && hdr->version > RAS_TABLE_VER_V1)
478 		res = __write_table_ras_info(control);
479 
480 	control->ras_num_recs = 0;
481 	control->ras_num_bad_pages = 0;
482 	control->ras_num_mca_recs = 0;
483 	control->ras_num_pa_recs = 0;
484 	control->ras_fri = 0;
485 
486 	amdgpu_dpm_send_hbm_bad_pages_num(adev, control->ras_num_bad_pages);
487 
488 	control->bad_channel_bitmap = 0;
489 	amdgpu_dpm_send_hbm_bad_channel_flag(adev, control->bad_channel_bitmap);
490 	con->update_channel_flag = false;
491 
492 	amdgpu_ras_debugfs_set_ret_size(control);
493 
494 	mutex_unlock(&control->ras_tbl_mutex);
495 
496 	return res;
497 }
498 
499 static void
500 __encode_table_record_to_buf(struct amdgpu_ras_eeprom_control *control,
501 			     struct eeprom_table_record *record,
502 			     unsigned char *buf)
503 {
504 	__le64 tmp = 0;
505 	int i = 0;
506 
507 	/* Next are all record fields according to EEPROM page spec in LE foramt */
508 	buf[i++] = record->err_type;
509 
510 	buf[i++] = record->bank;
511 
512 	tmp = cpu_to_le64(record->ts);
513 	memcpy(buf + i, &tmp, 8);
514 	i += 8;
515 
516 	tmp = cpu_to_le64((record->offset & 0xffffffffffff));
517 	memcpy(buf + i, &tmp, 6);
518 	i += 6;
519 
520 	buf[i++] = record->mem_channel;
521 	buf[i++] = record->mcumc_id;
522 
523 	tmp = cpu_to_le64((record->retired_page & 0xffffffffffff));
524 	memcpy(buf + i, &tmp, 6);
525 }
526 
527 static void
528 __decode_table_record_from_buf(struct amdgpu_ras_eeprom_control *control,
529 			       struct eeprom_table_record *record,
530 			       unsigned char *buf)
531 {
532 	__le64 tmp = 0;
533 	int i =  0;
534 
535 	/* Next are all record fields according to EEPROM page spec in LE foramt */
536 	record->err_type = buf[i++];
537 
538 	record->bank = buf[i++];
539 
540 	memcpy(&tmp, buf + i, 8);
541 	record->ts = le64_to_cpu(tmp);
542 	i += 8;
543 
544 	memcpy(&tmp, buf + i, 6);
545 	record->offset = (le64_to_cpu(tmp) & 0xffffffffffff);
546 	i += 6;
547 
548 	record->mem_channel = buf[i++];
549 	record->mcumc_id = buf[i++];
550 
551 	memcpy(&tmp, buf + i,  6);
552 	record->retired_page = (le64_to_cpu(tmp) & 0xffffffffffff);
553 }
554 
555 bool amdgpu_ras_eeprom_check_err_threshold(struct amdgpu_device *adev)
556 {
557 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
558 
559 	if (!__is_ras_eeprom_supported(adev) ||
560 	    !amdgpu_bad_page_threshold)
561 		return false;
562 
563 	/* skip check eeprom table for VEGA20 Gaming */
564 	if (!con)
565 		return false;
566 	else
567 		if (!(con->features & BIT(AMDGPU_RAS_BLOCK__UMC)))
568 			return false;
569 
570 	if (con->eeprom_control.tbl_hdr.header == RAS_TABLE_HDR_BAD) {
571 		if (con->eeprom_control.ras_num_bad_pages > con->bad_page_cnt_threshold)
572 			dev_warn(adev->dev, "RAS records:%d exceed threshold:%d",
573 				 con->eeprom_control.ras_num_bad_pages, con->bad_page_cnt_threshold);
574 		if ((amdgpu_bad_page_threshold == -1) ||
575 		    (amdgpu_bad_page_threshold == -2)) {
576 			dev_warn(adev->dev,
577 				 "Please consult AMD Service Action Guide (SAG) for appropriate service procedures.\n");
578 			return false;
579 		} else {
580 			dev_warn(adev->dev,
581 				 "Please consider adjusting the customized threshold.\n");
582 			return true;
583 		}
584 	}
585 
586 	return false;
587 }
588 
589 /**
590  * __amdgpu_ras_eeprom_write -- write indexed from buffer to EEPROM
591  * @control: pointer to control structure
592  * @buf: pointer to buffer containing data to write
593  * @fri: start writing at this index
594  * @num: number of records to write
595  *
596  * The caller must hold the table mutex in @control.
597  * Return 0 on success, -errno otherwise.
598  */
599 static int __amdgpu_ras_eeprom_write(struct amdgpu_ras_eeprom_control *control,
600 				     u8 *buf, const u32 fri, const u32 num)
601 {
602 	struct amdgpu_device *adev = to_amdgpu_device(control);
603 	u32 buf_size;
604 	int res;
605 
606 	/* i2c may be unstable in gpu reset */
607 	down_read(&adev->reset_domain->sem);
608 	buf_size = num * RAS_TABLE_RECORD_SIZE;
609 	res = amdgpu_eeprom_write(adev->pm.ras_eeprom_i2c_bus,
610 				  control->i2c_address +
611 				  RAS_INDEX_TO_OFFSET(control, fri),
612 				  buf, buf_size);
613 	up_read(&adev->reset_domain->sem);
614 	if (res < 0) {
615 		dev_err(adev->dev, "Writing %d EEPROM table records error:%d",
616 			num, res);
617 	} else if (res < buf_size) {
618 		/* Short write, return error.
619 		 */
620 		dev_err(adev->dev, "Wrote %d records out of %d",
621 			res / RAS_TABLE_RECORD_SIZE, num);
622 		res = -EIO;
623 	} else {
624 		res = 0;
625 	}
626 
627 	return res;
628 }
629 
630 static int
631 amdgpu_ras_eeprom_append_table(struct amdgpu_ras_eeprom_control *control,
632 			       struct eeprom_table_record *record,
633 			       const u32 num)
634 {
635 	struct amdgpu_ras *con = amdgpu_ras_get_context(to_amdgpu_device(control));
636 	struct amdgpu_device *adev = to_amdgpu_device(control);
637 	u32 a, b, i;
638 	u8 *buf, *pp;
639 	int res;
640 
641 	buf = kcalloc(num, RAS_TABLE_RECORD_SIZE, GFP_KERNEL);
642 	if (!buf)
643 		return -ENOMEM;
644 
645 	/* Encode all of them in one go.
646 	 */
647 	pp = buf;
648 	for (i = 0; i < num; i++, pp += RAS_TABLE_RECORD_SIZE) {
649 		__encode_table_record_to_buf(control, &record[i], pp);
650 
651 		/* update bad channel bitmap */
652 		if ((record[i].mem_channel < BITS_PER_TYPE(control->bad_channel_bitmap)) &&
653 		    !(control->bad_channel_bitmap & (1 << record[i].mem_channel))) {
654 			control->bad_channel_bitmap |= 1 << record[i].mem_channel;
655 			con->update_channel_flag = true;
656 		}
657 	}
658 
659 	/* a, first record index to write into.
660 	 * b, last record index to write into.
661 	 * a = first index to read (fri) + number of records in the table,
662 	 * b = a + @num - 1.
663 	 * Let N = control->ras_max_num_record_count, then we have,
664 	 * case 0: 0 <= a <= b < N,
665 	 *   just append @num records starting at a;
666 	 * case 1: 0 <= a < N <= b,
667 	 *   append (N - a) records starting at a, and
668 	 *   append the remainder,  b % N + 1, starting at 0.
669 	 * case 2: 0 <= fri < N <= a <= b, then modulo N we get two subcases,
670 	 * case 2a: 0 <= a <= b < N
671 	 *   append num records starting at a; and fix fri if b overwrote it,
672 	 *   and since a <= b, if b overwrote it then a must've also,
673 	 *   and if b didn't overwrite it, then a didn't also.
674 	 * case 2b: 0 <= b < a < N
675 	 *   write num records starting at a, which wraps around 0=N
676 	 *   and overwrite fri unconditionally. Now from case 2a,
677 	 *   this means that b eclipsed fri to overwrite it and wrap
678 	 *   around 0 again, i.e. b = 2N+r pre modulo N, so we unconditionally
679 	 *   set fri = b + 1 (mod N).
680 	 * Now, since fri is updated in every case, except the trivial case 0,
681 	 * the number of records present in the table after writing, is,
682 	 * num_recs - 1 = b - fri (mod N), and we take the positive value,
683 	 * by adding an arbitrary multiple of N before taking the modulo N
684 	 * as shown below.
685 	 */
686 	a = control->ras_fri + control->ras_num_recs;
687 	b = a + num  - 1;
688 	if (b < control->ras_max_record_count) {
689 		res = __amdgpu_ras_eeprom_write(control, buf, a, num);
690 	} else if (a < control->ras_max_record_count) {
691 		u32 g0, g1;
692 
693 		g0 = control->ras_max_record_count - a;
694 		g1 = b % control->ras_max_record_count + 1;
695 		res = __amdgpu_ras_eeprom_write(control, buf, a, g0);
696 		if (res)
697 			goto Out;
698 		res = __amdgpu_ras_eeprom_write(control,
699 						buf + g0 * RAS_TABLE_RECORD_SIZE,
700 						0, g1);
701 		if (res)
702 			goto Out;
703 		if (g1 > control->ras_fri)
704 			control->ras_fri = g1 % control->ras_max_record_count;
705 	} else {
706 		a %= control->ras_max_record_count;
707 		b %= control->ras_max_record_count;
708 
709 		if (a <= b) {
710 			/* Note that, b - a + 1 = num. */
711 			res = __amdgpu_ras_eeprom_write(control, buf, a, num);
712 			if (res)
713 				goto Out;
714 			if (b >= control->ras_fri)
715 				control->ras_fri = (b + 1) % control->ras_max_record_count;
716 		} else {
717 			u32 g0, g1;
718 
719 			/* b < a, which means, we write from
720 			 * a to the end of the table, and from
721 			 * the start of the table to b.
722 			 */
723 			g0 = control->ras_max_record_count - a;
724 			g1 = b + 1;
725 			res = __amdgpu_ras_eeprom_write(control, buf, a, g0);
726 			if (res)
727 				goto Out;
728 			res = __amdgpu_ras_eeprom_write(control,
729 							buf + g0 * RAS_TABLE_RECORD_SIZE,
730 							0, g1);
731 			if (res)
732 				goto Out;
733 			control->ras_fri = g1 % control->ras_max_record_count;
734 		}
735 	}
736 	control->ras_num_recs = 1 + (control->ras_max_record_count + b
737 				     - control->ras_fri)
738 		% control->ras_max_record_count;
739 
740 	/*old asics only save pa to eeprom like before*/
741 	if (IP_VERSION_MAJ(amdgpu_ip_version(adev, UMC_HWIP, 0)) < 12)
742 		control->ras_num_pa_recs += num;
743 	else
744 		control->ras_num_mca_recs += num;
745 
746 	control->ras_num_bad_pages = con->bad_page_num;
747 Out:
748 	kfree(buf);
749 	return res;
750 }
751 
752 static int
753 amdgpu_ras_eeprom_update_header(struct amdgpu_ras_eeprom_control *control)
754 {
755 	struct amdgpu_device *adev = to_amdgpu_device(control);
756 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
757 	u8 *buf, *pp, csum;
758 	u32 buf_size;
759 	int res;
760 
761 	/* Modify the header if it exceeds.
762 	 */
763 	if (amdgpu_bad_page_threshold != 0 &&
764 	    control->ras_num_bad_pages > ras->bad_page_cnt_threshold) {
765 		dev_warn(adev->dev,
766 			"Saved bad pages %d reaches threshold value %d\n",
767 			control->ras_num_bad_pages, ras->bad_page_cnt_threshold);
768 
769 		if (adev->cper.enabled && amdgpu_cper_generate_bp_threshold_record(adev))
770 			dev_warn(adev->dev, "fail to generate bad page threshold cper records\n");
771 
772 		if ((amdgpu_bad_page_threshold != -1) &&
773 		    (amdgpu_bad_page_threshold != -2)) {
774 			control->tbl_hdr.header = RAS_TABLE_HDR_BAD;
775 			if (control->tbl_hdr.version >= RAS_TABLE_VER_V2_1) {
776 				control->tbl_rai.rma_status = GPU_RETIRED__ECC_REACH_THRESHOLD;
777 				control->tbl_rai.health_percent = 0;
778 			}
779 			ras->is_rma = true;
780 		}
781 
782 		/* ignore the -ENOTSUPP return value */
783 		amdgpu_dpm_send_rma_reason(adev);
784 	}
785 
786 	if (control->tbl_hdr.version >= RAS_TABLE_VER_V2_1)
787 		control->tbl_hdr.tbl_size = RAS_TABLE_HEADER_SIZE +
788 					    RAS_TABLE_V2_1_INFO_SIZE +
789 					    control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
790 	else
791 		control->tbl_hdr.tbl_size = RAS_TABLE_HEADER_SIZE +
792 					    control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
793 	control->tbl_hdr.checksum = 0;
794 
795 	buf_size = control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
796 	buf = kcalloc(control->ras_num_recs, RAS_TABLE_RECORD_SIZE, GFP_KERNEL);
797 	if (!buf) {
798 		dev_err(adev->dev,
799 			"allocating memory for table of size %d bytes failed\n",
800 			control->tbl_hdr.tbl_size);
801 		res = -ENOMEM;
802 		goto Out;
803 	}
804 
805 	down_read(&adev->reset_domain->sem);
806 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
807 				 control->i2c_address +
808 				 control->ras_record_offset,
809 				 buf, buf_size);
810 	up_read(&adev->reset_domain->sem);
811 	if (res < 0) {
812 		dev_err(adev->dev, "EEPROM failed reading records:%d\n", res);
813 		goto Out;
814 	} else if (res < buf_size) {
815 		dev_err(adev->dev, "EEPROM read %d out of %d bytes\n", res,
816 			buf_size);
817 		res = -EIO;
818 		goto Out;
819 	}
820 
821 	/**
822 	 * bad page records have been stored in eeprom,
823 	 * now calculate gpu health percent
824 	 */
825 	if (amdgpu_bad_page_threshold != 0 &&
826 	    control->tbl_hdr.version >= RAS_TABLE_VER_V2_1 &&
827 	    control->ras_num_bad_pages <= ras->bad_page_cnt_threshold)
828 		control->tbl_rai.health_percent = ((ras->bad_page_cnt_threshold -
829 						   control->ras_num_bad_pages) * 100) /
830 						   ras->bad_page_cnt_threshold;
831 
832 	/* Recalc the checksum.
833 	 */
834 	csum = 0;
835 	for (pp = buf; pp < buf + buf_size; pp++)
836 		csum += *pp;
837 
838 	csum += __calc_hdr_byte_sum(control);
839 	if (control->tbl_hdr.version >= RAS_TABLE_VER_V2_1)
840 		csum += __calc_ras_info_byte_sum(control);
841 	/* avoid sign extension when assigning to "checksum" */
842 	csum = -csum;
843 	control->tbl_hdr.checksum = csum;
844 	res = __write_table_header(control);
845 	if (!res && control->tbl_hdr.version > RAS_TABLE_VER_V1)
846 		res = __write_table_ras_info(control);
847 Out:
848 	kfree(buf);
849 	return res;
850 }
851 
852 /**
853  * amdgpu_ras_eeprom_append -- append records to the EEPROM RAS table
854  * @control: pointer to control structure
855  * @record: array of records to append
856  * @num: number of records in @record array
857  *
858  * Append @num records to the table, calculate the checksum and write
859  * the table back to EEPROM. The maximum number of records that
860  * can be appended is between 1 and control->ras_max_record_count,
861  * regardless of how many records are already stored in the table.
862  *
863  * Return 0 on success or if EEPROM is not supported, -errno on error.
864  */
865 int amdgpu_ras_eeprom_append(struct amdgpu_ras_eeprom_control *control,
866 			     struct eeprom_table_record *record,
867 			     const u32 num)
868 {
869 	struct amdgpu_device *adev = to_amdgpu_device(control);
870 	int res, i;
871 	uint64_t nps = AMDGPU_NPS1_PARTITION_MODE;
872 
873 	if (!__is_ras_eeprom_supported(adev))
874 		return 0;
875 
876 	if (num == 0) {
877 		dev_err(adev->dev, "will not append 0 records\n");
878 		return -EINVAL;
879 	} else if (num > control->ras_max_record_count) {
880 		dev_err(adev->dev,
881 			"cannot append %d records than the size of table %d\n",
882 			num, control->ras_max_record_count);
883 		return -EINVAL;
884 	}
885 
886 	if (adev->gmc.gmc_funcs->query_mem_partition_mode)
887 		nps = adev->gmc.gmc_funcs->query_mem_partition_mode(adev);
888 
889 	/* set the new channel index flag */
890 	for (i = 0; i < num; i++)
891 		record[i].retired_page |= (nps << UMC_NPS_SHIFT);
892 
893 	mutex_lock(&control->ras_tbl_mutex);
894 
895 	res = amdgpu_ras_eeprom_append_table(control, record, num);
896 	if (!res)
897 		res = amdgpu_ras_eeprom_update_header(control);
898 	if (!res)
899 		amdgpu_ras_debugfs_set_ret_size(control);
900 
901 	mutex_unlock(&control->ras_tbl_mutex);
902 
903 	/* clear channel index flag, the flag is only saved on eeprom */
904 	for (i = 0; i < num; i++)
905 		record[i].retired_page &= ~(nps << UMC_NPS_SHIFT);
906 
907 	return res;
908 }
909 
910 /**
911  * __amdgpu_ras_eeprom_read -- read indexed from EEPROM into buffer
912  * @control: pointer to control structure
913  * @buf: pointer to buffer to read into
914  * @fri: first record index, start reading at this index, absolute index
915  * @num: number of records to read
916  *
917  * The caller must hold the table mutex in @control.
918  * Return 0 on success, -errno otherwise.
919  */
920 static int __amdgpu_ras_eeprom_read(struct amdgpu_ras_eeprom_control *control,
921 				    u8 *buf, const u32 fri, const u32 num)
922 {
923 	struct amdgpu_device *adev = to_amdgpu_device(control);
924 	u32 buf_size;
925 	int res;
926 
927 	/* i2c may be unstable in gpu reset */
928 	down_read(&adev->reset_domain->sem);
929 	buf_size = num * RAS_TABLE_RECORD_SIZE;
930 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
931 				 control->i2c_address +
932 				 RAS_INDEX_TO_OFFSET(control, fri),
933 				 buf, buf_size);
934 	up_read(&adev->reset_domain->sem);
935 	if (res < 0) {
936 		dev_err(adev->dev, "Reading %d EEPROM table records error:%d",
937 			num, res);
938 	} else if (res < buf_size) {
939 		/* Short read, return error.
940 		 */
941 		dev_err(adev->dev, "Read %d records out of %d",
942 			res / RAS_TABLE_RECORD_SIZE, num);
943 		res = -EIO;
944 	} else {
945 		res = 0;
946 	}
947 
948 	return res;
949 }
950 
951 /**
952  * amdgpu_ras_eeprom_read -- read EEPROM
953  * @control: pointer to control structure
954  * @record: array of records to read into
955  * @num: number of records in @record
956  *
957  * Reads num records from the RAS table in EEPROM and
958  * writes the data into @record array.
959  *
960  * Returns 0 on success, -errno on error.
961  */
962 int amdgpu_ras_eeprom_read(struct amdgpu_ras_eeprom_control *control,
963 			   struct eeprom_table_record *record,
964 			   const u32 num)
965 {
966 	struct amdgpu_device *adev = to_amdgpu_device(control);
967 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
968 	int i, res;
969 	u8 *buf, *pp;
970 	u32 g0, g1;
971 
972 	if (!__is_ras_eeprom_supported(adev))
973 		return 0;
974 
975 	if (num == 0) {
976 		dev_err(adev->dev, "will not read 0 records\n");
977 		return -EINVAL;
978 	} else if (num > control->ras_num_recs) {
979 		dev_err(adev->dev, "too many records to read:%d available:%d\n",
980 			num, control->ras_num_recs);
981 		return -EINVAL;
982 	}
983 
984 	buf = kcalloc(num, RAS_TABLE_RECORD_SIZE, GFP_KERNEL);
985 	if (!buf)
986 		return -ENOMEM;
987 
988 	/* Determine how many records to read, from the first record
989 	 * index, fri, to the end of the table, and from the beginning
990 	 * of the table, such that the total number of records is
991 	 * @num, and we handle wrap around when fri > 0 and
992 	 * fri + num > RAS_MAX_RECORD_COUNT.
993 	 *
994 	 * First we compute the index of the last element
995 	 * which would be fetched from each region,
996 	 * g0 is in [fri, fri + num - 1], and
997 	 * g1 is in [0, RAS_MAX_RECORD_COUNT - 1].
998 	 * Then, if g0 < RAS_MAX_RECORD_COUNT, the index of
999 	 * the last element to fetch, we set g0 to _the number_
1000 	 * of elements to fetch, @num, since we know that the last
1001 	 * indexed to be fetched does not exceed the table.
1002 	 *
1003 	 * If, however, g0 >= RAS_MAX_RECORD_COUNT, then
1004 	 * we set g0 to the number of elements to read
1005 	 * until the end of the table, and g1 to the number of
1006 	 * elements to read from the beginning of the table.
1007 	 */
1008 	g0 = control->ras_fri + num - 1;
1009 	g1 = g0 % control->ras_max_record_count;
1010 	if (g0 < control->ras_max_record_count) {
1011 		g0 = num;
1012 		g1 = 0;
1013 	} else {
1014 		g0 = control->ras_max_record_count - control->ras_fri;
1015 		g1 += 1;
1016 	}
1017 
1018 	mutex_lock(&control->ras_tbl_mutex);
1019 	res = __amdgpu_ras_eeprom_read(control, buf, control->ras_fri, g0);
1020 	if (res)
1021 		goto Out;
1022 	if (g1) {
1023 		res = __amdgpu_ras_eeprom_read(control,
1024 					       buf + g0 * RAS_TABLE_RECORD_SIZE,
1025 					       0, g1);
1026 		if (res)
1027 			goto Out;
1028 	}
1029 
1030 	res = 0;
1031 
1032 	/* Read up everything? Then transform.
1033 	 */
1034 	pp = buf;
1035 	for (i = 0; i < num; i++, pp += RAS_TABLE_RECORD_SIZE) {
1036 		__decode_table_record_from_buf(control, &record[i], pp);
1037 
1038 		/* update bad channel bitmap */
1039 		if ((record[i].mem_channel < BITS_PER_TYPE(control->bad_channel_bitmap)) &&
1040 		    !(control->bad_channel_bitmap & (1 << record[i].mem_channel))) {
1041 			control->bad_channel_bitmap |= 1 << record[i].mem_channel;
1042 			con->update_channel_flag = true;
1043 		}
1044 	}
1045 Out:
1046 	kfree(buf);
1047 	mutex_unlock(&control->ras_tbl_mutex);
1048 
1049 	return res;
1050 }
1051 
1052 uint32_t amdgpu_ras_eeprom_max_record_count(struct amdgpu_ras_eeprom_control *control)
1053 {
1054 	/* get available eeprom table version first before eeprom table init */
1055 	amdgpu_ras_set_eeprom_table_version(control);
1056 
1057 	if (control->tbl_hdr.version >= RAS_TABLE_VER_V2_1)
1058 		return RAS_MAX_RECORD_COUNT_V2_1;
1059 	else
1060 		return RAS_MAX_RECORD_COUNT;
1061 }
1062 
1063 static ssize_t
1064 amdgpu_ras_debugfs_eeprom_size_read(struct file *f, char __user *buf,
1065 				    size_t size, loff_t *pos)
1066 {
1067 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
1068 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1069 	struct amdgpu_ras_eeprom_control *control = ras ? &ras->eeprom_control : NULL;
1070 	u8 data[50];
1071 	int res;
1072 
1073 	if (!size)
1074 		return size;
1075 
1076 	if (!ras || !control) {
1077 		res = snprintf(data, sizeof(data), "Not supported\n");
1078 	} else {
1079 		res = snprintf(data, sizeof(data), "%d bytes or %d records\n",
1080 			       RAS_TBL_SIZE_BYTES, control->ras_max_record_count);
1081 	}
1082 
1083 	if (*pos >= res)
1084 		return 0;
1085 
1086 	res -= *pos;
1087 	res = min_t(size_t, res, size);
1088 
1089 	if (copy_to_user(buf, &data[*pos], res))
1090 		return -EFAULT;
1091 
1092 	*pos += res;
1093 
1094 	return res;
1095 }
1096 
1097 const struct file_operations amdgpu_ras_debugfs_eeprom_size_ops = {
1098 	.owner = THIS_MODULE,
1099 	.read = amdgpu_ras_debugfs_eeprom_size_read,
1100 	.write = NULL,
1101 	.llseek = default_llseek,
1102 };
1103 
1104 static const char *tbl_hdr_str = " Signature    Version  FirstOffs       Size   Checksum\n";
1105 static const char *tbl_hdr_fmt = "0x%08X 0x%08X 0x%08X 0x%08X 0x%08X\n";
1106 #define tbl_hdr_fmt_size (5 * (2+8) + 4 + 1)
1107 static const char *rec_hdr_str = "Index  Offset ErrType Bank/CU          TimeStamp      Offs/Addr MemChl MCUMCID    RetiredPage\n";
1108 static const char *rec_hdr_fmt = "%5d 0x%05X %7s    0x%02X 0x%016llX 0x%012llX   0x%02X    0x%02X 0x%012llX\n";
1109 #define rec_hdr_fmt_size (5 + 1 + 7 + 1 + 7 + 1 + 7 + 1 + 18 + 1 + 14 + 1 + 6 + 1 + 7 + 1 + 14 + 1)
1110 
1111 static const char *record_err_type_str[AMDGPU_RAS_EEPROM_ERR_COUNT] = {
1112 	"ignore",
1113 	"re",
1114 	"ue",
1115 };
1116 
1117 static loff_t amdgpu_ras_debugfs_table_size(struct amdgpu_ras_eeprom_control *control)
1118 {
1119 	return strlen(tbl_hdr_str) + tbl_hdr_fmt_size +
1120 		strlen(rec_hdr_str) + rec_hdr_fmt_size * control->ras_num_recs;
1121 }
1122 
1123 void amdgpu_ras_debugfs_set_ret_size(struct amdgpu_ras_eeprom_control *control)
1124 {
1125 	struct amdgpu_ras *ras = container_of(control, struct amdgpu_ras,
1126 					      eeprom_control);
1127 	struct dentry *de = ras->de_ras_eeprom_table;
1128 
1129 	if (de)
1130 		d_inode(de)->i_size = amdgpu_ras_debugfs_table_size(control);
1131 }
1132 
1133 static ssize_t amdgpu_ras_debugfs_table_read(struct file *f, char __user *buf,
1134 					     size_t size, loff_t *pos)
1135 {
1136 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
1137 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1138 	struct amdgpu_ras_eeprom_control *control = &ras->eeprom_control;
1139 	const size_t orig_size = size;
1140 	int res = -EFAULT;
1141 	size_t data_len;
1142 
1143 	mutex_lock(&control->ras_tbl_mutex);
1144 
1145 	/* We want *pos - data_len > 0, which means there's
1146 	 * bytes to be printed from data.
1147 	 */
1148 	data_len = strlen(tbl_hdr_str);
1149 	if (*pos < data_len) {
1150 		data_len -= *pos;
1151 		data_len = min_t(size_t, data_len, size);
1152 		if (copy_to_user(buf, &tbl_hdr_str[*pos], data_len))
1153 			goto Out;
1154 		buf += data_len;
1155 		size -= data_len;
1156 		*pos += data_len;
1157 	}
1158 
1159 	data_len = strlen(tbl_hdr_str) + tbl_hdr_fmt_size;
1160 	if (*pos < data_len && size > 0) {
1161 		u8 data[tbl_hdr_fmt_size + 1];
1162 		loff_t lpos;
1163 
1164 		snprintf(data, sizeof(data), tbl_hdr_fmt,
1165 			 control->tbl_hdr.header,
1166 			 control->tbl_hdr.version,
1167 			 control->tbl_hdr.first_rec_offset,
1168 			 control->tbl_hdr.tbl_size,
1169 			 control->tbl_hdr.checksum);
1170 
1171 		data_len -= *pos;
1172 		data_len = min_t(size_t, data_len, size);
1173 		lpos = *pos - strlen(tbl_hdr_str);
1174 		if (copy_to_user(buf, &data[lpos], data_len))
1175 			goto Out;
1176 		buf += data_len;
1177 		size -= data_len;
1178 		*pos += data_len;
1179 	}
1180 
1181 	data_len = strlen(tbl_hdr_str) + tbl_hdr_fmt_size + strlen(rec_hdr_str);
1182 	if (*pos < data_len && size > 0) {
1183 		loff_t lpos;
1184 
1185 		data_len -= *pos;
1186 		data_len = min_t(size_t, data_len, size);
1187 		lpos = *pos - strlen(tbl_hdr_str) - tbl_hdr_fmt_size;
1188 		if (copy_to_user(buf, &rec_hdr_str[lpos], data_len))
1189 			goto Out;
1190 		buf += data_len;
1191 		size -= data_len;
1192 		*pos += data_len;
1193 	}
1194 
1195 	data_len = amdgpu_ras_debugfs_table_size(control);
1196 	if (*pos < data_len && size > 0) {
1197 		u8 dare[RAS_TABLE_RECORD_SIZE];
1198 		u8 data[rec_hdr_fmt_size + 1];
1199 		struct eeprom_table_record record;
1200 		int s, r;
1201 
1202 		/* Find the starting record index
1203 		 */
1204 		s = *pos - strlen(tbl_hdr_str) - tbl_hdr_fmt_size -
1205 			strlen(rec_hdr_str);
1206 		s = s / rec_hdr_fmt_size;
1207 		r = *pos - strlen(tbl_hdr_str) - tbl_hdr_fmt_size -
1208 			strlen(rec_hdr_str);
1209 		r = r % rec_hdr_fmt_size;
1210 
1211 		for ( ; size > 0 && s < control->ras_num_recs; s++) {
1212 			u32 ai = RAS_RI_TO_AI(control, s);
1213 			/* Read a single record
1214 			 */
1215 			res = __amdgpu_ras_eeprom_read(control, dare, ai, 1);
1216 			if (res)
1217 				goto Out;
1218 			__decode_table_record_from_buf(control, &record, dare);
1219 			snprintf(data, sizeof(data), rec_hdr_fmt,
1220 				 s,
1221 				 RAS_INDEX_TO_OFFSET(control, ai),
1222 				 record_err_type_str[record.err_type],
1223 				 record.bank,
1224 				 record.ts,
1225 				 record.offset,
1226 				 record.mem_channel,
1227 				 record.mcumc_id,
1228 				 record.retired_page);
1229 
1230 			data_len = min_t(size_t, rec_hdr_fmt_size - r, size);
1231 			if (copy_to_user(buf, &data[r], data_len)) {
1232 				res = -EFAULT;
1233 				goto Out;
1234 			}
1235 			buf += data_len;
1236 			size -= data_len;
1237 			*pos += data_len;
1238 			r = 0;
1239 		}
1240 	}
1241 	res = 0;
1242 Out:
1243 	mutex_unlock(&control->ras_tbl_mutex);
1244 	return res < 0 ? res : orig_size - size;
1245 }
1246 
1247 static ssize_t
1248 amdgpu_ras_debugfs_eeprom_table_read(struct file *f, char __user *buf,
1249 				     size_t size, loff_t *pos)
1250 {
1251 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
1252 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1253 	struct amdgpu_ras_eeprom_control *control = ras ? &ras->eeprom_control : NULL;
1254 	u8 data[81];
1255 	int res;
1256 
1257 	if (!size)
1258 		return size;
1259 
1260 	if (!ras || !control) {
1261 		res = snprintf(data, sizeof(data), "Not supported\n");
1262 		if (*pos >= res)
1263 			return 0;
1264 
1265 		res -= *pos;
1266 		res = min_t(size_t, res, size);
1267 
1268 		if (copy_to_user(buf, &data[*pos], res))
1269 			return -EFAULT;
1270 
1271 		*pos += res;
1272 
1273 		return res;
1274 	} else {
1275 		return amdgpu_ras_debugfs_table_read(f, buf, size, pos);
1276 	}
1277 }
1278 
1279 const struct file_operations amdgpu_ras_debugfs_eeprom_table_ops = {
1280 	.owner = THIS_MODULE,
1281 	.read = amdgpu_ras_debugfs_eeprom_table_read,
1282 	.write = NULL,
1283 	.llseek = default_llseek,
1284 };
1285 
1286 /**
1287  * __verify_ras_table_checksum -- verify the RAS EEPROM table checksum
1288  * @control: pointer to control structure
1289  *
1290  * Check the checksum of the stored in EEPROM RAS table.
1291  *
1292  * Return 0 if the checksum is correct,
1293  * positive if it is not correct, and
1294  * -errno on I/O error.
1295  */
1296 static int __verify_ras_table_checksum(struct amdgpu_ras_eeprom_control *control)
1297 {
1298 	struct amdgpu_device *adev = to_amdgpu_device(control);
1299 	int buf_size, res;
1300 	u8  csum, *buf, *pp;
1301 
1302 	if (control->tbl_hdr.version >= RAS_TABLE_VER_V2_1)
1303 		buf_size = RAS_TABLE_HEADER_SIZE +
1304 			   RAS_TABLE_V2_1_INFO_SIZE +
1305 			   control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
1306 	else
1307 		buf_size = RAS_TABLE_HEADER_SIZE +
1308 			   control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
1309 
1310 	buf = kzalloc(buf_size, GFP_KERNEL);
1311 	if (!buf) {
1312 		dev_err(adev->dev,
1313 			"Out of memory checking RAS table checksum.\n");
1314 		return -ENOMEM;
1315 	}
1316 
1317 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
1318 				 control->i2c_address +
1319 				 control->ras_header_offset,
1320 				 buf, buf_size);
1321 	if (res < buf_size) {
1322 		dev_err(adev->dev, "Partial read for checksum, res:%d\n", res);
1323 		/* On partial reads, return -EIO.
1324 		 */
1325 		if (res >= 0)
1326 			res = -EIO;
1327 		goto Out;
1328 	}
1329 
1330 	csum = 0;
1331 	for (pp = buf; pp < buf + buf_size; pp++)
1332 		csum += *pp;
1333 Out:
1334 	kfree(buf);
1335 	return res < 0 ? res : csum;
1336 }
1337 
1338 static int __read_table_ras_info(struct amdgpu_ras_eeprom_control *control)
1339 {
1340 	struct amdgpu_ras_eeprom_table_ras_info *rai = &control->tbl_rai;
1341 	struct amdgpu_device *adev = to_amdgpu_device(control);
1342 	unsigned char *buf;
1343 	int res;
1344 
1345 	buf = kzalloc(RAS_TABLE_V2_1_INFO_SIZE, GFP_KERNEL);
1346 	if (!buf) {
1347 		dev_err(adev->dev,
1348 			"Failed to alloc buf to read EEPROM table ras info\n");
1349 		return -ENOMEM;
1350 	}
1351 
1352 	/**
1353 	 * EEPROM table V2_1 supports ras info,
1354 	 * read EEPROM table ras info
1355 	 */
1356 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
1357 				 control->i2c_address + control->ras_info_offset,
1358 				 buf, RAS_TABLE_V2_1_INFO_SIZE);
1359 	if (res < RAS_TABLE_V2_1_INFO_SIZE) {
1360 		dev_err(adev->dev,
1361 			"Failed to read EEPROM table ras info, res:%d", res);
1362 		res = res >= 0 ? -EIO : res;
1363 		goto Out;
1364 	}
1365 
1366 	__decode_table_ras_info_from_buf(rai, buf);
1367 
1368 Out:
1369 	kfree(buf);
1370 	return res == RAS_TABLE_V2_1_INFO_SIZE ? 0 : res;
1371 }
1372 
1373 int amdgpu_ras_eeprom_init(struct amdgpu_ras_eeprom_control *control)
1374 {
1375 	struct amdgpu_device *adev = to_amdgpu_device(control);
1376 	unsigned char buf[RAS_TABLE_HEADER_SIZE] = { 0 };
1377 	struct amdgpu_ras_eeprom_table_header *hdr = &control->tbl_hdr;
1378 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1379 	int res;
1380 
1381 	ras->is_rma = false;
1382 
1383 	if (!__is_ras_eeprom_supported(adev))
1384 		return 0;
1385 
1386 	/* Verify i2c adapter is initialized */
1387 	if (!adev->pm.ras_eeprom_i2c_bus || !adev->pm.ras_eeprom_i2c_bus->algo)
1388 		return -ENOENT;
1389 
1390 	if (!__get_eeprom_i2c_addr(adev, control))
1391 		return -EINVAL;
1392 
1393 	control->ras_header_offset = RAS_HDR_START;
1394 	control->ras_info_offset = RAS_TABLE_V2_1_INFO_START;
1395 	mutex_init(&control->ras_tbl_mutex);
1396 
1397 	/* Read the table header from EEPROM address */
1398 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
1399 				 control->i2c_address + control->ras_header_offset,
1400 				 buf, RAS_TABLE_HEADER_SIZE);
1401 	if (res < RAS_TABLE_HEADER_SIZE) {
1402 		dev_err(adev->dev, "Failed to read EEPROM table header, res:%d",
1403 			res);
1404 		return res >= 0 ? -EIO : res;
1405 	}
1406 
1407 	__decode_table_header_from_buf(hdr, buf);
1408 
1409 	if (hdr->header != RAS_TABLE_HDR_VAL &&
1410 	    hdr->header != RAS_TABLE_HDR_BAD) {
1411 		dev_info(adev->dev, "Creating a new EEPROM table");
1412 		return amdgpu_ras_eeprom_reset_table(control);
1413 	}
1414 
1415 	switch (hdr->version) {
1416 	case RAS_TABLE_VER_V2_1:
1417 	case RAS_TABLE_VER_V3:
1418 		control->ras_num_recs = RAS_NUM_RECS_V2_1(hdr);
1419 		control->ras_record_offset = RAS_RECORD_START_V2_1;
1420 		control->ras_max_record_count = RAS_MAX_RECORD_COUNT_V2_1;
1421 		break;
1422 	case RAS_TABLE_VER_V1:
1423 		control->ras_num_recs = RAS_NUM_RECS(hdr);
1424 		control->ras_record_offset = RAS_RECORD_START;
1425 		control->ras_max_record_count = RAS_MAX_RECORD_COUNT;
1426 		break;
1427 	default:
1428 		dev_err(adev->dev,
1429 			"RAS header invalid, unsupported version: %u",
1430 			hdr->version);
1431 		return -EINVAL;
1432 	}
1433 
1434 	if (control->ras_num_recs > control->ras_max_record_count) {
1435 		dev_err(adev->dev,
1436 			"RAS header invalid, records in header: %u max allowed :%u",
1437 			control->ras_num_recs, control->ras_max_record_count);
1438 		return -EINVAL;
1439 	}
1440 
1441 	control->ras_fri = RAS_OFFSET_TO_INDEX(control, hdr->first_rec_offset);
1442 	control->ras_num_mca_recs = 0;
1443 	control->ras_num_pa_recs = 0;
1444 	return 0;
1445 }
1446 
1447 int amdgpu_ras_eeprom_check(struct amdgpu_ras_eeprom_control *control)
1448 {
1449 	struct amdgpu_device *adev = to_amdgpu_device(control);
1450 	struct amdgpu_ras_eeprom_table_header *hdr = &control->tbl_hdr;
1451 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1452 	int res = 0;
1453 
1454 	if (!__is_ras_eeprom_supported(adev))
1455 		return 0;
1456 
1457 	/* Verify i2c adapter is initialized */
1458 	if (!adev->pm.ras_eeprom_i2c_bus || !adev->pm.ras_eeprom_i2c_bus->algo)
1459 		return -ENOENT;
1460 
1461 	if (!__get_eeprom_i2c_addr(adev, control))
1462 		return -EINVAL;
1463 
1464 	control->ras_num_bad_pages = ras->bad_page_num;
1465 
1466 	if (hdr->header == RAS_TABLE_HDR_VAL) {
1467 		dev_dbg(adev->dev,
1468 			"Found existing EEPROM table with %d records",
1469 			control->ras_num_bad_pages);
1470 
1471 		if (hdr->version >= RAS_TABLE_VER_V2_1) {
1472 			res = __read_table_ras_info(control);
1473 			if (res)
1474 				return res;
1475 		}
1476 
1477 		res = __verify_ras_table_checksum(control);
1478 		if (res)
1479 			dev_err(adev->dev,
1480 				"RAS table incorrect checksum or error:%d\n",
1481 				res);
1482 
1483 		/* Warn if we are at 90% of the threshold or above
1484 		 */
1485 		if (10 * control->ras_num_bad_pages >= 9 * ras->bad_page_cnt_threshold)
1486 			dev_warn(adev->dev, "RAS records:%u exceeds 90%% of threshold:%d",
1487 					control->ras_num_bad_pages,
1488 					ras->bad_page_cnt_threshold);
1489 	} else if (hdr->header == RAS_TABLE_HDR_BAD &&
1490 		   amdgpu_bad_page_threshold != 0) {
1491 		if (hdr->version >= RAS_TABLE_VER_V2_1) {
1492 			res = __read_table_ras_info(control);
1493 			if (res)
1494 				return res;
1495 		}
1496 
1497 		res = __verify_ras_table_checksum(control);
1498 		if (res) {
1499 			dev_err(adev->dev,
1500 				"RAS Table incorrect checksum or error:%d\n",
1501 				res);
1502 			return -EINVAL;
1503 		}
1504 		if (ras->bad_page_cnt_threshold >= control->ras_num_bad_pages) {
1505 			/* This means that, the threshold was increased since
1506 			 * the last time the system was booted, and now,
1507 			 * ras->bad_page_cnt_threshold - control->num_recs > 0,
1508 			 * so that at least one more record can be saved,
1509 			 * before the page count threshold is reached.
1510 			 */
1511 			dev_info(adev->dev,
1512 				 "records:%d threshold:%d, resetting "
1513 				 "RAS table header signature",
1514 				 control->ras_num_bad_pages,
1515 				 ras->bad_page_cnt_threshold);
1516 			res = amdgpu_ras_eeprom_correct_header_tag(control,
1517 								   RAS_TABLE_HDR_VAL);
1518 		} else {
1519 			dev_warn(adev->dev,
1520 				"RAS records:%d exceed threshold:%d\n",
1521 				control->ras_num_bad_pages, ras->bad_page_cnt_threshold);
1522 			if ((amdgpu_bad_page_threshold == -1) ||
1523 			    (amdgpu_bad_page_threshold == -2)) {
1524 				res = 0;
1525 				dev_warn(adev->dev,
1526 					 "Please consult AMD Service Action Guide (SAG) for appropriate service procedures\n");
1527 			} else {
1528 				ras->is_rma = true;
1529 				dev_warn(adev->dev,
1530 					 "User defined threshold is set, runtime service will be halt when threshold is reached\n");
1531 			}
1532 		}
1533 	}
1534 
1535 	return res < 0 ? res : 0;
1536 }
1537 
1538 void amdgpu_ras_eeprom_check_and_recover(struct amdgpu_device *adev)
1539 {
1540 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1541 	struct amdgpu_ras_eeprom_control *control;
1542 	int res;
1543 
1544 	if (!__is_ras_eeprom_supported(adev) || !ras)
1545 		return;
1546 	control = &ras->eeprom_control;
1547 	if (!control->is_eeprom_valid)
1548 		return;
1549 	res = __verify_ras_table_checksum(control);
1550 	if (res) {
1551 		dev_warn(adev->dev,
1552 			"RAS table incorrect checksum or error:%d, try to recover\n",
1553 			res);
1554 		if (!amdgpu_ras_eeprom_reset_table(control))
1555 			if (!amdgpu_ras_save_bad_pages(adev, NULL))
1556 				if (!__verify_ras_table_checksum(control)) {
1557 					dev_info(adev->dev, "RAS table recovery succeed\n");
1558 					return;
1559 				}
1560 		dev_err(adev->dev, "RAS table recovery failed\n");
1561 		control->is_eeprom_valid = false;
1562 	}
1563 	return;
1564 }