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