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