xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_ras_eeprom.c (revision 91b586cc05fdcddf3c63109dee5c7960cfb2e852)
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 bellow 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 (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 	case IP_VERSION(12, 0, 0):
417 		hdr->version = RAS_TABLE_VER_V2_1;
418 		return;
419 	default:
420 		hdr->version = RAS_TABLE_VER_V1;
421 		return;
422 	}
423 }
424 
425 /**
426  * amdgpu_ras_eeprom_reset_table -- Reset the RAS EEPROM table
427  * @control: pointer to control structure
428  *
429  * Reset the contents of the header of the RAS EEPROM table.
430  * Return 0 on success, -errno on error.
431  */
432 int amdgpu_ras_eeprom_reset_table(struct amdgpu_ras_eeprom_control *control)
433 {
434 	struct amdgpu_device *adev = to_amdgpu_device(control);
435 	struct amdgpu_ras_eeprom_table_header *hdr = &control->tbl_hdr;
436 	struct amdgpu_ras_eeprom_table_ras_info *rai = &control->tbl_rai;
437 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
438 	u8 csum;
439 	int res;
440 
441 	mutex_lock(&control->ras_tbl_mutex);
442 
443 	hdr->header = RAS_TABLE_HDR_VAL;
444 	amdgpu_ras_set_eeprom_table_version(control);
445 
446 	if (hdr->version == RAS_TABLE_VER_V2_1) {
447 		hdr->first_rec_offset = RAS_RECORD_START_V2_1;
448 		hdr->tbl_size = RAS_TABLE_HEADER_SIZE +
449 				RAS_TABLE_V2_1_INFO_SIZE;
450 		rai->rma_status = GPU_HEALTH_USABLE;
451 		/**
452 		 * GPU health represented as a percentage.
453 		 * 0 means worst health, 100 means fully health.
454 		 */
455 		rai->health_percent = 100;
456 		/* ecc_page_threshold = 0 means disable bad page retirement */
457 		rai->ecc_page_threshold = con->bad_page_cnt_threshold;
458 	} else {
459 		hdr->first_rec_offset = RAS_RECORD_START;
460 		hdr->tbl_size = RAS_TABLE_HEADER_SIZE;
461 	}
462 
463 	csum = __calc_hdr_byte_sum(control);
464 	if (hdr->version == RAS_TABLE_VER_V2_1)
465 		csum += __calc_ras_info_byte_sum(control);
466 	csum = -csum;
467 	hdr->checksum = csum;
468 	res = __write_table_header(control);
469 	if (!res && hdr->version > RAS_TABLE_VER_V1)
470 		res = __write_table_ras_info(control);
471 
472 	control->ras_num_recs = 0;
473 	control->ras_fri = 0;
474 
475 	amdgpu_dpm_send_hbm_bad_pages_num(adev, control->ras_num_recs);
476 
477 	control->bad_channel_bitmap = 0;
478 	amdgpu_dpm_send_hbm_bad_channel_flag(adev, control->bad_channel_bitmap);
479 	con->update_channel_flag = false;
480 
481 	amdgpu_ras_debugfs_set_ret_size(control);
482 
483 	mutex_unlock(&control->ras_tbl_mutex);
484 
485 	return res;
486 }
487 
488 static void
489 __encode_table_record_to_buf(struct amdgpu_ras_eeprom_control *control,
490 			     struct eeprom_table_record *record,
491 			     unsigned char *buf)
492 {
493 	__le64 tmp = 0;
494 	int i = 0;
495 
496 	/* Next are all record fields according to EEPROM page spec in LE foramt */
497 	buf[i++] = record->err_type;
498 
499 	buf[i++] = record->bank;
500 
501 	tmp = cpu_to_le64(record->ts);
502 	memcpy(buf + i, &tmp, 8);
503 	i += 8;
504 
505 	tmp = cpu_to_le64((record->offset & 0xffffffffffff));
506 	memcpy(buf + i, &tmp, 6);
507 	i += 6;
508 
509 	buf[i++] = record->mem_channel;
510 	buf[i++] = record->mcumc_id;
511 
512 	tmp = cpu_to_le64((record->retired_page & 0xffffffffffff));
513 	memcpy(buf + i, &tmp, 6);
514 }
515 
516 static void
517 __decode_table_record_from_buf(struct amdgpu_ras_eeprom_control *control,
518 			       struct eeprom_table_record *record,
519 			       unsigned char *buf)
520 {
521 	__le64 tmp = 0;
522 	int i =  0;
523 
524 	/* Next are all record fields according to EEPROM page spec in LE foramt */
525 	record->err_type = buf[i++];
526 
527 	record->bank = buf[i++];
528 
529 	memcpy(&tmp, buf + i, 8);
530 	record->ts = le64_to_cpu(tmp);
531 	i += 8;
532 
533 	memcpy(&tmp, buf + i, 6);
534 	record->offset = (le64_to_cpu(tmp) & 0xffffffffffff);
535 	i += 6;
536 
537 	record->mem_channel = buf[i++];
538 	record->mcumc_id = buf[i++];
539 
540 	memcpy(&tmp, buf + i,  6);
541 	record->retired_page = (le64_to_cpu(tmp) & 0xffffffffffff);
542 }
543 
544 bool amdgpu_ras_eeprom_check_err_threshold(struct amdgpu_device *adev)
545 {
546 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
547 
548 	if (!__is_ras_eeprom_supported(adev) ||
549 	    !amdgpu_bad_page_threshold)
550 		return false;
551 
552 	/* skip check eeprom table for VEGA20 Gaming */
553 	if (!con)
554 		return false;
555 	else
556 		if (!(con->features & BIT(AMDGPU_RAS_BLOCK__UMC)))
557 			return false;
558 
559 	if (con->eeprom_control.tbl_hdr.header == RAS_TABLE_HDR_BAD) {
560 		if (amdgpu_bad_page_threshold == -1) {
561 			dev_warn(adev->dev, "RAS records:%d exceed threshold:%d",
562 				con->eeprom_control.ras_num_recs, con->bad_page_cnt_threshold);
563 			dev_warn(adev->dev,
564 				"But GPU can be operated due to bad_page_threshold = -1.\n");
565 			return false;
566 		} else {
567 			dev_warn(adev->dev, "This GPU is in BAD status.");
568 			dev_warn(adev->dev, "Please retire it or set a larger "
569 				 "threshold value when reloading driver.\n");
570 			return true;
571 		}
572 	}
573 
574 	return false;
575 }
576 
577 /**
578  * __amdgpu_ras_eeprom_write -- write indexed from buffer to EEPROM
579  * @control: pointer to control structure
580  * @buf: pointer to buffer containing data to write
581  * @fri: start writing at this index
582  * @num: number of records to write
583  *
584  * The caller must hold the table mutex in @control.
585  * Return 0 on success, -errno otherwise.
586  */
587 static int __amdgpu_ras_eeprom_write(struct amdgpu_ras_eeprom_control *control,
588 				     u8 *buf, const u32 fri, const u32 num)
589 {
590 	struct amdgpu_device *adev = to_amdgpu_device(control);
591 	u32 buf_size;
592 	int res;
593 
594 	/* i2c may be unstable in gpu reset */
595 	down_read(&adev->reset_domain->sem);
596 	buf_size = num * RAS_TABLE_RECORD_SIZE;
597 	res = amdgpu_eeprom_write(adev->pm.ras_eeprom_i2c_bus,
598 				  control->i2c_address +
599 				  RAS_INDEX_TO_OFFSET(control, fri),
600 				  buf, buf_size);
601 	up_read(&adev->reset_domain->sem);
602 	if (res < 0) {
603 		DRM_ERROR("Writing %d EEPROM table records error:%d",
604 			  num, res);
605 	} else if (res < buf_size) {
606 		/* Short write, return error.
607 		 */
608 		DRM_ERROR("Wrote %d records out of %d",
609 			  res / RAS_TABLE_RECORD_SIZE, num);
610 		res = -EIO;
611 	} else {
612 		res = 0;
613 	}
614 
615 	return res;
616 }
617 
618 static int
619 amdgpu_ras_eeprom_append_table(struct amdgpu_ras_eeprom_control *control,
620 			       struct eeprom_table_record *record,
621 			       const u32 num)
622 {
623 	struct amdgpu_ras *con = amdgpu_ras_get_context(to_amdgpu_device(control));
624 	u32 a, b, i;
625 	u8 *buf, *pp;
626 	int res;
627 
628 	buf = kcalloc(num, RAS_TABLE_RECORD_SIZE, GFP_KERNEL);
629 	if (!buf)
630 		return -ENOMEM;
631 
632 	/* Encode all of them in one go.
633 	 */
634 	pp = buf;
635 	for (i = 0; i < num; i++, pp += RAS_TABLE_RECORD_SIZE) {
636 		__encode_table_record_to_buf(control, &record[i], pp);
637 
638 		/* update bad channel bitmap */
639 		if ((record[i].mem_channel < BITS_PER_TYPE(control->bad_channel_bitmap)) &&
640 		    !(control->bad_channel_bitmap & (1 << record[i].mem_channel))) {
641 			control->bad_channel_bitmap |= 1 << record[i].mem_channel;
642 			con->update_channel_flag = true;
643 		}
644 	}
645 
646 	/* a, first record index to write into.
647 	 * b, last record index to write into.
648 	 * a = first index to read (fri) + number of records in the table,
649 	 * b = a + @num - 1.
650 	 * Let N = control->ras_max_num_record_count, then we have,
651 	 * case 0: 0 <= a <= b < N,
652 	 *   just append @num records starting at a;
653 	 * case 1: 0 <= a < N <= b,
654 	 *   append (N - a) records starting at a, and
655 	 *   append the remainder,  b % N + 1, starting at 0.
656 	 * case 2: 0 <= fri < N <= a <= b, then modulo N we get two subcases,
657 	 * case 2a: 0 <= a <= b < N
658 	 *   append num records starting at a; and fix fri if b overwrote it,
659 	 *   and since a <= b, if b overwrote it then a must've also,
660 	 *   and if b didn't overwrite it, then a didn't also.
661 	 * case 2b: 0 <= b < a < N
662 	 *   write num records starting at a, which wraps around 0=N
663 	 *   and overwrite fri unconditionally. Now from case 2a,
664 	 *   this means that b eclipsed fri to overwrite it and wrap
665 	 *   around 0 again, i.e. b = 2N+r pre modulo N, so we unconditionally
666 	 *   set fri = b + 1 (mod N).
667 	 * Now, since fri is updated in every case, except the trivial case 0,
668 	 * the number of records present in the table after writing, is,
669 	 * num_recs - 1 = b - fri (mod N), and we take the positive value,
670 	 * by adding an arbitrary multiple of N before taking the modulo N
671 	 * as shown below.
672 	 */
673 	a = control->ras_fri + control->ras_num_recs;
674 	b = a + num  - 1;
675 	if (b < control->ras_max_record_count) {
676 		res = __amdgpu_ras_eeprom_write(control, buf, a, num);
677 	} else if (a < control->ras_max_record_count) {
678 		u32 g0, g1;
679 
680 		g0 = control->ras_max_record_count - a;
681 		g1 = b % control->ras_max_record_count + 1;
682 		res = __amdgpu_ras_eeprom_write(control, buf, a, g0);
683 		if (res)
684 			goto Out;
685 		res = __amdgpu_ras_eeprom_write(control,
686 						buf + g0 * RAS_TABLE_RECORD_SIZE,
687 						0, g1);
688 		if (res)
689 			goto Out;
690 		if (g1 > control->ras_fri)
691 			control->ras_fri = g1 % control->ras_max_record_count;
692 	} else {
693 		a %= control->ras_max_record_count;
694 		b %= control->ras_max_record_count;
695 
696 		if (a <= b) {
697 			/* Note that, b - a + 1 = num. */
698 			res = __amdgpu_ras_eeprom_write(control, buf, a, num);
699 			if (res)
700 				goto Out;
701 			if (b >= control->ras_fri)
702 				control->ras_fri = (b + 1) % control->ras_max_record_count;
703 		} else {
704 			u32 g0, g1;
705 
706 			/* b < a, which means, we write from
707 			 * a to the end of the table, and from
708 			 * the start of the table to b.
709 			 */
710 			g0 = control->ras_max_record_count - a;
711 			g1 = b + 1;
712 			res = __amdgpu_ras_eeprom_write(control, buf, a, g0);
713 			if (res)
714 				goto Out;
715 			res = __amdgpu_ras_eeprom_write(control,
716 							buf + g0 * RAS_TABLE_RECORD_SIZE,
717 							0, g1);
718 			if (res)
719 				goto Out;
720 			control->ras_fri = g1 % control->ras_max_record_count;
721 		}
722 	}
723 	control->ras_num_recs = 1 + (control->ras_max_record_count + b
724 				     - control->ras_fri)
725 		% control->ras_max_record_count;
726 Out:
727 	kfree(buf);
728 	return res;
729 }
730 
731 static int
732 amdgpu_ras_eeprom_update_header(struct amdgpu_ras_eeprom_control *control)
733 {
734 	struct amdgpu_device *adev = to_amdgpu_device(control);
735 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
736 	u8 *buf, *pp, csum;
737 	u32 buf_size;
738 	int res;
739 
740 	/* Modify the header if it exceeds.
741 	 */
742 	if (amdgpu_bad_page_threshold != 0 &&
743 	    control->ras_num_recs >= ras->bad_page_cnt_threshold) {
744 		dev_warn(adev->dev,
745 			"Saved bad pages %d reaches threshold value %d\n",
746 			control->ras_num_recs, ras->bad_page_cnt_threshold);
747 		control->tbl_hdr.header = RAS_TABLE_HDR_BAD;
748 		if (control->tbl_hdr.version == RAS_TABLE_VER_V2_1) {
749 			control->tbl_rai.rma_status = GPU_RETIRED__ECC_REACH_THRESHOLD;
750 			control->tbl_rai.health_percent = 0;
751 		}
752 
753 		/* ignore the -ENOTSUPP return value */
754 		amdgpu_dpm_send_rma_reason(adev);
755 	}
756 
757 	if (control->tbl_hdr.version == RAS_TABLE_VER_V2_1)
758 		control->tbl_hdr.tbl_size = RAS_TABLE_HEADER_SIZE +
759 					    RAS_TABLE_V2_1_INFO_SIZE +
760 					    control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
761 	else
762 		control->tbl_hdr.tbl_size = RAS_TABLE_HEADER_SIZE +
763 					    control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
764 	control->tbl_hdr.checksum = 0;
765 
766 	buf_size = control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
767 	buf = kcalloc(control->ras_num_recs, RAS_TABLE_RECORD_SIZE, GFP_KERNEL);
768 	if (!buf) {
769 		DRM_ERROR("allocating memory for table of size %d bytes failed\n",
770 			  control->tbl_hdr.tbl_size);
771 		res = -ENOMEM;
772 		goto Out;
773 	}
774 
775 	down_read(&adev->reset_domain->sem);
776 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
777 				 control->i2c_address +
778 				 control->ras_record_offset,
779 				 buf, buf_size);
780 	up_read(&adev->reset_domain->sem);
781 	if (res < 0) {
782 		DRM_ERROR("EEPROM failed reading records:%d\n",
783 			  res);
784 		goto Out;
785 	} else if (res < buf_size) {
786 		DRM_ERROR("EEPROM read %d out of %d bytes\n",
787 			  res, buf_size);
788 		res = -EIO;
789 		goto Out;
790 	}
791 
792 	/**
793 	 * bad page records have been stored in eeprom,
794 	 * now calculate gpu health percent
795 	 */
796 	if (amdgpu_bad_page_threshold != 0 &&
797 	    control->tbl_hdr.version == RAS_TABLE_VER_V2_1 &&
798 	    control->ras_num_recs < ras->bad_page_cnt_threshold)
799 		control->tbl_rai.health_percent = ((ras->bad_page_cnt_threshold -
800 						   control->ras_num_recs) * 100) /
801 						   ras->bad_page_cnt_threshold;
802 
803 	/* Recalc the checksum.
804 	 */
805 	csum = 0;
806 	for (pp = buf; pp < buf + buf_size; pp++)
807 		csum += *pp;
808 
809 	csum += __calc_hdr_byte_sum(control);
810 	if (control->tbl_hdr.version == RAS_TABLE_VER_V2_1)
811 		csum += __calc_ras_info_byte_sum(control);
812 	/* avoid sign extension when assigning to "checksum" */
813 	csum = -csum;
814 	control->tbl_hdr.checksum = csum;
815 	res = __write_table_header(control);
816 	if (!res && control->tbl_hdr.version > RAS_TABLE_VER_V1)
817 		res = __write_table_ras_info(control);
818 Out:
819 	kfree(buf);
820 	return res;
821 }
822 
823 /**
824  * amdgpu_ras_eeprom_append -- append records to the EEPROM RAS table
825  * @control: pointer to control structure
826  * @record: array of records to append
827  * @num: number of records in @record array
828  *
829  * Append @num records to the table, calculate the checksum and write
830  * the table back to EEPROM. The maximum number of records that
831  * can be appended is between 1 and control->ras_max_record_count,
832  * regardless of how many records are already stored in the table.
833  *
834  * Return 0 on success or if EEPROM is not supported, -errno on error.
835  */
836 int amdgpu_ras_eeprom_append(struct amdgpu_ras_eeprom_control *control,
837 			     struct eeprom_table_record *record,
838 			     const u32 num)
839 {
840 	struct amdgpu_device *adev = to_amdgpu_device(control);
841 	int res;
842 
843 	if (!__is_ras_eeprom_supported(adev))
844 		return 0;
845 
846 	if (num == 0) {
847 		DRM_ERROR("will not append 0 records\n");
848 		return -EINVAL;
849 	} else if (num > control->ras_max_record_count) {
850 		DRM_ERROR("cannot append %d records than the size of table %d\n",
851 			  num, control->ras_max_record_count);
852 		return -EINVAL;
853 	}
854 
855 	mutex_lock(&control->ras_tbl_mutex);
856 
857 	res = amdgpu_ras_eeprom_append_table(control, record, num);
858 	if (!res)
859 		res = amdgpu_ras_eeprom_update_header(control);
860 	if (!res)
861 		amdgpu_ras_debugfs_set_ret_size(control);
862 
863 	mutex_unlock(&control->ras_tbl_mutex);
864 	return res;
865 }
866 
867 /**
868  * __amdgpu_ras_eeprom_read -- read indexed from EEPROM into buffer
869  * @control: pointer to control structure
870  * @buf: pointer to buffer to read into
871  * @fri: first record index, start reading at this index, absolute index
872  * @num: number of records to read
873  *
874  * The caller must hold the table mutex in @control.
875  * Return 0 on success, -errno otherwise.
876  */
877 static int __amdgpu_ras_eeprom_read(struct amdgpu_ras_eeprom_control *control,
878 				    u8 *buf, const u32 fri, const u32 num)
879 {
880 	struct amdgpu_device *adev = to_amdgpu_device(control);
881 	u32 buf_size;
882 	int res;
883 
884 	/* i2c may be unstable in gpu reset */
885 	down_read(&adev->reset_domain->sem);
886 	buf_size = num * RAS_TABLE_RECORD_SIZE;
887 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
888 				 control->i2c_address +
889 				 RAS_INDEX_TO_OFFSET(control, fri),
890 				 buf, buf_size);
891 	up_read(&adev->reset_domain->sem);
892 	if (res < 0) {
893 		DRM_ERROR("Reading %d EEPROM table records error:%d",
894 			  num, res);
895 	} else if (res < buf_size) {
896 		/* Short read, return error.
897 		 */
898 		DRM_ERROR("Read %d records out of %d",
899 			  res / RAS_TABLE_RECORD_SIZE, num);
900 		res = -EIO;
901 	} else {
902 		res = 0;
903 	}
904 
905 	return res;
906 }
907 
908 /**
909  * amdgpu_ras_eeprom_read -- read EEPROM
910  * @control: pointer to control structure
911  * @record: array of records to read into
912  * @num: number of records in @record
913  *
914  * Reads num records from the RAS table in EEPROM and
915  * writes the data into @record array.
916  *
917  * Returns 0 on success, -errno on error.
918  */
919 int amdgpu_ras_eeprom_read(struct amdgpu_ras_eeprom_control *control,
920 			   struct eeprom_table_record *record,
921 			   const u32 num)
922 {
923 	struct amdgpu_device *adev = to_amdgpu_device(control);
924 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
925 	int i, res;
926 	u8 *buf, *pp;
927 	u32 g0, g1;
928 
929 	if (!__is_ras_eeprom_supported(adev))
930 		return 0;
931 
932 	if (num == 0) {
933 		DRM_ERROR("will not read 0 records\n");
934 		return -EINVAL;
935 	} else if (num > control->ras_num_recs) {
936 		DRM_ERROR("too many records to read:%d available:%d\n",
937 			  num, control->ras_num_recs);
938 		return -EINVAL;
939 	}
940 
941 	buf = kcalloc(num, RAS_TABLE_RECORD_SIZE, GFP_KERNEL);
942 	if (!buf)
943 		return -ENOMEM;
944 
945 	/* Determine how many records to read, from the first record
946 	 * index, fri, to the end of the table, and from the beginning
947 	 * of the table, such that the total number of records is
948 	 * @num, and we handle wrap around when fri > 0 and
949 	 * fri + num > RAS_MAX_RECORD_COUNT.
950 	 *
951 	 * First we compute the index of the last element
952 	 * which would be fetched from each region,
953 	 * g0 is in [fri, fri + num - 1], and
954 	 * g1 is in [0, RAS_MAX_RECORD_COUNT - 1].
955 	 * Then, if g0 < RAS_MAX_RECORD_COUNT, the index of
956 	 * the last element to fetch, we set g0 to _the number_
957 	 * of elements to fetch, @num, since we know that the last
958 	 * indexed to be fetched does not exceed the table.
959 	 *
960 	 * If, however, g0 >= RAS_MAX_RECORD_COUNT, then
961 	 * we set g0 to the number of elements to read
962 	 * until the end of the table, and g1 to the number of
963 	 * elements to read from the beginning of the table.
964 	 */
965 	g0 = control->ras_fri + num - 1;
966 	g1 = g0 % control->ras_max_record_count;
967 	if (g0 < control->ras_max_record_count) {
968 		g0 = num;
969 		g1 = 0;
970 	} else {
971 		g0 = control->ras_max_record_count - control->ras_fri;
972 		g1 += 1;
973 	}
974 
975 	mutex_lock(&control->ras_tbl_mutex);
976 	res = __amdgpu_ras_eeprom_read(control, buf, control->ras_fri, g0);
977 	if (res)
978 		goto Out;
979 	if (g1) {
980 		res = __amdgpu_ras_eeprom_read(control,
981 					       buf + g0 * RAS_TABLE_RECORD_SIZE,
982 					       0, g1);
983 		if (res)
984 			goto Out;
985 	}
986 
987 	res = 0;
988 
989 	/* Read up everything? Then transform.
990 	 */
991 	pp = buf;
992 	for (i = 0; i < num; i++, pp += RAS_TABLE_RECORD_SIZE) {
993 		__decode_table_record_from_buf(control, &record[i], pp);
994 
995 		/* update bad channel bitmap */
996 		if ((record[i].mem_channel < BITS_PER_TYPE(control->bad_channel_bitmap)) &&
997 		    !(control->bad_channel_bitmap & (1 << record[i].mem_channel))) {
998 			control->bad_channel_bitmap |= 1 << record[i].mem_channel;
999 			con->update_channel_flag = true;
1000 		}
1001 	}
1002 Out:
1003 	kfree(buf);
1004 	mutex_unlock(&control->ras_tbl_mutex);
1005 
1006 	return res;
1007 }
1008 
1009 uint32_t amdgpu_ras_eeprom_max_record_count(struct amdgpu_ras_eeprom_control *control)
1010 {
1011 	if (control->tbl_hdr.version == RAS_TABLE_VER_V2_1)
1012 		return RAS_MAX_RECORD_COUNT_V2_1;
1013 	else
1014 		return RAS_MAX_RECORD_COUNT;
1015 }
1016 
1017 static ssize_t
1018 amdgpu_ras_debugfs_eeprom_size_read(struct file *f, char __user *buf,
1019 				    size_t size, loff_t *pos)
1020 {
1021 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
1022 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1023 	struct amdgpu_ras_eeprom_control *control = ras ? &ras->eeprom_control : NULL;
1024 	u8 data[50];
1025 	int res;
1026 
1027 	if (!size)
1028 		return size;
1029 
1030 	if (!ras || !control) {
1031 		res = snprintf(data, sizeof(data), "Not supported\n");
1032 	} else {
1033 		res = snprintf(data, sizeof(data), "%d bytes or %d records\n",
1034 			       RAS_TBL_SIZE_BYTES, control->ras_max_record_count);
1035 	}
1036 
1037 	if (*pos >= res)
1038 		return 0;
1039 
1040 	res -= *pos;
1041 	res = min_t(size_t, res, size);
1042 
1043 	if (copy_to_user(buf, &data[*pos], res))
1044 		return -EFAULT;
1045 
1046 	*pos += res;
1047 
1048 	return res;
1049 }
1050 
1051 const struct file_operations amdgpu_ras_debugfs_eeprom_size_ops = {
1052 	.owner = THIS_MODULE,
1053 	.read = amdgpu_ras_debugfs_eeprom_size_read,
1054 	.write = NULL,
1055 	.llseek = default_llseek,
1056 };
1057 
1058 static const char *tbl_hdr_str = " Signature    Version  FirstOffs       Size   Checksum\n";
1059 static const char *tbl_hdr_fmt = "0x%08X 0x%08X 0x%08X 0x%08X 0x%08X\n";
1060 #define tbl_hdr_fmt_size (5 * (2+8) + 4 + 1)
1061 static const char *rec_hdr_str = "Index  Offset ErrType Bank/CU          TimeStamp      Offs/Addr MemChl MCUMCID    RetiredPage\n";
1062 static const char *rec_hdr_fmt = "%5d 0x%05X %7s    0x%02X 0x%016llX 0x%012llX   0x%02X    0x%02X 0x%012llX\n";
1063 #define rec_hdr_fmt_size (5 + 1 + 7 + 1 + 7 + 1 + 7 + 1 + 18 + 1 + 14 + 1 + 6 + 1 + 7 + 1 + 14 + 1)
1064 
1065 static const char *record_err_type_str[AMDGPU_RAS_EEPROM_ERR_COUNT] = {
1066 	"ignore",
1067 	"re",
1068 	"ue",
1069 };
1070 
1071 static loff_t amdgpu_ras_debugfs_table_size(struct amdgpu_ras_eeprom_control *control)
1072 {
1073 	return strlen(tbl_hdr_str) + tbl_hdr_fmt_size +
1074 		strlen(rec_hdr_str) + rec_hdr_fmt_size * control->ras_num_recs;
1075 }
1076 
1077 void amdgpu_ras_debugfs_set_ret_size(struct amdgpu_ras_eeprom_control *control)
1078 {
1079 	struct amdgpu_ras *ras = container_of(control, struct amdgpu_ras,
1080 					      eeprom_control);
1081 	struct dentry *de = ras->de_ras_eeprom_table;
1082 
1083 	if (de)
1084 		d_inode(de)->i_size = amdgpu_ras_debugfs_table_size(control);
1085 }
1086 
1087 static ssize_t amdgpu_ras_debugfs_table_read(struct file *f, char __user *buf,
1088 					     size_t size, loff_t *pos)
1089 {
1090 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
1091 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1092 	struct amdgpu_ras_eeprom_control *control = &ras->eeprom_control;
1093 	const size_t orig_size = size;
1094 	int res = -EFAULT;
1095 	size_t data_len;
1096 
1097 	mutex_lock(&control->ras_tbl_mutex);
1098 
1099 	/* We want *pos - data_len > 0, which means there's
1100 	 * bytes to be printed from data.
1101 	 */
1102 	data_len = strlen(tbl_hdr_str);
1103 	if (*pos < data_len) {
1104 		data_len -= *pos;
1105 		data_len = min_t(size_t, data_len, size);
1106 		if (copy_to_user(buf, &tbl_hdr_str[*pos], data_len))
1107 			goto Out;
1108 		buf += data_len;
1109 		size -= data_len;
1110 		*pos += data_len;
1111 	}
1112 
1113 	data_len = strlen(tbl_hdr_str) + tbl_hdr_fmt_size;
1114 	if (*pos < data_len && size > 0) {
1115 		u8 data[tbl_hdr_fmt_size + 1];
1116 		loff_t lpos;
1117 
1118 		snprintf(data, sizeof(data), tbl_hdr_fmt,
1119 			 control->tbl_hdr.header,
1120 			 control->tbl_hdr.version,
1121 			 control->tbl_hdr.first_rec_offset,
1122 			 control->tbl_hdr.tbl_size,
1123 			 control->tbl_hdr.checksum);
1124 
1125 		data_len -= *pos;
1126 		data_len = min_t(size_t, data_len, size);
1127 		lpos = *pos - strlen(tbl_hdr_str);
1128 		if (copy_to_user(buf, &data[lpos], data_len))
1129 			goto Out;
1130 		buf += data_len;
1131 		size -= data_len;
1132 		*pos += data_len;
1133 	}
1134 
1135 	data_len = strlen(tbl_hdr_str) + tbl_hdr_fmt_size + strlen(rec_hdr_str);
1136 	if (*pos < data_len && size > 0) {
1137 		loff_t lpos;
1138 
1139 		data_len -= *pos;
1140 		data_len = min_t(size_t, data_len, size);
1141 		lpos = *pos - strlen(tbl_hdr_str) - tbl_hdr_fmt_size;
1142 		if (copy_to_user(buf, &rec_hdr_str[lpos], data_len))
1143 			goto Out;
1144 		buf += data_len;
1145 		size -= data_len;
1146 		*pos += data_len;
1147 	}
1148 
1149 	data_len = amdgpu_ras_debugfs_table_size(control);
1150 	if (*pos < data_len && size > 0) {
1151 		u8 dare[RAS_TABLE_RECORD_SIZE];
1152 		u8 data[rec_hdr_fmt_size + 1];
1153 		struct eeprom_table_record record;
1154 		int s, r;
1155 
1156 		/* Find the starting record index
1157 		 */
1158 		s = *pos - strlen(tbl_hdr_str) - tbl_hdr_fmt_size -
1159 			strlen(rec_hdr_str);
1160 		s = s / rec_hdr_fmt_size;
1161 		r = *pos - strlen(tbl_hdr_str) - tbl_hdr_fmt_size -
1162 			strlen(rec_hdr_str);
1163 		r = r % rec_hdr_fmt_size;
1164 
1165 		for ( ; size > 0 && s < control->ras_num_recs; s++) {
1166 			u32 ai = RAS_RI_TO_AI(control, s);
1167 			/* Read a single record
1168 			 */
1169 			res = __amdgpu_ras_eeprom_read(control, dare, ai, 1);
1170 			if (res)
1171 				goto Out;
1172 			__decode_table_record_from_buf(control, &record, dare);
1173 			snprintf(data, sizeof(data), rec_hdr_fmt,
1174 				 s,
1175 				 RAS_INDEX_TO_OFFSET(control, ai),
1176 				 record_err_type_str[record.err_type],
1177 				 record.bank,
1178 				 record.ts,
1179 				 record.offset,
1180 				 record.mem_channel,
1181 				 record.mcumc_id,
1182 				 record.retired_page);
1183 
1184 			data_len = min_t(size_t, rec_hdr_fmt_size - r, size);
1185 			if (copy_to_user(buf, &data[r], data_len)) {
1186 				res = -EFAULT;
1187 				goto Out;
1188 			}
1189 			buf += data_len;
1190 			size -= data_len;
1191 			*pos += data_len;
1192 			r = 0;
1193 		}
1194 	}
1195 	res = 0;
1196 Out:
1197 	mutex_unlock(&control->ras_tbl_mutex);
1198 	return res < 0 ? res : orig_size - size;
1199 }
1200 
1201 static ssize_t
1202 amdgpu_ras_debugfs_eeprom_table_read(struct file *f, char __user *buf,
1203 				     size_t size, loff_t *pos)
1204 {
1205 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
1206 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1207 	struct amdgpu_ras_eeprom_control *control = ras ? &ras->eeprom_control : NULL;
1208 	u8 data[81];
1209 	int res;
1210 
1211 	if (!size)
1212 		return size;
1213 
1214 	if (!ras || !control) {
1215 		res = snprintf(data, sizeof(data), "Not supported\n");
1216 		if (*pos >= res)
1217 			return 0;
1218 
1219 		res -= *pos;
1220 		res = min_t(size_t, res, size);
1221 
1222 		if (copy_to_user(buf, &data[*pos], res))
1223 			return -EFAULT;
1224 
1225 		*pos += res;
1226 
1227 		return res;
1228 	} else {
1229 		return amdgpu_ras_debugfs_table_read(f, buf, size, pos);
1230 	}
1231 }
1232 
1233 const struct file_operations amdgpu_ras_debugfs_eeprom_table_ops = {
1234 	.owner = THIS_MODULE,
1235 	.read = amdgpu_ras_debugfs_eeprom_table_read,
1236 	.write = NULL,
1237 	.llseek = default_llseek,
1238 };
1239 
1240 /**
1241  * __verify_ras_table_checksum -- verify the RAS EEPROM table checksum
1242  * @control: pointer to control structure
1243  *
1244  * Check the checksum of the stored in EEPROM RAS table.
1245  *
1246  * Return 0 if the checksum is correct,
1247  * positive if it is not correct, and
1248  * -errno on I/O error.
1249  */
1250 static int __verify_ras_table_checksum(struct amdgpu_ras_eeprom_control *control)
1251 {
1252 	struct amdgpu_device *adev = to_amdgpu_device(control);
1253 	int buf_size, res;
1254 	u8  csum, *buf, *pp;
1255 
1256 	if (control->tbl_hdr.version == RAS_TABLE_VER_V2_1)
1257 		buf_size = RAS_TABLE_HEADER_SIZE +
1258 			   RAS_TABLE_V2_1_INFO_SIZE +
1259 			   control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
1260 	else
1261 		buf_size = RAS_TABLE_HEADER_SIZE +
1262 			   control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
1263 
1264 	buf = kzalloc(buf_size, GFP_KERNEL);
1265 	if (!buf) {
1266 		DRM_ERROR("Out of memory checking RAS table checksum.\n");
1267 		return -ENOMEM;
1268 	}
1269 
1270 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
1271 				 control->i2c_address +
1272 				 control->ras_header_offset,
1273 				 buf, buf_size);
1274 	if (res < buf_size) {
1275 		DRM_ERROR("Partial read for checksum, res:%d\n", res);
1276 		/* On partial reads, return -EIO.
1277 		 */
1278 		if (res >= 0)
1279 			res = -EIO;
1280 		goto Out;
1281 	}
1282 
1283 	csum = 0;
1284 	for (pp = buf; pp < buf + buf_size; pp++)
1285 		csum += *pp;
1286 Out:
1287 	kfree(buf);
1288 	return res < 0 ? res : csum;
1289 }
1290 
1291 static int __read_table_ras_info(struct amdgpu_ras_eeprom_control *control)
1292 {
1293 	struct amdgpu_ras_eeprom_table_ras_info *rai = &control->tbl_rai;
1294 	struct amdgpu_device *adev = to_amdgpu_device(control);
1295 	unsigned char *buf;
1296 	int res;
1297 
1298 	buf = kzalloc(RAS_TABLE_V2_1_INFO_SIZE, GFP_KERNEL);
1299 	if (!buf) {
1300 		DRM_ERROR("Failed to alloc buf to read EEPROM table ras info\n");
1301 		return -ENOMEM;
1302 	}
1303 
1304 	/**
1305 	 * EEPROM table V2_1 supports ras info,
1306 	 * read EEPROM table ras info
1307 	 */
1308 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
1309 				 control->i2c_address + control->ras_info_offset,
1310 				 buf, RAS_TABLE_V2_1_INFO_SIZE);
1311 	if (res < RAS_TABLE_V2_1_INFO_SIZE) {
1312 		DRM_ERROR("Failed to read EEPROM table ras info, res:%d", res);
1313 		res = res >= 0 ? -EIO : res;
1314 		goto Out;
1315 	}
1316 
1317 	__decode_table_ras_info_from_buf(rai, buf);
1318 
1319 Out:
1320 	kfree(buf);
1321 	return res == RAS_TABLE_V2_1_INFO_SIZE ? 0 : res;
1322 }
1323 
1324 int amdgpu_ras_eeprom_init(struct amdgpu_ras_eeprom_control *control,
1325 			   bool *exceed_err_limit)
1326 {
1327 	struct amdgpu_device *adev = to_amdgpu_device(control);
1328 	unsigned char buf[RAS_TABLE_HEADER_SIZE] = { 0 };
1329 	struct amdgpu_ras_eeprom_table_header *hdr = &control->tbl_hdr;
1330 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1331 	int res;
1332 
1333 	*exceed_err_limit = false;
1334 
1335 	if (!__is_ras_eeprom_supported(adev))
1336 		return 0;
1337 
1338 	/* Verify i2c adapter is initialized */
1339 	if (!adev->pm.ras_eeprom_i2c_bus || !adev->pm.ras_eeprom_i2c_bus->algo)
1340 		return -ENOENT;
1341 
1342 	if (!__get_eeprom_i2c_addr(adev, control))
1343 		return -EINVAL;
1344 
1345 	control->ras_header_offset = RAS_HDR_START;
1346 	control->ras_info_offset = RAS_TABLE_V2_1_INFO_START;
1347 	mutex_init(&control->ras_tbl_mutex);
1348 
1349 	/* Read the table header from EEPROM address */
1350 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
1351 				 control->i2c_address + control->ras_header_offset,
1352 				 buf, RAS_TABLE_HEADER_SIZE);
1353 	if (res < RAS_TABLE_HEADER_SIZE) {
1354 		DRM_ERROR("Failed to read EEPROM table header, res:%d", res);
1355 		return res >= 0 ? -EIO : res;
1356 	}
1357 
1358 	__decode_table_header_from_buf(hdr, buf);
1359 
1360 	if (hdr->version == RAS_TABLE_VER_V2_1) {
1361 		control->ras_num_recs = RAS_NUM_RECS_V2_1(hdr);
1362 		control->ras_record_offset = RAS_RECORD_START_V2_1;
1363 		control->ras_max_record_count = RAS_MAX_RECORD_COUNT_V2_1;
1364 	} else {
1365 		control->ras_num_recs = RAS_NUM_RECS(hdr);
1366 		control->ras_record_offset = RAS_RECORD_START;
1367 		control->ras_max_record_count = RAS_MAX_RECORD_COUNT;
1368 	}
1369 	control->ras_fri = RAS_OFFSET_TO_INDEX(control, hdr->first_rec_offset);
1370 
1371 	if (hdr->header == RAS_TABLE_HDR_VAL) {
1372 		DRM_DEBUG_DRIVER("Found existing EEPROM table with %d records",
1373 				 control->ras_num_recs);
1374 
1375 		if (hdr->version == RAS_TABLE_VER_V2_1) {
1376 			res = __read_table_ras_info(control);
1377 			if (res)
1378 				return res;
1379 		}
1380 
1381 		res = __verify_ras_table_checksum(control);
1382 		if (res)
1383 			DRM_ERROR("RAS table incorrect checksum or error:%d\n",
1384 				  res);
1385 
1386 		/* Warn if we are at 90% of the threshold or above
1387 		 */
1388 		if (10 * control->ras_num_recs >= 9 * ras->bad_page_cnt_threshold)
1389 			dev_warn(adev->dev, "RAS records:%u exceeds 90%% of threshold:%d",
1390 					control->ras_num_recs,
1391 					ras->bad_page_cnt_threshold);
1392 	} else if (hdr->header == RAS_TABLE_HDR_BAD &&
1393 		   amdgpu_bad_page_threshold != 0) {
1394 		if (hdr->version == RAS_TABLE_VER_V2_1) {
1395 			res = __read_table_ras_info(control);
1396 			if (res)
1397 				return res;
1398 		}
1399 
1400 		res = __verify_ras_table_checksum(control);
1401 		if (res)
1402 			DRM_ERROR("RAS Table incorrect checksum or error:%d\n",
1403 				  res);
1404 		if (ras->bad_page_cnt_threshold > control->ras_num_recs) {
1405 			/* This means that, the threshold was increased since
1406 			 * the last time the system was booted, and now,
1407 			 * ras->bad_page_cnt_threshold - control->num_recs > 0,
1408 			 * so that at least one more record can be saved,
1409 			 * before the page count threshold is reached.
1410 			 */
1411 			dev_info(adev->dev,
1412 				 "records:%d threshold:%d, resetting "
1413 				 "RAS table header signature",
1414 				 control->ras_num_recs,
1415 				 ras->bad_page_cnt_threshold);
1416 			res = amdgpu_ras_eeprom_correct_header_tag(control,
1417 								   RAS_TABLE_HDR_VAL);
1418 		} else {
1419 			dev_err(adev->dev, "RAS records:%d exceed threshold:%d",
1420 				control->ras_num_recs, ras->bad_page_cnt_threshold);
1421 			if (amdgpu_bad_page_threshold == -1) {
1422 				dev_warn(adev->dev, "GPU will be initialized due to bad_page_threshold = -1.");
1423 				res = 0;
1424 			} else {
1425 				*exceed_err_limit = true;
1426 				dev_err(adev->dev,
1427 					"RAS records:%d exceed threshold:%d, "
1428 					"GPU will not be initialized. Replace this GPU or increase the threshold",
1429 					control->ras_num_recs, ras->bad_page_cnt_threshold);
1430 			}
1431 		}
1432 	} else {
1433 		DRM_INFO("Creating a new EEPROM table");
1434 
1435 		res = amdgpu_ras_eeprom_reset_table(control);
1436 	}
1437 
1438 	return res < 0 ? res : 0;
1439 }
1440