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 #define EEPROM_I2C_MADDR_VEGA20         0x0
35 #define EEPROM_I2C_MADDR_ARCTURUS       0x40000
36 #define EEPROM_I2C_MADDR_ARCTURUS_D342  0x0
37 #define EEPROM_I2C_MADDR_SIENNA_CICHLID 0x0
38 #define EEPROM_I2C_MADDR_ALDEBARAN      0x0
39 
40 /*
41  * The 2 macros bellow represent the actual size in bytes that
42  * those entities occupy in the EEPROM memory.
43  * RAS_TABLE_RECORD_SIZE is different than sizeof(eeprom_table_record) which
44  * uses uint64 to store 6b fields such as retired_page.
45  */
46 #define RAS_TABLE_HEADER_SIZE   20
47 #define RAS_TABLE_RECORD_SIZE   24
48 
49 /* Table hdr is 'AMDR' */
50 #define RAS_TABLE_HDR_VAL       0x414d4452
51 #define RAS_TABLE_VER           0x00010000
52 
53 /* Bad GPU tag ‘BADG’ */
54 #define RAS_TABLE_HDR_BAD       0x42414447
55 
56 /* Assume 2-Mbit size EEPROM and take up the whole space. */
57 #define RAS_TBL_SIZE_BYTES      (256 * 1024)
58 #define RAS_TABLE_START         0
59 #define RAS_HDR_START           RAS_TABLE_START
60 #define RAS_RECORD_START        (RAS_HDR_START + RAS_TABLE_HEADER_SIZE)
61 #define RAS_MAX_RECORD_COUNT    ((RAS_TBL_SIZE_BYTES - RAS_TABLE_HEADER_SIZE) \
62 				 / RAS_TABLE_RECORD_SIZE)
63 
64 /* Given a zero-based index of an EEPROM RAS record, yields the EEPROM
65  * offset off of RAS_TABLE_START.  That is, this is something you can
66  * add to control->i2c_address, and then tell I2C layer to read
67  * from/write to there. _N is the so called absolute index,
68  * because it starts right after the table header.
69  */
70 #define RAS_INDEX_TO_OFFSET(_C, _N) ((_C)->ras_record_offset + \
71 				     (_N) * RAS_TABLE_RECORD_SIZE)
72 
73 #define RAS_OFFSET_TO_INDEX(_C, _O) (((_O) - \
74 				      (_C)->ras_record_offset) / RAS_TABLE_RECORD_SIZE)
75 
76 /* Given a 0-based relative record index, 0, 1, 2, ..., etc., off
77  * of "fri", return the absolute record index off of the end of
78  * the table header.
79  */
80 #define RAS_RI_TO_AI(_C, _I) (((_I) + (_C)->ras_fri) % \
81 			      (_C)->ras_max_record_count)
82 
83 #define RAS_NUM_RECS(_tbl_hdr)  (((_tbl_hdr)->tbl_size - \
84 				  RAS_TABLE_HEADER_SIZE) / RAS_TABLE_RECORD_SIZE)
85 
86 #define to_amdgpu_device(x) (container_of(x, struct amdgpu_ras, eeprom_control))->adev
87 
88 static bool __is_ras_eeprom_supported(struct amdgpu_device *adev)
89 {
90 	return  adev->asic_type == CHIP_VEGA20 ||
91 		adev->asic_type == CHIP_ARCTURUS ||
92 		adev->asic_type == CHIP_SIENNA_CICHLID ||
93 		adev->asic_type == CHIP_ALDEBARAN;
94 }
95 
96 static bool __get_eeprom_i2c_addr_arct(struct amdgpu_device *adev,
97 				       struct amdgpu_ras_eeprom_control *control)
98 {
99 	struct atom_context *atom_ctx = adev->mode_info.atom_context;
100 
101 	if (!control || !atom_ctx)
102 		return false;
103 
104 	if (strnstr(atom_ctx->vbios_version,
105 	            "D342",
106 		    sizeof(atom_ctx->vbios_version)))
107 		control->i2c_address = EEPROM_I2C_MADDR_ARCTURUS_D342;
108 	else
109 		control->i2c_address = EEPROM_I2C_MADDR_ARCTURUS;
110 
111 	return true;
112 }
113 
114 static bool __get_eeprom_i2c_addr(struct amdgpu_device *adev,
115 				  struct amdgpu_ras_eeprom_control *control)
116 {
117 	u8 i2c_addr;
118 
119 	if (!control)
120 		return false;
121 
122 	if (amdgpu_atomfirmware_ras_rom_addr(adev, &i2c_addr)) {
123 		/* The address given by VBIOS is an 8-bit, wire-format
124 		 * address, i.e. the most significant byte.
125 		 *
126 		 * Normalize it to a 19-bit EEPROM address. Remove the
127 		 * device type identifier and make it a 7-bit address;
128 		 * then make it a 19-bit EEPROM address. See top of
129 		 * amdgpu_eeprom.c.
130 		 */
131 		i2c_addr = (i2c_addr & 0x0F) >> 1;
132 		control->i2c_address = ((u32) i2c_addr) << 16;
133 
134 		return true;
135 	}
136 
137 	switch (adev->asic_type) {
138 	case CHIP_VEGA20:
139 		control->i2c_address = EEPROM_I2C_MADDR_VEGA20;
140 		break;
141 
142 	case CHIP_ARCTURUS:
143 		return __get_eeprom_i2c_addr_arct(adev, control);
144 
145 	case CHIP_SIENNA_CICHLID:
146 		control->i2c_address = EEPROM_I2C_MADDR_SIENNA_CICHLID;
147 		break;
148 
149 	case CHIP_ALDEBARAN:
150 		control->i2c_address = EEPROM_I2C_MADDR_ALDEBARAN;
151 		break;
152 
153 	default:
154 		return false;
155 	}
156 
157 	return true;
158 }
159 
160 static void
161 __encode_table_header_to_buf(struct amdgpu_ras_eeprom_table_header *hdr,
162 			     unsigned char *buf)
163 {
164 	u32 *pp = (uint32_t *)buf;
165 
166 	pp[0] = cpu_to_le32(hdr->header);
167 	pp[1] = cpu_to_le32(hdr->version);
168 	pp[2] = cpu_to_le32(hdr->first_rec_offset);
169 	pp[3] = cpu_to_le32(hdr->tbl_size);
170 	pp[4] = cpu_to_le32(hdr->checksum);
171 }
172 
173 static void
174 __decode_table_header_from_buf(struct amdgpu_ras_eeprom_table_header *hdr,
175 			       unsigned char *buf)
176 {
177 	u32 *pp = (uint32_t *)buf;
178 
179 	hdr->header	      = le32_to_cpu(pp[0]);
180 	hdr->version	      = le32_to_cpu(pp[1]);
181 	hdr->first_rec_offset = le32_to_cpu(pp[2]);
182 	hdr->tbl_size	      = le32_to_cpu(pp[3]);
183 	hdr->checksum	      = le32_to_cpu(pp[4]);
184 }
185 
186 static int __write_table_header(struct amdgpu_ras_eeprom_control *control)
187 {
188 	u8 buf[RAS_TABLE_HEADER_SIZE];
189 	struct amdgpu_device *adev = to_amdgpu_device(control);
190 	int res;
191 
192 	memset(buf, 0, sizeof(buf));
193 	__encode_table_header_to_buf(&control->tbl_hdr, buf);
194 
195 	/* i2c may be unstable in gpu reset */
196 	down_read(&adev->reset_sem);
197 	res = amdgpu_eeprom_write(adev->pm.ras_eeprom_i2c_bus,
198 				  control->i2c_address +
199 				  control->ras_header_offset,
200 				  buf, RAS_TABLE_HEADER_SIZE);
201 	up_read(&adev->reset_sem);
202 
203 	if (res < 0) {
204 		DRM_ERROR("Failed to write EEPROM table header:%d", res);
205 	} else if (res < RAS_TABLE_HEADER_SIZE) {
206 		DRM_ERROR("Short write:%d out of %d\n",
207 			  res, RAS_TABLE_HEADER_SIZE);
208 		res = -EIO;
209 	} else {
210 		res = 0;
211 	}
212 
213 	return res;
214 }
215 
216 static u8 __calc_hdr_byte_sum(const struct amdgpu_ras_eeprom_control *control)
217 {
218 	int ii;
219 	u8  *pp, csum;
220 	size_t sz;
221 
222 	/* Header checksum, skip checksum field in the calculation */
223 	sz = sizeof(control->tbl_hdr) - sizeof(control->tbl_hdr.checksum);
224 	pp = (u8 *) &control->tbl_hdr;
225 	csum = 0;
226 	for (ii = 0; ii < sz; ii++, pp++)
227 		csum += *pp;
228 
229 	return csum;
230 }
231 
232 static int amdgpu_ras_eeprom_correct_header_tag(
233 	struct amdgpu_ras_eeprom_control *control,
234 	uint32_t header)
235 {
236 	struct amdgpu_ras_eeprom_table_header *hdr = &control->tbl_hdr;
237 	u8 *hh;
238 	int res;
239 	u8 csum;
240 
241 	csum = -hdr->checksum;
242 
243 	hh = (void *) &hdr->header;
244 	csum -= (hh[0] + hh[1] + hh[2] + hh[3]);
245 	hh = (void *) &header;
246 	csum += hh[0] + hh[1] + hh[2] + hh[3];
247 	csum = -csum;
248 	mutex_lock(&control->ras_tbl_mutex);
249 	hdr->header = header;
250 	hdr->checksum = csum;
251 	res = __write_table_header(control);
252 	mutex_unlock(&control->ras_tbl_mutex);
253 
254 	return res;
255 }
256 
257 /**
258  * amdgpu_ras_eeprom_reset_table -- Reset the RAS EEPROM table
259  * @control: pointer to control structure
260  *
261  * Reset the contents of the header of the RAS EEPROM table.
262  * Return 0 on success, -errno on error.
263  */
264 int amdgpu_ras_eeprom_reset_table(struct amdgpu_ras_eeprom_control *control)
265 {
266 	struct amdgpu_device *adev = to_amdgpu_device(control);
267 	struct amdgpu_ras_eeprom_table_header *hdr = &control->tbl_hdr;
268 	u8 csum;
269 	int res;
270 
271 	mutex_lock(&control->ras_tbl_mutex);
272 
273 	hdr->header = RAS_TABLE_HDR_VAL;
274 	hdr->version = RAS_TABLE_VER;
275 	hdr->first_rec_offset = RAS_RECORD_START;
276 	hdr->tbl_size = RAS_TABLE_HEADER_SIZE;
277 
278 	csum = __calc_hdr_byte_sum(control);
279 	csum = -csum;
280 	hdr->checksum = csum;
281 	res = __write_table_header(control);
282 
283 	control->ras_num_recs = 0;
284 	control->ras_fri = 0;
285 
286 	amdgpu_dpm_send_hbm_bad_pages_num(adev, control->ras_num_recs);
287 
288 	amdgpu_ras_debugfs_set_ret_size(control);
289 
290 	mutex_unlock(&control->ras_tbl_mutex);
291 
292 	return res;
293 }
294 
295 static void
296 __encode_table_record_to_buf(struct amdgpu_ras_eeprom_control *control,
297 			     struct eeprom_table_record *record,
298 			     unsigned char *buf)
299 {
300 	__le64 tmp = 0;
301 	int i = 0;
302 
303 	/* Next are all record fields according to EEPROM page spec in LE foramt */
304 	buf[i++] = record->err_type;
305 
306 	buf[i++] = record->bank;
307 
308 	tmp = cpu_to_le64(record->ts);
309 	memcpy(buf + i, &tmp, 8);
310 	i += 8;
311 
312 	tmp = cpu_to_le64((record->offset & 0xffffffffffff));
313 	memcpy(buf + i, &tmp, 6);
314 	i += 6;
315 
316 	buf[i++] = record->mem_channel;
317 	buf[i++] = record->mcumc_id;
318 
319 	tmp = cpu_to_le64((record->retired_page & 0xffffffffffff));
320 	memcpy(buf + i, &tmp, 6);
321 }
322 
323 static void
324 __decode_table_record_from_buf(struct amdgpu_ras_eeprom_control *control,
325 			       struct eeprom_table_record *record,
326 			       unsigned char *buf)
327 {
328 	__le64 tmp = 0;
329 	int i =  0;
330 
331 	/* Next are all record fields according to EEPROM page spec in LE foramt */
332 	record->err_type = buf[i++];
333 
334 	record->bank = buf[i++];
335 
336 	memcpy(&tmp, buf + i, 8);
337 	record->ts = le64_to_cpu(tmp);
338 	i += 8;
339 
340 	memcpy(&tmp, buf + i, 6);
341 	record->offset = (le64_to_cpu(tmp) & 0xffffffffffff);
342 	i += 6;
343 
344 	record->mem_channel = buf[i++];
345 	record->mcumc_id = buf[i++];
346 
347 	memcpy(&tmp, buf + i,  6);
348 	record->retired_page = (le64_to_cpu(tmp) & 0xffffffffffff);
349 }
350 
351 bool amdgpu_ras_eeprom_check_err_threshold(struct amdgpu_device *adev)
352 {
353 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
354 
355 	if (!__is_ras_eeprom_supported(adev))
356 		return false;
357 
358 	/* skip check eeprom table for VEGA20 Gaming */
359 	if (!con)
360 		return false;
361 	else
362 		if (!(con->features & BIT(AMDGPU_RAS_BLOCK__UMC)))
363 			return false;
364 
365 	if (con->eeprom_control.tbl_hdr.header == RAS_TABLE_HDR_BAD) {
366 		dev_warn(adev->dev, "This GPU is in BAD status.");
367 		dev_warn(adev->dev, "Please retire it or set a larger "
368 			 "threshold value when reloading driver.\n");
369 		return true;
370 	}
371 
372 	return false;
373 }
374 
375 /**
376  * __amdgpu_ras_eeprom_write -- write indexed from buffer to EEPROM
377  * @control: pointer to control structure
378  * @buf: pointer to buffer containing data to write
379  * @fri: start writing at this index
380  * @num: number of records to write
381  *
382  * The caller must hold the table mutex in @control.
383  * Return 0 on success, -errno otherwise.
384  */
385 static int __amdgpu_ras_eeprom_write(struct amdgpu_ras_eeprom_control *control,
386 				     u8 *buf, const u32 fri, const u32 num)
387 {
388 	struct amdgpu_device *adev = to_amdgpu_device(control);
389 	u32 buf_size;
390 	int res;
391 
392 	/* i2c may be unstable in gpu reset */
393 	down_read(&adev->reset_sem);
394 	buf_size = num * RAS_TABLE_RECORD_SIZE;
395 	res = amdgpu_eeprom_write(adev->pm.ras_eeprom_i2c_bus,
396 				  control->i2c_address +
397 				  RAS_INDEX_TO_OFFSET(control, fri),
398 				  buf, buf_size);
399 	up_read(&adev->reset_sem);
400 	if (res < 0) {
401 		DRM_ERROR("Writing %d EEPROM table records error:%d",
402 			  num, res);
403 	} else if (res < buf_size) {
404 		/* Short write, return error.
405 		 */
406 		DRM_ERROR("Wrote %d records out of %d",
407 			  res / RAS_TABLE_RECORD_SIZE, num);
408 		res = -EIO;
409 	} else {
410 		res = 0;
411 	}
412 
413 	return res;
414 }
415 
416 static int
417 amdgpu_ras_eeprom_append_table(struct amdgpu_ras_eeprom_control *control,
418 			       struct eeprom_table_record *record,
419 			       const u32 num)
420 {
421 	u32 a, b, i;
422 	u8 *buf, *pp;
423 	int res;
424 
425 	buf = kcalloc(num, RAS_TABLE_RECORD_SIZE, GFP_KERNEL);
426 	if (!buf)
427 		return -ENOMEM;
428 
429 	/* Encode all of them in one go.
430 	 */
431 	pp = buf;
432 	for (i = 0; i < num; i++, pp += RAS_TABLE_RECORD_SIZE)
433 		__encode_table_record_to_buf(control, &record[i], pp);
434 
435 	/* a, first record index to write into.
436 	 * b, last record index to write into.
437 	 * a = first index to read (fri) + number of records in the table,
438 	 * b = a + @num - 1.
439 	 * Let N = control->ras_max_num_record_count, then we have,
440 	 * case 0: 0 <= a <= b < N,
441 	 *   just append @num records starting at a;
442 	 * case 1: 0 <= a < N <= b,
443 	 *   append (N - a) records starting at a, and
444 	 *   append the remainder,  b % N + 1, starting at 0.
445 	 * case 2: 0 <= fri < N <= a <= b, then modulo N we get two subcases,
446 	 * case 2a: 0 <= a <= b < N
447 	 *   append num records starting at a; and fix fri if b overwrote it,
448 	 *   and since a <= b, if b overwrote it then a must've also,
449 	 *   and if b didn't overwrite it, then a didn't also.
450 	 * case 2b: 0 <= b < a < N
451 	 *   write num records starting at a, which wraps around 0=N
452 	 *   and overwrite fri unconditionally. Now from case 2a,
453 	 *   this means that b eclipsed fri to overwrite it and wrap
454 	 *   around 0 again, i.e. b = 2N+r pre modulo N, so we unconditionally
455 	 *   set fri = b + 1 (mod N).
456 	 * Now, since fri is updated in every case, except the trivial case 0,
457 	 * the number of records present in the table after writing, is,
458 	 * num_recs - 1 = b - fri (mod N), and we take the positive value,
459 	 * by adding an arbitrary multiple of N before taking the modulo N
460 	 * as shown below.
461 	 */
462 	a = control->ras_fri + control->ras_num_recs;
463 	b = a + num  - 1;
464 	if (b < control->ras_max_record_count) {
465 		res = __amdgpu_ras_eeprom_write(control, buf, a, num);
466 	} else if (a < control->ras_max_record_count) {
467 		u32 g0, g1;
468 
469 		g0 = control->ras_max_record_count - a;
470 		g1 = b % control->ras_max_record_count + 1;
471 		res = __amdgpu_ras_eeprom_write(control, buf, a, g0);
472 		if (res)
473 			goto Out;
474 		res = __amdgpu_ras_eeprom_write(control,
475 						buf + g0 * RAS_TABLE_RECORD_SIZE,
476 						0, g1);
477 		if (res)
478 			goto Out;
479 		if (g1 > control->ras_fri)
480 			control->ras_fri = g1 % control->ras_max_record_count;
481 	} else {
482 		a %= control->ras_max_record_count;
483 		b %= control->ras_max_record_count;
484 
485 		if (a <= b) {
486 			/* Note that, b - a + 1 = num. */
487 			res = __amdgpu_ras_eeprom_write(control, buf, a, num);
488 			if (res)
489 				goto Out;
490 			if (b >= control->ras_fri)
491 				control->ras_fri = (b + 1) % control->ras_max_record_count;
492 		} else {
493 			u32 g0, g1;
494 
495 			/* b < a, which means, we write from
496 			 * a to the end of the table, and from
497 			 * the start of the table to b.
498 			 */
499 			g0 = control->ras_max_record_count - a;
500 			g1 = b + 1;
501 			res = __amdgpu_ras_eeprom_write(control, buf, a, g0);
502 			if (res)
503 				goto Out;
504 			res = __amdgpu_ras_eeprom_write(control,
505 							buf + g0 * RAS_TABLE_RECORD_SIZE,
506 							0, g1);
507 			if (res)
508 				goto Out;
509 			control->ras_fri = g1 % control->ras_max_record_count;
510 		}
511 	}
512 	control->ras_num_recs = 1 + (control->ras_max_record_count + b
513 				     - control->ras_fri)
514 		% control->ras_max_record_count;
515 Out:
516 	kfree(buf);
517 	return res;
518 }
519 
520 static int
521 amdgpu_ras_eeprom_update_header(struct amdgpu_ras_eeprom_control *control)
522 {
523 	struct amdgpu_device *adev = to_amdgpu_device(control);
524 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
525 	u8 *buf, *pp, csum;
526 	u32 buf_size;
527 	int res;
528 
529 	/* Modify the header if it exceeds.
530 	 */
531 	if (amdgpu_bad_page_threshold != 0 &&
532 	    control->ras_num_recs >= ras->bad_page_cnt_threshold) {
533 		dev_warn(adev->dev,
534 			"Saved bad pages %d reaches threshold value %d\n",
535 			control->ras_num_recs, ras->bad_page_cnt_threshold);
536 		control->tbl_hdr.header = RAS_TABLE_HDR_BAD;
537 	}
538 
539 	control->tbl_hdr.version = RAS_TABLE_VER;
540 	control->tbl_hdr.first_rec_offset = RAS_INDEX_TO_OFFSET(control, control->ras_fri);
541 	control->tbl_hdr.tbl_size = RAS_TABLE_HEADER_SIZE + control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
542 	control->tbl_hdr.checksum = 0;
543 
544 	buf_size = control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
545 	buf = kcalloc(control->ras_num_recs, RAS_TABLE_RECORD_SIZE, GFP_KERNEL);
546 	if (!buf) {
547 		DRM_ERROR("allocating memory for table of size %d bytes failed\n",
548 			  control->tbl_hdr.tbl_size);
549 		res = -ENOMEM;
550 		goto Out;
551 	}
552 
553 	down_read(&adev->reset_sem);
554 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
555 				 control->i2c_address +
556 				 control->ras_record_offset,
557 				 buf, buf_size);
558 	up_read(&adev->reset_sem);
559 	if (res < 0) {
560 		DRM_ERROR("EEPROM failed reading records:%d\n",
561 			  res);
562 		goto Out;
563 	} else if (res < buf_size) {
564 		DRM_ERROR("EEPROM read %d out of %d bytes\n",
565 			  res, buf_size);
566 		res = -EIO;
567 		goto Out;
568 	}
569 
570 	/* Recalc the checksum.
571 	 */
572 	csum = 0;
573 	for (pp = buf; pp < buf + buf_size; pp++)
574 		csum += *pp;
575 
576 	csum += __calc_hdr_byte_sum(control);
577 	/* avoid sign extension when assigning to "checksum" */
578 	csum = -csum;
579 	control->tbl_hdr.checksum = csum;
580 	res = __write_table_header(control);
581 Out:
582 	kfree(buf);
583 	return res;
584 }
585 
586 /**
587  * amdgpu_ras_eeprom_append -- append records to the EEPROM RAS table
588  * @control: pointer to control structure
589  * @record: array of records to append
590  * @num: number of records in @record array
591  *
592  * Append @num records to the table, calculate the checksum and write
593  * the table back to EEPROM. The maximum number of records that
594  * can be appended is between 1 and control->ras_max_record_count,
595  * regardless of how many records are already stored in the table.
596  *
597  * Return 0 on success or if EEPROM is not supported, -errno on error.
598  */
599 int amdgpu_ras_eeprom_append(struct amdgpu_ras_eeprom_control *control,
600 			     struct eeprom_table_record *record,
601 			     const u32 num)
602 {
603 	struct amdgpu_device *adev = to_amdgpu_device(control);
604 	int res;
605 
606 	if (!__is_ras_eeprom_supported(adev))
607 		return 0;
608 
609 	if (num == 0) {
610 		DRM_ERROR("will not append 0 records\n");
611 		return -EINVAL;
612 	} else if (num > control->ras_max_record_count) {
613 		DRM_ERROR("cannot append %d records than the size of table %d\n",
614 			  num, control->ras_max_record_count);
615 		return -EINVAL;
616 	}
617 
618 	mutex_lock(&control->ras_tbl_mutex);
619 
620 	res = amdgpu_ras_eeprom_append_table(control, record, num);
621 	if (!res)
622 		res = amdgpu_ras_eeprom_update_header(control);
623 	if (!res)
624 		amdgpu_ras_debugfs_set_ret_size(control);
625 
626 	mutex_unlock(&control->ras_tbl_mutex);
627 	return res;
628 }
629 
630 /**
631  * __amdgpu_ras_eeprom_read -- read indexed from EEPROM into buffer
632  * @control: pointer to control structure
633  * @buf: pointer to buffer to read into
634  * @fri: first record index, start reading at this index, absolute index
635  * @num: number of records to read
636  *
637  * The caller must hold the table mutex in @control.
638  * Return 0 on success, -errno otherwise.
639  */
640 static int __amdgpu_ras_eeprom_read(struct amdgpu_ras_eeprom_control *control,
641 				    u8 *buf, const u32 fri, const u32 num)
642 {
643 	struct amdgpu_device *adev = to_amdgpu_device(control);
644 	u32 buf_size;
645 	int res;
646 
647 	/* i2c may be unstable in gpu reset */
648 	down_read(&adev->reset_sem);
649 	buf_size = num * RAS_TABLE_RECORD_SIZE;
650 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
651 				 control->i2c_address +
652 				 RAS_INDEX_TO_OFFSET(control, fri),
653 				 buf, buf_size);
654 	up_read(&adev->reset_sem);
655 	if (res < 0) {
656 		DRM_ERROR("Reading %d EEPROM table records error:%d",
657 			  num, res);
658 	} else if (res < buf_size) {
659 		/* Short read, return error.
660 		 */
661 		DRM_ERROR("Read %d records out of %d",
662 			  res / RAS_TABLE_RECORD_SIZE, num);
663 		res = -EIO;
664 	} else {
665 		res = 0;
666 	}
667 
668 	return res;
669 }
670 
671 /**
672  * amdgpu_ras_eeprom_read -- read EEPROM
673  * @control: pointer to control structure
674  * @record: array of records to read into
675  * @num: number of records in @record
676  *
677  * Reads num records from the RAS table in EEPROM and
678  * writes the data into @record array.
679  *
680  * Returns 0 on success, -errno on error.
681  */
682 int amdgpu_ras_eeprom_read(struct amdgpu_ras_eeprom_control *control,
683 			   struct eeprom_table_record *record,
684 			   const u32 num)
685 {
686 	struct amdgpu_device *adev = to_amdgpu_device(control);
687 	int i, res;
688 	u8 *buf, *pp;
689 	u32 g0, g1;
690 
691 	if (!__is_ras_eeprom_supported(adev))
692 		return 0;
693 
694 	if (num == 0) {
695 		DRM_ERROR("will not read 0 records\n");
696 		return -EINVAL;
697 	} else if (num > control->ras_num_recs) {
698 		DRM_ERROR("too many records to read:%d available:%d\n",
699 			  num, control->ras_num_recs);
700 		return -EINVAL;
701 	}
702 
703 	buf = kcalloc(num, RAS_TABLE_RECORD_SIZE, GFP_KERNEL);
704 	if (!buf)
705 		return -ENOMEM;
706 
707 	/* Determine how many records to read, from the first record
708 	 * index, fri, to the end of the table, and from the beginning
709 	 * of the table, such that the total number of records is
710 	 * @num, and we handle wrap around when fri > 0 and
711 	 * fri + num > RAS_MAX_RECORD_COUNT.
712 	 *
713 	 * First we compute the index of the last element
714 	 * which would be fetched from each region,
715 	 * g0 is in [fri, fri + num - 1], and
716 	 * g1 is in [0, RAS_MAX_RECORD_COUNT - 1].
717 	 * Then, if g0 < RAS_MAX_RECORD_COUNT, the index of
718 	 * the last element to fetch, we set g0 to _the number_
719 	 * of elements to fetch, @num, since we know that the last
720 	 * indexed to be fetched does not exceed the table.
721 	 *
722 	 * If, however, g0 >= RAS_MAX_RECORD_COUNT, then
723 	 * we set g0 to the number of elements to read
724 	 * until the end of the table, and g1 to the number of
725 	 * elements to read from the beginning of the table.
726 	 */
727 	g0 = control->ras_fri + num - 1;
728 	g1 = g0 % control->ras_max_record_count;
729 	if (g0 < control->ras_max_record_count) {
730 		g0 = num;
731 		g1 = 0;
732 	} else {
733 		g0 = control->ras_max_record_count - control->ras_fri;
734 		g1 += 1;
735 	}
736 
737 	mutex_lock(&control->ras_tbl_mutex);
738 	res = __amdgpu_ras_eeprom_read(control, buf, control->ras_fri, g0);
739 	if (res)
740 		goto Out;
741 	if (g1) {
742 		res = __amdgpu_ras_eeprom_read(control,
743 					       buf + g0 * RAS_TABLE_RECORD_SIZE,
744 					       0, g1);
745 		if (res)
746 			goto Out;
747 	}
748 
749 	res = 0;
750 
751 	/* Read up everything? Then transform.
752 	 */
753 	pp = buf;
754 	for (i = 0; i < num; i++, pp += RAS_TABLE_RECORD_SIZE)
755 		__decode_table_record_from_buf(control, &record[i], pp);
756 Out:
757 	kfree(buf);
758 	mutex_unlock(&control->ras_tbl_mutex);
759 
760 	return res;
761 }
762 
763 uint32_t amdgpu_ras_eeprom_max_record_count(void)
764 {
765 	return RAS_MAX_RECORD_COUNT;
766 }
767 
768 static ssize_t
769 amdgpu_ras_debugfs_eeprom_size_read(struct file *f, char __user *buf,
770 				    size_t size, loff_t *pos)
771 {
772 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
773 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
774 	struct amdgpu_ras_eeprom_control *control = ras ? &ras->eeprom_control : NULL;
775 	u8 data[50];
776 	int res;
777 
778 	if (!size)
779 		return size;
780 
781 	if (!ras || !control) {
782 		res = snprintf(data, sizeof(data), "Not supported\n");
783 	} else {
784 		res = snprintf(data, sizeof(data), "%d bytes or %d records\n",
785 			       RAS_TBL_SIZE_BYTES, control->ras_max_record_count);
786 	}
787 
788 	if (*pos >= res)
789 		return 0;
790 
791 	res -= *pos;
792 	res = min_t(size_t, res, size);
793 
794 	if (copy_to_user(buf, &data[*pos], res))
795 		return -EFAULT;
796 
797 	*pos += res;
798 
799 	return res;
800 }
801 
802 const struct file_operations amdgpu_ras_debugfs_eeprom_size_ops = {
803 	.owner = THIS_MODULE,
804 	.read = amdgpu_ras_debugfs_eeprom_size_read,
805 	.write = NULL,
806 	.llseek = default_llseek,
807 };
808 
809 static const char *tbl_hdr_str = " Signature    Version  FirstOffs       Size   Checksum\n";
810 static const char *tbl_hdr_fmt = "0x%08X 0x%08X 0x%08X 0x%08X 0x%08X\n";
811 #define tbl_hdr_fmt_size (5 * (2+8) + 4 + 1)
812 static const char *rec_hdr_str = "Index  Offset ErrType Bank/CU          TimeStamp      Offs/Addr MemChl MCUMCID    RetiredPage\n";
813 static const char *rec_hdr_fmt = "%5d 0x%05X %7s    0x%02X 0x%016llX 0x%012llX   0x%02X    0x%02X 0x%012llX\n";
814 #define rec_hdr_fmt_size (5 + 1 + 7 + 1 + 7 + 1 + 7 + 1 + 18 + 1 + 14 + 1 + 6 + 1 + 7 + 1 + 14 + 1)
815 
816 static const char *record_err_type_str[AMDGPU_RAS_EEPROM_ERR_COUNT] = {
817 	"ignore",
818 	"re",
819 	"ue",
820 };
821 
822 static loff_t amdgpu_ras_debugfs_table_size(struct amdgpu_ras_eeprom_control *control)
823 {
824 	return strlen(tbl_hdr_str) + tbl_hdr_fmt_size +
825 		strlen(rec_hdr_str) + rec_hdr_fmt_size * control->ras_num_recs;
826 }
827 
828 void amdgpu_ras_debugfs_set_ret_size(struct amdgpu_ras_eeprom_control *control)
829 {
830 	struct amdgpu_ras *ras = container_of(control, struct amdgpu_ras,
831 					      eeprom_control);
832 	struct dentry *de = ras->de_ras_eeprom_table;
833 
834 	if (de)
835 		d_inode(de)->i_size = amdgpu_ras_debugfs_table_size(control);
836 }
837 
838 static ssize_t amdgpu_ras_debugfs_table_read(struct file *f, char __user *buf,
839 					     size_t size, loff_t *pos)
840 {
841 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
842 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
843 	struct amdgpu_ras_eeprom_control *control = &ras->eeprom_control;
844 	const size_t orig_size = size;
845 	int res = -EFAULT;
846 	size_t data_len;
847 
848 	mutex_lock(&control->ras_tbl_mutex);
849 
850 	/* We want *pos - data_len > 0, which means there's
851 	 * bytes to be printed from data.
852 	 */
853 	data_len = strlen(tbl_hdr_str);
854 	if (*pos < data_len) {
855 		data_len -= *pos;
856 		data_len = min_t(size_t, data_len, size);
857 		if (copy_to_user(buf, &tbl_hdr_str[*pos], data_len))
858 			goto Out;
859 		buf += data_len;
860 		size -= data_len;
861 		*pos += data_len;
862 	}
863 
864 	data_len = strlen(tbl_hdr_str) + tbl_hdr_fmt_size;
865 	if (*pos < data_len && size > 0) {
866 		u8 data[tbl_hdr_fmt_size + 1];
867 		loff_t lpos;
868 
869 		snprintf(data, sizeof(data), tbl_hdr_fmt,
870 			 control->tbl_hdr.header,
871 			 control->tbl_hdr.version,
872 			 control->tbl_hdr.first_rec_offset,
873 			 control->tbl_hdr.tbl_size,
874 			 control->tbl_hdr.checksum);
875 
876 		data_len -= *pos;
877 		data_len = min_t(size_t, data_len, size);
878 		lpos = *pos - strlen(tbl_hdr_str);
879 		if (copy_to_user(buf, &data[lpos], data_len))
880 			goto Out;
881 		buf += data_len;
882 		size -= data_len;
883 		*pos += data_len;
884 	}
885 
886 	data_len = strlen(tbl_hdr_str) + tbl_hdr_fmt_size + strlen(rec_hdr_str);
887 	if (*pos < data_len && size > 0) {
888 		loff_t lpos;
889 
890 		data_len -= *pos;
891 		data_len = min_t(size_t, data_len, size);
892 		lpos = *pos - strlen(tbl_hdr_str) - tbl_hdr_fmt_size;
893 		if (copy_to_user(buf, &rec_hdr_str[lpos], data_len))
894 			goto Out;
895 		buf += data_len;
896 		size -= data_len;
897 		*pos += data_len;
898 	}
899 
900 	data_len = amdgpu_ras_debugfs_table_size(control);
901 	if (*pos < data_len && size > 0) {
902 		u8 dare[RAS_TABLE_RECORD_SIZE];
903 		u8 data[rec_hdr_fmt_size + 1];
904 		struct eeprom_table_record record;
905 		int s, r;
906 
907 		/* Find the starting record index
908 		 */
909 		s = *pos - strlen(tbl_hdr_str) - tbl_hdr_fmt_size -
910 			strlen(rec_hdr_str);
911 		s = s / rec_hdr_fmt_size;
912 		r = *pos - strlen(tbl_hdr_str) - tbl_hdr_fmt_size -
913 			strlen(rec_hdr_str);
914 		r = r % rec_hdr_fmt_size;
915 
916 		for ( ; size > 0 && s < control->ras_num_recs; s++) {
917 			u32 ai = RAS_RI_TO_AI(control, s);
918 			/* Read a single record
919 			 */
920 			res = __amdgpu_ras_eeprom_read(control, dare, ai, 1);
921 			if (res)
922 				goto Out;
923 			__decode_table_record_from_buf(control, &record, dare);
924 			snprintf(data, sizeof(data), rec_hdr_fmt,
925 				 s,
926 				 RAS_INDEX_TO_OFFSET(control, ai),
927 				 record_err_type_str[record.err_type],
928 				 record.bank,
929 				 record.ts,
930 				 record.offset,
931 				 record.mem_channel,
932 				 record.mcumc_id,
933 				 record.retired_page);
934 
935 			data_len = min_t(size_t, rec_hdr_fmt_size - r, size);
936 			if (copy_to_user(buf, &data[r], data_len)) {
937 				res = -EFAULT;
938 				goto Out;
939 			}
940 			buf += data_len;
941 			size -= data_len;
942 			*pos += data_len;
943 			r = 0;
944 		}
945 	}
946 	res = 0;
947 Out:
948 	mutex_unlock(&control->ras_tbl_mutex);
949 	return res < 0 ? res : orig_size - size;
950 }
951 
952 static ssize_t
953 amdgpu_ras_debugfs_eeprom_table_read(struct file *f, char __user *buf,
954 				     size_t size, loff_t *pos)
955 {
956 	struct amdgpu_device *adev = (struct amdgpu_device *)file_inode(f)->i_private;
957 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
958 	struct amdgpu_ras_eeprom_control *control = ras ? &ras->eeprom_control : NULL;
959 	u8 data[81];
960 	int res;
961 
962 	if (!size)
963 		return size;
964 
965 	if (!ras || !control) {
966 		res = snprintf(data, sizeof(data), "Not supported\n");
967 		if (*pos >= res)
968 			return 0;
969 
970 		res -= *pos;
971 		res = min_t(size_t, res, size);
972 
973 		if (copy_to_user(buf, &data[*pos], res))
974 			return -EFAULT;
975 
976 		*pos += res;
977 
978 		return res;
979 	} else {
980 		return amdgpu_ras_debugfs_table_read(f, buf, size, pos);
981 	}
982 }
983 
984 const struct file_operations amdgpu_ras_debugfs_eeprom_table_ops = {
985 	.owner = THIS_MODULE,
986 	.read = amdgpu_ras_debugfs_eeprom_table_read,
987 	.write = NULL,
988 	.llseek = default_llseek,
989 };
990 
991 /**
992  * __verify_ras_table_checksum -- verify the RAS EEPROM table checksum
993  * @control: pointer to control structure
994  *
995  * Check the checksum of the stored in EEPROM RAS table.
996  *
997  * Return 0 if the checksum is correct,
998  * positive if it is not correct, and
999  * -errno on I/O error.
1000  */
1001 static int __verify_ras_table_checksum(struct amdgpu_ras_eeprom_control *control)
1002 {
1003 	struct amdgpu_device *adev = to_amdgpu_device(control);
1004 	int buf_size, res;
1005 	u8  csum, *buf, *pp;
1006 
1007 	buf_size = RAS_TABLE_HEADER_SIZE +
1008 		control->ras_num_recs * RAS_TABLE_RECORD_SIZE;
1009 	buf = kzalloc(buf_size, GFP_KERNEL);
1010 	if (!buf) {
1011 		DRM_ERROR("Out of memory checking RAS table checksum.\n");
1012 		return -ENOMEM;
1013 	}
1014 
1015 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
1016 				 control->i2c_address +
1017 				 control->ras_header_offset,
1018 				 buf, buf_size);
1019 	if (res < buf_size) {
1020 		DRM_ERROR("Partial read for checksum, res:%d\n", res);
1021 		/* On partial reads, return -EIO.
1022 		 */
1023 		if (res >= 0)
1024 			res = -EIO;
1025 		goto Out;
1026 	}
1027 
1028 	csum = 0;
1029 	for (pp = buf; pp < buf + buf_size; pp++)
1030 		csum += *pp;
1031 Out:
1032 	kfree(buf);
1033 	return res < 0 ? res : csum;
1034 }
1035 
1036 int amdgpu_ras_eeprom_init(struct amdgpu_ras_eeprom_control *control,
1037 			   bool *exceed_err_limit)
1038 {
1039 	struct amdgpu_device *adev = to_amdgpu_device(control);
1040 	unsigned char buf[RAS_TABLE_HEADER_SIZE] = { 0 };
1041 	struct amdgpu_ras_eeprom_table_header *hdr = &control->tbl_hdr;
1042 	struct amdgpu_ras *ras = amdgpu_ras_get_context(adev);
1043 	int res;
1044 
1045 	*exceed_err_limit = false;
1046 
1047 	if (!__is_ras_eeprom_supported(adev))
1048 		return 0;
1049 
1050 	/* Verify i2c adapter is initialized */
1051 	if (!adev->pm.ras_eeprom_i2c_bus || !adev->pm.ras_eeprom_i2c_bus->algo)
1052 		return -ENOENT;
1053 
1054 	if (!__get_eeprom_i2c_addr(adev, control))
1055 		return -EINVAL;
1056 
1057 	control->ras_header_offset = RAS_HDR_START;
1058 	control->ras_record_offset = RAS_RECORD_START;
1059 	control->ras_max_record_count  = RAS_MAX_RECORD_COUNT;
1060 	mutex_init(&control->ras_tbl_mutex);
1061 
1062 	/* Read the table header from EEPROM address */
1063 	res = amdgpu_eeprom_read(adev->pm.ras_eeprom_i2c_bus,
1064 				 control->i2c_address + control->ras_header_offset,
1065 				 buf, RAS_TABLE_HEADER_SIZE);
1066 	if (res < RAS_TABLE_HEADER_SIZE) {
1067 		DRM_ERROR("Failed to read EEPROM table header, res:%d", res);
1068 		return res >= 0 ? -EIO : res;
1069 	}
1070 
1071 	__decode_table_header_from_buf(hdr, buf);
1072 
1073 	control->ras_num_recs = RAS_NUM_RECS(hdr);
1074 	control->ras_fri = RAS_OFFSET_TO_INDEX(control, hdr->first_rec_offset);
1075 
1076 	if (hdr->header == RAS_TABLE_HDR_VAL) {
1077 		DRM_DEBUG_DRIVER("Found existing EEPROM table with %d records",
1078 				 control->ras_num_recs);
1079 		res = __verify_ras_table_checksum(control);
1080 		if (res)
1081 			DRM_ERROR("RAS table incorrect checksum or error:%d\n",
1082 				  res);
1083 
1084 		/* Warn if we are at 90% of the threshold or above
1085 		 */
1086 		if (10 * control->ras_num_recs >= 9 * ras->bad_page_cnt_threshold)
1087 			dev_warn(adev->dev, "RAS records:%u exceeds 90%% of threshold:%d",
1088 					control->ras_num_recs,
1089 					ras->bad_page_cnt_threshold);
1090 	} else if (hdr->header == RAS_TABLE_HDR_BAD &&
1091 		   amdgpu_bad_page_threshold != 0) {
1092 		res = __verify_ras_table_checksum(control);
1093 		if (res)
1094 			DRM_ERROR("RAS Table incorrect checksum or error:%d\n",
1095 				  res);
1096 		if (ras->bad_page_cnt_threshold > control->ras_num_recs) {
1097 			/* This means that, the threshold was increased since
1098 			 * the last time the system was booted, and now,
1099 			 * ras->bad_page_cnt_threshold - control->num_recs > 0,
1100 			 * so that at least one more record can be saved,
1101 			 * before the page count threshold is reached.
1102 			 */
1103 			dev_info(adev->dev,
1104 				 "records:%d threshold:%d, resetting "
1105 				 "RAS table header signature",
1106 				 control->ras_num_recs,
1107 				 ras->bad_page_cnt_threshold);
1108 			res = amdgpu_ras_eeprom_correct_header_tag(control,
1109 								   RAS_TABLE_HDR_VAL);
1110 		} else {
1111 			dev_err(adev->dev, "RAS records:%d exceed threshold:%d",
1112 				control->ras_num_recs, ras->bad_page_cnt_threshold);
1113 			if (amdgpu_bad_page_threshold == -2) {
1114 				dev_warn(adev->dev, "GPU will be initialized due to bad_page_threshold = -2.");
1115 				res = 0;
1116 			} else {
1117 				*exceed_err_limit = true;
1118 				dev_err(adev->dev,
1119 					"RAS records:%d exceed threshold:%d, "
1120 					"GPU will not be initialized. Replace this GPU or increase the threshold",
1121 					control->ras_num_recs, ras->bad_page_cnt_threshold);
1122 			}
1123 		}
1124 	} else {
1125 		DRM_INFO("Creating a new EEPROM table");
1126 
1127 		res = amdgpu_ras_eeprom_reset_table(control);
1128 	}
1129 
1130 	return res < 0 ? res : 0;
1131 }
1132