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