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