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