xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_ras_eeprom.c (revision 5c8d5e2619f7d2985adfe45608dc942ca8151aa3)
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 			/* ignore the -ENOTSUPP return value */
781 			amdgpu_dpm_send_rma_reason(adev);
782 		}
783 	}
784 
785 	if (control->tbl_hdr.version >= RAS_TABLE_VER_V2_1)
786 		control->tbl_hdr.tbl_size = RAS_TABLE_HEADER_SIZE +
787 					    RAS_TABLE_V2_1_INFO_SIZE +
788 					    control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
789 	else
790 		control->tbl_hdr.tbl_size = RAS_TABLE_HEADER_SIZE +
791 					    control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
792 	control->tbl_hdr.checksum = 0;
793 
794 	buf_size = control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
795 	buf = kcalloc(control->ras_num_recs, RAS_TABLE_RECORD_SIZE, GFP_KERNEL);
796 	if (!buf) {
797 		dev_err(adev->dev,
798 			"allocating memory for table of size %d bytes failed\n",
799 			control->tbl_hdr.tbl_size);
800 		res = -ENOMEM;
801 		goto Out;
802 	}
803 
804 	down_read(&adev->reset_domain->sem);
805 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
806 				 control->i2c_address +
807 				 control->ras_record_offset,
808 				 buf, buf_size);
809 	up_read(&adev->reset_domain->sem);
810 	if (res < 0) {
811 		dev_err(adev->dev, "EEPROM failed reading records:%d\n", res);
812 		goto Out;
813 	} else if (res < buf_size) {
814 		dev_err(adev->dev, "EEPROM read %d out of %d bytes\n", res,
815 			buf_size);
816 		res = -EIO;
817 		goto Out;
818 	}
819 
820 	/**
821 	 * bad page records have been stored in eeprom,
822 	 * now calculate gpu health percent
823 	 */
824 	if (amdgpu_bad_page_threshold != 0 &&
825 	    control->tbl_hdr.version >= RAS_TABLE_VER_V2_1 &&
826 	    control->ras_num_bad_pages <= ras->bad_page_cnt_threshold)
827 		control->tbl_rai.health_percent = ((ras->bad_page_cnt_threshold -
828 						   control->ras_num_bad_pages) * 100) /
829 						   ras->bad_page_cnt_threshold;
830 
831 	/* Recalc the checksum.
832 	 */
833 	csum = 0;
834 	for (pp = buf; pp < buf + buf_size; pp++)
835 		csum += *pp;
836 
837 	csum += __calc_hdr_byte_sum(control);
838 	if (control->tbl_hdr.version >= RAS_TABLE_VER_V2_1)
839 		csum += __calc_ras_info_byte_sum(control);
840 	/* avoid sign extension when assigning to "checksum" */
841 	csum = -csum;
842 	control->tbl_hdr.checksum = csum;
843 	res = __write_table_header(control);
844 	if (!res && control->tbl_hdr.version > RAS_TABLE_VER_V1)
845 		res = __write_table_ras_info(control);
846 Out:
847 	kfree(buf);
848 	return res;
849 }
850 
851 /**
852  * amdgpu_ras_eeprom_append -- append records to the EEPROM RAS table
853  * @control: pointer to control structure
854  * @record: array of records to append
855  * @num: number of records in @record array
856  *
857  * Append @num records to the table, calculate the checksum and write
858  * the table back to EEPROM. The maximum number of records that
859  * can be appended is between 1 and control->ras_max_record_count,
860  * regardless of how many records are already stored in the table.
861  *
862  * Return 0 on success or if EEPROM is not supported, -errno on error.
863  */
864 int amdgpu_ras_eeprom_append(struct amdgpu_ras_eeprom_control *control,
865 			     struct eeprom_table_record *record,
866 			     const u32 num)
867 {
868 	struct amdgpu_device *adev = to_amdgpu_device(control);
869 	int res, i;
870 	uint64_t nps = AMDGPU_NPS1_PARTITION_MODE;
871 
872 	if (!__is_ras_eeprom_supported(adev))
873 		return 0;
874 
875 	if (num == 0) {
876 		dev_err(adev->dev, "will not append 0 records\n");
877 		return -EINVAL;
878 	} else if (num > control->ras_max_record_count) {
879 		dev_err(adev->dev,
880 			"cannot append %d records than the size of table %d\n",
881 			num, control->ras_max_record_count);
882 		return -EINVAL;
883 	}
884 
885 	if (adev->gmc.gmc_funcs->query_mem_partition_mode)
886 		nps = adev->gmc.gmc_funcs->query_mem_partition_mode(adev);
887 
888 	/* set the new channel index flag */
889 	for (i = 0; i < num; i++)
890 		record[i].retired_page |= (nps << UMC_NPS_SHIFT);
891 
892 	mutex_lock(&control->ras_tbl_mutex);
893 
894 	res = amdgpu_ras_eeprom_append_table(control, record, num);
895 	if (!res)
896 		res = amdgpu_ras_eeprom_update_header(control);
897 	if (!res)
898 		amdgpu_ras_debugfs_set_ret_size(control);
899 
900 	mutex_unlock(&control->ras_tbl_mutex);
901 
902 	/* clear channel index flag, the flag is only saved on eeprom */
903 	for (i = 0; i < num; i++)
904 		record[i].retired_page &= ~(nps << UMC_NPS_SHIFT);
905 
906 	return res;
907 }
908 
909 /**
910  * __amdgpu_ras_eeprom_read -- read indexed from EEPROM into buffer
911  * @control: pointer to control structure
912  * @buf: pointer to buffer to read into
913  * @fri: first record index, start reading at this index, absolute index
914  * @num: number of records to read
915  *
916  * The caller must hold the table mutex in @control.
917  * Return 0 on success, -errno otherwise.
918  */
919 static int __amdgpu_ras_eeprom_read(struct amdgpu_ras_eeprom_control *control,
920 				    u8 *buf, const u32 fri, const u32 num)
921 {
922 	struct amdgpu_device *adev = to_amdgpu_device(control);
923 	u32 buf_size;
924 	int res;
925 
926 	/* i2c may be unstable in gpu reset */
927 	down_read(&adev->reset_domain->sem);
928 	buf_size = num * RAS_TABLE_RECORD_SIZE;
929 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
930 				 control->i2c_address +
931 				 RAS_INDEX_TO_OFFSET(control, fri),
932 				 buf, buf_size);
933 	up_read(&adev->reset_domain->sem);
934 	if (res < 0) {
935 		dev_err(adev->dev, "Reading %d EEPROM table records error:%d",
936 			num, res);
937 	} else if (res < buf_size) {
938 		/* Short read, return error.
939 		 */
940 		dev_err(adev->dev, "Read %d records out of %d",
941 			res / RAS_TABLE_RECORD_SIZE, num);
942 		res = -EIO;
943 	} else {
944 		res = 0;
945 	}
946 
947 	return res;
948 }
949 
950 /**
951  * amdgpu_ras_eeprom_read -- read EEPROM
952  * @control: pointer to control structure
953  * @record: array of records to read into
954  * @num: number of records in @record
955  *
956  * Reads num records from the RAS table in EEPROM and
957  * writes the data into @record array.
958  *
959  * Returns 0 on success, -errno on error.
960  */
961 int amdgpu_ras_eeprom_read(struct amdgpu_ras_eeprom_control *control,
962 			   struct eeprom_table_record *record,
963 			   const u32 num)
964 {
965 	struct amdgpu_device *adev = to_amdgpu_device(control);
966 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
967 	int i, res;
968 	u8 *buf, *pp;
969 	u32 g0, g1;
970 
971 	if (!__is_ras_eeprom_supported(adev))
972 		return 0;
973 
974 	if (num == 0) {
975 		dev_err(adev->dev, "will not read 0 records\n");
976 		return -EINVAL;
977 	} else if (num > control->ras_num_recs) {
978 		dev_err(adev->dev, "too many records to read:%d available:%d\n",
979 			num, control->ras_num_recs);
980 		return -EINVAL;
981 	}
982 
983 	buf = kcalloc(num, RAS_TABLE_RECORD_SIZE, GFP_KERNEL);
984 	if (!buf)
985 		return -ENOMEM;
986 
987 	/* Determine how many records to read, from the first record
988 	 * index, fri, to the end of the table, and from the beginning
989 	 * of the table, such that the total number of records is
990 	 * @num, and we handle wrap around when fri > 0 and
991 	 * fri + num > RAS_MAX_RECORD_COUNT.
992 	 *
993 	 * First we compute the index of the last element
994 	 * which would be fetched from each region,
995 	 * g0 is in [fri, fri + num - 1], and
996 	 * g1 is in [0, RAS_MAX_RECORD_COUNT - 1].
997 	 * Then, if g0 < RAS_MAX_RECORD_COUNT, the index of
998 	 * the last element to fetch, we set g0 to _the number_
999 	 * of elements to fetch, @num, since we know that the last
1000 	 * indexed to be fetched does not exceed the table.
1001 	 *
1002 	 * If, however, g0 >= RAS_MAX_RECORD_COUNT, then
1003 	 * we set g0 to the number of elements to read
1004 	 * until the end of the table, and g1 to the number of
1005 	 * elements to read from the beginning of the table.
1006 	 */
1007 	g0 = control->ras_fri + num - 1;
1008 	g1 = g0 % control->ras_max_record_count;
1009 	if (g0 < control->ras_max_record_count) {
1010 		g0 = num;
1011 		g1 = 0;
1012 	} else {
1013 		g0 = control->ras_max_record_count - control->ras_fri;
1014 		g1 += 1;
1015 	}
1016 
1017 	mutex_lock(&control->ras_tbl_mutex);
1018 	res = __amdgpu_ras_eeprom_read(control, buf, control->ras_fri, g0);
1019 	if (res)
1020 		goto Out;
1021 	if (g1) {
1022 		res = __amdgpu_ras_eeprom_read(control,
1023 					       buf + g0 * RAS_TABLE_RECORD_SIZE,
1024 					       0, g1);
1025 		if (res)
1026 			goto Out;
1027 	}
1028 
1029 	res = 0;
1030 
1031 	/* Read up everything? Then transform.
1032 	 */
1033 	pp = buf;
1034 	for (i = 0; i < num; i++, pp += RAS_TABLE_RECORD_SIZE) {
1035 		__decode_table_record_from_buf(control, &record[i], pp);
1036 
1037 		/* update bad channel bitmap */
1038 		if ((record[i].mem_channel < BITS_PER_TYPE(control->bad_channel_bitmap)) &&
1039 		    !(control->bad_channel_bitmap & (1 << record[i].mem_channel))) {
1040 			control->bad_channel_bitmap |= 1 << record[i].mem_channel;
1041 			con->update_channel_flag = true;
1042 		}
1043 	}
1044 Out:
1045 	kfree(buf);
1046 	mutex_unlock(&control->ras_tbl_mutex);
1047 
1048 	return res;
1049 }
1050 
1051 uint32_t amdgpu_ras_eeprom_max_record_count(struct amdgpu_ras_eeprom_control *control)
1052 {
1053 	/* get available eeprom table version first before eeprom table init */
1054 	amdgpu_ras_set_eeprom_table_version(control);
1055 
1056 	if (control->tbl_hdr.version >= RAS_TABLE_VER_V2_1)
1057 		return RAS_MAX_RECORD_COUNT_V2_1;
1058 	else
1059 		return RAS_MAX_RECORD_COUNT;
1060 }
1061 
1062 static ssize_t
1063 amdgpu_ras_debugfs_eeprom_size_read(struct file *f, char __user *buf,
1064 				    size_t size, loff_t *pos)
1065 {
1066 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
1067 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1068 	struct amdgpu_ras_eeprom_control *control = ras ? &ras->eeprom_control : NULL;
1069 	u8 data[50];
1070 	int res;
1071 
1072 	if (!size)
1073 		return size;
1074 
1075 	if (!ras || !control) {
1076 		res = snprintf(data, sizeof(data), "Not supported\n");
1077 	} else {
1078 		res = snprintf(data, sizeof(data), "%d bytes or %d records\n",
1079 			       RAS_TBL_SIZE_BYTES, control->ras_max_record_count);
1080 	}
1081 
1082 	if (*pos >= res)
1083 		return 0;
1084 
1085 	res -= *pos;
1086 	res = min_t(size_t, res, size);
1087 
1088 	if (copy_to_user(buf, &data[*pos], res))
1089 		return -EFAULT;
1090 
1091 	*pos += res;
1092 
1093 	return res;
1094 }
1095 
1096 const struct file_operations amdgpu_ras_debugfs_eeprom_size_ops = {
1097 	.owner = THIS_MODULE,
1098 	.read = amdgpu_ras_debugfs_eeprom_size_read,
1099 	.write = NULL,
1100 	.llseek = default_llseek,
1101 };
1102 
1103 static const char *tbl_hdr_str = " Signature    Version  FirstOffs       Size   Checksum\n";
1104 static const char *tbl_hdr_fmt = "0x%08X 0x%08X 0x%08X 0x%08X 0x%08X\n";
1105 #define tbl_hdr_fmt_size (5 * (2+8) + 4 + 1)
1106 static const char *rec_hdr_str = "Index  Offset ErrType Bank/CU          TimeStamp      Offs/Addr MemChl MCUMCID    RetiredPage\n";
1107 static const char *rec_hdr_fmt = "%5d 0x%05X %7s    0x%02X 0x%016llX 0x%012llX   0x%02X    0x%02X 0x%012llX\n";
1108 #define rec_hdr_fmt_size (5 + 1 + 7 + 1 + 7 + 1 + 7 + 1 + 18 + 1 + 14 + 1 + 6 + 1 + 7 + 1 + 14 + 1)
1109 
1110 static const char *record_err_type_str[AMDGPU_RAS_EEPROM_ERR_COUNT] = {
1111 	"ignore",
1112 	"re",
1113 	"ue",
1114 };
1115 
1116 static loff_t amdgpu_ras_debugfs_table_size(struct amdgpu_ras_eeprom_control *control)
1117 {
1118 	return strlen(tbl_hdr_str) + tbl_hdr_fmt_size +
1119 		strlen(rec_hdr_str) + rec_hdr_fmt_size * control->ras_num_recs;
1120 }
1121 
1122 void amdgpu_ras_debugfs_set_ret_size(struct amdgpu_ras_eeprom_control *control)
1123 {
1124 	struct amdgpu_ras *ras = container_of(control, struct amdgpu_ras,
1125 					      eeprom_control);
1126 	struct dentry *de = ras->de_ras_eeprom_table;
1127 
1128 	if (de)
1129 		d_inode(de)->i_size = amdgpu_ras_debugfs_table_size(control);
1130 }
1131 
1132 static ssize_t amdgpu_ras_debugfs_table_read(struct file *f, char __user *buf,
1133 					     size_t size, loff_t *pos)
1134 {
1135 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
1136 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1137 	struct amdgpu_ras_eeprom_control *control = &ras->eeprom_control;
1138 	const size_t orig_size = size;
1139 	int res = -EFAULT;
1140 	size_t data_len;
1141 
1142 	mutex_lock(&control->ras_tbl_mutex);
1143 
1144 	/* We want *pos - data_len > 0, which means there's
1145 	 * bytes to be printed from data.
1146 	 */
1147 	data_len = strlen(tbl_hdr_str);
1148 	if (*pos < data_len) {
1149 		data_len -= *pos;
1150 		data_len = min_t(size_t, data_len, size);
1151 		if (copy_to_user(buf, &tbl_hdr_str[*pos], data_len))
1152 			goto Out;
1153 		buf += data_len;
1154 		size -= data_len;
1155 		*pos += data_len;
1156 	}
1157 
1158 	data_len = strlen(tbl_hdr_str) + tbl_hdr_fmt_size;
1159 	if (*pos < data_len && size > 0) {
1160 		u8 data[tbl_hdr_fmt_size + 1];
1161 		loff_t lpos;
1162 
1163 		snprintf(data, sizeof(data), tbl_hdr_fmt,
1164 			 control->tbl_hdr.header,
1165 			 control->tbl_hdr.version,
1166 			 control->tbl_hdr.first_rec_offset,
1167 			 control->tbl_hdr.tbl_size,
1168 			 control->tbl_hdr.checksum);
1169 
1170 		data_len -= *pos;
1171 		data_len = min_t(size_t, data_len, size);
1172 		lpos = *pos - strlen(tbl_hdr_str);
1173 		if (copy_to_user(buf, &data[lpos], data_len))
1174 			goto Out;
1175 		buf += data_len;
1176 		size -= data_len;
1177 		*pos += data_len;
1178 	}
1179 
1180 	data_len = strlen(tbl_hdr_str) + tbl_hdr_fmt_size + strlen(rec_hdr_str);
1181 	if (*pos < data_len && size > 0) {
1182 		loff_t lpos;
1183 
1184 		data_len -= *pos;
1185 		data_len = min_t(size_t, data_len, size);
1186 		lpos = *pos - strlen(tbl_hdr_str) - tbl_hdr_fmt_size;
1187 		if (copy_to_user(buf, &rec_hdr_str[lpos], data_len))
1188 			goto Out;
1189 		buf += data_len;
1190 		size -= data_len;
1191 		*pos += data_len;
1192 	}
1193 
1194 	data_len = amdgpu_ras_debugfs_table_size(control);
1195 	if (*pos < data_len && size > 0) {
1196 		u8 dare[RAS_TABLE_RECORD_SIZE];
1197 		u8 data[rec_hdr_fmt_size + 1];
1198 		struct eeprom_table_record record;
1199 		int s, r;
1200 
1201 		/* Find the starting record index
1202 		 */
1203 		s = *pos - strlen(tbl_hdr_str) - tbl_hdr_fmt_size -
1204 			strlen(rec_hdr_str);
1205 		s = s / rec_hdr_fmt_size;
1206 		r = *pos - strlen(tbl_hdr_str) - tbl_hdr_fmt_size -
1207 			strlen(rec_hdr_str);
1208 		r = r % rec_hdr_fmt_size;
1209 
1210 		for ( ; size > 0 && s < control->ras_num_recs; s++) {
1211 			u32 ai = RAS_RI_TO_AI(control, s);
1212 			/* Read a single record
1213 			 */
1214 			res = __amdgpu_ras_eeprom_read(control, dare, ai, 1);
1215 			if (res)
1216 				goto Out;
1217 			__decode_table_record_from_buf(control, &record, dare);
1218 			snprintf(data, sizeof(data), rec_hdr_fmt,
1219 				 s,
1220 				 RAS_INDEX_TO_OFFSET(control, ai),
1221 				 record_err_type_str[record.err_type],
1222 				 record.bank,
1223 				 record.ts,
1224 				 record.offset,
1225 				 record.mem_channel,
1226 				 record.mcumc_id,
1227 				 record.retired_page);
1228 
1229 			data_len = min_t(size_t, rec_hdr_fmt_size - r, size);
1230 			if (copy_to_user(buf, &data[r], data_len)) {
1231 				res = -EFAULT;
1232 				goto Out;
1233 			}
1234 			buf += data_len;
1235 			size -= data_len;
1236 			*pos += data_len;
1237 			r = 0;
1238 		}
1239 	}
1240 	res = 0;
1241 Out:
1242 	mutex_unlock(&control->ras_tbl_mutex);
1243 	return res < 0 ? res : orig_size - size;
1244 }
1245 
1246 static ssize_t
1247 amdgpu_ras_debugfs_eeprom_table_read(struct file *f, char __user *buf,
1248 				     size_t size, loff_t *pos)
1249 {
1250 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
1251 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1252 	struct amdgpu_ras_eeprom_control *control = ras ? &ras->eeprom_control : NULL;
1253 	u8 data[81];
1254 	int res;
1255 
1256 	if (!size)
1257 		return size;
1258 
1259 	if (!ras || !control) {
1260 		res = snprintf(data, sizeof(data), "Not supported\n");
1261 		if (*pos >= res)
1262 			return 0;
1263 
1264 		res -= *pos;
1265 		res = min_t(size_t, res, size);
1266 
1267 		if (copy_to_user(buf, &data[*pos], res))
1268 			return -EFAULT;
1269 
1270 		*pos += res;
1271 
1272 		return res;
1273 	} else {
1274 		return amdgpu_ras_debugfs_table_read(f, buf, size, pos);
1275 	}
1276 }
1277 
1278 const struct file_operations amdgpu_ras_debugfs_eeprom_table_ops = {
1279 	.owner = THIS_MODULE,
1280 	.read = amdgpu_ras_debugfs_eeprom_table_read,
1281 	.write = NULL,
1282 	.llseek = default_llseek,
1283 };
1284 
1285 /**
1286  * __verify_ras_table_checksum -- verify the RAS EEPROM table checksum
1287  * @control: pointer to control structure
1288  *
1289  * Check the checksum of the stored in EEPROM RAS table.
1290  *
1291  * Return 0 if the checksum is correct,
1292  * positive if it is not correct, and
1293  * -errno on I/O error.
1294  */
1295 static int __verify_ras_table_checksum(struct amdgpu_ras_eeprom_control *control)
1296 {
1297 	struct amdgpu_device *adev = to_amdgpu_device(control);
1298 	int buf_size, res;
1299 	u8  csum, *buf, *pp;
1300 
1301 	if (control->tbl_hdr.version >= RAS_TABLE_VER_V2_1)
1302 		buf_size = RAS_TABLE_HEADER_SIZE +
1303 			   RAS_TABLE_V2_1_INFO_SIZE +
1304 			   control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
1305 	else
1306 		buf_size = RAS_TABLE_HEADER_SIZE +
1307 			   control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
1308 
1309 	buf = kzalloc(buf_size, GFP_KERNEL);
1310 	if (!buf) {
1311 		dev_err(adev->dev,
1312 			"Out of memory checking RAS table checksum.\n");
1313 		return -ENOMEM;
1314 	}
1315 
1316 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
1317 				 control->i2c_address +
1318 				 control->ras_header_offset,
1319 				 buf, buf_size);
1320 	if (res < buf_size) {
1321 		dev_err(adev->dev, "Partial read for checksum, res:%d\n", res);
1322 		/* On partial reads, return -EIO.
1323 		 */
1324 		if (res >= 0)
1325 			res = -EIO;
1326 		goto Out;
1327 	}
1328 
1329 	csum = 0;
1330 	for (pp = buf; pp < buf + buf_size; pp++)
1331 		csum += *pp;
1332 Out:
1333 	kfree(buf);
1334 	return res < 0 ? res : csum;
1335 }
1336 
1337 static int __read_table_ras_info(struct amdgpu_ras_eeprom_control *control)
1338 {
1339 	struct amdgpu_ras_eeprom_table_ras_info *rai = &control->tbl_rai;
1340 	struct amdgpu_device *adev = to_amdgpu_device(control);
1341 	unsigned char *buf;
1342 	int res;
1343 
1344 	buf = kzalloc(RAS_TABLE_V2_1_INFO_SIZE, GFP_KERNEL);
1345 	if (!buf) {
1346 		dev_err(adev->dev,
1347 			"Failed to alloc buf to read EEPROM table ras info\n");
1348 		return -ENOMEM;
1349 	}
1350 
1351 	/**
1352 	 * EEPROM table V2_1 supports ras info,
1353 	 * read EEPROM table ras info
1354 	 */
1355 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
1356 				 control->i2c_address + control->ras_info_offset,
1357 				 buf, RAS_TABLE_V2_1_INFO_SIZE);
1358 	if (res < RAS_TABLE_V2_1_INFO_SIZE) {
1359 		dev_err(adev->dev,
1360 			"Failed to read EEPROM table ras info, res:%d", res);
1361 		res = res >= 0 ? -EIO : res;
1362 		goto Out;
1363 	}
1364 
1365 	__decode_table_ras_info_from_buf(rai, buf);
1366 
1367 Out:
1368 	kfree(buf);
1369 	return res == RAS_TABLE_V2_1_INFO_SIZE ? 0 : res;
1370 }
1371 
1372 int amdgpu_ras_eeprom_init(struct amdgpu_ras_eeprom_control *control)
1373 {
1374 	struct amdgpu_device *adev = to_amdgpu_device(control);
1375 	unsigned char buf[RAS_TABLE_HEADER_SIZE] = { 0 };
1376 	struct amdgpu_ras_eeprom_table_header *hdr = &control->tbl_hdr;
1377 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1378 	int res;
1379 
1380 	ras->is_rma = false;
1381 
1382 	if (!__is_ras_eeprom_supported(adev))
1383 		return 0;
1384 
1385 	/* Verify i2c adapter is initialized */
1386 	if (!adev->pm.ras_eeprom_i2c_bus || !adev->pm.ras_eeprom_i2c_bus->algo)
1387 		return -ENOENT;
1388 
1389 	if (!__get_eeprom_i2c_addr(adev, control))
1390 		return -EINVAL;
1391 
1392 	control->ras_header_offset = RAS_HDR_START;
1393 	control->ras_info_offset = RAS_TABLE_V2_1_INFO_START;
1394 	mutex_init(&control->ras_tbl_mutex);
1395 
1396 	/* Read the table header from EEPROM address */
1397 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
1398 				 control->i2c_address + control->ras_header_offset,
1399 				 buf, RAS_TABLE_HEADER_SIZE);
1400 	if (res < RAS_TABLE_HEADER_SIZE) {
1401 		dev_err(adev->dev, "Failed to read EEPROM table header, res:%d",
1402 			res);
1403 		return res >= 0 ? -EIO : res;
1404 	}
1405 
1406 	__decode_table_header_from_buf(hdr, buf);
1407 
1408 	if (hdr->header != RAS_TABLE_HDR_VAL &&
1409 	    hdr->header != RAS_TABLE_HDR_BAD) {
1410 		dev_info(adev->dev, "Creating a new EEPROM table");
1411 		return amdgpu_ras_eeprom_reset_table(control);
1412 	}
1413 
1414 	switch (hdr->version) {
1415 	case RAS_TABLE_VER_V2_1:
1416 	case RAS_TABLE_VER_V3:
1417 		control->ras_num_recs = RAS_NUM_RECS_V2_1(hdr);
1418 		control->ras_record_offset = RAS_RECORD_START_V2_1;
1419 		control->ras_max_record_count = RAS_MAX_RECORD_COUNT_V2_1;
1420 		break;
1421 	case RAS_TABLE_VER_V1:
1422 		control->ras_num_recs = RAS_NUM_RECS(hdr);
1423 		control->ras_record_offset = RAS_RECORD_START;
1424 		control->ras_max_record_count = RAS_MAX_RECORD_COUNT;
1425 		break;
1426 	default:
1427 		dev_err(adev->dev,
1428 			"RAS header invalid, unsupported version: %u",
1429 			hdr->version);
1430 		return -EINVAL;
1431 	}
1432 
1433 	if (control->ras_num_recs > control->ras_max_record_count) {
1434 		dev_err(adev->dev,
1435 			"RAS header invalid, records in header: %u max allowed :%u",
1436 			control->ras_num_recs, control->ras_max_record_count);
1437 		return -EINVAL;
1438 	}
1439 
1440 	control->ras_fri = RAS_OFFSET_TO_INDEX(control, hdr->first_rec_offset);
1441 	control->ras_num_mca_recs = 0;
1442 	control->ras_num_pa_recs = 0;
1443 	return 0;
1444 }
1445 
1446 int amdgpu_ras_eeprom_check(struct amdgpu_ras_eeprom_control *control)
1447 {
1448 	struct amdgpu_device *adev = to_amdgpu_device(control);
1449 	struct amdgpu_ras_eeprom_table_header *hdr = &control->tbl_hdr;
1450 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1451 	int res = 0;
1452 
1453 	if (!__is_ras_eeprom_supported(adev))
1454 		return 0;
1455 
1456 	/* Verify i2c adapter is initialized */
1457 	if (!adev->pm.ras_eeprom_i2c_bus || !adev->pm.ras_eeprom_i2c_bus->algo)
1458 		return -ENOENT;
1459 
1460 	if (!__get_eeprom_i2c_addr(adev, control))
1461 		return -EINVAL;
1462 
1463 	control->ras_num_bad_pages = ras->bad_page_num;
1464 
1465 	if (hdr->header == RAS_TABLE_HDR_VAL) {
1466 		dev_dbg(adev->dev,
1467 			"Found existing EEPROM table with %d records",
1468 			control->ras_num_bad_pages);
1469 
1470 		if (hdr->version >= RAS_TABLE_VER_V2_1) {
1471 			res = __read_table_ras_info(control);
1472 			if (res)
1473 				return res;
1474 		}
1475 
1476 		res = __verify_ras_table_checksum(control);
1477 		if (res)
1478 			dev_err(adev->dev,
1479 				"RAS table incorrect checksum or error:%d\n",
1480 				res);
1481 
1482 		/* Warn if we are at 90% of the threshold or above
1483 		 */
1484 		if (10 * control->ras_num_bad_pages >= 9 * ras->bad_page_cnt_threshold)
1485 			dev_warn(adev->dev, "RAS records:%u exceeds 90%% of threshold:%d",
1486 					control->ras_num_bad_pages,
1487 					ras->bad_page_cnt_threshold);
1488 	} else if (hdr->header == RAS_TABLE_HDR_BAD &&
1489 		   amdgpu_bad_page_threshold != 0) {
1490 		if (hdr->version >= RAS_TABLE_VER_V2_1) {
1491 			res = __read_table_ras_info(control);
1492 			if (res)
1493 				return res;
1494 		}
1495 
1496 		res = __verify_ras_table_checksum(control);
1497 		if (res) {
1498 			dev_err(adev->dev,
1499 				"RAS Table incorrect checksum or error:%d\n",
1500 				res);
1501 			return -EINVAL;
1502 		}
1503 		if (ras->bad_page_cnt_threshold >= control->ras_num_bad_pages) {
1504 			/* This means that, the threshold was increased since
1505 			 * the last time the system was booted, and now,
1506 			 * ras->bad_page_cnt_threshold - control->num_recs > 0,
1507 			 * so that at least one more record can be saved,
1508 			 * before the page count threshold is reached.
1509 			 */
1510 			dev_info(adev->dev,
1511 				 "records:%d threshold:%d, resetting "
1512 				 "RAS table header signature",
1513 				 control->ras_num_bad_pages,
1514 				 ras->bad_page_cnt_threshold);
1515 			res = amdgpu_ras_eeprom_correct_header_tag(control,
1516 								   RAS_TABLE_HDR_VAL);
1517 		} else {
1518 			dev_warn(adev->dev,
1519 				"RAS records:%d exceed threshold:%d\n",
1520 				control->ras_num_bad_pages, ras->bad_page_cnt_threshold);
1521 			if ((amdgpu_bad_page_threshold == -1) ||
1522 			    (amdgpu_bad_page_threshold == -2)) {
1523 				res = 0;
1524 				dev_warn(adev->dev,
1525 					 "Please consult AMD Service Action Guide (SAG) for appropriate service procedures\n");
1526 			} else {
1527 				ras->is_rma = true;
1528 				dev_warn(adev->dev,
1529 					 "User defined threshold is set, runtime service will be halt when threshold is reached\n");
1530 			}
1531 		}
1532 	}
1533 
1534 	return res < 0 ? res : 0;
1535 }
1536 
1537 void amdgpu_ras_eeprom_check_and_recover(struct amdgpu_device *adev)
1538 {
1539 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1540 	struct amdgpu_ras_eeprom_control *control;
1541 	int res;
1542 
1543 	if (!__is_ras_eeprom_supported(adev) || !ras)
1544 		return;
1545 	control = &ras->eeprom_control;
1546 	if (!control->is_eeprom_valid)
1547 		return;
1548 	res = __verify_ras_table_checksum(control);
1549 	if (res) {
1550 		dev_warn(adev->dev,
1551 			"RAS table incorrect checksum or error:%d, try to recover\n",
1552 			res);
1553 		if (!amdgpu_ras_eeprom_reset_table(control))
1554 			if (!amdgpu_ras_save_bad_pages(adev, NULL))
1555 				if (!__verify_ras_table_checksum(control)) {
1556 					dev_info(adev->dev, "RAS table recovery succeed\n");
1557 					return;
1558 				}
1559 		dev_err(adev->dev, "RAS table recovery failed\n");
1560 		control->is_eeprom_valid = false;
1561 	}
1562 	return;
1563 }