1 // SPDX-License-Identifier: GPL-2.0
3 #define pr_fmt(fmt) "papr-scm: " fmt
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>
18 #include <asm/plpar_wrappers.h>
19 #include <asm/papr_pdsm.h>
21 #include <asm/unaligned.h>
22 #include <linux/perf_event.h>
24 #define BIND_ANY_ADDR (~0ul)
26 #define PAPR_SCM_DIMM_CMD_MASK \
27 ((1ul << ND_CMD_GET_CONFIG_SIZE) | \
28 (1ul << ND_CMD_GET_CONFIG_DATA) | \
29 (1ul << ND_CMD_SET_CONFIG_DATA) | \
32 /* DIMM health bitmap indicators */
33 /* SCM device is unable to persist memory contents */
34 #define PAPR_PMEM_UNARMED (1ULL << (63 - 0))
35 /* SCM device failed to persist memory contents */
36 #define PAPR_PMEM_SHUTDOWN_DIRTY (1ULL << (63 - 1))
37 /* SCM device contents are persisted from previous IPL */
38 #define PAPR_PMEM_SHUTDOWN_CLEAN (1ULL << (63 - 2))
39 /* SCM device contents are not persisted from previous IPL */
40 #define PAPR_PMEM_EMPTY (1ULL << (63 - 3))
41 /* SCM device memory life remaining is critically low */
42 #define PAPR_PMEM_HEALTH_CRITICAL (1ULL << (63 - 4))
43 /* SCM device will be garded off next IPL due to failure */
44 #define PAPR_PMEM_HEALTH_FATAL (1ULL << (63 - 5))
45 /* SCM contents cannot persist due to current platform health status */
46 #define PAPR_PMEM_HEALTH_UNHEALTHY (1ULL << (63 - 6))
47 /* SCM device is unable to persist memory contents in certain conditions */
48 #define PAPR_PMEM_HEALTH_NON_CRITICAL (1ULL << (63 - 7))
49 /* SCM device is encrypted */
50 #define PAPR_PMEM_ENCRYPTED (1ULL << (63 - 8))
51 /* SCM device has been scrubbed and locked */
52 #define PAPR_PMEM_SCRUBBED_AND_LOCKED (1ULL << (63 - 9))
54 /* Bits status indicators for health bitmap indicating unarmed dimm */
55 #define PAPR_PMEM_UNARMED_MASK (PAPR_PMEM_UNARMED | \
56 PAPR_PMEM_HEALTH_UNHEALTHY)
58 /* Bits status indicators for health bitmap indicating unflushed dimm */
59 #define PAPR_PMEM_BAD_SHUTDOWN_MASK (PAPR_PMEM_SHUTDOWN_DIRTY)
61 /* Bits status indicators for health bitmap indicating unrestored dimm */
62 #define PAPR_PMEM_BAD_RESTORE_MASK (PAPR_PMEM_EMPTY)
64 /* Bit status indicators for smart event notification */
65 #define PAPR_PMEM_SMART_EVENT_MASK (PAPR_PMEM_HEALTH_CRITICAL | \
66 PAPR_PMEM_HEALTH_FATAL | \
67 PAPR_PMEM_HEALTH_UNHEALTHY)
69 #define PAPR_SCM_PERF_STATS_EYECATCHER __stringify(SCMSTATS)
70 #define PAPR_SCM_PERF_STATS_VERSION 0x1
72 /* Struct holding a single performance metric */
73 struct papr_scm_perf_stat {
78 /* Struct exchanged between kernel and PHYP for fetching drc perf stats */
79 struct papr_scm_perf_stats {
81 /* Should be PAPR_SCM_PERF_STATS_VERSION */
83 /* Number of stats following */
84 __be32 num_statistics;
85 /* zero or more performance matrics */
86 struct papr_scm_perf_stat scm_statistic[];
89 /* private struct associated with each region */
90 struct papr_scm_priv {
91 struct platform_device *pdev;
92 struct device_node *dn;
98 bool hcall_flush_required;
102 struct nvdimm_bus_descriptor bus_desc;
103 struct nvdimm_bus *bus;
104 struct nvdimm *nvdimm;
106 struct nd_region *region;
107 struct nd_interleave_set nd_set;
108 struct list_head region_list;
110 /* Protect dimm health data from concurrent read/writes */
111 struct mutex health_mutex;
113 /* Last time the health information of the dimm was updated */
114 unsigned long lasthealth_jiffies;
116 /* Health information for the dimm */
119 /* Holds the last known dirty shutdown counter value */
120 u64 dirty_shutdown_counter;
122 /* length of the stat buffer as expected by phyp */
123 size_t stat_buffer_len;
125 /* The bits which needs to be overridden */
126 u64 health_bitmap_inject_mask;
129 static int papr_scm_pmem_flush(struct nd_region *nd_region,
130 struct bio *bio __maybe_unused)
132 struct papr_scm_priv *p = nd_region_provider_data(nd_region);
133 unsigned long ret_buf[PLPAR_HCALL_BUFSIZE], token = 0;
136 dev_dbg(&p->pdev->dev, "flush drc 0x%x", p->drc_index);
139 rc = plpar_hcall(H_SCM_FLUSH, ret_buf, p->drc_index, token);
142 /* Check if we are stalled for some time */
143 if (H_IS_LONG_BUSY(rc)) {
144 msleep(get_longbusy_msecs(rc));
146 } else if (rc == H_BUSY) {
149 } while (rc == H_BUSY);
152 dev_err(&p->pdev->dev, "flush error: %ld", rc);
155 dev_dbg(&p->pdev->dev, "flush drc 0x%x complete", p->drc_index);
161 static LIST_HEAD(papr_nd_regions);
162 static DEFINE_MUTEX(papr_ndr_lock);
164 static int drc_pmem_bind(struct papr_scm_priv *p)
166 unsigned long ret[PLPAR_HCALL_BUFSIZE];
172 * When the hypervisor cannot map all the requested memory in a single
173 * hcall it returns H_BUSY and we call again with the token until
174 * we get H_SUCCESS. Aborting the retry loop before getting H_SUCCESS
175 * leave the system in an undefined state, so we wait.
180 rc = plpar_hcall(H_SCM_BIND_MEM, ret, p->drc_index, 0,
181 p->blocks, BIND_ANY_ADDR, token);
186 } while (rc == H_BUSY);
191 p->bound_addr = saved;
192 dev_dbg(&p->pdev->dev, "bound drc 0x%x to 0x%lx\n",
193 p->drc_index, (unsigned long)saved);
197 static void drc_pmem_unbind(struct papr_scm_priv *p)
199 unsigned long ret[PLPAR_HCALL_BUFSIZE];
203 dev_dbg(&p->pdev->dev, "unbind drc 0x%x\n", p->drc_index);
205 /* NB: unbind has the same retry requirements as drc_pmem_bind() */
208 /* Unbind of all SCM resources associated with drcIndex */
209 rc = plpar_hcall(H_SCM_UNBIND_ALL, ret, H_UNBIND_SCOPE_DRC,
210 p->drc_index, token);
213 /* Check if we are stalled for some time */
214 if (H_IS_LONG_BUSY(rc)) {
215 msleep(get_longbusy_msecs(rc));
217 } else if (rc == H_BUSY) {
221 } while (rc == H_BUSY);
224 dev_err(&p->pdev->dev, "unbind error: %lld\n", rc);
226 dev_dbg(&p->pdev->dev, "unbind drc 0x%x complete\n",
232 static int drc_pmem_query_n_bind(struct papr_scm_priv *p)
234 unsigned long start_addr;
235 unsigned long end_addr;
236 unsigned long ret[PLPAR_HCALL_BUFSIZE];
240 rc = plpar_hcall(H_SCM_QUERY_BLOCK_MEM_BINDING, ret,
246 /* Make sure the full region is bound. */
247 rc = plpar_hcall(H_SCM_QUERY_BLOCK_MEM_BINDING, ret,
248 p->drc_index, p->blocks - 1);
253 if ((end_addr - start_addr) != ((p->blocks - 1) * p->block_size))
256 p->bound_addr = start_addr;
257 dev_dbg(&p->pdev->dev, "bound drc 0x%x to 0x%lx\n", p->drc_index, start_addr);
261 dev_info(&p->pdev->dev,
262 "Failed to query, trying an unbind followed by bind");
264 return drc_pmem_bind(p);
268 * Query the Dimm performance stats from PHYP and copy them (if returned) to
269 * provided struct papr_scm_perf_stats instance 'stats' that can hold atleast
270 * (num_stats + header) bytes.
271 * - If buff_stats == NULL the return value is the size in bytes of the buffer
272 * needed to hold all supported performance-statistics.
273 * - If buff_stats != NULL and num_stats == 0 then we copy all known
274 * performance-statistics to 'buff_stat' and expect to be large enough to
276 * - if buff_stats != NULL and num_stats > 0 then copy the requested
277 * performance-statistics to buff_stats.
279 static ssize_t drc_pmem_query_stats(struct papr_scm_priv *p,
280 struct papr_scm_perf_stats *buff_stats,
281 unsigned int num_stats)
283 unsigned long ret[PLPAR_HCALL_BUFSIZE];
287 /* Setup the out buffer */
289 memcpy(buff_stats->eye_catcher,
290 PAPR_SCM_PERF_STATS_EYECATCHER, 8);
291 buff_stats->stats_version =
292 cpu_to_be32(PAPR_SCM_PERF_STATS_VERSION);
293 buff_stats->num_statistics =
294 cpu_to_be32(num_stats);
297 * Calculate the buffer size based on num-stats provided
298 * or use the prefetched max buffer length
301 /* Calculate size from the num_stats */
302 size = sizeof(struct papr_scm_perf_stats) +
303 num_stats * sizeof(struct papr_scm_perf_stat);
305 size = p->stat_buffer_len;
307 /* In case of no out buffer ignore the size */
311 /* Do the HCALL asking PHYP for info */
312 rc = plpar_hcall(H_SCM_PERFORMANCE_STATS, ret, p->drc_index,
313 buff_stats ? virt_to_phys(buff_stats) : 0,
316 /* Check if the error was due to an unknown stat-id */
317 if (rc == H_PARTIAL) {
318 dev_err(&p->pdev->dev,
319 "Unknown performance stats, Err:0x%016lX\n", ret[0]);
321 } else if (rc == H_AUTHORITY) {
322 dev_info(&p->pdev->dev,
323 "Permission denied while accessing performance stats");
325 } else if (rc == H_UNSUPPORTED) {
326 dev_dbg(&p->pdev->dev, "Performance stats unsupported\n");
328 } else if (rc != H_SUCCESS) {
329 dev_err(&p->pdev->dev,
330 "Failed to query performance stats, Err:%lld\n", rc);
334 /* Handle case where stat buffer size was requested */
335 dev_dbg(&p->pdev->dev,
336 "Performance stats size %ld\n", ret[0]);
340 /* Successfully fetched the requested stats from phyp */
341 dev_dbg(&p->pdev->dev,
342 "Performance stats returned %d stats\n",
343 be32_to_cpu(buff_stats->num_statistics));
347 #ifdef CONFIG_PERF_EVENTS
348 #define to_nvdimm_pmu(_pmu) container_of(_pmu, struct nvdimm_pmu, pmu)
350 static const char * const nvdimm_events_map[] = {
369 static int papr_scm_pmu_get_value(struct perf_event *event, struct device *dev, u64 *count)
371 struct papr_scm_perf_stat *stat;
372 struct papr_scm_perf_stats *stats;
373 struct papr_scm_priv *p = dev_get_drvdata(dev);
376 /* Invalid eventcode */
377 if (event->attr.config == 0 || event->attr.config >= ARRAY_SIZE(nvdimm_events_map))
380 /* Allocate request buffer enough to hold single performance stat */
381 size = sizeof(struct papr_scm_perf_stats) +
382 sizeof(struct papr_scm_perf_stat);
387 stats = kzalloc(size, GFP_KERNEL);
391 stat = &stats->scm_statistic[0];
392 memcpy(&stat->stat_id,
393 nvdimm_events_map[event->attr.config],
394 sizeof(stat->stat_id));
397 rc = drc_pmem_query_stats(p, stats, 1);
403 *count = be64_to_cpu(stat->stat_val);
408 static int papr_scm_pmu_event_init(struct perf_event *event)
410 struct nvdimm_pmu *nd_pmu = to_nvdimm_pmu(event->pmu);
411 struct papr_scm_priv *p;
416 /* test the event attr type for PMU enumeration */
417 if (event->attr.type != event->pmu->type)
420 /* it does not support event sampling mode */
421 if (is_sampling_event(event))
424 /* no branch sampling */
425 if (has_branch_stack(event))
428 p = (struct papr_scm_priv *)nd_pmu->dev->driver_data;
432 /* Invalid eventcode */
433 if (event->attr.config == 0 || event->attr.config > 16)
439 static int papr_scm_pmu_add(struct perf_event *event, int flags)
443 struct nvdimm_pmu *nd_pmu = to_nvdimm_pmu(event->pmu);
448 if (flags & PERF_EF_START) {
449 rc = papr_scm_pmu_get_value(event, nd_pmu->dev, &count);
453 local64_set(&event->hw.prev_count, count);
459 static void papr_scm_pmu_read(struct perf_event *event)
463 struct nvdimm_pmu *nd_pmu = to_nvdimm_pmu(event->pmu);
468 rc = papr_scm_pmu_get_value(event, nd_pmu->dev, &now);
472 prev = local64_xchg(&event->hw.prev_count, now);
473 local64_add(now - prev, &event->count);
476 static void papr_scm_pmu_del(struct perf_event *event, int flags)
478 papr_scm_pmu_read(event);
481 static void papr_scm_pmu_register(struct papr_scm_priv *p)
483 struct nvdimm_pmu *nd_pmu;
486 nd_pmu = kzalloc(sizeof(*nd_pmu), GFP_KERNEL);
492 if (!p->stat_buffer_len) {
494 goto pmu_check_events_err;
497 nd_pmu->pmu.task_ctx_nr = perf_invalid_context;
498 nd_pmu->pmu.name = nvdimm_name(p->nvdimm);
499 nd_pmu->pmu.event_init = papr_scm_pmu_event_init;
500 nd_pmu->pmu.read = papr_scm_pmu_read;
501 nd_pmu->pmu.add = papr_scm_pmu_add;
502 nd_pmu->pmu.del = papr_scm_pmu_del;
504 nd_pmu->pmu.capabilities = PERF_PMU_CAP_NO_INTERRUPT |
505 PERF_PMU_CAP_NO_EXCLUDE;
507 /*updating the cpumask variable */
508 nodeid = numa_map_to_online_node(dev_to_node(&p->pdev->dev));
509 nd_pmu->arch_cpumask = *cpumask_of_node(nodeid);
511 rc = register_nvdimm_pmu(nd_pmu, p->pdev);
513 goto pmu_check_events_err;
516 * Set archdata.priv value to nvdimm_pmu structure, to handle the
517 * unregistering of pmu device.
519 p->pdev->archdata.priv = nd_pmu;
522 pmu_check_events_err:
525 dev_info(&p->pdev->dev, "nvdimm pmu didn't register rc=%d\n", rc);
529 static void papr_scm_pmu_register(struct papr_scm_priv *p) { }
533 * Issue hcall to retrieve dimm health info and populate papr_scm_priv with the
534 * health information.
536 static int __drc_pmem_query_health(struct papr_scm_priv *p)
538 unsigned long ret[PLPAR_HCALL_BUFSIZE];
542 /* issue the hcall */
543 rc = plpar_hcall(H_SCM_HEALTH, ret, p->drc_index);
545 bitmap = ret[0] & ret[1];
546 else if (rc == H_FUNCTION)
547 dev_info_once(&p->pdev->dev,
548 "Hcall H_SCM_HEALTH not implemented, assuming empty health bitmap");
551 dev_err(&p->pdev->dev,
552 "Failed to query health information, Err:%ld\n", rc);
556 p->lasthealth_jiffies = jiffies;
557 /* Allow injecting specific health bits via inject mask. */
558 if (p->health_bitmap_inject_mask)
559 bitmap = (bitmap & ~p->health_bitmap_inject_mask) |
560 p->health_bitmap_inject_mask;
561 WRITE_ONCE(p->health_bitmap, bitmap);
562 dev_dbg(&p->pdev->dev,
563 "Queried dimm health info. Bitmap:0x%016lx Mask:0x%016lx\n",
569 /* Min interval in seconds for assuming stable dimm health */
570 #define MIN_HEALTH_QUERY_INTERVAL 60
572 /* Query cached health info and if needed call drc_pmem_query_health */
573 static int drc_pmem_query_health(struct papr_scm_priv *p)
575 unsigned long cache_timeout;
578 /* Protect concurrent modifications to papr_scm_priv */
579 rc = mutex_lock_interruptible(&p->health_mutex);
583 /* Jiffies offset for which the health data is assumed to be same */
584 cache_timeout = p->lasthealth_jiffies +
585 msecs_to_jiffies(MIN_HEALTH_QUERY_INTERVAL * 1000);
587 /* Fetch new health info is its older than MIN_HEALTH_QUERY_INTERVAL */
588 if (time_after(jiffies, cache_timeout))
589 rc = __drc_pmem_query_health(p);
591 /* Assume cached health data is valid */
594 mutex_unlock(&p->health_mutex);
598 static int papr_scm_meta_get(struct papr_scm_priv *p,
599 struct nd_cmd_get_config_data_hdr *hdr)
601 unsigned long data[PLPAR_HCALL_BUFSIZE];
602 unsigned long offset, data_offset;
606 if ((hdr->in_offset + hdr->in_length) > p->metadata_size)
609 for (len = hdr->in_length; len; len -= read) {
611 data_offset = hdr->in_length - len;
612 offset = hdr->in_offset + data_offset;
623 ret = plpar_hcall(H_SCM_READ_METADATA, data, p->drc_index,
626 if (ret == H_PARAMETER) /* bad DRC index */
629 return -EINVAL; /* other invalid parameter */
633 *(uint64_t *)(hdr->out_buf + data_offset) = be64_to_cpu(data[0]);
636 *(uint32_t *)(hdr->out_buf + data_offset) = be32_to_cpu(data[0] & 0xffffffff);
640 *(uint16_t *)(hdr->out_buf + data_offset) = be16_to_cpu(data[0] & 0xffff);
644 *(uint8_t *)(hdr->out_buf + data_offset) = (data[0] & 0xff);
651 static int papr_scm_meta_set(struct papr_scm_priv *p,
652 struct nd_cmd_set_config_hdr *hdr)
654 unsigned long offset, data_offset;
660 if ((hdr->in_offset + hdr->in_length) > p->metadata_size)
663 for (len = hdr->in_length; len; len -= wrote) {
665 data_offset = hdr->in_length - len;
666 offset = hdr->in_offset + data_offset;
669 data = *(uint64_t *)(hdr->in_buf + data_offset);
670 data_be = cpu_to_be64(data);
672 } else if (len >= 4) {
673 data = *(uint32_t *)(hdr->in_buf + data_offset);
675 data_be = cpu_to_be32(data);
677 } else if (len >= 2) {
678 data = *(uint16_t *)(hdr->in_buf + data_offset);
680 data_be = cpu_to_be16(data);
683 data_be = *(uint8_t *)(hdr->in_buf + data_offset);
688 ret = plpar_hcall_norets(H_SCM_WRITE_METADATA, p->drc_index,
689 offset, data_be, wrote);
690 if (ret == H_PARAMETER) /* bad DRC index */
693 return -EINVAL; /* other invalid parameter */
700 * Do a sanity checks on the inputs args to dimm-control function and return
701 * '0' if valid. Validation of PDSM payloads happens later in
702 * papr_scm_service_pdsm.
704 static int is_cmd_valid(struct nvdimm *nvdimm, unsigned int cmd, void *buf,
705 unsigned int buf_len)
707 unsigned long cmd_mask = PAPR_SCM_DIMM_CMD_MASK;
708 struct nd_cmd_pkg *nd_cmd;
709 struct papr_scm_priv *p;
712 /* Only dimm-specific calls are supported atm */
716 /* get the provider data from struct nvdimm */
717 p = nvdimm_provider_data(nvdimm);
719 if (!test_bit(cmd, &cmd_mask)) {
720 dev_dbg(&p->pdev->dev, "Unsupported cmd=%u\n", cmd);
724 /* For CMD_CALL verify pdsm request */
725 if (cmd == ND_CMD_CALL) {
726 /* Verify the envelope and envelop size */
728 buf_len < (sizeof(struct nd_cmd_pkg) + ND_PDSM_HDR_SIZE)) {
729 dev_dbg(&p->pdev->dev, "Invalid pkg size=%u\n",
734 /* Verify that the nd_cmd_pkg.nd_family is correct */
735 nd_cmd = (struct nd_cmd_pkg *)buf;
737 if (nd_cmd->nd_family != NVDIMM_FAMILY_PAPR) {
738 dev_dbg(&p->pdev->dev, "Invalid pkg family=0x%llx\n",
743 pdsm = (enum papr_pdsm)nd_cmd->nd_command;
745 /* Verify if the pdsm command is valid */
746 if (pdsm <= PAPR_PDSM_MIN || pdsm >= PAPR_PDSM_MAX) {
747 dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Invalid PDSM\n",
752 /* Have enough space to hold returned 'nd_pkg_pdsm' header */
753 if (nd_cmd->nd_size_out < ND_PDSM_HDR_SIZE) {
754 dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Invalid payload\n",
760 /* Let the command be further processed */
764 static int papr_pdsm_fuel_gauge(struct papr_scm_priv *p,
765 union nd_pdsm_payload *payload)
769 struct papr_scm_perf_stat *stat;
770 struct papr_scm_perf_stats *stats;
772 /* Silently fail if fetching performance metrics isn't supported */
773 if (!p->stat_buffer_len)
776 /* Allocate request buffer enough to hold single performance stat */
777 size = sizeof(struct papr_scm_perf_stats) +
778 sizeof(struct papr_scm_perf_stat);
780 stats = kzalloc(size, GFP_KERNEL);
784 stat = &stats->scm_statistic[0];
785 memcpy(&stat->stat_id, "MemLife ", sizeof(stat->stat_id));
788 /* Fetch the fuel gauge and populate it in payload */
789 rc = drc_pmem_query_stats(p, stats, 1);
791 dev_dbg(&p->pdev->dev, "Err(%d) fetching fuel gauge\n", rc);
795 statval = be64_to_cpu(stat->stat_val);
796 dev_dbg(&p->pdev->dev,
797 "Fetched fuel-gauge %llu", statval);
798 payload->health.extension_flags |=
799 PDSM_DIMM_HEALTH_RUN_GAUGE_VALID;
800 payload->health.dimm_fuel_gauge = statval;
802 rc = sizeof(struct nd_papr_pdsm_health);
809 /* Add the dirty-shutdown-counter value to the pdsm */
810 static int papr_pdsm_dsc(struct papr_scm_priv *p,
811 union nd_pdsm_payload *payload)
813 payload->health.extension_flags |= PDSM_DIMM_DSC_VALID;
814 payload->health.dimm_dsc = p->dirty_shutdown_counter;
816 return sizeof(struct nd_papr_pdsm_health);
819 /* Fetch the DIMM health info and populate it in provided package. */
820 static int papr_pdsm_health(struct papr_scm_priv *p,
821 union nd_pdsm_payload *payload)
825 /* Ensure dimm health mutex is taken preventing concurrent access */
826 rc = mutex_lock_interruptible(&p->health_mutex);
830 /* Always fetch upto date dimm health data ignoring cached values */
831 rc = __drc_pmem_query_health(p);
833 mutex_unlock(&p->health_mutex);
837 /* update health struct with various flags derived from health bitmap */
838 payload->health = (struct nd_papr_pdsm_health) {
839 .extension_flags = 0,
840 .dimm_unarmed = !!(p->health_bitmap & PAPR_PMEM_UNARMED_MASK),
841 .dimm_bad_shutdown = !!(p->health_bitmap & PAPR_PMEM_BAD_SHUTDOWN_MASK),
842 .dimm_bad_restore = !!(p->health_bitmap & PAPR_PMEM_BAD_RESTORE_MASK),
843 .dimm_scrubbed = !!(p->health_bitmap & PAPR_PMEM_SCRUBBED_AND_LOCKED),
844 .dimm_locked = !!(p->health_bitmap & PAPR_PMEM_SCRUBBED_AND_LOCKED),
845 .dimm_encrypted = !!(p->health_bitmap & PAPR_PMEM_ENCRYPTED),
846 .dimm_health = PAPR_PDSM_DIMM_HEALTHY,
849 /* Update field dimm_health based on health_bitmap flags */
850 if (p->health_bitmap & PAPR_PMEM_HEALTH_FATAL)
851 payload->health.dimm_health = PAPR_PDSM_DIMM_FATAL;
852 else if (p->health_bitmap & PAPR_PMEM_HEALTH_CRITICAL)
853 payload->health.dimm_health = PAPR_PDSM_DIMM_CRITICAL;
854 else if (p->health_bitmap & PAPR_PMEM_HEALTH_UNHEALTHY)
855 payload->health.dimm_health = PAPR_PDSM_DIMM_UNHEALTHY;
857 /* struct populated hence can release the mutex now */
858 mutex_unlock(&p->health_mutex);
860 /* Populate the fuel gauge meter in the payload */
861 papr_pdsm_fuel_gauge(p, payload);
862 /* Populate the dirty-shutdown-counter field */
863 papr_pdsm_dsc(p, payload);
865 rc = sizeof(struct nd_papr_pdsm_health);
871 /* Inject a smart error Add the dirty-shutdown-counter value to the pdsm */
872 static int papr_pdsm_smart_inject(struct papr_scm_priv *p,
873 union nd_pdsm_payload *payload)
876 u32 supported_flags = 0;
877 u64 inject_mask = 0, clear_mask = 0;
880 /* Check for individual smart error flags and update inject/clear masks */
881 if (payload->smart_inject.flags & PDSM_SMART_INJECT_HEALTH_FATAL) {
882 supported_flags |= PDSM_SMART_INJECT_HEALTH_FATAL;
883 if (payload->smart_inject.fatal_enable)
884 inject_mask |= PAPR_PMEM_HEALTH_FATAL;
886 clear_mask |= PAPR_PMEM_HEALTH_FATAL;
889 if (payload->smart_inject.flags & PDSM_SMART_INJECT_BAD_SHUTDOWN) {
890 supported_flags |= PDSM_SMART_INJECT_BAD_SHUTDOWN;
891 if (payload->smart_inject.unsafe_shutdown_enable)
892 inject_mask |= PAPR_PMEM_SHUTDOWN_DIRTY;
894 clear_mask |= PAPR_PMEM_SHUTDOWN_DIRTY;
897 dev_dbg(&p->pdev->dev, "[Smart-inject] inject_mask=%#llx clear_mask=%#llx\n",
898 inject_mask, clear_mask);
900 /* Prevent concurrent access to dimm health bitmap related members */
901 rc = mutex_lock_interruptible(&p->health_mutex);
905 /* Use inject/clear masks to set health_bitmap_inject_mask */
906 mask = READ_ONCE(p->health_bitmap_inject_mask);
907 mask = (mask & ~clear_mask) | inject_mask;
908 WRITE_ONCE(p->health_bitmap_inject_mask, mask);
910 /* Invalidate cached health bitmap */
911 p->lasthealth_jiffies = 0;
913 mutex_unlock(&p->health_mutex);
915 /* Return the supported flags back to userspace */
916 payload->smart_inject.flags = supported_flags;
918 return sizeof(struct nd_papr_pdsm_health);
922 * 'struct pdsm_cmd_desc'
923 * Identifies supported PDSMs' expected length of in/out payloads
924 * and pdsm service function.
926 * size_in : Size of input payload if any in the PDSM request.
927 * size_out : Size of output payload if any in the PDSM request.
928 * service : Service function for the PDSM request. Return semantics:
929 * rc < 0 : Error servicing PDSM and rc indicates the error.
930 * rc >=0 : Serviced successfully and 'rc' indicate number of
931 * bytes written to payload.
933 struct pdsm_cmd_desc {
936 int (*service)(struct papr_scm_priv *dimm,
937 union nd_pdsm_payload *payload);
940 /* Holds all supported PDSMs' command descriptors */
941 static const struct pdsm_cmd_desc __pdsm_cmd_descriptors[] = {
947 /* New PDSM command descriptors to be added below */
949 [PAPR_PDSM_HEALTH] = {
951 .size_out = sizeof(struct nd_papr_pdsm_health),
952 .service = papr_pdsm_health,
955 [PAPR_PDSM_SMART_INJECT] = {
956 .size_in = sizeof(struct nd_papr_pdsm_smart_inject),
957 .size_out = sizeof(struct nd_papr_pdsm_smart_inject),
958 .service = papr_pdsm_smart_inject,
968 /* Given a valid pdsm cmd return its command descriptor else return NULL */
969 static inline const struct pdsm_cmd_desc *pdsm_cmd_desc(enum papr_pdsm cmd)
971 if (cmd >= 0 || cmd < ARRAY_SIZE(__pdsm_cmd_descriptors))
972 return &__pdsm_cmd_descriptors[cmd];
978 * For a given pdsm request call an appropriate service function.
979 * Returns errors if any while handling the pdsm command package.
981 static int papr_scm_service_pdsm(struct papr_scm_priv *p,
982 struct nd_cmd_pkg *pkg)
984 /* Get the PDSM header and PDSM command */
985 struct nd_pkg_pdsm *pdsm_pkg = (struct nd_pkg_pdsm *)pkg->nd_payload;
986 enum papr_pdsm pdsm = (enum papr_pdsm)pkg->nd_command;
987 const struct pdsm_cmd_desc *pdsc;
990 /* Fetch corresponding pdsm descriptor for validation and servicing */
991 pdsc = pdsm_cmd_desc(pdsm);
993 /* Validate pdsm descriptor */
994 /* Ensure that reserved fields are 0 */
995 if (pdsm_pkg->reserved[0] || pdsm_pkg->reserved[1]) {
996 dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Invalid reserved field\n",
1001 /* If pdsm expects some input, then ensure that the size_in matches */
1002 if (pdsc->size_in &&
1003 pkg->nd_size_in != (pdsc->size_in + ND_PDSM_HDR_SIZE)) {
1004 dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Mismatched size_in=%d\n",
1005 pdsm, pkg->nd_size_in);
1009 /* If pdsm wants to return data, then ensure that size_out matches */
1010 if (pdsc->size_out &&
1011 pkg->nd_size_out != (pdsc->size_out + ND_PDSM_HDR_SIZE)) {
1012 dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Mismatched size_out=%d\n",
1013 pdsm, pkg->nd_size_out);
1017 /* Service the pdsm */
1018 if (pdsc->service) {
1019 dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Servicing..\n", pdsm);
1021 rc = pdsc->service(p, &pdsm_pkg->payload);
1024 /* error encountered while servicing pdsm */
1025 pdsm_pkg->cmd_status = rc;
1026 pkg->nd_fw_size = ND_PDSM_HDR_SIZE;
1028 /* pdsm serviced and 'rc' bytes written to payload */
1029 pdsm_pkg->cmd_status = 0;
1030 pkg->nd_fw_size = ND_PDSM_HDR_SIZE + rc;
1033 dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Unsupported PDSM request\n",
1035 pdsm_pkg->cmd_status = -ENOENT;
1036 pkg->nd_fw_size = ND_PDSM_HDR_SIZE;
1039 return pdsm_pkg->cmd_status;
1042 static int papr_scm_ndctl(struct nvdimm_bus_descriptor *nd_desc,
1043 struct nvdimm *nvdimm, unsigned int cmd, void *buf,
1044 unsigned int buf_len, int *cmd_rc)
1046 struct nd_cmd_get_config_size *get_size_hdr;
1047 struct nd_cmd_pkg *call_pkg = NULL;
1048 struct papr_scm_priv *p;
1051 rc = is_cmd_valid(nvdimm, cmd, buf, buf_len);
1053 pr_debug("Invalid cmd=0x%x. Err=%d\n", cmd, rc);
1057 /* Use a local variable in case cmd_rc pointer is NULL */
1061 p = nvdimm_provider_data(nvdimm);
1064 case ND_CMD_GET_CONFIG_SIZE:
1067 get_size_hdr->status = 0;
1068 get_size_hdr->max_xfer = 8;
1069 get_size_hdr->config_size = p->metadata_size;
1073 case ND_CMD_GET_CONFIG_DATA:
1074 *cmd_rc = papr_scm_meta_get(p, buf);
1077 case ND_CMD_SET_CONFIG_DATA:
1078 *cmd_rc = papr_scm_meta_set(p, buf);
1082 call_pkg = (struct nd_cmd_pkg *)buf;
1083 *cmd_rc = papr_scm_service_pdsm(p, call_pkg);
1087 dev_dbg(&p->pdev->dev, "Unknown command = %d\n", cmd);
1091 dev_dbg(&p->pdev->dev, "returned with cmd_rc = %d\n", *cmd_rc);
1096 static ssize_t health_bitmap_inject_show(struct device *dev,
1097 struct device_attribute *attr,
1100 struct nvdimm *dimm = to_nvdimm(dev);
1101 struct papr_scm_priv *p = nvdimm_provider_data(dimm);
1103 return sprintf(buf, "%#llx\n",
1104 READ_ONCE(p->health_bitmap_inject_mask));
1107 static DEVICE_ATTR_ADMIN_RO(health_bitmap_inject);
1109 static ssize_t perf_stats_show(struct device *dev,
1110 struct device_attribute *attr, char *buf)
1115 struct papr_scm_perf_stat *stat;
1116 struct papr_scm_perf_stats *stats;
1117 struct nvdimm *dimm = to_nvdimm(dev);
1118 struct papr_scm_priv *p = nvdimm_provider_data(dimm);
1120 if (!p->stat_buffer_len)
1123 /* Allocate the buffer for phyp where stats are written */
1124 stats = kzalloc(p->stat_buffer_len, GFP_KERNEL);
1128 /* Ask phyp to return all dimm perf stats */
1129 rc = drc_pmem_query_stats(p, stats, 0);
1133 * Go through the returned output buffer and print stats and
1134 * values. Since stat_id is essentially a char string of
1135 * 8 bytes, simply use the string format specifier to print it.
1137 seq_buf_init(&s, buf, PAGE_SIZE);
1138 for (index = 0, stat = stats->scm_statistic;
1139 index < be32_to_cpu(stats->num_statistics);
1141 seq_buf_printf(&s, "%.8s = 0x%016llX\n",
1143 be64_to_cpu(stat->stat_val));
1148 return rc ? rc : (ssize_t)seq_buf_used(&s);
1150 static DEVICE_ATTR_ADMIN_RO(perf_stats);
1152 static ssize_t flags_show(struct device *dev,
1153 struct device_attribute *attr, char *buf)
1155 struct nvdimm *dimm = to_nvdimm(dev);
1156 struct papr_scm_priv *p = nvdimm_provider_data(dimm);
1161 rc = drc_pmem_query_health(p);
1165 /* Copy health_bitmap locally, check masks & update out buffer */
1166 health = READ_ONCE(p->health_bitmap);
1168 seq_buf_init(&s, buf, PAGE_SIZE);
1169 if (health & PAPR_PMEM_UNARMED_MASK)
1170 seq_buf_printf(&s, "not_armed ");
1172 if (health & PAPR_PMEM_BAD_SHUTDOWN_MASK)
1173 seq_buf_printf(&s, "flush_fail ");
1175 if (health & PAPR_PMEM_BAD_RESTORE_MASK)
1176 seq_buf_printf(&s, "restore_fail ");
1178 if (health & PAPR_PMEM_ENCRYPTED)
1179 seq_buf_printf(&s, "encrypted ");
1181 if (health & PAPR_PMEM_SMART_EVENT_MASK)
1182 seq_buf_printf(&s, "smart_notify ");
1184 if (health & PAPR_PMEM_SCRUBBED_AND_LOCKED)
1185 seq_buf_printf(&s, "scrubbed locked ");
1187 if (seq_buf_used(&s))
1188 seq_buf_printf(&s, "\n");
1190 return seq_buf_used(&s);
1192 DEVICE_ATTR_RO(flags);
1194 static ssize_t dirty_shutdown_show(struct device *dev,
1195 struct device_attribute *attr, char *buf)
1197 struct nvdimm *dimm = to_nvdimm(dev);
1198 struct papr_scm_priv *p = nvdimm_provider_data(dimm);
1200 return sysfs_emit(buf, "%llu\n", p->dirty_shutdown_counter);
1202 DEVICE_ATTR_RO(dirty_shutdown);
1204 static umode_t papr_nd_attribute_visible(struct kobject *kobj,
1205 struct attribute *attr, int n)
1207 struct device *dev = kobj_to_dev(kobj);
1208 struct nvdimm *nvdimm = to_nvdimm(dev);
1209 struct papr_scm_priv *p = nvdimm_provider_data(nvdimm);
1211 /* For if perf-stats not available remove perf_stats sysfs */
1212 if (attr == &dev_attr_perf_stats.attr && p->stat_buffer_len == 0)
1218 /* papr_scm specific dimm attributes */
1219 static struct attribute *papr_nd_attributes[] = {
1220 &dev_attr_flags.attr,
1221 &dev_attr_perf_stats.attr,
1222 &dev_attr_dirty_shutdown.attr,
1223 &dev_attr_health_bitmap_inject.attr,
1227 static const struct attribute_group papr_nd_attribute_group = {
1229 .is_visible = papr_nd_attribute_visible,
1230 .attrs = papr_nd_attributes,
1233 static const struct attribute_group *papr_nd_attr_groups[] = {
1234 &papr_nd_attribute_group,
1238 static int papr_scm_nvdimm_init(struct papr_scm_priv *p)
1240 struct device *dev = &p->pdev->dev;
1241 struct nd_mapping_desc mapping;
1242 struct nd_region_desc ndr_desc;
1243 unsigned long dimm_flags;
1244 int target_nid, online_nid;
1246 p->bus_desc.ndctl = papr_scm_ndctl;
1247 p->bus_desc.module = THIS_MODULE;
1248 p->bus_desc.of_node = p->pdev->dev.of_node;
1249 p->bus_desc.provider_name = kstrdup(p->pdev->name, GFP_KERNEL);
1251 /* Set the dimm command family mask to accept PDSMs */
1252 set_bit(NVDIMM_FAMILY_PAPR, &p->bus_desc.dimm_family_mask);
1254 if (!p->bus_desc.provider_name)
1257 p->bus = nvdimm_bus_register(NULL, &p->bus_desc);
1259 dev_err(dev, "Error creating nvdimm bus %pOF\n", p->dn);
1260 kfree(p->bus_desc.provider_name);
1265 set_bit(NDD_LABELING, &dimm_flags);
1268 * Check if the nvdimm is unarmed. No locking needed as we are still
1269 * initializing. Ignore error encountered if any.
1271 __drc_pmem_query_health(p);
1273 if (p->health_bitmap & PAPR_PMEM_UNARMED_MASK)
1274 set_bit(NDD_UNARMED, &dimm_flags);
1276 p->nvdimm = nvdimm_create(p->bus, p, papr_nd_attr_groups,
1277 dimm_flags, PAPR_SCM_DIMM_CMD_MASK, 0, NULL);
1279 dev_err(dev, "Error creating DIMM object for %pOF\n", p->dn);
1283 if (nvdimm_bus_check_dimm_count(p->bus, 1))
1286 /* now add the region */
1288 memset(&mapping, 0, sizeof(mapping));
1289 mapping.nvdimm = p->nvdimm;
1291 mapping.size = p->blocks * p->block_size; // XXX: potential overflow?
1293 memset(&ndr_desc, 0, sizeof(ndr_desc));
1294 target_nid = dev_to_node(&p->pdev->dev);
1295 online_nid = numa_map_to_online_node(target_nid);
1296 ndr_desc.numa_node = online_nid;
1297 ndr_desc.target_node = target_nid;
1298 ndr_desc.res = &p->res;
1299 ndr_desc.of_node = p->dn;
1300 ndr_desc.provider_data = p;
1301 ndr_desc.mapping = &mapping;
1302 ndr_desc.num_mappings = 1;
1303 ndr_desc.nd_set = &p->nd_set;
1305 if (p->hcall_flush_required) {
1306 set_bit(ND_REGION_ASYNC, &ndr_desc.flags);
1307 ndr_desc.flush = papr_scm_pmem_flush;
1311 p->region = nvdimm_volatile_region_create(p->bus, &ndr_desc);
1313 set_bit(ND_REGION_PERSIST_MEMCTRL, &ndr_desc.flags);
1314 p->region = nvdimm_pmem_region_create(p->bus, &ndr_desc);
1317 dev_err(dev, "Error registering region %pR from %pOF\n",
1318 ndr_desc.res, p->dn);
1321 if (target_nid != online_nid)
1322 dev_info(dev, "Region registered with target node %d and online node %d",
1323 target_nid, online_nid);
1325 mutex_lock(&papr_ndr_lock);
1326 list_add_tail(&p->region_list, &papr_nd_regions);
1327 mutex_unlock(&papr_ndr_lock);
1331 err: nvdimm_bus_unregister(p->bus);
1332 kfree(p->bus_desc.provider_name);
1336 static void papr_scm_add_badblock(struct nd_region *region,
1337 struct nvdimm_bus *bus, u64 phys_addr)
1339 u64 aligned_addr = ALIGN_DOWN(phys_addr, L1_CACHE_BYTES);
1341 if (nvdimm_bus_add_badrange(bus, aligned_addr, L1_CACHE_BYTES)) {
1342 pr_err("Bad block registration for 0x%llx failed\n", phys_addr);
1346 pr_debug("Add memory range (0x%llx - 0x%llx) as bad range\n",
1347 aligned_addr, aligned_addr + L1_CACHE_BYTES);
1349 nvdimm_region_notify(region, NVDIMM_REVALIDATE_POISON);
1352 static int handle_mce_ue(struct notifier_block *nb, unsigned long val,
1355 struct machine_check_event *evt = data;
1356 struct papr_scm_priv *p;
1360 if (evt->error_type != MCE_ERROR_TYPE_UE)
1363 if (list_empty(&papr_nd_regions))
1367 * The physical address obtained here is PAGE_SIZE aligned, so get the
1368 * exact address from the effective address
1370 phys_addr = evt->u.ue_error.physical_address +
1371 (evt->u.ue_error.effective_address & ~PAGE_MASK);
1373 if (!evt->u.ue_error.physical_address_provided ||
1374 !is_zone_device_page(pfn_to_page(phys_addr >> PAGE_SHIFT)))
1377 /* mce notifier is called from a process context, so mutex is safe */
1378 mutex_lock(&papr_ndr_lock);
1379 list_for_each_entry(p, &papr_nd_regions, region_list) {
1380 if (phys_addr >= p->res.start && phys_addr <= p->res.end) {
1387 papr_scm_add_badblock(p->region, p->bus, phys_addr);
1389 mutex_unlock(&papr_ndr_lock);
1391 return found ? NOTIFY_OK : NOTIFY_DONE;
1394 static struct notifier_block mce_ue_nb = {
1395 .notifier_call = handle_mce_ue
1398 static int papr_scm_probe(struct platform_device *pdev)
1400 struct device_node *dn = pdev->dev.of_node;
1401 u32 drc_index, metadata_size;
1402 u64 blocks, block_size;
1403 struct papr_scm_priv *p;
1404 u8 uuid_raw[UUID_SIZE];
1405 const char *uuid_str;
1410 /* check we have all the required DT properties */
1411 if (of_property_read_u32(dn, "ibm,my-drc-index", &drc_index)) {
1412 dev_err(&pdev->dev, "%pOF: missing drc-index!\n", dn);
1416 if (of_property_read_u64(dn, "ibm,block-size", &block_size)) {
1417 dev_err(&pdev->dev, "%pOF: missing block-size!\n", dn);
1421 if (of_property_read_u64(dn, "ibm,number-of-blocks", &blocks)) {
1422 dev_err(&pdev->dev, "%pOF: missing number-of-blocks!\n", dn);
1426 if (of_property_read_string(dn, "ibm,unit-guid", &uuid_str)) {
1427 dev_err(&pdev->dev, "%pOF: missing unit-guid!\n", dn);
1432 p = kzalloc(sizeof(*p), GFP_KERNEL);
1436 /* Initialize the dimm mutex */
1437 mutex_init(&p->health_mutex);
1439 /* optional DT properties */
1440 of_property_read_u32(dn, "ibm,metadata-size", &metadata_size);
1443 p->drc_index = drc_index;
1444 p->block_size = block_size;
1446 p->is_volatile = !of_property_read_bool(dn, "ibm,cache-flush-required");
1447 p->hcall_flush_required = of_property_read_bool(dn, "ibm,hcall-flush-required");
1449 if (of_property_read_u64(dn, "ibm,persistence-failed-count",
1450 &p->dirty_shutdown_counter))
1451 p->dirty_shutdown_counter = 0;
1453 /* We just need to ensure that set cookies are unique across */
1454 uuid_parse(uuid_str, &uuid);
1457 * The cookie1 and cookie2 are not really little endian.
1458 * We store a raw buffer representation of the
1459 * uuid string so that we can compare this with the label
1460 * area cookie irrespective of the endian configuration
1461 * with which the kernel is built.
1463 * Historically we stored the cookie in the below format.
1464 * for a uuid string 72511b67-0b3b-42fd-8d1d-5be3cae8bcaa
1465 * cookie1 was 0xfd423b0b671b5172
1466 * cookie2 was 0xaabce8cae35b1d8d
1468 export_uuid(uuid_raw, &uuid);
1469 p->nd_set.cookie1 = get_unaligned_le64(&uuid_raw[0]);
1470 p->nd_set.cookie2 = get_unaligned_le64(&uuid_raw[8]);
1473 p->metadata_size = metadata_size;
1476 /* request the hypervisor to bind this region to somewhere in memory */
1477 rc = drc_pmem_bind(p);
1479 /* If phyp says drc memory still bound then force unbound and retry */
1480 if (rc == H_OVERLAP)
1481 rc = drc_pmem_query_n_bind(p);
1483 if (rc != H_SUCCESS) {
1484 dev_err(&p->pdev->dev, "bind err: %d\n", rc);
1489 /* setup the resource for the newly bound range */
1490 p->res.start = p->bound_addr;
1491 p->res.end = p->bound_addr + p->blocks * p->block_size - 1;
1492 p->res.name = pdev->name;
1493 p->res.flags = IORESOURCE_MEM;
1495 /* Try retrieving the stat buffer and see if its supported */
1496 stat_size = drc_pmem_query_stats(p, NULL, 0);
1497 if (stat_size > 0) {
1498 p->stat_buffer_len = stat_size;
1499 dev_dbg(&p->pdev->dev, "Max perf-stat size %lu-bytes\n",
1500 p->stat_buffer_len);
1503 rc = papr_scm_nvdimm_init(p);
1507 platform_set_drvdata(pdev, p);
1508 papr_scm_pmu_register(p);
1512 err2: drc_pmem_unbind(p);
1517 static int papr_scm_remove(struct platform_device *pdev)
1519 struct papr_scm_priv *p = platform_get_drvdata(pdev);
1521 mutex_lock(&papr_ndr_lock);
1522 list_del(&p->region_list);
1523 mutex_unlock(&papr_ndr_lock);
1525 nvdimm_bus_unregister(p->bus);
1528 if (pdev->archdata.priv)
1529 unregister_nvdimm_pmu(pdev->archdata.priv);
1531 pdev->archdata.priv = NULL;
1532 kfree(p->bus_desc.provider_name);
1538 static const struct of_device_id papr_scm_match[] = {
1539 { .compatible = "ibm,pmemory" },
1540 { .compatible = "ibm,pmemory-v2" },
1544 static struct platform_driver papr_scm_driver = {
1545 .probe = papr_scm_probe,
1546 .remove = papr_scm_remove,
1549 .of_match_table = papr_scm_match,
1553 static int __init papr_scm_init(void)
1557 ret = platform_driver_register(&papr_scm_driver);
1559 mce_register_notifier(&mce_ue_nb);
1563 module_init(papr_scm_init);
1565 static void __exit papr_scm_exit(void)
1567 mce_unregister_notifier(&mce_ue_nb);
1568 platform_driver_unregister(&papr_scm_driver);
1570 module_exit(papr_scm_exit);
1572 MODULE_DEVICE_TABLE(of, papr_scm_match);
1573 MODULE_LICENSE("GPL");
1574 MODULE_AUTHOR("IBM Corporation");