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