GNU Linux-libre 5.10.217-gnu1
[releases.git] / arch / powerpc / platforms / pseries / papr_scm.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #define pr_fmt(fmt)     "papr-scm: " fmt
4
5 #include <linux/of.h>
6 #include <linux/kernel.h>
7 #include <linux/module.h>
8 #include <linux/ioport.h>
9 #include <linux/slab.h>
10 #include <linux/ndctl.h>
11 #include <linux/sched.h>
12 #include <linux/libnvdimm.h>
13 #include <linux/platform_device.h>
14 #include <linux/delay.h>
15 #include <linux/seq_buf.h>
16 #include <linux/nd.h>
17
18 #include <asm/plpar_wrappers.h>
19 #include <asm/papr_pdsm.h>
20 #include <asm/mce.h>
21 #include <asm/unaligned.h>
22
23 #define BIND_ANY_ADDR (~0ul)
24
25 #define PAPR_SCM_DIMM_CMD_MASK \
26         ((1ul << ND_CMD_GET_CONFIG_SIZE) | \
27          (1ul << ND_CMD_GET_CONFIG_DATA) | \
28          (1ul << ND_CMD_SET_CONFIG_DATA) | \
29          (1ul << ND_CMD_CALL))
30
31 /* DIMM health bitmap bitmap indicators */
32 /* SCM device is unable to persist memory contents */
33 #define PAPR_PMEM_UNARMED                   (1ULL << (63 - 0))
34 /* SCM device failed to persist memory contents */
35 #define PAPR_PMEM_SHUTDOWN_DIRTY            (1ULL << (63 - 1))
36 /* SCM device contents are persisted from previous IPL */
37 #define PAPR_PMEM_SHUTDOWN_CLEAN            (1ULL << (63 - 2))
38 /* SCM device contents are not persisted from previous IPL */
39 #define PAPR_PMEM_EMPTY                     (1ULL << (63 - 3))
40 /* SCM device memory life remaining is critically low */
41 #define PAPR_PMEM_HEALTH_CRITICAL           (1ULL << (63 - 4))
42 /* SCM device will be garded off next IPL due to failure */
43 #define PAPR_PMEM_HEALTH_FATAL              (1ULL << (63 - 5))
44 /* SCM contents cannot persist due to current platform health status */
45 #define PAPR_PMEM_HEALTH_UNHEALTHY          (1ULL << (63 - 6))
46 /* SCM device is unable to persist memory contents in certain conditions */
47 #define PAPR_PMEM_HEALTH_NON_CRITICAL       (1ULL << (63 - 7))
48 /* SCM device is encrypted */
49 #define PAPR_PMEM_ENCRYPTED                 (1ULL << (63 - 8))
50 /* SCM device has been scrubbed and locked */
51 #define PAPR_PMEM_SCRUBBED_AND_LOCKED       (1ULL << (63 - 9))
52
53 /* Bits status indicators for health bitmap indicating unarmed dimm */
54 #define PAPR_PMEM_UNARMED_MASK (PAPR_PMEM_UNARMED |             \
55                                 PAPR_PMEM_HEALTH_UNHEALTHY)
56
57 /* Bits status indicators for health bitmap indicating unflushed dimm */
58 #define PAPR_PMEM_BAD_SHUTDOWN_MASK (PAPR_PMEM_SHUTDOWN_DIRTY)
59
60 /* Bits status indicators for health bitmap indicating unrestored dimm */
61 #define PAPR_PMEM_BAD_RESTORE_MASK  (PAPR_PMEM_EMPTY)
62
63 /* Bit status indicators for smart event notification */
64 #define PAPR_PMEM_SMART_EVENT_MASK (PAPR_PMEM_HEALTH_CRITICAL | \
65                                     PAPR_PMEM_HEALTH_FATAL |    \
66                                     PAPR_PMEM_HEALTH_UNHEALTHY)
67
68 #define PAPR_SCM_PERF_STATS_EYECATCHER __stringify(SCMSTATS)
69 #define PAPR_SCM_PERF_STATS_VERSION 0x1
70
71 /* Struct holding a single performance metric */
72 struct papr_scm_perf_stat {
73         u8 stat_id[8];
74         __be64 stat_val;
75 } __packed;
76
77 /* Struct exchanged between kernel and PHYP for fetching drc perf stats */
78 struct papr_scm_perf_stats {
79         u8 eye_catcher[8];
80         /* Should be PAPR_SCM_PERF_STATS_VERSION */
81         __be32 stats_version;
82         /* Number of stats following */
83         __be32 num_statistics;
84         /* zero or more performance matrics */
85         struct papr_scm_perf_stat scm_statistic[];
86 } __packed;
87
88 /* private struct associated with each region */
89 struct papr_scm_priv {
90         struct platform_device *pdev;
91         struct device_node *dn;
92         uint32_t drc_index;
93         uint64_t blocks;
94         uint64_t block_size;
95         int metadata_size;
96         bool is_volatile;
97
98         uint64_t bound_addr;
99
100         struct nvdimm_bus_descriptor bus_desc;
101         struct nvdimm_bus *bus;
102         struct nvdimm *nvdimm;
103         struct resource res;
104         struct nd_region *region;
105         struct nd_interleave_set nd_set;
106         struct list_head region_list;
107
108         /* Protect dimm health data from concurrent read/writes */
109         struct mutex health_mutex;
110
111         /* Last time the health information of the dimm was updated */
112         unsigned long lasthealth_jiffies;
113
114         /* Health information for the dimm */
115         u64 health_bitmap;
116
117         /* length of the stat buffer as expected by phyp */
118         size_t stat_buffer_len;
119 };
120
121 static LIST_HEAD(papr_nd_regions);
122 static DEFINE_MUTEX(papr_ndr_lock);
123
124 static int drc_pmem_bind(struct papr_scm_priv *p)
125 {
126         unsigned long ret[PLPAR_HCALL_BUFSIZE];
127         uint64_t saved = 0;
128         uint64_t token;
129         int64_t rc;
130
131         /*
132          * When the hypervisor cannot map all the requested memory in a single
133          * hcall it returns H_BUSY and we call again with the token until
134          * we get H_SUCCESS. Aborting the retry loop before getting H_SUCCESS
135          * leave the system in an undefined state, so we wait.
136          */
137         token = 0;
138
139         do {
140                 rc = plpar_hcall(H_SCM_BIND_MEM, ret, p->drc_index, 0,
141                                 p->blocks, BIND_ANY_ADDR, token);
142                 token = ret[0];
143                 if (!saved)
144                         saved = ret[1];
145                 cond_resched();
146         } while (rc == H_BUSY);
147
148         if (rc)
149                 return rc;
150
151         p->bound_addr = saved;
152         dev_dbg(&p->pdev->dev, "bound drc 0x%x to 0x%lx\n",
153                 p->drc_index, (unsigned long)saved);
154         return rc;
155 }
156
157 static void drc_pmem_unbind(struct papr_scm_priv *p)
158 {
159         unsigned long ret[PLPAR_HCALL_BUFSIZE];
160         uint64_t token = 0;
161         int64_t rc;
162
163         dev_dbg(&p->pdev->dev, "unbind drc 0x%x\n", p->drc_index);
164
165         /* NB: unbind has the same retry requirements as drc_pmem_bind() */
166         do {
167
168                 /* Unbind of all SCM resources associated with drcIndex */
169                 rc = plpar_hcall(H_SCM_UNBIND_ALL, ret, H_UNBIND_SCOPE_DRC,
170                                  p->drc_index, token);
171                 token = ret[0];
172
173                 /* Check if we are stalled for some time */
174                 if (H_IS_LONG_BUSY(rc)) {
175                         msleep(get_longbusy_msecs(rc));
176                         rc = H_BUSY;
177                 } else if (rc == H_BUSY) {
178                         cond_resched();
179                 }
180
181         } while (rc == H_BUSY);
182
183         if (rc)
184                 dev_err(&p->pdev->dev, "unbind error: %lld\n", rc);
185         else
186                 dev_dbg(&p->pdev->dev, "unbind drc 0x%x complete\n",
187                         p->drc_index);
188
189         return;
190 }
191
192 static int drc_pmem_query_n_bind(struct papr_scm_priv *p)
193 {
194         unsigned long start_addr;
195         unsigned long end_addr;
196         unsigned long ret[PLPAR_HCALL_BUFSIZE];
197         int64_t rc;
198
199
200         rc = plpar_hcall(H_SCM_QUERY_BLOCK_MEM_BINDING, ret,
201                          p->drc_index, 0);
202         if (rc)
203                 goto err_out;
204         start_addr = ret[0];
205
206         /* Make sure the full region is bound. */
207         rc = plpar_hcall(H_SCM_QUERY_BLOCK_MEM_BINDING, ret,
208                          p->drc_index, p->blocks - 1);
209         if (rc)
210                 goto err_out;
211         end_addr = ret[0];
212
213         if ((end_addr - start_addr) != ((p->blocks - 1) * p->block_size))
214                 goto err_out;
215
216         p->bound_addr = start_addr;
217         dev_dbg(&p->pdev->dev, "bound drc 0x%x to 0x%lx\n", p->drc_index, start_addr);
218         return rc;
219
220 err_out:
221         dev_info(&p->pdev->dev,
222                  "Failed to query, trying an unbind followed by bind");
223         drc_pmem_unbind(p);
224         return drc_pmem_bind(p);
225 }
226
227 /*
228  * Query the Dimm performance stats from PHYP and copy them (if returned) to
229  * provided struct papr_scm_perf_stats instance 'stats' that can hold atleast
230  * (num_stats + header) bytes.
231  * - If buff_stats == NULL the return value is the size in byes of the buffer
232  * needed to hold all supported performance-statistics.
233  * - If buff_stats != NULL and num_stats == 0 then we copy all known
234  * performance-statistics to 'buff_stat' and expect to be large enough to
235  * hold them.
236  * - if buff_stats != NULL and num_stats > 0 then copy the requested
237  * performance-statistics to buff_stats.
238  */
239 static ssize_t drc_pmem_query_stats(struct papr_scm_priv *p,
240                                     struct papr_scm_perf_stats *buff_stats,
241                                     unsigned int num_stats)
242 {
243         unsigned long ret[PLPAR_HCALL_BUFSIZE];
244         size_t size;
245         s64 rc;
246
247         /* Setup the out buffer */
248         if (buff_stats) {
249                 memcpy(buff_stats->eye_catcher,
250                        PAPR_SCM_PERF_STATS_EYECATCHER, 8);
251                 buff_stats->stats_version =
252                         cpu_to_be32(PAPR_SCM_PERF_STATS_VERSION);
253                 buff_stats->num_statistics =
254                         cpu_to_be32(num_stats);
255
256                 /*
257                  * Calculate the buffer size based on num-stats provided
258                  * or use the prefetched max buffer length
259                  */
260                 if (num_stats)
261                         /* Calculate size from the num_stats */
262                         size = sizeof(struct papr_scm_perf_stats) +
263                                 num_stats * sizeof(struct papr_scm_perf_stat);
264                 else
265                         size = p->stat_buffer_len;
266         } else {
267                 /* In case of no out buffer ignore the size */
268                 size = 0;
269         }
270
271         /* Do the HCALL asking PHYP for info */
272         rc = plpar_hcall(H_SCM_PERFORMANCE_STATS, ret, p->drc_index,
273                          buff_stats ? virt_to_phys(buff_stats) : 0,
274                          size);
275
276         /* Check if the error was due to an unknown stat-id */
277         if (rc == H_PARTIAL) {
278                 dev_err(&p->pdev->dev,
279                         "Unknown performance stats, Err:0x%016lX\n", ret[0]);
280                 return -ENOENT;
281         } else if (rc != H_SUCCESS) {
282                 dev_err(&p->pdev->dev,
283                         "Failed to query performance stats, Err:%lld\n", rc);
284                 return -EIO;
285
286         } else if (!size) {
287                 /* Handle case where stat buffer size was requested */
288                 dev_dbg(&p->pdev->dev,
289                         "Performance stats size %ld\n", ret[0]);
290                 return ret[0];
291         }
292
293         /* Successfully fetched the requested stats from phyp */
294         dev_dbg(&p->pdev->dev,
295                 "Performance stats returned %d stats\n",
296                 be32_to_cpu(buff_stats->num_statistics));
297         return 0;
298 }
299
300 /*
301  * Issue hcall to retrieve dimm health info and populate papr_scm_priv with the
302  * health information.
303  */
304 static int __drc_pmem_query_health(struct papr_scm_priv *p)
305 {
306         unsigned long ret[PLPAR_HCALL_BUFSIZE];
307         long rc;
308
309         /* issue the hcall */
310         rc = plpar_hcall(H_SCM_HEALTH, ret, p->drc_index);
311         if (rc != H_SUCCESS) {
312                 dev_err(&p->pdev->dev,
313                         "Failed to query health information, Err:%ld\n", rc);
314                 return -ENXIO;
315         }
316
317         p->lasthealth_jiffies = jiffies;
318         p->health_bitmap = ret[0] & ret[1];
319
320         dev_dbg(&p->pdev->dev,
321                 "Queried dimm health info. Bitmap:0x%016lx Mask:0x%016lx\n",
322                 ret[0], ret[1]);
323
324         return 0;
325 }
326
327 /* Min interval in seconds for assuming stable dimm health */
328 #define MIN_HEALTH_QUERY_INTERVAL 60
329
330 /* Query cached health info and if needed call drc_pmem_query_health */
331 static int drc_pmem_query_health(struct papr_scm_priv *p)
332 {
333         unsigned long cache_timeout;
334         int rc;
335
336         /* Protect concurrent modifications to papr_scm_priv */
337         rc = mutex_lock_interruptible(&p->health_mutex);
338         if (rc)
339                 return rc;
340
341         /* Jiffies offset for which the health data is assumed to be same */
342         cache_timeout = p->lasthealth_jiffies +
343                 msecs_to_jiffies(MIN_HEALTH_QUERY_INTERVAL * 1000);
344
345         /* Fetch new health info is its older than MIN_HEALTH_QUERY_INTERVAL */
346         if (time_after(jiffies, cache_timeout))
347                 rc = __drc_pmem_query_health(p);
348         else
349                 /* Assume cached health data is valid */
350                 rc = 0;
351
352         mutex_unlock(&p->health_mutex);
353         return rc;
354 }
355
356 static int papr_scm_meta_get(struct papr_scm_priv *p,
357                              struct nd_cmd_get_config_data_hdr *hdr)
358 {
359         unsigned long data[PLPAR_HCALL_BUFSIZE];
360         unsigned long offset, data_offset;
361         int len, read;
362         int64_t ret;
363
364         if ((hdr->in_offset + hdr->in_length) > p->metadata_size)
365                 return -EINVAL;
366
367         for (len = hdr->in_length; len; len -= read) {
368
369                 data_offset = hdr->in_length - len;
370                 offset = hdr->in_offset + data_offset;
371
372                 if (len >= 8)
373                         read = 8;
374                 else if (len >= 4)
375                         read = 4;
376                 else if (len >= 2)
377                         read = 2;
378                 else
379                         read = 1;
380
381                 ret = plpar_hcall(H_SCM_READ_METADATA, data, p->drc_index,
382                                   offset, read);
383
384                 if (ret == H_PARAMETER) /* bad DRC index */
385                         return -ENODEV;
386                 if (ret)
387                         return -EINVAL; /* other invalid parameter */
388
389                 switch (read) {
390                 case 8:
391                         *(uint64_t *)(hdr->out_buf + data_offset) = be64_to_cpu(data[0]);
392                         break;
393                 case 4:
394                         *(uint32_t *)(hdr->out_buf + data_offset) = be32_to_cpu(data[0] & 0xffffffff);
395                         break;
396
397                 case 2:
398                         *(uint16_t *)(hdr->out_buf + data_offset) = be16_to_cpu(data[0] & 0xffff);
399                         break;
400
401                 case 1:
402                         *(uint8_t *)(hdr->out_buf + data_offset) = (data[0] & 0xff);
403                         break;
404                 }
405         }
406         return 0;
407 }
408
409 static int papr_scm_meta_set(struct papr_scm_priv *p,
410                              struct nd_cmd_set_config_hdr *hdr)
411 {
412         unsigned long offset, data_offset;
413         int len, wrote;
414         unsigned long data;
415         __be64 data_be;
416         int64_t ret;
417
418         if ((hdr->in_offset + hdr->in_length) > p->metadata_size)
419                 return -EINVAL;
420
421         for (len = hdr->in_length; len; len -= wrote) {
422
423                 data_offset = hdr->in_length - len;
424                 offset = hdr->in_offset + data_offset;
425
426                 if (len >= 8) {
427                         data = *(uint64_t *)(hdr->in_buf + data_offset);
428                         data_be = cpu_to_be64(data);
429                         wrote = 8;
430                 } else if (len >= 4) {
431                         data = *(uint32_t *)(hdr->in_buf + data_offset);
432                         data &= 0xffffffff;
433                         data_be = cpu_to_be32(data);
434                         wrote = 4;
435                 } else if (len >= 2) {
436                         data = *(uint16_t *)(hdr->in_buf + data_offset);
437                         data &= 0xffff;
438                         data_be = cpu_to_be16(data);
439                         wrote = 2;
440                 } else {
441                         data_be = *(uint8_t *)(hdr->in_buf + data_offset);
442                         data_be &= 0xff;
443                         wrote = 1;
444                 }
445
446                 ret = plpar_hcall_norets(H_SCM_WRITE_METADATA, p->drc_index,
447                                          offset, data_be, wrote);
448                 if (ret == H_PARAMETER) /* bad DRC index */
449                         return -ENODEV;
450                 if (ret)
451                         return -EINVAL; /* other invalid parameter */
452         }
453
454         return 0;
455 }
456
457 /*
458  * Do a sanity checks on the inputs args to dimm-control function and return
459  * '0' if valid. Validation of PDSM payloads happens later in
460  * papr_scm_service_pdsm.
461  */
462 static int is_cmd_valid(struct nvdimm *nvdimm, unsigned int cmd, void *buf,
463                         unsigned int buf_len)
464 {
465         unsigned long cmd_mask = PAPR_SCM_DIMM_CMD_MASK;
466         struct nd_cmd_pkg *nd_cmd;
467         struct papr_scm_priv *p;
468         enum papr_pdsm pdsm;
469
470         /* Only dimm-specific calls are supported atm */
471         if (!nvdimm)
472                 return -EINVAL;
473
474         /* get the provider data from struct nvdimm */
475         p = nvdimm_provider_data(nvdimm);
476
477         if (!test_bit(cmd, &cmd_mask)) {
478                 dev_dbg(&p->pdev->dev, "Unsupported cmd=%u\n", cmd);
479                 return -EINVAL;
480         }
481
482         /* For CMD_CALL verify pdsm request */
483         if (cmd == ND_CMD_CALL) {
484                 /* Verify the envelope and envelop size */
485                 if (!buf ||
486                     buf_len < (sizeof(struct nd_cmd_pkg) + ND_PDSM_HDR_SIZE)) {
487                         dev_dbg(&p->pdev->dev, "Invalid pkg size=%u\n",
488                                 buf_len);
489                         return -EINVAL;
490                 }
491
492                 /* Verify that the nd_cmd_pkg.nd_family is correct */
493                 nd_cmd = (struct nd_cmd_pkg *)buf;
494
495                 if (nd_cmd->nd_family != NVDIMM_FAMILY_PAPR) {
496                         dev_dbg(&p->pdev->dev, "Invalid pkg family=0x%llx\n",
497                                 nd_cmd->nd_family);
498                         return -EINVAL;
499                 }
500
501                 pdsm = (enum papr_pdsm)nd_cmd->nd_command;
502
503                 /* Verify if the pdsm command is valid */
504                 if (pdsm <= PAPR_PDSM_MIN || pdsm >= PAPR_PDSM_MAX) {
505                         dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Invalid PDSM\n",
506                                 pdsm);
507                         return -EINVAL;
508                 }
509
510                 /* Have enough space to hold returned 'nd_pkg_pdsm' header */
511                 if (nd_cmd->nd_size_out < ND_PDSM_HDR_SIZE) {
512                         dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Invalid payload\n",
513                                 pdsm);
514                         return -EINVAL;
515                 }
516         }
517
518         /* Let the command be further processed */
519         return 0;
520 }
521
522 static int papr_pdsm_fuel_gauge(struct papr_scm_priv *p,
523                                 union nd_pdsm_payload *payload)
524 {
525         int rc, size;
526         u64 statval;
527         struct papr_scm_perf_stat *stat;
528         struct papr_scm_perf_stats *stats;
529
530         /* Silently fail if fetching performance metrics isn't  supported */
531         if (!p->stat_buffer_len)
532                 return 0;
533
534         /* Allocate request buffer enough to hold single performance stat */
535         size = sizeof(struct papr_scm_perf_stats) +
536                 sizeof(struct papr_scm_perf_stat);
537
538         stats = kzalloc(size, GFP_KERNEL);
539         if (!stats)
540                 return -ENOMEM;
541
542         stat = &stats->scm_statistic[0];
543         memcpy(&stat->stat_id, "MemLife ", sizeof(stat->stat_id));
544         stat->stat_val = 0;
545
546         /* Fetch the fuel gauge and populate it in payload */
547         rc = drc_pmem_query_stats(p, stats, 1);
548         if (rc < 0) {
549                 dev_dbg(&p->pdev->dev, "Err(%d) fetching fuel gauge\n", rc);
550                 goto free_stats;
551         }
552
553         statval = be64_to_cpu(stat->stat_val);
554         dev_dbg(&p->pdev->dev,
555                 "Fetched fuel-gauge %llu", statval);
556         payload->health.extension_flags |=
557                 PDSM_DIMM_HEALTH_RUN_GAUGE_VALID;
558         payload->health.dimm_fuel_gauge = statval;
559
560         rc = sizeof(struct nd_papr_pdsm_health);
561
562 free_stats:
563         kfree(stats);
564         return rc;
565 }
566
567 /* Fetch the DIMM health info and populate it in provided package. */
568 static int papr_pdsm_health(struct papr_scm_priv *p,
569                             union nd_pdsm_payload *payload)
570 {
571         int rc;
572
573         /* Ensure dimm health mutex is taken preventing concurrent access */
574         rc = mutex_lock_interruptible(&p->health_mutex);
575         if (rc)
576                 goto out;
577
578         /* Always fetch upto date dimm health data ignoring cached values */
579         rc = __drc_pmem_query_health(p);
580         if (rc) {
581                 mutex_unlock(&p->health_mutex);
582                 goto out;
583         }
584
585         /* update health struct with various flags derived from health bitmap */
586         payload->health = (struct nd_papr_pdsm_health) {
587                 .extension_flags = 0,
588                 .dimm_unarmed = !!(p->health_bitmap & PAPR_PMEM_UNARMED_MASK),
589                 .dimm_bad_shutdown = !!(p->health_bitmap & PAPR_PMEM_BAD_SHUTDOWN_MASK),
590                 .dimm_bad_restore = !!(p->health_bitmap & PAPR_PMEM_BAD_RESTORE_MASK),
591                 .dimm_scrubbed = !!(p->health_bitmap & PAPR_PMEM_SCRUBBED_AND_LOCKED),
592                 .dimm_locked = !!(p->health_bitmap & PAPR_PMEM_SCRUBBED_AND_LOCKED),
593                 .dimm_encrypted = !!(p->health_bitmap & PAPR_PMEM_ENCRYPTED),
594                 .dimm_health = PAPR_PDSM_DIMM_HEALTHY,
595         };
596
597         /* Update field dimm_health based on health_bitmap flags */
598         if (p->health_bitmap & PAPR_PMEM_HEALTH_FATAL)
599                 payload->health.dimm_health = PAPR_PDSM_DIMM_FATAL;
600         else if (p->health_bitmap & PAPR_PMEM_HEALTH_CRITICAL)
601                 payload->health.dimm_health = PAPR_PDSM_DIMM_CRITICAL;
602         else if (p->health_bitmap & PAPR_PMEM_HEALTH_UNHEALTHY)
603                 payload->health.dimm_health = PAPR_PDSM_DIMM_UNHEALTHY;
604
605         /* struct populated hence can release the mutex now */
606         mutex_unlock(&p->health_mutex);
607
608         /* Populate the fuel gauge meter in the payload */
609         papr_pdsm_fuel_gauge(p, payload);
610
611         rc = sizeof(struct nd_papr_pdsm_health);
612
613 out:
614         return rc;
615 }
616
617 /*
618  * 'struct pdsm_cmd_desc'
619  * Identifies supported PDSMs' expected length of in/out payloads
620  * and pdsm service function.
621  *
622  * size_in      : Size of input payload if any in the PDSM request.
623  * size_out     : Size of output payload if any in the PDSM request.
624  * service      : Service function for the PDSM request. Return semantics:
625  *                rc < 0 : Error servicing PDSM and rc indicates the error.
626  *                rc >=0 : Serviced successfully and 'rc' indicate number of
627  *                      bytes written to payload.
628  */
629 struct pdsm_cmd_desc {
630         u32 size_in;
631         u32 size_out;
632         int (*service)(struct papr_scm_priv *dimm,
633                        union nd_pdsm_payload *payload);
634 };
635
636 /* Holds all supported PDSMs' command descriptors */
637 static const struct pdsm_cmd_desc __pdsm_cmd_descriptors[] = {
638         [PAPR_PDSM_MIN] = {
639                 .size_in = 0,
640                 .size_out = 0,
641                 .service = NULL,
642         },
643         /* New PDSM command descriptors to be added below */
644
645         [PAPR_PDSM_HEALTH] = {
646                 .size_in = 0,
647                 .size_out = sizeof(struct nd_papr_pdsm_health),
648                 .service = papr_pdsm_health,
649         },
650         /* Empty */
651         [PAPR_PDSM_MAX] = {
652                 .size_in = 0,
653                 .size_out = 0,
654                 .service = NULL,
655         },
656 };
657
658 /* Given a valid pdsm cmd return its command descriptor else return NULL */
659 static inline const struct pdsm_cmd_desc *pdsm_cmd_desc(enum papr_pdsm cmd)
660 {
661         if (cmd >= 0 || cmd < ARRAY_SIZE(__pdsm_cmd_descriptors))
662                 return &__pdsm_cmd_descriptors[cmd];
663
664         return NULL;
665 }
666
667 /*
668  * For a given pdsm request call an appropriate service function.
669  * Returns errors if any while handling the pdsm command package.
670  */
671 static int papr_scm_service_pdsm(struct papr_scm_priv *p,
672                                  struct nd_cmd_pkg *pkg)
673 {
674         /* Get the PDSM header and PDSM command */
675         struct nd_pkg_pdsm *pdsm_pkg = (struct nd_pkg_pdsm *)pkg->nd_payload;
676         enum papr_pdsm pdsm = (enum papr_pdsm)pkg->nd_command;
677         const struct pdsm_cmd_desc *pdsc;
678         int rc;
679
680         /* Fetch corresponding pdsm descriptor for validation and servicing */
681         pdsc = pdsm_cmd_desc(pdsm);
682
683         /* Validate pdsm descriptor */
684         /* Ensure that reserved fields are 0 */
685         if (pdsm_pkg->reserved[0] || pdsm_pkg->reserved[1]) {
686                 dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Invalid reserved field\n",
687                         pdsm);
688                 return -EINVAL;
689         }
690
691         /* If pdsm expects some input, then ensure that the size_in matches */
692         if (pdsc->size_in &&
693             pkg->nd_size_in != (pdsc->size_in + ND_PDSM_HDR_SIZE)) {
694                 dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Mismatched size_in=%d\n",
695                         pdsm, pkg->nd_size_in);
696                 return -EINVAL;
697         }
698
699         /* If pdsm wants to return data, then ensure that  size_out matches */
700         if (pdsc->size_out &&
701             pkg->nd_size_out != (pdsc->size_out + ND_PDSM_HDR_SIZE)) {
702                 dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Mismatched size_out=%d\n",
703                         pdsm, pkg->nd_size_out);
704                 return -EINVAL;
705         }
706
707         /* Service the pdsm */
708         if (pdsc->service) {
709                 dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Servicing..\n", pdsm);
710
711                 rc = pdsc->service(p, &pdsm_pkg->payload);
712
713                 if (rc < 0) {
714                         /* error encountered while servicing pdsm */
715                         pdsm_pkg->cmd_status = rc;
716                         pkg->nd_fw_size = ND_PDSM_HDR_SIZE;
717                 } else {
718                         /* pdsm serviced and 'rc' bytes written to payload */
719                         pdsm_pkg->cmd_status = 0;
720                         pkg->nd_fw_size = ND_PDSM_HDR_SIZE + rc;
721                 }
722         } else {
723                 dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Unsupported PDSM request\n",
724                         pdsm);
725                 pdsm_pkg->cmd_status = -ENOENT;
726                 pkg->nd_fw_size = ND_PDSM_HDR_SIZE;
727         }
728
729         return pdsm_pkg->cmd_status;
730 }
731
732 static int papr_scm_ndctl(struct nvdimm_bus_descriptor *nd_desc,
733                           struct nvdimm *nvdimm, unsigned int cmd, void *buf,
734                           unsigned int buf_len, int *cmd_rc)
735 {
736         struct nd_cmd_get_config_size *get_size_hdr;
737         struct nd_cmd_pkg *call_pkg = NULL;
738         struct papr_scm_priv *p;
739         int rc;
740
741         rc = is_cmd_valid(nvdimm, cmd, buf, buf_len);
742         if (rc) {
743                 pr_debug("Invalid cmd=0x%x. Err=%d\n", cmd, rc);
744                 return rc;
745         }
746
747         /* Use a local variable in case cmd_rc pointer is NULL */
748         if (!cmd_rc)
749                 cmd_rc = &rc;
750
751         p = nvdimm_provider_data(nvdimm);
752
753         switch (cmd) {
754         case ND_CMD_GET_CONFIG_SIZE:
755                 get_size_hdr = buf;
756
757                 get_size_hdr->status = 0;
758                 get_size_hdr->max_xfer = 8;
759                 get_size_hdr->config_size = p->metadata_size;
760                 *cmd_rc = 0;
761                 break;
762
763         case ND_CMD_GET_CONFIG_DATA:
764                 *cmd_rc = papr_scm_meta_get(p, buf);
765                 break;
766
767         case ND_CMD_SET_CONFIG_DATA:
768                 *cmd_rc = papr_scm_meta_set(p, buf);
769                 break;
770
771         case ND_CMD_CALL:
772                 call_pkg = (struct nd_cmd_pkg *)buf;
773                 *cmd_rc = papr_scm_service_pdsm(p, call_pkg);
774                 break;
775
776         default:
777                 dev_dbg(&p->pdev->dev, "Unknown command = %d\n", cmd);
778                 return -EINVAL;
779         }
780
781         dev_dbg(&p->pdev->dev, "returned with cmd_rc = %d\n", *cmd_rc);
782
783         return 0;
784 }
785
786 static ssize_t perf_stats_show(struct device *dev,
787                                struct device_attribute *attr, char *buf)
788 {
789         int index;
790         ssize_t rc;
791         struct seq_buf s;
792         struct papr_scm_perf_stat *stat;
793         struct papr_scm_perf_stats *stats;
794         struct nvdimm *dimm = to_nvdimm(dev);
795         struct papr_scm_priv *p = nvdimm_provider_data(dimm);
796
797         if (!p->stat_buffer_len)
798                 return -ENOENT;
799
800         /* Allocate the buffer for phyp where stats are written */
801         stats = kzalloc(p->stat_buffer_len, GFP_KERNEL);
802         if (!stats)
803                 return -ENOMEM;
804
805         /* Ask phyp to return all dimm perf stats */
806         rc = drc_pmem_query_stats(p, stats, 0);
807         if (rc)
808                 goto free_stats;
809         /*
810          * Go through the returned output buffer and print stats and
811          * values. Since stat_id is essentially a char string of
812          * 8 bytes, simply use the string format specifier to print it.
813          */
814         seq_buf_init(&s, buf, PAGE_SIZE);
815         for (index = 0, stat = stats->scm_statistic;
816              index < be32_to_cpu(stats->num_statistics);
817              ++index, ++stat) {
818                 seq_buf_printf(&s, "%.8s = 0x%016llX\n",
819                                stat->stat_id,
820                                be64_to_cpu(stat->stat_val));
821         }
822
823 free_stats:
824         kfree(stats);
825         return rc ? rc : (ssize_t)seq_buf_used(&s);
826 }
827 static DEVICE_ATTR_ADMIN_RO(perf_stats);
828
829 static ssize_t flags_show(struct device *dev,
830                           struct device_attribute *attr, char *buf)
831 {
832         struct nvdimm *dimm = to_nvdimm(dev);
833         struct papr_scm_priv *p = nvdimm_provider_data(dimm);
834         struct seq_buf s;
835         u64 health;
836         int rc;
837
838         rc = drc_pmem_query_health(p);
839         if (rc)
840                 return rc;
841
842         /* Copy health_bitmap locally, check masks & update out buffer */
843         health = READ_ONCE(p->health_bitmap);
844
845         seq_buf_init(&s, buf, PAGE_SIZE);
846         if (health & PAPR_PMEM_UNARMED_MASK)
847                 seq_buf_printf(&s, "not_armed ");
848
849         if (health & PAPR_PMEM_BAD_SHUTDOWN_MASK)
850                 seq_buf_printf(&s, "flush_fail ");
851
852         if (health & PAPR_PMEM_BAD_RESTORE_MASK)
853                 seq_buf_printf(&s, "restore_fail ");
854
855         if (health & PAPR_PMEM_ENCRYPTED)
856                 seq_buf_printf(&s, "encrypted ");
857
858         if (health & PAPR_PMEM_SMART_EVENT_MASK)
859                 seq_buf_printf(&s, "smart_notify ");
860
861         if (health & PAPR_PMEM_SCRUBBED_AND_LOCKED)
862                 seq_buf_printf(&s, "scrubbed locked ");
863
864         if (seq_buf_used(&s))
865                 seq_buf_printf(&s, "\n");
866
867         return seq_buf_used(&s);
868 }
869 DEVICE_ATTR_RO(flags);
870
871 static umode_t papr_nd_attribute_visible(struct kobject *kobj,
872                                          struct attribute *attr, int n)
873 {
874         struct device *dev = kobj_to_dev(kobj);
875         struct nvdimm *nvdimm = to_nvdimm(dev);
876         struct papr_scm_priv *p = nvdimm_provider_data(nvdimm);
877
878         /* For if perf-stats not available remove perf_stats sysfs */
879         if (attr == &dev_attr_perf_stats.attr && p->stat_buffer_len == 0)
880                 return 0;
881
882         return attr->mode;
883 }
884
885 /* papr_scm specific dimm attributes */
886 static struct attribute *papr_nd_attributes[] = {
887         &dev_attr_flags.attr,
888         &dev_attr_perf_stats.attr,
889         NULL,
890 };
891
892 static struct attribute_group papr_nd_attribute_group = {
893         .name = "papr",
894         .is_visible = papr_nd_attribute_visible,
895         .attrs = papr_nd_attributes,
896 };
897
898 static const struct attribute_group *papr_nd_attr_groups[] = {
899         &papr_nd_attribute_group,
900         NULL,
901 };
902
903 static int papr_scm_nvdimm_init(struct papr_scm_priv *p)
904 {
905         struct device *dev = &p->pdev->dev;
906         struct nd_mapping_desc mapping;
907         struct nd_region_desc ndr_desc;
908         unsigned long dimm_flags;
909         int target_nid, online_nid;
910
911         p->bus_desc.ndctl = papr_scm_ndctl;
912         p->bus_desc.module = THIS_MODULE;
913         p->bus_desc.of_node = p->pdev->dev.of_node;
914         p->bus_desc.provider_name = kstrdup(p->pdev->name, GFP_KERNEL);
915
916         /* Set the dimm command family mask to accept PDSMs */
917         set_bit(NVDIMM_FAMILY_PAPR, &p->bus_desc.dimm_family_mask);
918
919         if (!p->bus_desc.provider_name)
920                 return -ENOMEM;
921
922         p->bus = nvdimm_bus_register(NULL, &p->bus_desc);
923         if (!p->bus) {
924                 dev_err(dev, "Error creating nvdimm bus %pOF\n", p->dn);
925                 kfree(p->bus_desc.provider_name);
926                 return -ENXIO;
927         }
928
929         dimm_flags = 0;
930         set_bit(NDD_LABELING, &dimm_flags);
931
932         p->nvdimm = nvdimm_create(p->bus, p, papr_nd_attr_groups,
933                                   dimm_flags, PAPR_SCM_DIMM_CMD_MASK, 0, NULL);
934         if (!p->nvdimm) {
935                 dev_err(dev, "Error creating DIMM object for %pOF\n", p->dn);
936                 goto err;
937         }
938
939         if (nvdimm_bus_check_dimm_count(p->bus, 1))
940                 goto err;
941
942         /* now add the region */
943
944         memset(&mapping, 0, sizeof(mapping));
945         mapping.nvdimm = p->nvdimm;
946         mapping.start = 0;
947         mapping.size = p->blocks * p->block_size; // XXX: potential overflow?
948
949         memset(&ndr_desc, 0, sizeof(ndr_desc));
950         target_nid = dev_to_node(&p->pdev->dev);
951         online_nid = numa_map_to_online_node(target_nid);
952         ndr_desc.numa_node = online_nid;
953         ndr_desc.target_node = target_nid;
954         ndr_desc.res = &p->res;
955         ndr_desc.of_node = p->dn;
956         ndr_desc.provider_data = p;
957         ndr_desc.mapping = &mapping;
958         ndr_desc.num_mappings = 1;
959         ndr_desc.nd_set = &p->nd_set;
960
961         if (p->is_volatile)
962                 p->region = nvdimm_volatile_region_create(p->bus, &ndr_desc);
963         else {
964                 set_bit(ND_REGION_PERSIST_MEMCTRL, &ndr_desc.flags);
965                 p->region = nvdimm_pmem_region_create(p->bus, &ndr_desc);
966         }
967         if (!p->region) {
968                 dev_err(dev, "Error registering region %pR from %pOF\n",
969                                 ndr_desc.res, p->dn);
970                 goto err;
971         }
972         if (target_nid != online_nid)
973                 dev_info(dev, "Region registered with target node %d and online node %d",
974                          target_nid, online_nid);
975
976         mutex_lock(&papr_ndr_lock);
977         list_add_tail(&p->region_list, &papr_nd_regions);
978         mutex_unlock(&papr_ndr_lock);
979
980         return 0;
981
982 err:    nvdimm_bus_unregister(p->bus);
983         kfree(p->bus_desc.provider_name);
984         return -ENXIO;
985 }
986
987 static void papr_scm_add_badblock(struct nd_region *region,
988                                   struct nvdimm_bus *bus, u64 phys_addr)
989 {
990         u64 aligned_addr = ALIGN_DOWN(phys_addr, L1_CACHE_BYTES);
991
992         if (nvdimm_bus_add_badrange(bus, aligned_addr, L1_CACHE_BYTES)) {
993                 pr_err("Bad block registration for 0x%llx failed\n", phys_addr);
994                 return;
995         }
996
997         pr_debug("Add memory range (0x%llx - 0x%llx) as bad range\n",
998                  aligned_addr, aligned_addr + L1_CACHE_BYTES);
999
1000         nvdimm_region_notify(region, NVDIMM_REVALIDATE_POISON);
1001 }
1002
1003 static int handle_mce_ue(struct notifier_block *nb, unsigned long val,
1004                          void *data)
1005 {
1006         struct machine_check_event *evt = data;
1007         struct papr_scm_priv *p;
1008         u64 phys_addr;
1009         bool found = false;
1010
1011         if (evt->error_type != MCE_ERROR_TYPE_UE)
1012                 return NOTIFY_DONE;
1013
1014         if (list_empty(&papr_nd_regions))
1015                 return NOTIFY_DONE;
1016
1017         /*
1018          * The physical address obtained here is PAGE_SIZE aligned, so get the
1019          * exact address from the effective address
1020          */
1021         phys_addr = evt->u.ue_error.physical_address +
1022                         (evt->u.ue_error.effective_address & ~PAGE_MASK);
1023
1024         if (!evt->u.ue_error.physical_address_provided ||
1025             !is_zone_device_page(pfn_to_page(phys_addr >> PAGE_SHIFT)))
1026                 return NOTIFY_DONE;
1027
1028         /* mce notifier is called from a process context, so mutex is safe */
1029         mutex_lock(&papr_ndr_lock);
1030         list_for_each_entry(p, &papr_nd_regions, region_list) {
1031                 if (phys_addr >= p->res.start && phys_addr <= p->res.end) {
1032                         found = true;
1033                         break;
1034                 }
1035         }
1036
1037         if (found)
1038                 papr_scm_add_badblock(p->region, p->bus, phys_addr);
1039
1040         mutex_unlock(&papr_ndr_lock);
1041
1042         return found ? NOTIFY_OK : NOTIFY_DONE;
1043 }
1044
1045 static struct notifier_block mce_ue_nb = {
1046         .notifier_call = handle_mce_ue
1047 };
1048
1049 static int papr_scm_probe(struct platform_device *pdev)
1050 {
1051         struct device_node *dn = pdev->dev.of_node;
1052         u32 drc_index, metadata_size;
1053         u64 blocks, block_size;
1054         struct papr_scm_priv *p;
1055         u8 uuid_raw[UUID_SIZE];
1056         const char *uuid_str;
1057         ssize_t stat_size;
1058         uuid_t uuid;
1059         int rc;
1060
1061         /* check we have all the required DT properties */
1062         if (of_property_read_u32(dn, "ibm,my-drc-index", &drc_index)) {
1063                 dev_err(&pdev->dev, "%pOF: missing drc-index!\n", dn);
1064                 return -ENODEV;
1065         }
1066
1067         if (of_property_read_u64(dn, "ibm,block-size", &block_size)) {
1068                 dev_err(&pdev->dev, "%pOF: missing block-size!\n", dn);
1069                 return -ENODEV;
1070         }
1071
1072         if (of_property_read_u64(dn, "ibm,number-of-blocks", &blocks)) {
1073                 dev_err(&pdev->dev, "%pOF: missing number-of-blocks!\n", dn);
1074                 return -ENODEV;
1075         }
1076
1077         if (of_property_read_string(dn, "ibm,unit-guid", &uuid_str)) {
1078                 dev_err(&pdev->dev, "%pOF: missing unit-guid!\n", dn);
1079                 return -ENODEV;
1080         }
1081
1082         /*
1083          * open firmware platform device create won't update the NUMA 
1084          * distance table. For PAPR SCM devices we use numa_map_to_online_node()
1085          * to find the nearest online NUMA node and that requires correct
1086          * distance table information.
1087          */
1088         update_numa_distance(dn);
1089
1090         p = kzalloc(sizeof(*p), GFP_KERNEL);
1091         if (!p)
1092                 return -ENOMEM;
1093
1094         /* Initialize the dimm mutex */
1095         mutex_init(&p->health_mutex);
1096
1097         /* optional DT properties */
1098         of_property_read_u32(dn, "ibm,metadata-size", &metadata_size);
1099
1100         p->dn = dn;
1101         p->drc_index = drc_index;
1102         p->block_size = block_size;
1103         p->blocks = blocks;
1104         p->is_volatile = !of_property_read_bool(dn, "ibm,cache-flush-required");
1105
1106         /* We just need to ensure that set cookies are unique across */
1107         uuid_parse(uuid_str, &uuid);
1108
1109         /*
1110          * The cookie1 and cookie2 are not really little endian.
1111          * We store a raw buffer representation of the
1112          * uuid string so that we can compare this with the label
1113          * area cookie irrespective of the endian configuration
1114          * with which the kernel is built.
1115          *
1116          * Historically we stored the cookie in the below format.
1117          * for a uuid string 72511b67-0b3b-42fd-8d1d-5be3cae8bcaa
1118          *      cookie1 was 0xfd423b0b671b5172
1119          *      cookie2 was 0xaabce8cae35b1d8d
1120          */
1121         export_uuid(uuid_raw, &uuid);
1122         p->nd_set.cookie1 = get_unaligned_le64(&uuid_raw[0]);
1123         p->nd_set.cookie2 = get_unaligned_le64(&uuid_raw[8]);
1124
1125         /* might be zero */
1126         p->metadata_size = metadata_size;
1127         p->pdev = pdev;
1128
1129         /* request the hypervisor to bind this region to somewhere in memory */
1130         rc = drc_pmem_bind(p);
1131
1132         /* If phyp says drc memory still bound then force unbound and retry */
1133         if (rc == H_OVERLAP)
1134                 rc = drc_pmem_query_n_bind(p);
1135
1136         if (rc != H_SUCCESS) {
1137                 dev_err(&p->pdev->dev, "bind err: %d\n", rc);
1138                 rc = -ENXIO;
1139                 goto err;
1140         }
1141
1142         /* setup the resource for the newly bound range */
1143         p->res.start = p->bound_addr;
1144         p->res.end   = p->bound_addr + p->blocks * p->block_size - 1;
1145         p->res.name  = pdev->name;
1146         p->res.flags = IORESOURCE_MEM;
1147
1148         /* Try retrieving the stat buffer and see if its supported */
1149         stat_size = drc_pmem_query_stats(p, NULL, 0);
1150         if (stat_size > 0) {
1151                 p->stat_buffer_len = stat_size;
1152                 dev_dbg(&p->pdev->dev, "Max perf-stat size %lu-bytes\n",
1153                         p->stat_buffer_len);
1154         }
1155
1156         rc = papr_scm_nvdimm_init(p);
1157         if (rc)
1158                 goto err2;
1159
1160         platform_set_drvdata(pdev, p);
1161
1162         return 0;
1163
1164 err2:   drc_pmem_unbind(p);
1165 err:    kfree(p);
1166         return rc;
1167 }
1168
1169 static int papr_scm_remove(struct platform_device *pdev)
1170 {
1171         struct papr_scm_priv *p = platform_get_drvdata(pdev);
1172
1173         mutex_lock(&papr_ndr_lock);
1174         list_del(&p->region_list);
1175         mutex_unlock(&papr_ndr_lock);
1176
1177         nvdimm_bus_unregister(p->bus);
1178         drc_pmem_unbind(p);
1179         kfree(p->bus_desc.provider_name);
1180         kfree(p);
1181
1182         return 0;
1183 }
1184
1185 static const struct of_device_id papr_scm_match[] = {
1186         { .compatible = "ibm,pmemory" },
1187         { .compatible = "ibm,pmemory-v2" },
1188         { },
1189 };
1190
1191 static struct platform_driver papr_scm_driver = {
1192         .probe = papr_scm_probe,
1193         .remove = papr_scm_remove,
1194         .driver = {
1195                 .name = "papr_scm",
1196                 .of_match_table = papr_scm_match,
1197         },
1198 };
1199
1200 static int __init papr_scm_init(void)
1201 {
1202         int ret;
1203
1204         ret = platform_driver_register(&papr_scm_driver);
1205         if (!ret)
1206                 mce_register_notifier(&mce_ue_nb);
1207
1208         return ret;
1209 }
1210 module_init(papr_scm_init);
1211
1212 static void __exit papr_scm_exit(void)
1213 {
1214         mce_unregister_notifier(&mce_ue_nb);
1215         platform_driver_unregister(&papr_scm_driver);
1216 }
1217 module_exit(papr_scm_exit);
1218
1219 MODULE_DEVICE_TABLE(of, papr_scm_match);
1220 MODULE_LICENSE("GPL");
1221 MODULE_AUTHOR("IBM Corporation");