Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 
0003 #define pr_fmt(fmt) "papr-scm: " fmt
0004 
0005 #include <linux/of.h>
0006 #include <linux/kernel.h>
0007 #include <linux/module.h>
0008 #include <linux/ioport.h>
0009 #include <linux/slab.h>
0010 #include <linux/ndctl.h>
0011 #include <linux/sched.h>
0012 #include <linux/libnvdimm.h>
0013 #include <linux/platform_device.h>
0014 #include <linux/delay.h>
0015 #include <linux/seq_buf.h>
0016 #include <linux/nd.h>
0017 
0018 #include <asm/plpar_wrappers.h>
0019 #include <asm/papr_pdsm.h>
0020 #include <asm/mce.h>
0021 #include <asm/unaligned.h>
0022 #include <linux/perf_event.h>
0023 
0024 #define BIND_ANY_ADDR (~0ul)
0025 
0026 #define PAPR_SCM_DIMM_CMD_MASK \
0027     ((1ul << ND_CMD_GET_CONFIG_SIZE) | \
0028      (1ul << ND_CMD_GET_CONFIG_DATA) | \
0029      (1ul << ND_CMD_SET_CONFIG_DATA) | \
0030      (1ul << ND_CMD_CALL))
0031 
0032 /* DIMM health bitmap indicators */
0033 /* SCM device is unable to persist memory contents */
0034 #define PAPR_PMEM_UNARMED                   (1ULL << (63 - 0))
0035 /* SCM device failed to persist memory contents */
0036 #define PAPR_PMEM_SHUTDOWN_DIRTY            (1ULL << (63 - 1))
0037 /* SCM device contents are persisted from previous IPL */
0038 #define PAPR_PMEM_SHUTDOWN_CLEAN            (1ULL << (63 - 2))
0039 /* SCM device contents are not persisted from previous IPL */
0040 #define PAPR_PMEM_EMPTY                     (1ULL << (63 - 3))
0041 /* SCM device memory life remaining is critically low */
0042 #define PAPR_PMEM_HEALTH_CRITICAL           (1ULL << (63 - 4))
0043 /* SCM device will be garded off next IPL due to failure */
0044 #define PAPR_PMEM_HEALTH_FATAL              (1ULL << (63 - 5))
0045 /* SCM contents cannot persist due to current platform health status */
0046 #define PAPR_PMEM_HEALTH_UNHEALTHY          (1ULL << (63 - 6))
0047 /* SCM device is unable to persist memory contents in certain conditions */
0048 #define PAPR_PMEM_HEALTH_NON_CRITICAL       (1ULL << (63 - 7))
0049 /* SCM device is encrypted */
0050 #define PAPR_PMEM_ENCRYPTED                 (1ULL << (63 - 8))
0051 /* SCM device has been scrubbed and locked */
0052 #define PAPR_PMEM_SCRUBBED_AND_LOCKED       (1ULL << (63 - 9))
0053 
0054 /* Bits status indicators for health bitmap indicating unarmed dimm */
0055 #define PAPR_PMEM_UNARMED_MASK (PAPR_PMEM_UNARMED |     \
0056                 PAPR_PMEM_HEALTH_UNHEALTHY)
0057 
0058 /* Bits status indicators for health bitmap indicating unflushed dimm */
0059 #define PAPR_PMEM_BAD_SHUTDOWN_MASK (PAPR_PMEM_SHUTDOWN_DIRTY)
0060 
0061 /* Bits status indicators for health bitmap indicating unrestored dimm */
0062 #define PAPR_PMEM_BAD_RESTORE_MASK  (PAPR_PMEM_EMPTY)
0063 
0064 /* Bit status indicators for smart event notification */
0065 #define PAPR_PMEM_SMART_EVENT_MASK (PAPR_PMEM_HEALTH_CRITICAL | \
0066                     PAPR_PMEM_HEALTH_FATAL |    \
0067                     PAPR_PMEM_HEALTH_UNHEALTHY)
0068 
0069 #define PAPR_SCM_PERF_STATS_EYECATCHER __stringify(SCMSTATS)
0070 #define PAPR_SCM_PERF_STATS_VERSION 0x1
0071 
0072 /* Struct holding a single performance metric */
0073 struct papr_scm_perf_stat {
0074     u8 stat_id[8];
0075     __be64 stat_val;
0076 } __packed;
0077 
0078 /* Struct exchanged between kernel and PHYP for fetching drc perf stats */
0079 struct papr_scm_perf_stats {
0080     u8 eye_catcher[8];
0081     /* Should be PAPR_SCM_PERF_STATS_VERSION */
0082     __be32 stats_version;
0083     /* Number of stats following */
0084     __be32 num_statistics;
0085     /* zero or more performance matrics */
0086     struct papr_scm_perf_stat scm_statistic[];
0087 } __packed;
0088 
0089 /* private struct associated with each region */
0090 struct papr_scm_priv {
0091     struct platform_device *pdev;
0092     struct device_node *dn;
0093     uint32_t drc_index;
0094     uint64_t blocks;
0095     uint64_t block_size;
0096     int metadata_size;
0097     bool is_volatile;
0098     bool hcall_flush_required;
0099 
0100     uint64_t bound_addr;
0101 
0102     struct nvdimm_bus_descriptor bus_desc;
0103     struct nvdimm_bus *bus;
0104     struct nvdimm *nvdimm;
0105     struct resource res;
0106     struct nd_region *region;
0107     struct nd_interleave_set nd_set;
0108     struct list_head region_list;
0109 
0110     /* Protect dimm health data from concurrent read/writes */
0111     struct mutex health_mutex;
0112 
0113     /* Last time the health information of the dimm was updated */
0114     unsigned long lasthealth_jiffies;
0115 
0116     /* Health information for the dimm */
0117     u64 health_bitmap;
0118 
0119     /* Holds the last known dirty shutdown counter value */
0120     u64 dirty_shutdown_counter;
0121 
0122     /* length of the stat buffer as expected by phyp */
0123     size_t stat_buffer_len;
0124 
0125     /* The bits which needs to be overridden */
0126     u64 health_bitmap_inject_mask;
0127 };
0128 
0129 static int papr_scm_pmem_flush(struct nd_region *nd_region,
0130                    struct bio *bio __maybe_unused)
0131 {
0132     struct papr_scm_priv *p = nd_region_provider_data(nd_region);
0133     unsigned long ret_buf[PLPAR_HCALL_BUFSIZE], token = 0;
0134     long rc;
0135 
0136     dev_dbg(&p->pdev->dev, "flush drc 0x%x", p->drc_index);
0137 
0138     do {
0139         rc = plpar_hcall(H_SCM_FLUSH, ret_buf, p->drc_index, token);
0140         token = ret_buf[0];
0141 
0142         /* Check if we are stalled for some time */
0143         if (H_IS_LONG_BUSY(rc)) {
0144             msleep(get_longbusy_msecs(rc));
0145             rc = H_BUSY;
0146         } else if (rc == H_BUSY) {
0147             cond_resched();
0148         }
0149     } while (rc == H_BUSY);
0150 
0151     if (rc) {
0152         dev_err(&p->pdev->dev, "flush error: %ld", rc);
0153         rc = -EIO;
0154     } else {
0155         dev_dbg(&p->pdev->dev, "flush drc 0x%x complete", p->drc_index);
0156     }
0157 
0158     return rc;
0159 }
0160 
0161 static LIST_HEAD(papr_nd_regions);
0162 static DEFINE_MUTEX(papr_ndr_lock);
0163 
0164 static int drc_pmem_bind(struct papr_scm_priv *p)
0165 {
0166     unsigned long ret[PLPAR_HCALL_BUFSIZE];
0167     uint64_t saved = 0;
0168     uint64_t token;
0169     int64_t rc;
0170 
0171     /*
0172      * When the hypervisor cannot map all the requested memory in a single
0173      * hcall it returns H_BUSY and we call again with the token until
0174      * we get H_SUCCESS. Aborting the retry loop before getting H_SUCCESS
0175      * leave the system in an undefined state, so we wait.
0176      */
0177     token = 0;
0178 
0179     do {
0180         rc = plpar_hcall(H_SCM_BIND_MEM, ret, p->drc_index, 0,
0181                 p->blocks, BIND_ANY_ADDR, token);
0182         token = ret[0];
0183         if (!saved)
0184             saved = ret[1];
0185         cond_resched();
0186     } while (rc == H_BUSY);
0187 
0188     if (rc)
0189         return rc;
0190 
0191     p->bound_addr = saved;
0192     dev_dbg(&p->pdev->dev, "bound drc 0x%x to 0x%lx\n",
0193         p->drc_index, (unsigned long)saved);
0194     return rc;
0195 }
0196 
0197 static void drc_pmem_unbind(struct papr_scm_priv *p)
0198 {
0199     unsigned long ret[PLPAR_HCALL_BUFSIZE];
0200     uint64_t token = 0;
0201     int64_t rc;
0202 
0203     dev_dbg(&p->pdev->dev, "unbind drc 0x%x\n", p->drc_index);
0204 
0205     /* NB: unbind has the same retry requirements as drc_pmem_bind() */
0206     do {
0207 
0208         /* Unbind of all SCM resources associated with drcIndex */
0209         rc = plpar_hcall(H_SCM_UNBIND_ALL, ret, H_UNBIND_SCOPE_DRC,
0210                  p->drc_index, token);
0211         token = ret[0];
0212 
0213         /* Check if we are stalled for some time */
0214         if (H_IS_LONG_BUSY(rc)) {
0215             msleep(get_longbusy_msecs(rc));
0216             rc = H_BUSY;
0217         } else if (rc == H_BUSY) {
0218             cond_resched();
0219         }
0220 
0221     } while (rc == H_BUSY);
0222 
0223     if (rc)
0224         dev_err(&p->pdev->dev, "unbind error: %lld\n", rc);
0225     else
0226         dev_dbg(&p->pdev->dev, "unbind drc 0x%x complete\n",
0227             p->drc_index);
0228 
0229     return;
0230 }
0231 
0232 static int drc_pmem_query_n_bind(struct papr_scm_priv *p)
0233 {
0234     unsigned long start_addr;
0235     unsigned long end_addr;
0236     unsigned long ret[PLPAR_HCALL_BUFSIZE];
0237     int64_t rc;
0238 
0239 
0240     rc = plpar_hcall(H_SCM_QUERY_BLOCK_MEM_BINDING, ret,
0241              p->drc_index, 0);
0242     if (rc)
0243         goto err_out;
0244     start_addr = ret[0];
0245 
0246     /* Make sure the full region is bound. */
0247     rc = plpar_hcall(H_SCM_QUERY_BLOCK_MEM_BINDING, ret,
0248              p->drc_index, p->blocks - 1);
0249     if (rc)
0250         goto err_out;
0251     end_addr = ret[0];
0252 
0253     if ((end_addr - start_addr) != ((p->blocks - 1) * p->block_size))
0254         goto err_out;
0255 
0256     p->bound_addr = start_addr;
0257     dev_dbg(&p->pdev->dev, "bound drc 0x%x to 0x%lx\n", p->drc_index, start_addr);
0258     return rc;
0259 
0260 err_out:
0261     dev_info(&p->pdev->dev,
0262          "Failed to query, trying an unbind followed by bind");
0263     drc_pmem_unbind(p);
0264     return drc_pmem_bind(p);
0265 }
0266 
0267 /*
0268  * Query the Dimm performance stats from PHYP and copy them (if returned) to
0269  * provided struct papr_scm_perf_stats instance 'stats' that can hold atleast
0270  * (num_stats + header) bytes.
0271  * - If buff_stats == NULL the return value is the size in bytes of the buffer
0272  * needed to hold all supported performance-statistics.
0273  * - If buff_stats != NULL and num_stats == 0 then we copy all known
0274  * performance-statistics to 'buff_stat' and expect to be large enough to
0275  * hold them.
0276  * - if buff_stats != NULL and num_stats > 0 then copy the requested
0277  * performance-statistics to buff_stats.
0278  */
0279 static ssize_t drc_pmem_query_stats(struct papr_scm_priv *p,
0280                     struct papr_scm_perf_stats *buff_stats,
0281                     unsigned int num_stats)
0282 {
0283     unsigned long ret[PLPAR_HCALL_BUFSIZE];
0284     size_t size;
0285     s64 rc;
0286 
0287     /* Setup the out buffer */
0288     if (buff_stats) {
0289         memcpy(buff_stats->eye_catcher,
0290                PAPR_SCM_PERF_STATS_EYECATCHER, 8);
0291         buff_stats->stats_version =
0292             cpu_to_be32(PAPR_SCM_PERF_STATS_VERSION);
0293         buff_stats->num_statistics =
0294             cpu_to_be32(num_stats);
0295 
0296         /*
0297          * Calculate the buffer size based on num-stats provided
0298          * or use the prefetched max buffer length
0299          */
0300         if (num_stats)
0301             /* Calculate size from the num_stats */
0302             size = sizeof(struct papr_scm_perf_stats) +
0303                 num_stats * sizeof(struct papr_scm_perf_stat);
0304         else
0305             size = p->stat_buffer_len;
0306     } else {
0307         /* In case of no out buffer ignore the size */
0308         size = 0;
0309     }
0310 
0311     /* Do the HCALL asking PHYP for info */
0312     rc = plpar_hcall(H_SCM_PERFORMANCE_STATS, ret, p->drc_index,
0313              buff_stats ? virt_to_phys(buff_stats) : 0,
0314              size);
0315 
0316     /* Check if the error was due to an unknown stat-id */
0317     if (rc == H_PARTIAL) {
0318         dev_err(&p->pdev->dev,
0319             "Unknown performance stats, Err:0x%016lX\n", ret[0]);
0320         return -ENOENT;
0321     } else if (rc == H_AUTHORITY) {
0322         dev_info(&p->pdev->dev,
0323              "Permission denied while accessing performance stats");
0324         return -EPERM;
0325     } else if (rc == H_UNSUPPORTED) {
0326         dev_dbg(&p->pdev->dev, "Performance stats unsupported\n");
0327         return -EOPNOTSUPP;
0328     } else if (rc != H_SUCCESS) {
0329         dev_err(&p->pdev->dev,
0330             "Failed to query performance stats, Err:%lld\n", rc);
0331         return -EIO;
0332 
0333     } else if (!size) {
0334         /* Handle case where stat buffer size was requested */
0335         dev_dbg(&p->pdev->dev,
0336             "Performance stats size %ld\n", ret[0]);
0337         return ret[0];
0338     }
0339 
0340     /* Successfully fetched the requested stats from phyp */
0341     dev_dbg(&p->pdev->dev,
0342         "Performance stats returned %d stats\n",
0343         be32_to_cpu(buff_stats->num_statistics));
0344     return 0;
0345 }
0346 
0347 #ifdef CONFIG_PERF_EVENTS
0348 #define to_nvdimm_pmu(_pmu) container_of(_pmu, struct nvdimm_pmu, pmu)
0349 
0350 static const char * const nvdimm_events_map[] = {
0351     [1] = "CtlResCt",
0352     [2] = "CtlResTm",
0353     [3] = "PonSecs ",
0354     [4] = "MemLife ",
0355     [5] = "CritRscU",
0356     [6] = "HostLCnt",
0357     [7] = "HostSCnt",
0358     [8] = "HostSDur",
0359     [9] = "HostLDur",
0360     [10] = "MedRCnt ",
0361     [11] = "MedWCnt ",
0362     [12] = "MedRDur ",
0363     [13] = "MedWDur ",
0364     [14] = "CchRHCnt",
0365     [15] = "CchWHCnt",
0366     [16] = "FastWCnt",
0367 };
0368 
0369 static int papr_scm_pmu_get_value(struct perf_event *event, struct device *dev, u64 *count)
0370 {
0371     struct papr_scm_perf_stat *stat;
0372     struct papr_scm_perf_stats *stats;
0373     struct papr_scm_priv *p = dev_get_drvdata(dev);
0374     int rc, size;
0375 
0376     /* Invalid eventcode */
0377     if (event->attr.config == 0 || event->attr.config >= ARRAY_SIZE(nvdimm_events_map))
0378         return -EINVAL;
0379 
0380     /* Allocate request buffer enough to hold single performance stat */
0381     size = sizeof(struct papr_scm_perf_stats) +
0382         sizeof(struct papr_scm_perf_stat);
0383 
0384     if (!p)
0385         return -EINVAL;
0386 
0387     stats = kzalloc(size, GFP_KERNEL);
0388     if (!stats)
0389         return -ENOMEM;
0390 
0391     stat = &stats->scm_statistic[0];
0392     memcpy(&stat->stat_id,
0393            nvdimm_events_map[event->attr.config],
0394         sizeof(stat->stat_id));
0395     stat->stat_val = 0;
0396 
0397     rc = drc_pmem_query_stats(p, stats, 1);
0398     if (rc < 0) {
0399         kfree(stats);
0400         return rc;
0401     }
0402 
0403     *count = be64_to_cpu(stat->stat_val);
0404     kfree(stats);
0405     return 0;
0406 }
0407 
0408 static int papr_scm_pmu_event_init(struct perf_event *event)
0409 {
0410     struct nvdimm_pmu *nd_pmu = to_nvdimm_pmu(event->pmu);
0411     struct papr_scm_priv *p;
0412 
0413     if (!nd_pmu)
0414         return -EINVAL;
0415 
0416     /* test the event attr type for PMU enumeration */
0417     if (event->attr.type != event->pmu->type)
0418         return -ENOENT;
0419 
0420     /* it does not support event sampling mode */
0421     if (is_sampling_event(event))
0422         return -EOPNOTSUPP;
0423 
0424     /* no branch sampling */
0425     if (has_branch_stack(event))
0426         return -EOPNOTSUPP;
0427 
0428     p = (struct papr_scm_priv *)nd_pmu->dev->driver_data;
0429     if (!p)
0430         return -EINVAL;
0431 
0432     /* Invalid eventcode */
0433     if (event->attr.config == 0 || event->attr.config > 16)
0434         return -EINVAL;
0435 
0436     return 0;
0437 }
0438 
0439 static int papr_scm_pmu_add(struct perf_event *event, int flags)
0440 {
0441     u64 count;
0442     int rc;
0443     struct nvdimm_pmu *nd_pmu = to_nvdimm_pmu(event->pmu);
0444 
0445     if (!nd_pmu)
0446         return -EINVAL;
0447 
0448     if (flags & PERF_EF_START) {
0449         rc = papr_scm_pmu_get_value(event, nd_pmu->dev, &count);
0450         if (rc)
0451             return rc;
0452 
0453         local64_set(&event->hw.prev_count, count);
0454     }
0455 
0456     return 0;
0457 }
0458 
0459 static void papr_scm_pmu_read(struct perf_event *event)
0460 {
0461     u64 prev, now;
0462     int rc;
0463     struct nvdimm_pmu *nd_pmu = to_nvdimm_pmu(event->pmu);
0464 
0465     if (!nd_pmu)
0466         return;
0467 
0468     rc = papr_scm_pmu_get_value(event, nd_pmu->dev, &now);
0469     if (rc)
0470         return;
0471 
0472     prev = local64_xchg(&event->hw.prev_count, now);
0473     local64_add(now - prev, &event->count);
0474 }
0475 
0476 static void papr_scm_pmu_del(struct perf_event *event, int flags)
0477 {
0478     papr_scm_pmu_read(event);
0479 }
0480 
0481 static void papr_scm_pmu_register(struct papr_scm_priv *p)
0482 {
0483     struct nvdimm_pmu *nd_pmu;
0484     int rc, nodeid;
0485 
0486     nd_pmu = kzalloc(sizeof(*nd_pmu), GFP_KERNEL);
0487     if (!nd_pmu) {
0488         rc = -ENOMEM;
0489         goto pmu_err_print;
0490     }
0491 
0492     if (!p->stat_buffer_len) {
0493         rc = -ENOENT;
0494         goto pmu_check_events_err;
0495     }
0496 
0497     nd_pmu->pmu.task_ctx_nr = perf_invalid_context;
0498     nd_pmu->pmu.name = nvdimm_name(p->nvdimm);
0499     nd_pmu->pmu.event_init = papr_scm_pmu_event_init;
0500     nd_pmu->pmu.read = papr_scm_pmu_read;
0501     nd_pmu->pmu.add = papr_scm_pmu_add;
0502     nd_pmu->pmu.del = papr_scm_pmu_del;
0503 
0504     nd_pmu->pmu.capabilities = PERF_PMU_CAP_NO_INTERRUPT |
0505                 PERF_PMU_CAP_NO_EXCLUDE;
0506 
0507     /*updating the cpumask variable */
0508     nodeid = numa_map_to_online_node(dev_to_node(&p->pdev->dev));
0509     nd_pmu->arch_cpumask = *cpumask_of_node(nodeid);
0510 
0511     rc = register_nvdimm_pmu(nd_pmu, p->pdev);
0512     if (rc)
0513         goto pmu_check_events_err;
0514 
0515     /*
0516      * Set archdata.priv value to nvdimm_pmu structure, to handle the
0517      * unregistering of pmu device.
0518      */
0519     p->pdev->archdata.priv = nd_pmu;
0520     return;
0521 
0522 pmu_check_events_err:
0523     kfree(nd_pmu);
0524 pmu_err_print:
0525     dev_info(&p->pdev->dev, "nvdimm pmu didn't register rc=%d\n", rc);
0526 }
0527 
0528 #else
0529 static void papr_scm_pmu_register(struct papr_scm_priv *p) { }
0530 #endif
0531 
0532 /*
0533  * Issue hcall to retrieve dimm health info and populate papr_scm_priv with the
0534  * health information.
0535  */
0536 static int __drc_pmem_query_health(struct papr_scm_priv *p)
0537 {
0538     unsigned long ret[PLPAR_HCALL_BUFSIZE];
0539     u64 bitmap = 0;
0540     long rc;
0541 
0542     /* issue the hcall */
0543     rc = plpar_hcall(H_SCM_HEALTH, ret, p->drc_index);
0544     if (rc == H_SUCCESS)
0545         bitmap = ret[0] & ret[1];
0546     else if (rc == H_FUNCTION)
0547         dev_info_once(&p->pdev->dev,
0548                   "Hcall H_SCM_HEALTH not implemented, assuming empty health bitmap");
0549     else {
0550 
0551         dev_err(&p->pdev->dev,
0552             "Failed to query health information, Err:%ld\n", rc);
0553         return -ENXIO;
0554     }
0555 
0556     p->lasthealth_jiffies = jiffies;
0557     /* Allow injecting specific health bits via inject mask. */
0558     if (p->health_bitmap_inject_mask)
0559         bitmap = (bitmap & ~p->health_bitmap_inject_mask) |
0560             p->health_bitmap_inject_mask;
0561     WRITE_ONCE(p->health_bitmap, bitmap);
0562     dev_dbg(&p->pdev->dev,
0563         "Queried dimm health info. Bitmap:0x%016lx Mask:0x%016lx\n",
0564         ret[0], ret[1]);
0565 
0566     return 0;
0567 }
0568 
0569 /* Min interval in seconds for assuming stable dimm health */
0570 #define MIN_HEALTH_QUERY_INTERVAL 60
0571 
0572 /* Query cached health info and if needed call drc_pmem_query_health */
0573 static int drc_pmem_query_health(struct papr_scm_priv *p)
0574 {
0575     unsigned long cache_timeout;
0576     int rc;
0577 
0578     /* Protect concurrent modifications to papr_scm_priv */
0579     rc = mutex_lock_interruptible(&p->health_mutex);
0580     if (rc)
0581         return rc;
0582 
0583     /* Jiffies offset for which the health data is assumed to be same */
0584     cache_timeout = p->lasthealth_jiffies +
0585         msecs_to_jiffies(MIN_HEALTH_QUERY_INTERVAL * 1000);
0586 
0587     /* Fetch new health info is its older than MIN_HEALTH_QUERY_INTERVAL */
0588     if (time_after(jiffies, cache_timeout))
0589         rc = __drc_pmem_query_health(p);
0590     else
0591         /* Assume cached health data is valid */
0592         rc = 0;
0593 
0594     mutex_unlock(&p->health_mutex);
0595     return rc;
0596 }
0597 
0598 static int papr_scm_meta_get(struct papr_scm_priv *p,
0599                  struct nd_cmd_get_config_data_hdr *hdr)
0600 {
0601     unsigned long data[PLPAR_HCALL_BUFSIZE];
0602     unsigned long offset, data_offset;
0603     int len, read;
0604     int64_t ret;
0605 
0606     if ((hdr->in_offset + hdr->in_length) > p->metadata_size)
0607         return -EINVAL;
0608 
0609     for (len = hdr->in_length; len; len -= read) {
0610 
0611         data_offset = hdr->in_length - len;
0612         offset = hdr->in_offset + data_offset;
0613 
0614         if (len >= 8)
0615             read = 8;
0616         else if (len >= 4)
0617             read = 4;
0618         else if (len >= 2)
0619             read = 2;
0620         else
0621             read = 1;
0622 
0623         ret = plpar_hcall(H_SCM_READ_METADATA, data, p->drc_index,
0624                   offset, read);
0625 
0626         if (ret == H_PARAMETER) /* bad DRC index */
0627             return -ENODEV;
0628         if (ret)
0629             return -EINVAL; /* other invalid parameter */
0630 
0631         switch (read) {
0632         case 8:
0633             *(uint64_t *)(hdr->out_buf + data_offset) = be64_to_cpu(data[0]);
0634             break;
0635         case 4:
0636             *(uint32_t *)(hdr->out_buf + data_offset) = be32_to_cpu(data[0] & 0xffffffff);
0637             break;
0638 
0639         case 2:
0640             *(uint16_t *)(hdr->out_buf + data_offset) = be16_to_cpu(data[0] & 0xffff);
0641             break;
0642 
0643         case 1:
0644             *(uint8_t *)(hdr->out_buf + data_offset) = (data[0] & 0xff);
0645             break;
0646         }
0647     }
0648     return 0;
0649 }
0650 
0651 static int papr_scm_meta_set(struct papr_scm_priv *p,
0652                  struct nd_cmd_set_config_hdr *hdr)
0653 {
0654     unsigned long offset, data_offset;
0655     int len, wrote;
0656     unsigned long data;
0657     __be64 data_be;
0658     int64_t ret;
0659 
0660     if ((hdr->in_offset + hdr->in_length) > p->metadata_size)
0661         return -EINVAL;
0662 
0663     for (len = hdr->in_length; len; len -= wrote) {
0664 
0665         data_offset = hdr->in_length - len;
0666         offset = hdr->in_offset + data_offset;
0667 
0668         if (len >= 8) {
0669             data = *(uint64_t *)(hdr->in_buf + data_offset);
0670             data_be = cpu_to_be64(data);
0671             wrote = 8;
0672         } else if (len >= 4) {
0673             data = *(uint32_t *)(hdr->in_buf + data_offset);
0674             data &= 0xffffffff;
0675             data_be = cpu_to_be32(data);
0676             wrote = 4;
0677         } else if (len >= 2) {
0678             data = *(uint16_t *)(hdr->in_buf + data_offset);
0679             data &= 0xffff;
0680             data_be = cpu_to_be16(data);
0681             wrote = 2;
0682         } else {
0683             data_be = *(uint8_t *)(hdr->in_buf + data_offset);
0684             data_be &= 0xff;
0685             wrote = 1;
0686         }
0687 
0688         ret = plpar_hcall_norets(H_SCM_WRITE_METADATA, p->drc_index,
0689                      offset, data_be, wrote);
0690         if (ret == H_PARAMETER) /* bad DRC index */
0691             return -ENODEV;
0692         if (ret)
0693             return -EINVAL; /* other invalid parameter */
0694     }
0695 
0696     return 0;
0697 }
0698 
0699 /*
0700  * Do a sanity checks on the inputs args to dimm-control function and return
0701  * '0' if valid. Validation of PDSM payloads happens later in
0702  * papr_scm_service_pdsm.
0703  */
0704 static int is_cmd_valid(struct nvdimm *nvdimm, unsigned int cmd, void *buf,
0705             unsigned int buf_len)
0706 {
0707     unsigned long cmd_mask = PAPR_SCM_DIMM_CMD_MASK;
0708     struct nd_cmd_pkg *nd_cmd;
0709     struct papr_scm_priv *p;
0710     enum papr_pdsm pdsm;
0711 
0712     /* Only dimm-specific calls are supported atm */
0713     if (!nvdimm)
0714         return -EINVAL;
0715 
0716     /* get the provider data from struct nvdimm */
0717     p = nvdimm_provider_data(nvdimm);
0718 
0719     if (!test_bit(cmd, &cmd_mask)) {
0720         dev_dbg(&p->pdev->dev, "Unsupported cmd=%u\n", cmd);
0721         return -EINVAL;
0722     }
0723 
0724     /* For CMD_CALL verify pdsm request */
0725     if (cmd == ND_CMD_CALL) {
0726         /* Verify the envelope and envelop size */
0727         if (!buf ||
0728             buf_len < (sizeof(struct nd_cmd_pkg) + ND_PDSM_HDR_SIZE)) {
0729             dev_dbg(&p->pdev->dev, "Invalid pkg size=%u\n",
0730                 buf_len);
0731             return -EINVAL;
0732         }
0733 
0734         /* Verify that the nd_cmd_pkg.nd_family is correct */
0735         nd_cmd = (struct nd_cmd_pkg *)buf;
0736 
0737         if (nd_cmd->nd_family != NVDIMM_FAMILY_PAPR) {
0738             dev_dbg(&p->pdev->dev, "Invalid pkg family=0x%llx\n",
0739                 nd_cmd->nd_family);
0740             return -EINVAL;
0741         }
0742 
0743         pdsm = (enum papr_pdsm)nd_cmd->nd_command;
0744 
0745         /* Verify if the pdsm command is valid */
0746         if (pdsm <= PAPR_PDSM_MIN || pdsm >= PAPR_PDSM_MAX) {
0747             dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Invalid PDSM\n",
0748                 pdsm);
0749             return -EINVAL;
0750         }
0751 
0752         /* Have enough space to hold returned 'nd_pkg_pdsm' header */
0753         if (nd_cmd->nd_size_out < ND_PDSM_HDR_SIZE) {
0754             dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Invalid payload\n",
0755                 pdsm);
0756             return -EINVAL;
0757         }
0758     }
0759 
0760     /* Let the command be further processed */
0761     return 0;
0762 }
0763 
0764 static int papr_pdsm_fuel_gauge(struct papr_scm_priv *p,
0765                 union nd_pdsm_payload *payload)
0766 {
0767     int rc, size;
0768     u64 statval;
0769     struct papr_scm_perf_stat *stat;
0770     struct papr_scm_perf_stats *stats;
0771 
0772     /* Silently fail if fetching performance metrics isn't  supported */
0773     if (!p->stat_buffer_len)
0774         return 0;
0775 
0776     /* Allocate request buffer enough to hold single performance stat */
0777     size = sizeof(struct papr_scm_perf_stats) +
0778         sizeof(struct papr_scm_perf_stat);
0779 
0780     stats = kzalloc(size, GFP_KERNEL);
0781     if (!stats)
0782         return -ENOMEM;
0783 
0784     stat = &stats->scm_statistic[0];
0785     memcpy(&stat->stat_id, "MemLife ", sizeof(stat->stat_id));
0786     stat->stat_val = 0;
0787 
0788     /* Fetch the fuel gauge and populate it in payload */
0789     rc = drc_pmem_query_stats(p, stats, 1);
0790     if (rc < 0) {
0791         dev_dbg(&p->pdev->dev, "Err(%d) fetching fuel gauge\n", rc);
0792         goto free_stats;
0793     }
0794 
0795     statval = be64_to_cpu(stat->stat_val);
0796     dev_dbg(&p->pdev->dev,
0797         "Fetched fuel-gauge %llu", statval);
0798     payload->health.extension_flags |=
0799         PDSM_DIMM_HEALTH_RUN_GAUGE_VALID;
0800     payload->health.dimm_fuel_gauge = statval;
0801 
0802     rc = sizeof(struct nd_papr_pdsm_health);
0803 
0804 free_stats:
0805     kfree(stats);
0806     return rc;
0807 }
0808 
0809 /* Add the dirty-shutdown-counter value to the pdsm */
0810 static int papr_pdsm_dsc(struct papr_scm_priv *p,
0811              union nd_pdsm_payload *payload)
0812 {
0813     payload->health.extension_flags |= PDSM_DIMM_DSC_VALID;
0814     payload->health.dimm_dsc = p->dirty_shutdown_counter;
0815 
0816     return sizeof(struct nd_papr_pdsm_health);
0817 }
0818 
0819 /* Fetch the DIMM health info and populate it in provided package. */
0820 static int papr_pdsm_health(struct papr_scm_priv *p,
0821                 union nd_pdsm_payload *payload)
0822 {
0823     int rc;
0824 
0825     /* Ensure dimm health mutex is taken preventing concurrent access */
0826     rc = mutex_lock_interruptible(&p->health_mutex);
0827     if (rc)
0828         goto out;
0829 
0830     /* Always fetch upto date dimm health data ignoring cached values */
0831     rc = __drc_pmem_query_health(p);
0832     if (rc) {
0833         mutex_unlock(&p->health_mutex);
0834         goto out;
0835     }
0836 
0837     /* update health struct with various flags derived from health bitmap */
0838     payload->health = (struct nd_papr_pdsm_health) {
0839         .extension_flags = 0,
0840         .dimm_unarmed = !!(p->health_bitmap & PAPR_PMEM_UNARMED_MASK),
0841         .dimm_bad_shutdown = !!(p->health_bitmap & PAPR_PMEM_BAD_SHUTDOWN_MASK),
0842         .dimm_bad_restore = !!(p->health_bitmap & PAPR_PMEM_BAD_RESTORE_MASK),
0843         .dimm_scrubbed = !!(p->health_bitmap & PAPR_PMEM_SCRUBBED_AND_LOCKED),
0844         .dimm_locked = !!(p->health_bitmap & PAPR_PMEM_SCRUBBED_AND_LOCKED),
0845         .dimm_encrypted = !!(p->health_bitmap & PAPR_PMEM_ENCRYPTED),
0846         .dimm_health = PAPR_PDSM_DIMM_HEALTHY,
0847     };
0848 
0849     /* Update field dimm_health based on health_bitmap flags */
0850     if (p->health_bitmap & PAPR_PMEM_HEALTH_FATAL)
0851         payload->health.dimm_health = PAPR_PDSM_DIMM_FATAL;
0852     else if (p->health_bitmap & PAPR_PMEM_HEALTH_CRITICAL)
0853         payload->health.dimm_health = PAPR_PDSM_DIMM_CRITICAL;
0854     else if (p->health_bitmap & PAPR_PMEM_HEALTH_UNHEALTHY)
0855         payload->health.dimm_health = PAPR_PDSM_DIMM_UNHEALTHY;
0856 
0857     /* struct populated hence can release the mutex now */
0858     mutex_unlock(&p->health_mutex);
0859 
0860     /* Populate the fuel gauge meter in the payload */
0861     papr_pdsm_fuel_gauge(p, payload);
0862     /* Populate the dirty-shutdown-counter field */
0863     papr_pdsm_dsc(p, payload);
0864 
0865     rc = sizeof(struct nd_papr_pdsm_health);
0866 
0867 out:
0868     return rc;
0869 }
0870 
0871 /* Inject a smart error Add the dirty-shutdown-counter value to the pdsm */
0872 static int papr_pdsm_smart_inject(struct papr_scm_priv *p,
0873                   union nd_pdsm_payload *payload)
0874 {
0875     int rc;
0876     u32 supported_flags = 0;
0877     u64 inject_mask = 0, clear_mask = 0;
0878     u64 mask;
0879 
0880     /* Check for individual smart error flags and update inject/clear masks */
0881     if (payload->smart_inject.flags & PDSM_SMART_INJECT_HEALTH_FATAL) {
0882         supported_flags |= PDSM_SMART_INJECT_HEALTH_FATAL;
0883         if (payload->smart_inject.fatal_enable)
0884             inject_mask |= PAPR_PMEM_HEALTH_FATAL;
0885         else
0886             clear_mask |= PAPR_PMEM_HEALTH_FATAL;
0887     }
0888 
0889     if (payload->smart_inject.flags & PDSM_SMART_INJECT_BAD_SHUTDOWN) {
0890         supported_flags |= PDSM_SMART_INJECT_BAD_SHUTDOWN;
0891         if (payload->smart_inject.unsafe_shutdown_enable)
0892             inject_mask |= PAPR_PMEM_SHUTDOWN_DIRTY;
0893         else
0894             clear_mask |= PAPR_PMEM_SHUTDOWN_DIRTY;
0895     }
0896 
0897     dev_dbg(&p->pdev->dev, "[Smart-inject] inject_mask=%#llx clear_mask=%#llx\n",
0898         inject_mask, clear_mask);
0899 
0900     /* Prevent concurrent access to dimm health bitmap related members */
0901     rc = mutex_lock_interruptible(&p->health_mutex);
0902     if (rc)
0903         return rc;
0904 
0905     /* Use inject/clear masks to set health_bitmap_inject_mask */
0906     mask = READ_ONCE(p->health_bitmap_inject_mask);
0907     mask = (mask & ~clear_mask) | inject_mask;
0908     WRITE_ONCE(p->health_bitmap_inject_mask, mask);
0909 
0910     /* Invalidate cached health bitmap */
0911     p->lasthealth_jiffies = 0;
0912 
0913     mutex_unlock(&p->health_mutex);
0914 
0915     /* Return the supported flags back to userspace */
0916     payload->smart_inject.flags = supported_flags;
0917 
0918     return sizeof(struct nd_papr_pdsm_health);
0919 }
0920 
0921 /*
0922  * 'struct pdsm_cmd_desc'
0923  * Identifies supported PDSMs' expected length of in/out payloads
0924  * and pdsm service function.
0925  *
0926  * size_in  : Size of input payload if any in the PDSM request.
0927  * size_out : Size of output payload if any in the PDSM request.
0928  * service  : Service function for the PDSM request. Return semantics:
0929  *        rc < 0 : Error servicing PDSM and rc indicates the error.
0930  *        rc >=0 : Serviced successfully and 'rc' indicate number of
0931  *          bytes written to payload.
0932  */
0933 struct pdsm_cmd_desc {
0934     u32 size_in;
0935     u32 size_out;
0936     int (*service)(struct papr_scm_priv *dimm,
0937                union nd_pdsm_payload *payload);
0938 };
0939 
0940 /* Holds all supported PDSMs' command descriptors */
0941 static const struct pdsm_cmd_desc __pdsm_cmd_descriptors[] = {
0942     [PAPR_PDSM_MIN] = {
0943         .size_in = 0,
0944         .size_out = 0,
0945         .service = NULL,
0946     },
0947     /* New PDSM command descriptors to be added below */
0948 
0949     [PAPR_PDSM_HEALTH] = {
0950         .size_in = 0,
0951         .size_out = sizeof(struct nd_papr_pdsm_health),
0952         .service = papr_pdsm_health,
0953     },
0954 
0955     [PAPR_PDSM_SMART_INJECT] = {
0956         .size_in = sizeof(struct nd_papr_pdsm_smart_inject),
0957         .size_out = sizeof(struct nd_papr_pdsm_smart_inject),
0958         .service = papr_pdsm_smart_inject,
0959     },
0960     /* Empty */
0961     [PAPR_PDSM_MAX] = {
0962         .size_in = 0,
0963         .size_out = 0,
0964         .service = NULL,
0965     },
0966 };
0967 
0968 /* Given a valid pdsm cmd return its command descriptor else return NULL */
0969 static inline const struct pdsm_cmd_desc *pdsm_cmd_desc(enum papr_pdsm cmd)
0970 {
0971     if (cmd >= 0 || cmd < ARRAY_SIZE(__pdsm_cmd_descriptors))
0972         return &__pdsm_cmd_descriptors[cmd];
0973 
0974     return NULL;
0975 }
0976 
0977 /*
0978  * For a given pdsm request call an appropriate service function.
0979  * Returns errors if any while handling the pdsm command package.
0980  */
0981 static int papr_scm_service_pdsm(struct papr_scm_priv *p,
0982                  struct nd_cmd_pkg *pkg)
0983 {
0984     /* Get the PDSM header and PDSM command */
0985     struct nd_pkg_pdsm *pdsm_pkg = (struct nd_pkg_pdsm *)pkg->nd_payload;
0986     enum papr_pdsm pdsm = (enum papr_pdsm)pkg->nd_command;
0987     const struct pdsm_cmd_desc *pdsc;
0988     int rc;
0989 
0990     /* Fetch corresponding pdsm descriptor for validation and servicing */
0991     pdsc = pdsm_cmd_desc(pdsm);
0992 
0993     /* Validate pdsm descriptor */
0994     /* Ensure that reserved fields are 0 */
0995     if (pdsm_pkg->reserved[0] || pdsm_pkg->reserved[1]) {
0996         dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Invalid reserved field\n",
0997             pdsm);
0998         return -EINVAL;
0999     }
1000 
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);
1006         return -EINVAL;
1007     }
1008 
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);
1014         return -EINVAL;
1015     }
1016 
1017     /* Service the pdsm */
1018     if (pdsc->service) {
1019         dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Servicing..\n", pdsm);
1020 
1021         rc = pdsc->service(p, &pdsm_pkg->payload);
1022 
1023         if (rc < 0) {
1024             /* error encountered while servicing pdsm */
1025             pdsm_pkg->cmd_status = rc;
1026             pkg->nd_fw_size = ND_PDSM_HDR_SIZE;
1027         } else {
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;
1031         }
1032     } else {
1033         dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Unsupported PDSM request\n",
1034             pdsm);
1035         pdsm_pkg->cmd_status = -ENOENT;
1036         pkg->nd_fw_size = ND_PDSM_HDR_SIZE;
1037     }
1038 
1039     return pdsm_pkg->cmd_status;
1040 }
1041 
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)
1045 {
1046     struct nd_cmd_get_config_size *get_size_hdr;
1047     struct nd_cmd_pkg *call_pkg = NULL;
1048     struct papr_scm_priv *p;
1049     int rc;
1050 
1051     rc = is_cmd_valid(nvdimm, cmd, buf, buf_len);
1052     if (rc) {
1053         pr_debug("Invalid cmd=0x%x. Err=%d\n", cmd, rc);
1054         return rc;
1055     }
1056 
1057     /* Use a local variable in case cmd_rc pointer is NULL */
1058     if (!cmd_rc)
1059         cmd_rc = &rc;
1060 
1061     p = nvdimm_provider_data(nvdimm);
1062 
1063     switch (cmd) {
1064     case ND_CMD_GET_CONFIG_SIZE:
1065         get_size_hdr = buf;
1066 
1067         get_size_hdr->status = 0;
1068         get_size_hdr->max_xfer = 8;
1069         get_size_hdr->config_size = p->metadata_size;
1070         *cmd_rc = 0;
1071         break;
1072 
1073     case ND_CMD_GET_CONFIG_DATA:
1074         *cmd_rc = papr_scm_meta_get(p, buf);
1075         break;
1076 
1077     case ND_CMD_SET_CONFIG_DATA:
1078         *cmd_rc = papr_scm_meta_set(p, buf);
1079         break;
1080 
1081     case ND_CMD_CALL:
1082         call_pkg = (struct nd_cmd_pkg *)buf;
1083         *cmd_rc = papr_scm_service_pdsm(p, call_pkg);
1084         break;
1085 
1086     default:
1087         dev_dbg(&p->pdev->dev, "Unknown command = %d\n", cmd);
1088         return -EINVAL;
1089     }
1090 
1091     dev_dbg(&p->pdev->dev, "returned with cmd_rc = %d\n", *cmd_rc);
1092 
1093     return 0;
1094 }
1095 
1096 static ssize_t health_bitmap_inject_show(struct device *dev,
1097                      struct device_attribute *attr,
1098                      char *buf)
1099 {
1100     struct nvdimm *dimm = to_nvdimm(dev);
1101     struct papr_scm_priv *p = nvdimm_provider_data(dimm);
1102 
1103     return sprintf(buf, "%#llx\n",
1104                READ_ONCE(p->health_bitmap_inject_mask));
1105 }
1106 
1107 static DEVICE_ATTR_ADMIN_RO(health_bitmap_inject);
1108 
1109 static ssize_t perf_stats_show(struct device *dev,
1110                    struct device_attribute *attr, char *buf)
1111 {
1112     int index;
1113     ssize_t rc;
1114     struct seq_buf s;
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);
1119 
1120     if (!p->stat_buffer_len)
1121         return -ENOENT;
1122 
1123     /* Allocate the buffer for phyp where stats are written */
1124     stats = kzalloc(p->stat_buffer_len, GFP_KERNEL);
1125     if (!stats)
1126         return -ENOMEM;
1127 
1128     /* Ask phyp to return all dimm perf stats */
1129     rc = drc_pmem_query_stats(p, stats, 0);
1130     if (rc)
1131         goto free_stats;
1132     /*
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.
1136      */
1137     seq_buf_init(&s, buf, PAGE_SIZE);
1138     for (index = 0, stat = stats->scm_statistic;
1139          index < be32_to_cpu(stats->num_statistics);
1140          ++index, ++stat) {
1141         seq_buf_printf(&s, "%.8s = 0x%016llX\n",
1142                    stat->stat_id,
1143                    be64_to_cpu(stat->stat_val));
1144     }
1145 
1146 free_stats:
1147     kfree(stats);
1148     return rc ? rc : (ssize_t)seq_buf_used(&s);
1149 }
1150 static DEVICE_ATTR_ADMIN_RO(perf_stats);
1151 
1152 static ssize_t flags_show(struct device *dev,
1153               struct device_attribute *attr, char *buf)
1154 {
1155     struct nvdimm *dimm = to_nvdimm(dev);
1156     struct papr_scm_priv *p = nvdimm_provider_data(dimm);
1157     struct seq_buf s;
1158     u64 health;
1159     int rc;
1160 
1161     rc = drc_pmem_query_health(p);
1162     if (rc)
1163         return rc;
1164 
1165     /* Copy health_bitmap locally, check masks & update out buffer */
1166     health = READ_ONCE(p->health_bitmap);
1167 
1168     seq_buf_init(&s, buf, PAGE_SIZE);
1169     if (health & PAPR_PMEM_UNARMED_MASK)
1170         seq_buf_printf(&s, "not_armed ");
1171 
1172     if (health & PAPR_PMEM_BAD_SHUTDOWN_MASK)
1173         seq_buf_printf(&s, "flush_fail ");
1174 
1175     if (health & PAPR_PMEM_BAD_RESTORE_MASK)
1176         seq_buf_printf(&s, "restore_fail ");
1177 
1178     if (health & PAPR_PMEM_ENCRYPTED)
1179         seq_buf_printf(&s, "encrypted ");
1180 
1181     if (health & PAPR_PMEM_SMART_EVENT_MASK)
1182         seq_buf_printf(&s, "smart_notify ");
1183 
1184     if (health & PAPR_PMEM_SCRUBBED_AND_LOCKED)
1185         seq_buf_printf(&s, "scrubbed locked ");
1186 
1187     if (seq_buf_used(&s))
1188         seq_buf_printf(&s, "\n");
1189 
1190     return seq_buf_used(&s);
1191 }
1192 DEVICE_ATTR_RO(flags);
1193 
1194 static ssize_t dirty_shutdown_show(struct device *dev,
1195               struct device_attribute *attr, char *buf)
1196 {
1197     struct nvdimm *dimm = to_nvdimm(dev);
1198     struct papr_scm_priv *p = nvdimm_provider_data(dimm);
1199 
1200     return sysfs_emit(buf, "%llu\n", p->dirty_shutdown_counter);
1201 }
1202 DEVICE_ATTR_RO(dirty_shutdown);
1203 
1204 static umode_t papr_nd_attribute_visible(struct kobject *kobj,
1205                      struct attribute *attr, int n)
1206 {
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);
1210 
1211     /* For if perf-stats not available remove perf_stats sysfs */
1212     if (attr == &dev_attr_perf_stats.attr && p->stat_buffer_len == 0)
1213         return 0;
1214 
1215     return attr->mode;
1216 }
1217 
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,
1224     NULL,
1225 };
1226 
1227 static const struct attribute_group papr_nd_attribute_group = {
1228     .name = "papr",
1229     .is_visible = papr_nd_attribute_visible,
1230     .attrs = papr_nd_attributes,
1231 };
1232 
1233 static const struct attribute_group *papr_nd_attr_groups[] = {
1234     &papr_nd_attribute_group,
1235     NULL,
1236 };
1237 
1238 static int papr_scm_nvdimm_init(struct papr_scm_priv *p)
1239 {
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;
1245 
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);
1250 
1251     /* Set the dimm command family mask to accept PDSMs */
1252     set_bit(NVDIMM_FAMILY_PAPR, &p->bus_desc.dimm_family_mask);
1253 
1254     if (!p->bus_desc.provider_name)
1255         return -ENOMEM;
1256 
1257     p->bus = nvdimm_bus_register(NULL, &p->bus_desc);
1258     if (!p->bus) {
1259         dev_err(dev, "Error creating nvdimm bus %pOF\n", p->dn);
1260         kfree(p->bus_desc.provider_name);
1261         return -ENXIO;
1262     }
1263 
1264     dimm_flags = 0;
1265     set_bit(NDD_LABELING, &dimm_flags);
1266 
1267     /*
1268      * Check if the nvdimm is unarmed. No locking needed as we are still
1269      * initializing. Ignore error encountered if any.
1270      */
1271     __drc_pmem_query_health(p);
1272 
1273     if (p->health_bitmap & PAPR_PMEM_UNARMED_MASK)
1274         set_bit(NDD_UNARMED, &dimm_flags);
1275 
1276     p->nvdimm = nvdimm_create(p->bus, p, papr_nd_attr_groups,
1277                   dimm_flags, PAPR_SCM_DIMM_CMD_MASK, 0, NULL);
1278     if (!p->nvdimm) {
1279         dev_err(dev, "Error creating DIMM object for %pOF\n", p->dn);
1280         goto err;
1281     }
1282 
1283     if (nvdimm_bus_check_dimm_count(p->bus, 1))
1284         goto err;
1285 
1286     /* now add the region */
1287 
1288     memset(&mapping, 0, sizeof(mapping));
1289     mapping.nvdimm = p->nvdimm;
1290     mapping.start = 0;
1291     mapping.size = p->blocks * p->block_size; // XXX: potential overflow?
1292 
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;
1304 
1305     if (p->hcall_flush_required) {
1306         set_bit(ND_REGION_ASYNC, &ndr_desc.flags);
1307         ndr_desc.flush = papr_scm_pmem_flush;
1308     }
1309 
1310     if (p->is_volatile)
1311         p->region = nvdimm_volatile_region_create(p->bus, &ndr_desc);
1312     else {
1313         set_bit(ND_REGION_PERSIST_MEMCTRL, &ndr_desc.flags);
1314         p->region = nvdimm_pmem_region_create(p->bus, &ndr_desc);
1315     }
1316     if (!p->region) {
1317         dev_err(dev, "Error registering region %pR from %pOF\n",
1318                 ndr_desc.res, p->dn);
1319         goto err;
1320     }
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);
1324 
1325     mutex_lock(&papr_ndr_lock);
1326     list_add_tail(&p->region_list, &papr_nd_regions);
1327     mutex_unlock(&papr_ndr_lock);
1328 
1329     return 0;
1330 
1331 err:    nvdimm_bus_unregister(p->bus);
1332     kfree(p->bus_desc.provider_name);
1333     return -ENXIO;
1334 }
1335 
1336 static void papr_scm_add_badblock(struct nd_region *region,
1337                   struct nvdimm_bus *bus, u64 phys_addr)
1338 {
1339     u64 aligned_addr = ALIGN_DOWN(phys_addr, L1_CACHE_BYTES);
1340 
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);
1343         return;
1344     }
1345 
1346     pr_debug("Add memory range (0x%llx - 0x%llx) as bad range\n",
1347          aligned_addr, aligned_addr + L1_CACHE_BYTES);
1348 
1349     nvdimm_region_notify(region, NVDIMM_REVALIDATE_POISON);
1350 }
1351 
1352 static int handle_mce_ue(struct notifier_block *nb, unsigned long val,
1353              void *data)
1354 {
1355     struct machine_check_event *evt = data;
1356     struct papr_scm_priv *p;
1357     u64 phys_addr;
1358     bool found = false;
1359 
1360     if (evt->error_type != MCE_ERROR_TYPE_UE)
1361         return NOTIFY_DONE;
1362 
1363     if (list_empty(&papr_nd_regions))
1364         return NOTIFY_DONE;
1365 
1366     /*
1367      * The physical address obtained here is PAGE_SIZE aligned, so get the
1368      * exact address from the effective address
1369      */
1370     phys_addr = evt->u.ue_error.physical_address +
1371             (evt->u.ue_error.effective_address & ~PAGE_MASK);
1372 
1373     if (!evt->u.ue_error.physical_address_provided ||
1374         !is_zone_device_page(pfn_to_page(phys_addr >> PAGE_SHIFT)))
1375         return NOTIFY_DONE;
1376 
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) {
1381             found = true;
1382             break;
1383         }
1384     }
1385 
1386     if (found)
1387         papr_scm_add_badblock(p->region, p->bus, phys_addr);
1388 
1389     mutex_unlock(&papr_ndr_lock);
1390 
1391     return found ? NOTIFY_OK : NOTIFY_DONE;
1392 }
1393 
1394 static struct notifier_block mce_ue_nb = {
1395     .notifier_call = handle_mce_ue
1396 };
1397 
1398 static int papr_scm_probe(struct platform_device *pdev)
1399 {
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;
1406     ssize_t stat_size;
1407     uuid_t uuid;
1408     int rc;
1409 
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);
1413         return -ENODEV;
1414     }
1415 
1416     if (of_property_read_u64(dn, "ibm,block-size", &block_size)) {
1417         dev_err(&pdev->dev, "%pOF: missing block-size!\n", dn);
1418         return -ENODEV;
1419     }
1420 
1421     if (of_property_read_u64(dn, "ibm,number-of-blocks", &blocks)) {
1422         dev_err(&pdev->dev, "%pOF: missing number-of-blocks!\n", dn);
1423         return -ENODEV;
1424     }
1425 
1426     if (of_property_read_string(dn, "ibm,unit-guid", &uuid_str)) {
1427         dev_err(&pdev->dev, "%pOF: missing unit-guid!\n", dn);
1428         return -ENODEV;
1429     }
1430 
1431 
1432     p = kzalloc(sizeof(*p), GFP_KERNEL);
1433     if (!p)
1434         return -ENOMEM;
1435 
1436     /* Initialize the dimm mutex */
1437     mutex_init(&p->health_mutex);
1438 
1439     /* optional DT properties */
1440     of_property_read_u32(dn, "ibm,metadata-size", &metadata_size);
1441 
1442     p->dn = dn;
1443     p->drc_index = drc_index;
1444     p->block_size = block_size;
1445     p->blocks = blocks;
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");
1448 
1449     if (of_property_read_u64(dn, "ibm,persistence-failed-count",
1450                  &p->dirty_shutdown_counter))
1451         p->dirty_shutdown_counter = 0;
1452 
1453     /* We just need to ensure that set cookies are unique across */
1454     uuid_parse(uuid_str, &uuid);
1455 
1456     /*
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.
1462      *
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
1467      */
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]);
1471 
1472     /* might be zero */
1473     p->metadata_size = metadata_size;
1474     p->pdev = pdev;
1475 
1476     /* request the hypervisor to bind this region to somewhere in memory */
1477     rc = drc_pmem_bind(p);
1478 
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);
1482 
1483     if (rc != H_SUCCESS) {
1484         dev_err(&p->pdev->dev, "bind err: %d\n", rc);
1485         rc = -ENXIO;
1486         goto err;
1487     }
1488 
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;
1494 
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);
1501     }
1502 
1503     rc = papr_scm_nvdimm_init(p);
1504     if (rc)
1505         goto err2;
1506 
1507     platform_set_drvdata(pdev, p);
1508     papr_scm_pmu_register(p);
1509 
1510     return 0;
1511 
1512 err2:   drc_pmem_unbind(p);
1513 err:    kfree(p);
1514     return rc;
1515 }
1516 
1517 static int papr_scm_remove(struct platform_device *pdev)
1518 {
1519     struct papr_scm_priv *p = platform_get_drvdata(pdev);
1520 
1521     mutex_lock(&papr_ndr_lock);
1522     list_del(&p->region_list);
1523     mutex_unlock(&papr_ndr_lock);
1524 
1525     nvdimm_bus_unregister(p->bus);
1526     drc_pmem_unbind(p);
1527 
1528     if (pdev->archdata.priv)
1529         unregister_nvdimm_pmu(pdev->archdata.priv);
1530 
1531     pdev->archdata.priv = NULL;
1532     kfree(p->bus_desc.provider_name);
1533     kfree(p);
1534 
1535     return 0;
1536 }
1537 
1538 static const struct of_device_id papr_scm_match[] = {
1539     { .compatible = "ibm,pmemory" },
1540     { .compatible = "ibm,pmemory-v2" },
1541     { },
1542 };
1543 
1544 static struct platform_driver papr_scm_driver = {
1545     .probe = papr_scm_probe,
1546     .remove = papr_scm_remove,
1547     .driver = {
1548         .name = "papr_scm",
1549         .of_match_table = papr_scm_match,
1550     },
1551 };
1552 
1553 static int __init papr_scm_init(void)
1554 {
1555     int ret;
1556 
1557     ret = platform_driver_register(&papr_scm_driver);
1558     if (!ret)
1559         mce_register_notifier(&mce_ue_nb);
1560 
1561     return ret;
1562 }
1563 module_init(papr_scm_init);
1564 
1565 static void __exit papr_scm_exit(void)
1566 {
1567     mce_unregister_notifier(&mce_ue_nb);
1568     platform_driver_unregister(&papr_scm_driver);
1569 }
1570 module_exit(papr_scm_exit);
1571 
1572 MODULE_DEVICE_TABLE(of, papr_scm_match);
1573 MODULE_LICENSE("GPL");
1574 MODULE_AUTHOR("IBM Corporation");