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