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 
17 #include <asm/plpar_wrappers.h>
18 #include <asm/papr_pdsm.h>
19 
20 #define BIND_ANY_ADDR (~0ul)
21 
22 #define PAPR_SCM_DIMM_CMD_MASK \
23 	((1ul << ND_CMD_GET_CONFIG_SIZE) | \
24 	 (1ul << ND_CMD_GET_CONFIG_DATA) | \
25 	 (1ul << ND_CMD_SET_CONFIG_DATA) | \
26 	 (1ul << ND_CMD_CALL))
27 
28 /* DIMM health bitmap bitmap indicators */
29 /* SCM device is unable to persist memory contents */
30 #define PAPR_PMEM_UNARMED                   (1ULL << (63 - 0))
31 /* SCM device failed to persist memory contents */
32 #define PAPR_PMEM_SHUTDOWN_DIRTY            (1ULL << (63 - 1))
33 /* SCM device contents are persisted from previous IPL */
34 #define PAPR_PMEM_SHUTDOWN_CLEAN            (1ULL << (63 - 2))
35 /* SCM device contents are not persisted from previous IPL */
36 #define PAPR_PMEM_EMPTY                     (1ULL << (63 - 3))
37 /* SCM device memory life remaining is critically low */
38 #define PAPR_PMEM_HEALTH_CRITICAL           (1ULL << (63 - 4))
39 /* SCM device will be garded off next IPL due to failure */
40 #define PAPR_PMEM_HEALTH_FATAL              (1ULL << (63 - 5))
41 /* SCM contents cannot persist due to current platform health status */
42 #define PAPR_PMEM_HEALTH_UNHEALTHY          (1ULL << (63 - 6))
43 /* SCM device is unable to persist memory contents in certain conditions */
44 #define PAPR_PMEM_HEALTH_NON_CRITICAL       (1ULL << (63 - 7))
45 /* SCM device is encrypted */
46 #define PAPR_PMEM_ENCRYPTED                 (1ULL << (63 - 8))
47 /* SCM device has been scrubbed and locked */
48 #define PAPR_PMEM_SCRUBBED_AND_LOCKED       (1ULL << (63 - 9))
49 
50 /* Bits status indicators for health bitmap indicating unarmed dimm */
51 #define PAPR_PMEM_UNARMED_MASK (PAPR_PMEM_UNARMED |		\
52 				PAPR_PMEM_HEALTH_UNHEALTHY)
53 
54 /* Bits status indicators for health bitmap indicating unflushed dimm */
55 #define PAPR_PMEM_BAD_SHUTDOWN_MASK (PAPR_PMEM_SHUTDOWN_DIRTY)
56 
57 /* Bits status indicators for health bitmap indicating unrestored dimm */
58 #define PAPR_PMEM_BAD_RESTORE_MASK  (PAPR_PMEM_EMPTY)
59 
60 /* Bit status indicators for smart event notification */
61 #define PAPR_PMEM_SMART_EVENT_MASK (PAPR_PMEM_HEALTH_CRITICAL | \
62 				    PAPR_PMEM_HEALTH_FATAL |	\
63 				    PAPR_PMEM_HEALTH_UNHEALTHY)
64 
65 /* private struct associated with each region */
66 struct papr_scm_priv {
67 	struct platform_device *pdev;
68 	struct device_node *dn;
69 	uint32_t drc_index;
70 	uint64_t blocks;
71 	uint64_t block_size;
72 	int metadata_size;
73 	bool is_volatile;
74 
75 	uint64_t bound_addr;
76 
77 	struct nvdimm_bus_descriptor bus_desc;
78 	struct nvdimm_bus *bus;
79 	struct nvdimm *nvdimm;
80 	struct resource res;
81 	struct nd_region *region;
82 	struct nd_interleave_set nd_set;
83 
84 	/* Protect dimm health data from concurrent read/writes */
85 	struct mutex health_mutex;
86 
87 	/* Last time the health information of the dimm was updated */
88 	unsigned long lasthealth_jiffies;
89 
90 	/* Health information for the dimm */
91 	u64 health_bitmap;
92 };
93 
94 static int drc_pmem_bind(struct papr_scm_priv *p)
95 {
96 	unsigned long ret[PLPAR_HCALL_BUFSIZE];
97 	uint64_t saved = 0;
98 	uint64_t token;
99 	int64_t rc;
100 
101 	/*
102 	 * When the hypervisor cannot map all the requested memory in a single
103 	 * hcall it returns H_BUSY and we call again with the token until
104 	 * we get H_SUCCESS. Aborting the retry loop before getting H_SUCCESS
105 	 * leave the system in an undefined state, so we wait.
106 	 */
107 	token = 0;
108 
109 	do {
110 		rc = plpar_hcall(H_SCM_BIND_MEM, ret, p->drc_index, 0,
111 				p->blocks, BIND_ANY_ADDR, token);
112 		token = ret[0];
113 		if (!saved)
114 			saved = ret[1];
115 		cond_resched();
116 	} while (rc == H_BUSY);
117 
118 	if (rc)
119 		return rc;
120 
121 	p->bound_addr = saved;
122 	dev_dbg(&p->pdev->dev, "bound drc 0x%x to 0x%lx\n",
123 		p->drc_index, (unsigned long)saved);
124 	return rc;
125 }
126 
127 static void drc_pmem_unbind(struct papr_scm_priv *p)
128 {
129 	unsigned long ret[PLPAR_HCALL_BUFSIZE];
130 	uint64_t token = 0;
131 	int64_t rc;
132 
133 	dev_dbg(&p->pdev->dev, "unbind drc 0x%x\n", p->drc_index);
134 
135 	/* NB: unbind has the same retry requirements as drc_pmem_bind() */
136 	do {
137 
138 		/* Unbind of all SCM resources associated with drcIndex */
139 		rc = plpar_hcall(H_SCM_UNBIND_ALL, ret, H_UNBIND_SCOPE_DRC,
140 				 p->drc_index, token);
141 		token = ret[0];
142 
143 		/* Check if we are stalled for some time */
144 		if (H_IS_LONG_BUSY(rc)) {
145 			msleep(get_longbusy_msecs(rc));
146 			rc = H_BUSY;
147 		} else if (rc == H_BUSY) {
148 			cond_resched();
149 		}
150 
151 	} while (rc == H_BUSY);
152 
153 	if (rc)
154 		dev_err(&p->pdev->dev, "unbind error: %lld\n", rc);
155 	else
156 		dev_dbg(&p->pdev->dev, "unbind drc 0x%x complete\n",
157 			p->drc_index);
158 
159 	return;
160 }
161 
162 static int drc_pmem_query_n_bind(struct papr_scm_priv *p)
163 {
164 	unsigned long start_addr;
165 	unsigned long end_addr;
166 	unsigned long ret[PLPAR_HCALL_BUFSIZE];
167 	int64_t rc;
168 
169 
170 	rc = plpar_hcall(H_SCM_QUERY_BLOCK_MEM_BINDING, ret,
171 			 p->drc_index, 0);
172 	if (rc)
173 		goto err_out;
174 	start_addr = ret[0];
175 
176 	/* Make sure the full region is bound. */
177 	rc = plpar_hcall(H_SCM_QUERY_BLOCK_MEM_BINDING, ret,
178 			 p->drc_index, p->blocks - 1);
179 	if (rc)
180 		goto err_out;
181 	end_addr = ret[0];
182 
183 	if ((end_addr - start_addr) != ((p->blocks - 1) * p->block_size))
184 		goto err_out;
185 
186 	p->bound_addr = start_addr;
187 	dev_dbg(&p->pdev->dev, "bound drc 0x%x to 0x%lx\n", p->drc_index, start_addr);
188 	return rc;
189 
190 err_out:
191 	dev_info(&p->pdev->dev,
192 		 "Failed to query, trying an unbind followed by bind");
193 	drc_pmem_unbind(p);
194 	return drc_pmem_bind(p);
195 }
196 
197 /*
198  * Issue hcall to retrieve dimm health info and populate papr_scm_priv with the
199  * health information.
200  */
201 static int __drc_pmem_query_health(struct papr_scm_priv *p)
202 {
203 	unsigned long ret[PLPAR_HCALL_BUFSIZE];
204 	long rc;
205 
206 	/* issue the hcall */
207 	rc = plpar_hcall(H_SCM_HEALTH, ret, p->drc_index);
208 	if (rc != H_SUCCESS) {
209 		dev_err(&p->pdev->dev,
210 			"Failed to query health information, Err:%ld\n", rc);
211 		return -ENXIO;
212 	}
213 
214 	p->lasthealth_jiffies = jiffies;
215 	p->health_bitmap = ret[0] & ret[1];
216 
217 	dev_dbg(&p->pdev->dev,
218 		"Queried dimm health info. Bitmap:0x%016lx Mask:0x%016lx\n",
219 		ret[0], ret[1]);
220 
221 	return 0;
222 }
223 
224 /* Min interval in seconds for assuming stable dimm health */
225 #define MIN_HEALTH_QUERY_INTERVAL 60
226 
227 /* Query cached health info and if needed call drc_pmem_query_health */
228 static int drc_pmem_query_health(struct papr_scm_priv *p)
229 {
230 	unsigned long cache_timeout;
231 	int rc;
232 
233 	/* Protect concurrent modifications to papr_scm_priv */
234 	rc = mutex_lock_interruptible(&p->health_mutex);
235 	if (rc)
236 		return rc;
237 
238 	/* Jiffies offset for which the health data is assumed to be same */
239 	cache_timeout = p->lasthealth_jiffies +
240 		msecs_to_jiffies(MIN_HEALTH_QUERY_INTERVAL * 1000);
241 
242 	/* Fetch new health info is its older than MIN_HEALTH_QUERY_INTERVAL */
243 	if (time_after(jiffies, cache_timeout))
244 		rc = __drc_pmem_query_health(p);
245 	else
246 		/* Assume cached health data is valid */
247 		rc = 0;
248 
249 	mutex_unlock(&p->health_mutex);
250 	return rc;
251 }
252 
253 static int papr_scm_meta_get(struct papr_scm_priv *p,
254 			     struct nd_cmd_get_config_data_hdr *hdr)
255 {
256 	unsigned long data[PLPAR_HCALL_BUFSIZE];
257 	unsigned long offset, data_offset;
258 	int len, read;
259 	int64_t ret;
260 
261 	if ((hdr->in_offset + hdr->in_length) > p->metadata_size)
262 		return -EINVAL;
263 
264 	for (len = hdr->in_length; len; len -= read) {
265 
266 		data_offset = hdr->in_length - len;
267 		offset = hdr->in_offset + data_offset;
268 
269 		if (len >= 8)
270 			read = 8;
271 		else if (len >= 4)
272 			read = 4;
273 		else if (len >= 2)
274 			read = 2;
275 		else
276 			read = 1;
277 
278 		ret = plpar_hcall(H_SCM_READ_METADATA, data, p->drc_index,
279 				  offset, read);
280 
281 		if (ret == H_PARAMETER) /* bad DRC index */
282 			return -ENODEV;
283 		if (ret)
284 			return -EINVAL; /* other invalid parameter */
285 
286 		switch (read) {
287 		case 8:
288 			*(uint64_t *)(hdr->out_buf + data_offset) = be64_to_cpu(data[0]);
289 			break;
290 		case 4:
291 			*(uint32_t *)(hdr->out_buf + data_offset) = be32_to_cpu(data[0] & 0xffffffff);
292 			break;
293 
294 		case 2:
295 			*(uint16_t *)(hdr->out_buf + data_offset) = be16_to_cpu(data[0] & 0xffff);
296 			break;
297 
298 		case 1:
299 			*(uint8_t *)(hdr->out_buf + data_offset) = (data[0] & 0xff);
300 			break;
301 		}
302 	}
303 	return 0;
304 }
305 
306 static int papr_scm_meta_set(struct papr_scm_priv *p,
307 			     struct nd_cmd_set_config_hdr *hdr)
308 {
309 	unsigned long offset, data_offset;
310 	int len, wrote;
311 	unsigned long data;
312 	__be64 data_be;
313 	int64_t ret;
314 
315 	if ((hdr->in_offset + hdr->in_length) > p->metadata_size)
316 		return -EINVAL;
317 
318 	for (len = hdr->in_length; len; len -= wrote) {
319 
320 		data_offset = hdr->in_length - len;
321 		offset = hdr->in_offset + data_offset;
322 
323 		if (len >= 8) {
324 			data = *(uint64_t *)(hdr->in_buf + data_offset);
325 			data_be = cpu_to_be64(data);
326 			wrote = 8;
327 		} else if (len >= 4) {
328 			data = *(uint32_t *)(hdr->in_buf + data_offset);
329 			data &= 0xffffffff;
330 			data_be = cpu_to_be32(data);
331 			wrote = 4;
332 		} else if (len >= 2) {
333 			data = *(uint16_t *)(hdr->in_buf + data_offset);
334 			data &= 0xffff;
335 			data_be = cpu_to_be16(data);
336 			wrote = 2;
337 		} else {
338 			data_be = *(uint8_t *)(hdr->in_buf + data_offset);
339 			data_be &= 0xff;
340 			wrote = 1;
341 		}
342 
343 		ret = plpar_hcall_norets(H_SCM_WRITE_METADATA, p->drc_index,
344 					 offset, data_be, wrote);
345 		if (ret == H_PARAMETER) /* bad DRC index */
346 			return -ENODEV;
347 		if (ret)
348 			return -EINVAL; /* other invalid parameter */
349 	}
350 
351 	return 0;
352 }
353 
354 /*
355  * Do a sanity checks on the inputs args to dimm-control function and return
356  * '0' if valid. Validation of PDSM payloads happens later in
357  * papr_scm_service_pdsm.
358  */
359 static int is_cmd_valid(struct nvdimm *nvdimm, unsigned int cmd, void *buf,
360 			unsigned int buf_len)
361 {
362 	unsigned long cmd_mask = PAPR_SCM_DIMM_CMD_MASK;
363 	struct nd_cmd_pkg *nd_cmd;
364 	struct papr_scm_priv *p;
365 	enum papr_pdsm pdsm;
366 
367 	/* Only dimm-specific calls are supported atm */
368 	if (!nvdimm)
369 		return -EINVAL;
370 
371 	/* get the provider data from struct nvdimm */
372 	p = nvdimm_provider_data(nvdimm);
373 
374 	if (!test_bit(cmd, &cmd_mask)) {
375 		dev_dbg(&p->pdev->dev, "Unsupported cmd=%u\n", cmd);
376 		return -EINVAL;
377 	}
378 
379 	/* For CMD_CALL verify pdsm request */
380 	if (cmd == ND_CMD_CALL) {
381 		/* Verify the envelope and envelop size */
382 		if (!buf ||
383 		    buf_len < (sizeof(struct nd_cmd_pkg) + ND_PDSM_HDR_SIZE)) {
384 			dev_dbg(&p->pdev->dev, "Invalid pkg size=%u\n",
385 				buf_len);
386 			return -EINVAL;
387 		}
388 
389 		/* Verify that the nd_cmd_pkg.nd_family is correct */
390 		nd_cmd = (struct nd_cmd_pkg *)buf;
391 
392 		if (nd_cmd->nd_family != NVDIMM_FAMILY_PAPR) {
393 			dev_dbg(&p->pdev->dev, "Invalid pkg family=0x%llx\n",
394 				nd_cmd->nd_family);
395 			return -EINVAL;
396 		}
397 
398 		pdsm = (enum papr_pdsm)nd_cmd->nd_command;
399 
400 		/* Verify if the pdsm command is valid */
401 		if (pdsm <= PAPR_PDSM_MIN || pdsm >= PAPR_PDSM_MAX) {
402 			dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Invalid PDSM\n",
403 				pdsm);
404 			return -EINVAL;
405 		}
406 
407 		/* Have enough space to hold returned 'nd_pkg_pdsm' header */
408 		if (nd_cmd->nd_size_out < ND_PDSM_HDR_SIZE) {
409 			dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Invalid payload\n",
410 				pdsm);
411 			return -EINVAL;
412 		}
413 	}
414 
415 	/* Let the command be further processed */
416 	return 0;
417 }
418 
419 /* Fetch the DIMM health info and populate it in provided package. */
420 static int papr_pdsm_health(struct papr_scm_priv *p,
421 			    union nd_pdsm_payload *payload)
422 {
423 	int rc;
424 
425 	/* Ensure dimm health mutex is taken preventing concurrent access */
426 	rc = mutex_lock_interruptible(&p->health_mutex);
427 	if (rc)
428 		goto out;
429 
430 	/* Always fetch upto date dimm health data ignoring cached values */
431 	rc = __drc_pmem_query_health(p);
432 	if (rc) {
433 		mutex_unlock(&p->health_mutex);
434 		goto out;
435 	}
436 
437 	/* update health struct with various flags derived from health bitmap */
438 	payload->health = (struct nd_papr_pdsm_health) {
439 		.extension_flags = 0,
440 		.dimm_unarmed = !!(p->health_bitmap & PAPR_PMEM_UNARMED_MASK),
441 		.dimm_bad_shutdown = !!(p->health_bitmap & PAPR_PMEM_BAD_SHUTDOWN_MASK),
442 		.dimm_bad_restore = !!(p->health_bitmap & PAPR_PMEM_BAD_RESTORE_MASK),
443 		.dimm_scrubbed = !!(p->health_bitmap & PAPR_PMEM_SCRUBBED_AND_LOCKED),
444 		.dimm_locked = !!(p->health_bitmap & PAPR_PMEM_SCRUBBED_AND_LOCKED),
445 		.dimm_encrypted = !!(p->health_bitmap & PAPR_PMEM_ENCRYPTED),
446 		.dimm_health = PAPR_PDSM_DIMM_HEALTHY,
447 	};
448 
449 	/* Update field dimm_health based on health_bitmap flags */
450 	if (p->health_bitmap & PAPR_PMEM_HEALTH_FATAL)
451 		payload->health.dimm_health = PAPR_PDSM_DIMM_FATAL;
452 	else if (p->health_bitmap & PAPR_PMEM_HEALTH_CRITICAL)
453 		payload->health.dimm_health = PAPR_PDSM_DIMM_CRITICAL;
454 	else if (p->health_bitmap & PAPR_PMEM_HEALTH_UNHEALTHY)
455 		payload->health.dimm_health = PAPR_PDSM_DIMM_UNHEALTHY;
456 
457 	/* struct populated hence can release the mutex now */
458 	mutex_unlock(&p->health_mutex);
459 	rc = sizeof(struct nd_papr_pdsm_health);
460 
461 out:
462 	return rc;
463 }
464 
465 /*
466  * 'struct pdsm_cmd_desc'
467  * Identifies supported PDSMs' expected length of in/out payloads
468  * and pdsm service function.
469  *
470  * size_in	: Size of input payload if any in the PDSM request.
471  * size_out	: Size of output payload if any in the PDSM request.
472  * service	: Service function for the PDSM request. Return semantics:
473  *		  rc < 0 : Error servicing PDSM and rc indicates the error.
474  *		  rc >=0 : Serviced successfully and 'rc' indicate number of
475  *			bytes written to payload.
476  */
477 struct pdsm_cmd_desc {
478 	u32 size_in;
479 	u32 size_out;
480 	int (*service)(struct papr_scm_priv *dimm,
481 		       union nd_pdsm_payload *payload);
482 };
483 
484 /* Holds all supported PDSMs' command descriptors */
485 static const struct pdsm_cmd_desc __pdsm_cmd_descriptors[] = {
486 	[PAPR_PDSM_MIN] = {
487 		.size_in = 0,
488 		.size_out = 0,
489 		.service = NULL,
490 	},
491 	/* New PDSM command descriptors to be added below */
492 
493 	[PAPR_PDSM_HEALTH] = {
494 		.size_in = 0,
495 		.size_out = sizeof(struct nd_papr_pdsm_health),
496 		.service = papr_pdsm_health,
497 	},
498 	/* Empty */
499 	[PAPR_PDSM_MAX] = {
500 		.size_in = 0,
501 		.size_out = 0,
502 		.service = NULL,
503 	},
504 };
505 
506 /* Given a valid pdsm cmd return its command descriptor else return NULL */
507 static inline const struct pdsm_cmd_desc *pdsm_cmd_desc(enum papr_pdsm cmd)
508 {
509 	if (cmd >= 0 || cmd < ARRAY_SIZE(__pdsm_cmd_descriptors))
510 		return &__pdsm_cmd_descriptors[cmd];
511 
512 	return NULL;
513 }
514 
515 /*
516  * For a given pdsm request call an appropriate service function.
517  * Returns errors if any while handling the pdsm command package.
518  */
519 static int papr_scm_service_pdsm(struct papr_scm_priv *p,
520 				 struct nd_cmd_pkg *pkg)
521 {
522 	/* Get the PDSM header and PDSM command */
523 	struct nd_pkg_pdsm *pdsm_pkg = (struct nd_pkg_pdsm *)pkg->nd_payload;
524 	enum papr_pdsm pdsm = (enum papr_pdsm)pkg->nd_command;
525 	const struct pdsm_cmd_desc *pdsc;
526 	int rc;
527 
528 	/* Fetch corresponding pdsm descriptor for validation and servicing */
529 	pdsc = pdsm_cmd_desc(pdsm);
530 
531 	/* Validate pdsm descriptor */
532 	/* Ensure that reserved fields are 0 */
533 	if (pdsm_pkg->reserved[0] || pdsm_pkg->reserved[1]) {
534 		dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Invalid reserved field\n",
535 			pdsm);
536 		return -EINVAL;
537 	}
538 
539 	/* If pdsm expects some input, then ensure that the size_in matches */
540 	if (pdsc->size_in &&
541 	    pkg->nd_size_in != (pdsc->size_in + ND_PDSM_HDR_SIZE)) {
542 		dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Mismatched size_in=%d\n",
543 			pdsm, pkg->nd_size_in);
544 		return -EINVAL;
545 	}
546 
547 	/* If pdsm wants to return data, then ensure that  size_out matches */
548 	if (pdsc->size_out &&
549 	    pkg->nd_size_out != (pdsc->size_out + ND_PDSM_HDR_SIZE)) {
550 		dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Mismatched size_out=%d\n",
551 			pdsm, pkg->nd_size_out);
552 		return -EINVAL;
553 	}
554 
555 	/* Service the pdsm */
556 	if (pdsc->service) {
557 		dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Servicing..\n", pdsm);
558 
559 		rc = pdsc->service(p, &pdsm_pkg->payload);
560 
561 		if (rc < 0) {
562 			/* error encountered while servicing pdsm */
563 			pdsm_pkg->cmd_status = rc;
564 			pkg->nd_fw_size = ND_PDSM_HDR_SIZE;
565 		} else {
566 			/* pdsm serviced and 'rc' bytes written to payload */
567 			pdsm_pkg->cmd_status = 0;
568 			pkg->nd_fw_size = ND_PDSM_HDR_SIZE + rc;
569 		}
570 	} else {
571 		dev_dbg(&p->pdev->dev, "PDSM[0x%x]: Unsupported PDSM request\n",
572 			pdsm);
573 		pdsm_pkg->cmd_status = -ENOENT;
574 		pkg->nd_fw_size = ND_PDSM_HDR_SIZE;
575 	}
576 
577 	return pdsm_pkg->cmd_status;
578 }
579 
580 static int papr_scm_ndctl(struct nvdimm_bus_descriptor *nd_desc,
581 			  struct nvdimm *nvdimm, unsigned int cmd, void *buf,
582 			  unsigned int buf_len, int *cmd_rc)
583 {
584 	struct nd_cmd_get_config_size *get_size_hdr;
585 	struct nd_cmd_pkg *call_pkg = NULL;
586 	struct papr_scm_priv *p;
587 	int rc;
588 
589 	rc = is_cmd_valid(nvdimm, cmd, buf, buf_len);
590 	if (rc) {
591 		pr_debug("Invalid cmd=0x%x. Err=%d\n", cmd, rc);
592 		return rc;
593 	}
594 
595 	/* Use a local variable in case cmd_rc pointer is NULL */
596 	if (!cmd_rc)
597 		cmd_rc = &rc;
598 
599 	p = nvdimm_provider_data(nvdimm);
600 
601 	switch (cmd) {
602 	case ND_CMD_GET_CONFIG_SIZE:
603 		get_size_hdr = buf;
604 
605 		get_size_hdr->status = 0;
606 		get_size_hdr->max_xfer = 8;
607 		get_size_hdr->config_size = p->metadata_size;
608 		*cmd_rc = 0;
609 		break;
610 
611 	case ND_CMD_GET_CONFIG_DATA:
612 		*cmd_rc = papr_scm_meta_get(p, buf);
613 		break;
614 
615 	case ND_CMD_SET_CONFIG_DATA:
616 		*cmd_rc = papr_scm_meta_set(p, buf);
617 		break;
618 
619 	case ND_CMD_CALL:
620 		call_pkg = (struct nd_cmd_pkg *)buf;
621 		*cmd_rc = papr_scm_service_pdsm(p, call_pkg);
622 		break;
623 
624 	default:
625 		dev_dbg(&p->pdev->dev, "Unknown command = %d\n", cmd);
626 		return -EINVAL;
627 	}
628 
629 	dev_dbg(&p->pdev->dev, "returned with cmd_rc = %d\n", *cmd_rc);
630 
631 	return 0;
632 }
633 
634 static ssize_t flags_show(struct device *dev,
635 			  struct device_attribute *attr, char *buf)
636 {
637 	struct nvdimm *dimm = to_nvdimm(dev);
638 	struct papr_scm_priv *p = nvdimm_provider_data(dimm);
639 	struct seq_buf s;
640 	u64 health;
641 	int rc;
642 
643 	rc = drc_pmem_query_health(p);
644 	if (rc)
645 		return rc;
646 
647 	/* Copy health_bitmap locally, check masks & update out buffer */
648 	health = READ_ONCE(p->health_bitmap);
649 
650 	seq_buf_init(&s, buf, PAGE_SIZE);
651 	if (health & PAPR_PMEM_UNARMED_MASK)
652 		seq_buf_printf(&s, "not_armed ");
653 
654 	if (health & PAPR_PMEM_BAD_SHUTDOWN_MASK)
655 		seq_buf_printf(&s, "flush_fail ");
656 
657 	if (health & PAPR_PMEM_BAD_RESTORE_MASK)
658 		seq_buf_printf(&s, "restore_fail ");
659 
660 	if (health & PAPR_PMEM_ENCRYPTED)
661 		seq_buf_printf(&s, "encrypted ");
662 
663 	if (health & PAPR_PMEM_SMART_EVENT_MASK)
664 		seq_buf_printf(&s, "smart_notify ");
665 
666 	if (health & PAPR_PMEM_SCRUBBED_AND_LOCKED)
667 		seq_buf_printf(&s, "scrubbed locked ");
668 
669 	if (seq_buf_used(&s))
670 		seq_buf_printf(&s, "\n");
671 
672 	return seq_buf_used(&s);
673 }
674 DEVICE_ATTR_RO(flags);
675 
676 /* papr_scm specific dimm attributes */
677 static struct attribute *papr_nd_attributes[] = {
678 	&dev_attr_flags.attr,
679 	NULL,
680 };
681 
682 static struct attribute_group papr_nd_attribute_group = {
683 	.name = "papr",
684 	.attrs = papr_nd_attributes,
685 };
686 
687 static const struct attribute_group *papr_nd_attr_groups[] = {
688 	&papr_nd_attribute_group,
689 	NULL,
690 };
691 
692 static int papr_scm_nvdimm_init(struct papr_scm_priv *p)
693 {
694 	struct device *dev = &p->pdev->dev;
695 	struct nd_mapping_desc mapping;
696 	struct nd_region_desc ndr_desc;
697 	unsigned long dimm_flags;
698 	int target_nid, online_nid;
699 
700 	p->bus_desc.ndctl = papr_scm_ndctl;
701 	p->bus_desc.module = THIS_MODULE;
702 	p->bus_desc.of_node = p->pdev->dev.of_node;
703 	p->bus_desc.provider_name = kstrdup(p->pdev->name, GFP_KERNEL);
704 
705 	if (!p->bus_desc.provider_name)
706 		return -ENOMEM;
707 
708 	p->bus = nvdimm_bus_register(NULL, &p->bus_desc);
709 	if (!p->bus) {
710 		dev_err(dev, "Error creating nvdimm bus %pOF\n", p->dn);
711 		kfree(p->bus_desc.provider_name);
712 		return -ENXIO;
713 	}
714 
715 	dimm_flags = 0;
716 	set_bit(NDD_LABELING, &dimm_flags);
717 
718 	p->nvdimm = nvdimm_create(p->bus, p, papr_nd_attr_groups,
719 				  dimm_flags, PAPR_SCM_DIMM_CMD_MASK, 0, NULL);
720 	if (!p->nvdimm) {
721 		dev_err(dev, "Error creating DIMM object for %pOF\n", p->dn);
722 		goto err;
723 	}
724 
725 	if (nvdimm_bus_check_dimm_count(p->bus, 1))
726 		goto err;
727 
728 	/* now add the region */
729 
730 	memset(&mapping, 0, sizeof(mapping));
731 	mapping.nvdimm = p->nvdimm;
732 	mapping.start = 0;
733 	mapping.size = p->blocks * p->block_size; // XXX: potential overflow?
734 
735 	memset(&ndr_desc, 0, sizeof(ndr_desc));
736 	target_nid = dev_to_node(&p->pdev->dev);
737 	online_nid = numa_map_to_online_node(target_nid);
738 	ndr_desc.numa_node = online_nid;
739 	ndr_desc.target_node = target_nid;
740 	ndr_desc.res = &p->res;
741 	ndr_desc.of_node = p->dn;
742 	ndr_desc.provider_data = p;
743 	ndr_desc.mapping = &mapping;
744 	ndr_desc.num_mappings = 1;
745 	ndr_desc.nd_set = &p->nd_set;
746 
747 	if (p->is_volatile)
748 		p->region = nvdimm_volatile_region_create(p->bus, &ndr_desc);
749 	else {
750 		set_bit(ND_REGION_PERSIST_MEMCTRL, &ndr_desc.flags);
751 		p->region = nvdimm_pmem_region_create(p->bus, &ndr_desc);
752 	}
753 	if (!p->region) {
754 		dev_err(dev, "Error registering region %pR from %pOF\n",
755 				ndr_desc.res, p->dn);
756 		goto err;
757 	}
758 	if (target_nid != online_nid)
759 		dev_info(dev, "Region registered with target node %d and online node %d",
760 			 target_nid, online_nid);
761 
762 	return 0;
763 
764 err:	nvdimm_bus_unregister(p->bus);
765 	kfree(p->bus_desc.provider_name);
766 	return -ENXIO;
767 }
768 
769 static int papr_scm_probe(struct platform_device *pdev)
770 {
771 	struct device_node *dn = pdev->dev.of_node;
772 	u32 drc_index, metadata_size;
773 	u64 blocks, block_size;
774 	struct papr_scm_priv *p;
775 	const char *uuid_str;
776 	u64 uuid[2];
777 	int rc;
778 
779 	/* check we have all the required DT properties */
780 	if (of_property_read_u32(dn, "ibm,my-drc-index", &drc_index)) {
781 		dev_err(&pdev->dev, "%pOF: missing drc-index!\n", dn);
782 		return -ENODEV;
783 	}
784 
785 	if (of_property_read_u64(dn, "ibm,block-size", &block_size)) {
786 		dev_err(&pdev->dev, "%pOF: missing block-size!\n", dn);
787 		return -ENODEV;
788 	}
789 
790 	if (of_property_read_u64(dn, "ibm,number-of-blocks", &blocks)) {
791 		dev_err(&pdev->dev, "%pOF: missing number-of-blocks!\n", dn);
792 		return -ENODEV;
793 	}
794 
795 	if (of_property_read_string(dn, "ibm,unit-guid", &uuid_str)) {
796 		dev_err(&pdev->dev, "%pOF: missing unit-guid!\n", dn);
797 		return -ENODEV;
798 	}
799 
800 
801 	p = kzalloc(sizeof(*p), GFP_KERNEL);
802 	if (!p)
803 		return -ENOMEM;
804 
805 	/* Initialize the dimm mutex */
806 	mutex_init(&p->health_mutex);
807 
808 	/* optional DT properties */
809 	of_property_read_u32(dn, "ibm,metadata-size", &metadata_size);
810 
811 	p->dn = dn;
812 	p->drc_index = drc_index;
813 	p->block_size = block_size;
814 	p->blocks = blocks;
815 	p->is_volatile = !of_property_read_bool(dn, "ibm,cache-flush-required");
816 
817 	/* We just need to ensure that set cookies are unique across */
818 	uuid_parse(uuid_str, (uuid_t *) uuid);
819 	/*
820 	 * cookie1 and cookie2 are not really little endian
821 	 * we store a little endian representation of the
822 	 * uuid str so that we can compare this with the label
823 	 * area cookie irrespective of the endian config with which
824 	 * the kernel is built.
825 	 */
826 	p->nd_set.cookie1 = cpu_to_le64(uuid[0]);
827 	p->nd_set.cookie2 = cpu_to_le64(uuid[1]);
828 
829 	/* might be zero */
830 	p->metadata_size = metadata_size;
831 	p->pdev = pdev;
832 
833 	/* request the hypervisor to bind this region to somewhere in memory */
834 	rc = drc_pmem_bind(p);
835 
836 	/* If phyp says drc memory still bound then force unbound and retry */
837 	if (rc == H_OVERLAP)
838 		rc = drc_pmem_query_n_bind(p);
839 
840 	if (rc != H_SUCCESS) {
841 		dev_err(&p->pdev->dev, "bind err: %d\n", rc);
842 		rc = -ENXIO;
843 		goto err;
844 	}
845 
846 	/* setup the resource for the newly bound range */
847 	p->res.start = p->bound_addr;
848 	p->res.end   = p->bound_addr + p->blocks * p->block_size - 1;
849 	p->res.name  = pdev->name;
850 	p->res.flags = IORESOURCE_MEM;
851 
852 	rc = papr_scm_nvdimm_init(p);
853 	if (rc)
854 		goto err2;
855 
856 	platform_set_drvdata(pdev, p);
857 
858 	return 0;
859 
860 err2:	drc_pmem_unbind(p);
861 err:	kfree(p);
862 	return rc;
863 }
864 
865 static int papr_scm_remove(struct platform_device *pdev)
866 {
867 	struct papr_scm_priv *p = platform_get_drvdata(pdev);
868 
869 	nvdimm_bus_unregister(p->bus);
870 	drc_pmem_unbind(p);
871 	kfree(p->bus_desc.provider_name);
872 	kfree(p);
873 
874 	return 0;
875 }
876 
877 static const struct of_device_id papr_scm_match[] = {
878 	{ .compatible = "ibm,pmemory" },
879 	{ },
880 };
881 
882 static struct platform_driver papr_scm_driver = {
883 	.probe = papr_scm_probe,
884 	.remove = papr_scm_remove,
885 	.driver = {
886 		.name = "papr_scm",
887 		.of_match_table = papr_scm_match,
888 	},
889 };
890 
891 module_platform_driver(papr_scm_driver);
892 MODULE_DEVICE_TABLE(of, papr_scm_match);
893 MODULE_LICENSE("GPL");
894 MODULE_AUTHOR("IBM Corporation");
895