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