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