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