cxl/pci: Add HDM decoder capabilities
[linux-2.6-microblaze.git] / drivers / cxl / pci.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright(c) 2020 Intel Corporation. All rights reserved. */
3 #include <uapi/linux/cxl_mem.h>
4 #include <linux/security.h>
5 #include <linux/debugfs.h>
6 #include <linux/module.h>
7 #include <linux/sizes.h>
8 #include <linux/mutex.h>
9 #include <linux/list.h>
10 #include <linux/cdev.h>
11 #include <linux/idr.h>
12 #include <linux/pci.h>
13 #include <linux/io.h>
14 #include <linux/io-64-nonatomic-lo-hi.h>
15 #include "pci.h"
16 #include "cxl.h"
17 #include "mem.h"
18
19 /**
20  * DOC: cxl pci
21  *
22  * This implements the PCI exclusive functionality for a CXL device as it is
23  * defined by the Compute Express Link specification. CXL devices may surface
24  * certain functionality even if it isn't CXL enabled.
25  *
26  * The driver has several responsibilities, mainly:
27  *  - Create the memX device and register on the CXL bus.
28  *  - Enumerate device's register interface and map them.
29  *  - Probe the device attributes to establish sysfs interface.
30  *  - Provide an IOCTL interface to userspace to communicate with the device for
31  *    things like firmware update.
32  */
33
34 #define cxl_doorbell_busy(cxlm)                                                \
35         (readl((cxlm)->regs.mbox + CXLDEV_MBOX_CTRL_OFFSET) &                  \
36          CXLDEV_MBOX_CTRL_DOORBELL)
37
38 /* CXL 2.0 - 8.2.8.4 */
39 #define CXL_MAILBOX_TIMEOUT_MS (2 * HZ)
40
41 enum opcode {
42         CXL_MBOX_OP_INVALID             = 0x0000,
43         CXL_MBOX_OP_RAW                 = CXL_MBOX_OP_INVALID,
44         CXL_MBOX_OP_GET_FW_INFO         = 0x0200,
45         CXL_MBOX_OP_ACTIVATE_FW         = 0x0202,
46         CXL_MBOX_OP_GET_SUPPORTED_LOGS  = 0x0400,
47         CXL_MBOX_OP_GET_LOG             = 0x0401,
48         CXL_MBOX_OP_IDENTIFY            = 0x4000,
49         CXL_MBOX_OP_GET_PARTITION_INFO  = 0x4100,
50         CXL_MBOX_OP_SET_PARTITION_INFO  = 0x4101,
51         CXL_MBOX_OP_GET_LSA             = 0x4102,
52         CXL_MBOX_OP_SET_LSA             = 0x4103,
53         CXL_MBOX_OP_GET_HEALTH_INFO     = 0x4200,
54         CXL_MBOX_OP_SET_SHUTDOWN_STATE  = 0x4204,
55         CXL_MBOX_OP_SCAN_MEDIA          = 0x4304,
56         CXL_MBOX_OP_GET_SCAN_MEDIA      = 0x4305,
57         CXL_MBOX_OP_MAX                 = 0x10000
58 };
59
60 /**
61  * struct mbox_cmd - A command to be submitted to hardware.
62  * @opcode: (input) The command set and command submitted to hardware.
63  * @payload_in: (input) Pointer to the input payload.
64  * @payload_out: (output) Pointer to the output payload. Must be allocated by
65  *               the caller.
66  * @size_in: (input) Number of bytes to load from @payload_in.
67  * @size_out: (input) Max number of bytes loaded into @payload_out.
68  *            (output) Number of bytes generated by the device. For fixed size
69  *            outputs commands this is always expected to be deterministic. For
70  *            variable sized output commands, it tells the exact number of bytes
71  *            written.
72  * @return_code: (output) Error code returned from hardware.
73  *
74  * This is the primary mechanism used to send commands to the hardware.
75  * All the fields except @payload_* correspond exactly to the fields described in
76  * Command Register section of the CXL 2.0 8.2.8.4.5. @payload_in and
77  * @payload_out are written to, and read from the Command Payload Registers
78  * defined in CXL 2.0 8.2.8.4.8.
79  */
80 struct mbox_cmd {
81         u16 opcode;
82         void *payload_in;
83         void *payload_out;
84         size_t size_in;
85         size_t size_out;
86         u16 return_code;
87 #define CXL_MBOX_SUCCESS 0
88 };
89
90 static int cxl_mem_major;
91 static DEFINE_IDA(cxl_memdev_ida);
92 static DECLARE_RWSEM(cxl_memdev_rwsem);
93 static struct dentry *cxl_debugfs;
94 static bool cxl_raw_allow_all;
95
96 enum {
97         CEL_UUID,
98         VENDOR_DEBUG_UUID,
99 };
100
101 /* See CXL 2.0 Table 170. Get Log Input Payload */
102 static const uuid_t log_uuid[] = {
103         [CEL_UUID] = UUID_INIT(0xda9c0b5, 0xbf41, 0x4b78, 0x8f, 0x79, 0x96,
104                                0xb1, 0x62, 0x3b, 0x3f, 0x17),
105         [VENDOR_DEBUG_UUID] = UUID_INIT(0xe1819d9, 0x11a9, 0x400c, 0x81, 0x1f,
106                                         0xd6, 0x07, 0x19, 0x40, 0x3d, 0x86),
107 };
108
109 /**
110  * struct cxl_mem_command - Driver representation of a memory device command
111  * @info: Command information as it exists for the UAPI
112  * @opcode: The actual bits used for the mailbox protocol
113  * @flags: Set of flags effecting driver behavior.
114  *
115  *  * %CXL_CMD_FLAG_FORCE_ENABLE: In cases of error, commands with this flag
116  *    will be enabled by the driver regardless of what hardware may have
117  *    advertised.
118  *
119  * The cxl_mem_command is the driver's internal representation of commands that
120  * are supported by the driver. Some of these commands may not be supported by
121  * the hardware. The driver will use @info to validate the fields passed in by
122  * the user then submit the @opcode to the hardware.
123  *
124  * See struct cxl_command_info.
125  */
126 struct cxl_mem_command {
127         struct cxl_command_info info;
128         enum opcode opcode;
129         u32 flags;
130 #define CXL_CMD_FLAG_NONE 0
131 #define CXL_CMD_FLAG_FORCE_ENABLE BIT(0)
132 };
133
134 #define CXL_CMD(_id, sin, sout, _flags)                                        \
135         [CXL_MEM_COMMAND_ID_##_id] = {                                         \
136         .info = {                                                              \
137                         .id = CXL_MEM_COMMAND_ID_##_id,                        \
138                         .size_in = sin,                                        \
139                         .size_out = sout,                                      \
140                 },                                                             \
141         .opcode = CXL_MBOX_OP_##_id,                                           \
142         .flags = _flags,                                                       \
143         }
144
145 /*
146  * This table defines the supported mailbox commands for the driver. This table
147  * is made up of a UAPI structure. Non-negative values as parameters in the
148  * table will be validated against the user's input. For example, if size_in is
149  * 0, and the user passed in 1, it is an error.
150  */
151 static struct cxl_mem_command mem_commands[CXL_MEM_COMMAND_ID_MAX] = {
152         CXL_CMD(IDENTIFY, 0, 0x43, CXL_CMD_FLAG_FORCE_ENABLE),
153 #ifdef CONFIG_CXL_MEM_RAW_COMMANDS
154         CXL_CMD(RAW, ~0, ~0, 0),
155 #endif
156         CXL_CMD(GET_SUPPORTED_LOGS, 0, ~0, CXL_CMD_FLAG_FORCE_ENABLE),
157         CXL_CMD(GET_FW_INFO, 0, 0x50, 0),
158         CXL_CMD(GET_PARTITION_INFO, 0, 0x20, 0),
159         CXL_CMD(GET_LSA, 0x8, ~0, 0),
160         CXL_CMD(GET_HEALTH_INFO, 0, 0x12, 0),
161         CXL_CMD(GET_LOG, 0x18, ~0, CXL_CMD_FLAG_FORCE_ENABLE),
162 };
163
164 /*
165  * Commands that RAW doesn't permit. The rationale for each:
166  *
167  * CXL_MBOX_OP_ACTIVATE_FW: Firmware activation requires adjustment /
168  * coordination of transaction timeout values at the root bridge level.
169  *
170  * CXL_MBOX_OP_SET_PARTITION_INFO: The device memory map may change live
171  * and needs to be coordinated with HDM updates.
172  *
173  * CXL_MBOX_OP_SET_LSA: The label storage area may be cached by the
174  * driver and any writes from userspace invalidates those contents.
175  *
176  * CXL_MBOX_OP_SET_SHUTDOWN_STATE: Set shutdown state assumes no writes
177  * to the device after it is marked clean, userspace can not make that
178  * assertion.
179  *
180  * CXL_MBOX_OP_[GET_]SCAN_MEDIA: The kernel provides a native error list that
181  * is kept up to date with patrol notifications and error management.
182  */
183 static u16 cxl_disabled_raw_commands[] = {
184         CXL_MBOX_OP_ACTIVATE_FW,
185         CXL_MBOX_OP_SET_PARTITION_INFO,
186         CXL_MBOX_OP_SET_LSA,
187         CXL_MBOX_OP_SET_SHUTDOWN_STATE,
188         CXL_MBOX_OP_SCAN_MEDIA,
189         CXL_MBOX_OP_GET_SCAN_MEDIA,
190 };
191
192 /*
193  * Command sets that RAW doesn't permit. All opcodes in this set are
194  * disabled because they pass plain text security payloads over the
195  * user/kernel boundary. This functionality is intended to be wrapped
196  * behind the keys ABI which allows for encrypted payloads in the UAPI
197  */
198 static u8 security_command_sets[] = {
199         0x44, /* Sanitize */
200         0x45, /* Persistent Memory Data-at-rest Security */
201         0x46, /* Security Passthrough */
202 };
203
204 #define cxl_for_each_cmd(cmd)                                                  \
205         for ((cmd) = &mem_commands[0];                                         \
206              ((cmd) - mem_commands) < ARRAY_SIZE(mem_commands); (cmd)++)
207
208 #define cxl_cmd_count ARRAY_SIZE(mem_commands)
209
210 static int cxl_mem_wait_for_doorbell(struct cxl_mem *cxlm)
211 {
212         const unsigned long start = jiffies;
213         unsigned long end = start;
214
215         while (cxl_doorbell_busy(cxlm)) {
216                 end = jiffies;
217
218                 if (time_after(end, start + CXL_MAILBOX_TIMEOUT_MS)) {
219                         /* Check again in case preempted before timeout test */
220                         if (!cxl_doorbell_busy(cxlm))
221                                 break;
222                         return -ETIMEDOUT;
223                 }
224                 cpu_relax();
225         }
226
227         dev_dbg(&cxlm->pdev->dev, "Doorbell wait took %dms",
228                 jiffies_to_msecs(end) - jiffies_to_msecs(start));
229         return 0;
230 }
231
232 static bool cxl_is_security_command(u16 opcode)
233 {
234         int i;
235
236         for (i = 0; i < ARRAY_SIZE(security_command_sets); i++)
237                 if (security_command_sets[i] == (opcode >> 8))
238                         return true;
239         return false;
240 }
241
242 static void cxl_mem_mbox_timeout(struct cxl_mem *cxlm,
243                                  struct mbox_cmd *mbox_cmd)
244 {
245         struct device *dev = &cxlm->pdev->dev;
246
247         dev_dbg(dev, "Mailbox command (opcode: %#x size: %zub) timed out\n",
248                 mbox_cmd->opcode, mbox_cmd->size_in);
249 }
250
251 /**
252  * __cxl_mem_mbox_send_cmd() - Execute a mailbox command
253  * @cxlm: The CXL memory device to communicate with.
254  * @mbox_cmd: Command to send to the memory device.
255  *
256  * Context: Any context. Expects mbox_mutex to be held.
257  * Return: -ETIMEDOUT if timeout occurred waiting for completion. 0 on success.
258  *         Caller should check the return code in @mbox_cmd to make sure it
259  *         succeeded.
260  *
261  * This is a generic form of the CXL mailbox send command thus only using the
262  * registers defined by the mailbox capability ID - CXL 2.0 8.2.8.4. Memory
263  * devices, and perhaps other types of CXL devices may have further information
264  * available upon error conditions. Driver facilities wishing to send mailbox
265  * commands should use the wrapper command.
266  *
267  * The CXL spec allows for up to two mailboxes. The intention is for the primary
268  * mailbox to be OS controlled and the secondary mailbox to be used by system
269  * firmware. This allows the OS and firmware to communicate with the device and
270  * not need to coordinate with each other. The driver only uses the primary
271  * mailbox.
272  */
273 static int __cxl_mem_mbox_send_cmd(struct cxl_mem *cxlm,
274                                    struct mbox_cmd *mbox_cmd)
275 {
276         void __iomem *payload = cxlm->regs.mbox + CXLDEV_MBOX_PAYLOAD_OFFSET;
277         u64 cmd_reg, status_reg;
278         size_t out_len;
279         int rc;
280
281         lockdep_assert_held(&cxlm->mbox_mutex);
282
283         /*
284          * Here are the steps from 8.2.8.4 of the CXL 2.0 spec.
285          *   1. Caller reads MB Control Register to verify doorbell is clear
286          *   2. Caller writes Command Register
287          *   3. Caller writes Command Payload Registers if input payload is non-empty
288          *   4. Caller writes MB Control Register to set doorbell
289          *   5. Caller either polls for doorbell to be clear or waits for interrupt if configured
290          *   6. Caller reads MB Status Register to fetch Return code
291          *   7. If command successful, Caller reads Command Register to get Payload Length
292          *   8. If output payload is non-empty, host reads Command Payload Registers
293          *
294          * Hardware is free to do whatever it wants before the doorbell is rung,
295          * and isn't allowed to change anything after it clears the doorbell. As
296          * such, steps 2 and 3 can happen in any order, and steps 6, 7, 8 can
297          * also happen in any order (though some orders might not make sense).
298          */
299
300         /* #1 */
301         if (cxl_doorbell_busy(cxlm)) {
302                 dev_err_ratelimited(&cxlm->pdev->dev,
303                                     "Mailbox re-busy after acquiring\n");
304                 return -EBUSY;
305         }
306
307         cmd_reg = FIELD_PREP(CXLDEV_MBOX_CMD_COMMAND_OPCODE_MASK,
308                              mbox_cmd->opcode);
309         if (mbox_cmd->size_in) {
310                 if (WARN_ON(!mbox_cmd->payload_in))
311                         return -EINVAL;
312
313                 cmd_reg |= FIELD_PREP(CXLDEV_MBOX_CMD_PAYLOAD_LENGTH_MASK,
314                                       mbox_cmd->size_in);
315                 memcpy_toio(payload, mbox_cmd->payload_in, mbox_cmd->size_in);
316         }
317
318         /* #2, #3 */
319         writeq(cmd_reg, cxlm->regs.mbox + CXLDEV_MBOX_CMD_OFFSET);
320
321         /* #4 */
322         dev_dbg(&cxlm->pdev->dev, "Sending command\n");
323         writel(CXLDEV_MBOX_CTRL_DOORBELL,
324                cxlm->regs.mbox + CXLDEV_MBOX_CTRL_OFFSET);
325
326         /* #5 */
327         rc = cxl_mem_wait_for_doorbell(cxlm);
328         if (rc == -ETIMEDOUT) {
329                 cxl_mem_mbox_timeout(cxlm, mbox_cmd);
330                 return rc;
331         }
332
333         /* #6 */
334         status_reg = readq(cxlm->regs.mbox + CXLDEV_MBOX_STATUS_OFFSET);
335         mbox_cmd->return_code =
336                 FIELD_GET(CXLDEV_MBOX_STATUS_RET_CODE_MASK, status_reg);
337
338         if (mbox_cmd->return_code != 0) {
339                 dev_dbg(&cxlm->pdev->dev, "Mailbox operation had an error\n");
340                 return 0;
341         }
342
343         /* #7 */
344         cmd_reg = readq(cxlm->regs.mbox + CXLDEV_MBOX_CMD_OFFSET);
345         out_len = FIELD_GET(CXLDEV_MBOX_CMD_PAYLOAD_LENGTH_MASK, cmd_reg);
346
347         /* #8 */
348         if (out_len && mbox_cmd->payload_out) {
349                 /*
350                  * Sanitize the copy. If hardware misbehaves, out_len per the
351                  * spec can actually be greater than the max allowed size (21
352                  * bits available but spec defined 1M max). The caller also may
353                  * have requested less data than the hardware supplied even
354                  * within spec.
355                  */
356                 size_t n = min3(mbox_cmd->size_out, cxlm->payload_size, out_len);
357
358                 memcpy_fromio(mbox_cmd->payload_out, payload, n);
359                 mbox_cmd->size_out = n;
360         } else {
361                 mbox_cmd->size_out = 0;
362         }
363
364         return 0;
365 }
366
367 /**
368  * cxl_mem_mbox_get() - Acquire exclusive access to the mailbox.
369  * @cxlm: The memory device to gain access to.
370  *
371  * Context: Any context. Takes the mbox_mutex.
372  * Return: 0 if exclusive access was acquired.
373  */
374 static int cxl_mem_mbox_get(struct cxl_mem *cxlm)
375 {
376         struct device *dev = &cxlm->pdev->dev;
377         u64 md_status;
378         int rc;
379
380         mutex_lock_io(&cxlm->mbox_mutex);
381
382         /*
383          * XXX: There is some amount of ambiguity in the 2.0 version of the spec
384          * around the mailbox interface ready (8.2.8.5.1.1).  The purpose of the
385          * bit is to allow firmware running on the device to notify the driver
386          * that it's ready to receive commands. It is unclear if the bit needs
387          * to be read for each transaction mailbox, ie. the firmware can switch
388          * it on and off as needed. Second, there is no defined timeout for
389          * mailbox ready, like there is for the doorbell interface.
390          *
391          * Assumptions:
392          * 1. The firmware might toggle the Mailbox Interface Ready bit, check
393          *    it for every command.
394          *
395          * 2. If the doorbell is clear, the firmware should have first set the
396          *    Mailbox Interface Ready bit. Therefore, waiting for the doorbell
397          *    to be ready is sufficient.
398          */
399         rc = cxl_mem_wait_for_doorbell(cxlm);
400         if (rc) {
401                 dev_warn(dev, "Mailbox interface not ready\n");
402                 goto out;
403         }
404
405         md_status = readq(cxlm->regs.memdev + CXLMDEV_STATUS_OFFSET);
406         if (!(md_status & CXLMDEV_MBOX_IF_READY && CXLMDEV_READY(md_status))) {
407                 dev_err(dev, "mbox: reported doorbell ready, but not mbox ready\n");
408                 rc = -EBUSY;
409                 goto out;
410         }
411
412         /*
413          * Hardware shouldn't allow a ready status but also have failure bits
414          * set. Spit out an error, this should be a bug report
415          */
416         rc = -EFAULT;
417         if (md_status & CXLMDEV_DEV_FATAL) {
418                 dev_err(dev, "mbox: reported ready, but fatal\n");
419                 goto out;
420         }
421         if (md_status & CXLMDEV_FW_HALT) {
422                 dev_err(dev, "mbox: reported ready, but halted\n");
423                 goto out;
424         }
425         if (CXLMDEV_RESET_NEEDED(md_status)) {
426                 dev_err(dev, "mbox: reported ready, but reset needed\n");
427                 goto out;
428         }
429
430         /* with lock held */
431         return 0;
432
433 out:
434         mutex_unlock(&cxlm->mbox_mutex);
435         return rc;
436 }
437
438 /**
439  * cxl_mem_mbox_put() - Release exclusive access to the mailbox.
440  * @cxlm: The CXL memory device to communicate with.
441  *
442  * Context: Any context. Expects mbox_mutex to be held.
443  */
444 static void cxl_mem_mbox_put(struct cxl_mem *cxlm)
445 {
446         mutex_unlock(&cxlm->mbox_mutex);
447 }
448
449 /**
450  * handle_mailbox_cmd_from_user() - Dispatch a mailbox command for userspace.
451  * @cxlm: The CXL memory device to communicate with.
452  * @cmd: The validated command.
453  * @in_payload: Pointer to userspace's input payload.
454  * @out_payload: Pointer to userspace's output payload.
455  * @size_out: (Input) Max payload size to copy out.
456  *            (Output) Payload size hardware generated.
457  * @retval: Hardware generated return code from the operation.
458  *
459  * Return:
460  *  * %0        - Mailbox transaction succeeded. This implies the mailbox
461  *                protocol completed successfully not that the operation itself
462  *                was successful.
463  *  * %-ENOMEM  - Couldn't allocate a bounce buffer.
464  *  * %-EFAULT  - Something happened with copy_to/from_user.
465  *  * %-EINTR   - Mailbox acquisition interrupted.
466  *  * %-EXXX    - Transaction level failures.
467  *
468  * Creates the appropriate mailbox command and dispatches it on behalf of a
469  * userspace request. The input and output payloads are copied between
470  * userspace.
471  *
472  * See cxl_send_cmd().
473  */
474 static int handle_mailbox_cmd_from_user(struct cxl_mem *cxlm,
475                                         const struct cxl_mem_command *cmd,
476                                         u64 in_payload, u64 out_payload,
477                                         s32 *size_out, u32 *retval)
478 {
479         struct device *dev = &cxlm->pdev->dev;
480         struct mbox_cmd mbox_cmd = {
481                 .opcode = cmd->opcode,
482                 .size_in = cmd->info.size_in,
483                 .size_out = cmd->info.size_out,
484         };
485         int rc;
486
487         if (cmd->info.size_out) {
488                 mbox_cmd.payload_out = kvzalloc(cmd->info.size_out, GFP_KERNEL);
489                 if (!mbox_cmd.payload_out)
490                         return -ENOMEM;
491         }
492
493         if (cmd->info.size_in) {
494                 mbox_cmd.payload_in = vmemdup_user(u64_to_user_ptr(in_payload),
495                                                    cmd->info.size_in);
496                 if (IS_ERR(mbox_cmd.payload_in)) {
497                         kvfree(mbox_cmd.payload_out);
498                         return PTR_ERR(mbox_cmd.payload_in);
499                 }
500         }
501
502         rc = cxl_mem_mbox_get(cxlm);
503         if (rc)
504                 goto out;
505
506         dev_dbg(dev,
507                 "Submitting %s command for user\n"
508                 "\topcode: %x\n"
509                 "\tsize: %ub\n",
510                 cxl_command_names[cmd->info.id].name, mbox_cmd.opcode,
511                 cmd->info.size_in);
512
513         dev_WARN_ONCE(dev, cmd->info.id == CXL_MEM_COMMAND_ID_RAW,
514                       "raw command path used\n");
515
516         rc = __cxl_mem_mbox_send_cmd(cxlm, &mbox_cmd);
517         cxl_mem_mbox_put(cxlm);
518         if (rc)
519                 goto out;
520
521         /*
522          * @size_out contains the max size that's allowed to be written back out
523          * to userspace. While the payload may have written more output than
524          * this it will have to be ignored.
525          */
526         if (mbox_cmd.size_out) {
527                 dev_WARN_ONCE(dev, mbox_cmd.size_out > *size_out,
528                               "Invalid return size\n");
529                 if (copy_to_user(u64_to_user_ptr(out_payload),
530                                  mbox_cmd.payload_out, mbox_cmd.size_out)) {
531                         rc = -EFAULT;
532                         goto out;
533                 }
534         }
535
536         *size_out = mbox_cmd.size_out;
537         *retval = mbox_cmd.return_code;
538
539 out:
540         kvfree(mbox_cmd.payload_in);
541         kvfree(mbox_cmd.payload_out);
542         return rc;
543 }
544
545 static bool cxl_mem_raw_command_allowed(u16 opcode)
546 {
547         int i;
548
549         if (!IS_ENABLED(CONFIG_CXL_MEM_RAW_COMMANDS))
550                 return false;
551
552         if (security_locked_down(LOCKDOWN_NONE))
553                 return false;
554
555         if (cxl_raw_allow_all)
556                 return true;
557
558         if (cxl_is_security_command(opcode))
559                 return false;
560
561         for (i = 0; i < ARRAY_SIZE(cxl_disabled_raw_commands); i++)
562                 if (cxl_disabled_raw_commands[i] == opcode)
563                         return false;
564
565         return true;
566 }
567
568 /**
569  * cxl_validate_cmd_from_user() - Check fields for CXL_MEM_SEND_COMMAND.
570  * @cxlm: &struct cxl_mem device whose mailbox will be used.
571  * @send_cmd: &struct cxl_send_command copied in from userspace.
572  * @out_cmd: Sanitized and populated &struct cxl_mem_command.
573  *
574  * Return:
575  *  * %0        - @out_cmd is ready to send.
576  *  * %-ENOTTY  - Invalid command specified.
577  *  * %-EINVAL  - Reserved fields or invalid values were used.
578  *  * %-ENOMEM  - Input or output buffer wasn't sized properly.
579  *  * %-EPERM   - Attempted to use a protected command.
580  *
581  * The result of this command is a fully validated command in @out_cmd that is
582  * safe to send to the hardware.
583  *
584  * See handle_mailbox_cmd_from_user()
585  */
586 static int cxl_validate_cmd_from_user(struct cxl_mem *cxlm,
587                                       const struct cxl_send_command *send_cmd,
588                                       struct cxl_mem_command *out_cmd)
589 {
590         const struct cxl_command_info *info;
591         struct cxl_mem_command *c;
592
593         if (send_cmd->id == 0 || send_cmd->id >= CXL_MEM_COMMAND_ID_MAX)
594                 return -ENOTTY;
595
596         /*
597          * The user can never specify an input payload larger than what hardware
598          * supports, but output can be arbitrarily large (simply write out as
599          * much data as the hardware provides).
600          */
601         if (send_cmd->in.size > cxlm->payload_size)
602                 return -EINVAL;
603
604         /*
605          * Checks are bypassed for raw commands but a WARN/taint will occur
606          * later in the callchain
607          */
608         if (send_cmd->id == CXL_MEM_COMMAND_ID_RAW) {
609                 const struct cxl_mem_command temp = {
610                         .info = {
611                                 .id = CXL_MEM_COMMAND_ID_RAW,
612                                 .flags = 0,
613                                 .size_in = send_cmd->in.size,
614                                 .size_out = send_cmd->out.size,
615                         },
616                         .opcode = send_cmd->raw.opcode
617                 };
618
619                 if (send_cmd->raw.rsvd)
620                         return -EINVAL;
621
622                 /*
623                  * Unlike supported commands, the output size of RAW commands
624                  * gets passed along without further checking, so it must be
625                  * validated here.
626                  */
627                 if (send_cmd->out.size > cxlm->payload_size)
628                         return -EINVAL;
629
630                 if (!cxl_mem_raw_command_allowed(send_cmd->raw.opcode))
631                         return -EPERM;
632
633                 memcpy(out_cmd, &temp, sizeof(temp));
634
635                 return 0;
636         }
637
638         if (send_cmd->flags & ~CXL_MEM_COMMAND_FLAG_MASK)
639                 return -EINVAL;
640
641         if (send_cmd->rsvd)
642                 return -EINVAL;
643
644         if (send_cmd->in.rsvd || send_cmd->out.rsvd)
645                 return -EINVAL;
646
647         /* Convert user's command into the internal representation */
648         c = &mem_commands[send_cmd->id];
649         info = &c->info;
650
651         /* Check that the command is enabled for hardware */
652         if (!test_bit(info->id, cxlm->enabled_cmds))
653                 return -ENOTTY;
654
655         /* Check the input buffer is the expected size */
656         if (info->size_in >= 0 && info->size_in != send_cmd->in.size)
657                 return -ENOMEM;
658
659         /* Check the output buffer is at least large enough */
660         if (info->size_out >= 0 && send_cmd->out.size < info->size_out)
661                 return -ENOMEM;
662
663         memcpy(out_cmd, c, sizeof(*c));
664         out_cmd->info.size_in = send_cmd->in.size;
665         /*
666          * XXX: out_cmd->info.size_out will be controlled by the driver, and the
667          * specified number of bytes @send_cmd->out.size will be copied back out
668          * to userspace.
669          */
670
671         return 0;
672 }
673
674 static int cxl_query_cmd(struct cxl_memdev *cxlmd,
675                          struct cxl_mem_query_commands __user *q)
676 {
677         struct device *dev = &cxlmd->dev;
678         struct cxl_mem_command *cmd;
679         u32 n_commands;
680         int j = 0;
681
682         dev_dbg(dev, "Query IOCTL\n");
683
684         if (get_user(n_commands, &q->n_commands))
685                 return -EFAULT;
686
687         /* returns the total number if 0 elements are requested. */
688         if (n_commands == 0)
689                 return put_user(cxl_cmd_count, &q->n_commands);
690
691         /*
692          * otherwise, return max(n_commands, total commands) cxl_command_info
693          * structures.
694          */
695         cxl_for_each_cmd(cmd) {
696                 const struct cxl_command_info *info = &cmd->info;
697
698                 if (copy_to_user(&q->commands[j++], info, sizeof(*info)))
699                         return -EFAULT;
700
701                 if (j == n_commands)
702                         break;
703         }
704
705         return 0;
706 }
707
708 static int cxl_send_cmd(struct cxl_memdev *cxlmd,
709                         struct cxl_send_command __user *s)
710 {
711         struct cxl_mem *cxlm = cxlmd->cxlm;
712         struct device *dev = &cxlmd->dev;
713         struct cxl_send_command send;
714         struct cxl_mem_command c;
715         int rc;
716
717         dev_dbg(dev, "Send IOCTL\n");
718
719         if (copy_from_user(&send, s, sizeof(send)))
720                 return -EFAULT;
721
722         rc = cxl_validate_cmd_from_user(cxlmd->cxlm, &send, &c);
723         if (rc)
724                 return rc;
725
726         /* Prepare to handle a full payload for variable sized output */
727         if (c.info.size_out < 0)
728                 c.info.size_out = cxlm->payload_size;
729
730         rc = handle_mailbox_cmd_from_user(cxlm, &c, send.in.payload,
731                                           send.out.payload, &send.out.size,
732                                           &send.retval);
733         if (rc)
734                 return rc;
735
736         if (copy_to_user(s, &send, sizeof(send)))
737                 return -EFAULT;
738
739         return 0;
740 }
741
742 static long __cxl_memdev_ioctl(struct cxl_memdev *cxlmd, unsigned int cmd,
743                                unsigned long arg)
744 {
745         switch (cmd) {
746         case CXL_MEM_QUERY_COMMANDS:
747                 return cxl_query_cmd(cxlmd, (void __user *)arg);
748         case CXL_MEM_SEND_COMMAND:
749                 return cxl_send_cmd(cxlmd, (void __user *)arg);
750         default:
751                 return -ENOTTY;
752         }
753 }
754
755 static long cxl_memdev_ioctl(struct file *file, unsigned int cmd,
756                              unsigned long arg)
757 {
758         struct cxl_memdev *cxlmd = file->private_data;
759         int rc = -ENXIO;
760
761         down_read(&cxl_memdev_rwsem);
762         if (cxlmd->cxlm)
763                 rc = __cxl_memdev_ioctl(cxlmd, cmd, arg);
764         up_read(&cxl_memdev_rwsem);
765
766         return rc;
767 }
768
769 static int cxl_memdev_open(struct inode *inode, struct file *file)
770 {
771         struct cxl_memdev *cxlmd =
772                 container_of(inode->i_cdev, typeof(*cxlmd), cdev);
773
774         get_device(&cxlmd->dev);
775         file->private_data = cxlmd;
776
777         return 0;
778 }
779
780 static int cxl_memdev_release_file(struct inode *inode, struct file *file)
781 {
782         struct cxl_memdev *cxlmd =
783                 container_of(inode->i_cdev, typeof(*cxlmd), cdev);
784
785         put_device(&cxlmd->dev);
786
787         return 0;
788 }
789
790 static const struct file_operations cxl_memdev_fops = {
791         .owner = THIS_MODULE,
792         .unlocked_ioctl = cxl_memdev_ioctl,
793         .open = cxl_memdev_open,
794         .release = cxl_memdev_release_file,
795         .compat_ioctl = compat_ptr_ioctl,
796         .llseek = noop_llseek,
797 };
798
799 static inline struct cxl_mem_command *cxl_mem_find_command(u16 opcode)
800 {
801         struct cxl_mem_command *c;
802
803         cxl_for_each_cmd(c)
804                 if (c->opcode == opcode)
805                         return c;
806
807         return NULL;
808 }
809
810 /**
811  * cxl_mem_mbox_send_cmd() - Send a mailbox command to a memory device.
812  * @cxlm: The CXL memory device to communicate with.
813  * @opcode: Opcode for the mailbox command.
814  * @in: The input payload for the mailbox command.
815  * @in_size: The length of the input payload
816  * @out: Caller allocated buffer for the output.
817  * @out_size: Expected size of output.
818  *
819  * Context: Any context. Will acquire and release mbox_mutex.
820  * Return:
821  *  * %>=0      - Number of bytes returned in @out.
822  *  * %-E2BIG   - Payload is too large for hardware.
823  *  * %-EBUSY   - Couldn't acquire exclusive mailbox access.
824  *  * %-EFAULT  - Hardware error occurred.
825  *  * %-ENXIO   - Command completed, but device reported an error.
826  *  * %-EIO     - Unexpected output size.
827  *
828  * Mailbox commands may execute successfully yet the device itself reported an
829  * error. While this distinction can be useful for commands from userspace, the
830  * kernel will only be able to use results when both are successful.
831  *
832  * See __cxl_mem_mbox_send_cmd()
833  */
834 static int cxl_mem_mbox_send_cmd(struct cxl_mem *cxlm, u16 opcode,
835                                  void *in, size_t in_size,
836                                  void *out, size_t out_size)
837 {
838         const struct cxl_mem_command *cmd = cxl_mem_find_command(opcode);
839         struct mbox_cmd mbox_cmd = {
840                 .opcode = opcode,
841                 .payload_in = in,
842                 .size_in = in_size,
843                 .size_out = out_size,
844                 .payload_out = out,
845         };
846         int rc;
847
848         if (out_size > cxlm->payload_size)
849                 return -E2BIG;
850
851         rc = cxl_mem_mbox_get(cxlm);
852         if (rc)
853                 return rc;
854
855         rc = __cxl_mem_mbox_send_cmd(cxlm, &mbox_cmd);
856         cxl_mem_mbox_put(cxlm);
857         if (rc)
858                 return rc;
859
860         /* TODO: Map return code to proper kernel style errno */
861         if (mbox_cmd.return_code != CXL_MBOX_SUCCESS)
862                 return -ENXIO;
863
864         /*
865          * Variable sized commands can't be validated and so it's up to the
866          * caller to do that if they wish.
867          */
868         if (cmd->info.size_out >= 0 && mbox_cmd.size_out != out_size)
869                 return -EIO;
870
871         return 0;
872 }
873
874 static int cxl_mem_setup_mailbox(struct cxl_mem *cxlm)
875 {
876         const int cap = readl(cxlm->regs.mbox + CXLDEV_MBOX_CAPS_OFFSET);
877
878         cxlm->payload_size =
879                 1 << FIELD_GET(CXLDEV_MBOX_CAP_PAYLOAD_SIZE_MASK, cap);
880
881         /*
882          * CXL 2.0 8.2.8.4.3 Mailbox Capabilities Register
883          *
884          * If the size is too small, mandatory commands will not work and so
885          * there's no point in going forward. If the size is too large, there's
886          * no harm is soft limiting it.
887          */
888         cxlm->payload_size = min_t(size_t, cxlm->payload_size, SZ_1M);
889         if (cxlm->payload_size < 256) {
890                 dev_err(&cxlm->pdev->dev, "Mailbox is too small (%zub)",
891                         cxlm->payload_size);
892                 return -ENXIO;
893         }
894
895         dev_dbg(&cxlm->pdev->dev, "Mailbox payload sized %zu",
896                 cxlm->payload_size);
897
898         return 0;
899 }
900
901 static struct cxl_mem *cxl_mem_create(struct pci_dev *pdev)
902 {
903         struct device *dev = &pdev->dev;
904         struct cxl_mem *cxlm;
905
906         cxlm = devm_kzalloc(dev, sizeof(*cxlm), GFP_KERNEL);
907         if (!cxlm) {
908                 dev_err(dev, "No memory available\n");
909                 return ERR_PTR(-ENOMEM);
910         }
911
912         mutex_init(&cxlm->mbox_mutex);
913         cxlm->pdev = pdev;
914         cxlm->enabled_cmds =
915                 devm_kmalloc_array(dev, BITS_TO_LONGS(cxl_cmd_count),
916                                    sizeof(unsigned long),
917                                    GFP_KERNEL | __GFP_ZERO);
918         if (!cxlm->enabled_cmds) {
919                 dev_err(dev, "No memory available for bitmap\n");
920                 return ERR_PTR(-ENOMEM);
921         }
922
923         return cxlm;
924 }
925
926 static void __iomem *cxl_mem_map_regblock(struct cxl_mem *cxlm,
927                                           u8 bar, u64 offset)
928 {
929         struct pci_dev *pdev = cxlm->pdev;
930         struct device *dev = &pdev->dev;
931         void __iomem *addr;
932
933         /* Basic sanity check that BAR is big enough */
934         if (pci_resource_len(pdev, bar) < offset) {
935                 dev_err(dev, "BAR%d: %pr: too small (offset: %#llx)\n", bar,
936                         &pdev->resource[bar], (unsigned long long)offset);
937                 return IOMEM_ERR_PTR(-ENXIO);
938         }
939
940         addr = pci_iomap(pdev, bar, 0);
941         if (!addr) {
942                 dev_err(dev, "failed to map registers\n");
943                 return addr;
944         }
945
946         dev_dbg(dev, "Mapped CXL Memory Device resource bar %u @ %#llx\n",
947                 bar, offset);
948
949         return addr;
950 }
951
952 static void cxl_mem_unmap_regblock(struct cxl_mem *cxlm, void __iomem *base)
953 {
954         pci_iounmap(cxlm->pdev, base);
955 }
956
957 static int cxl_mem_dvsec(struct pci_dev *pdev, int dvsec)
958 {
959         int pos;
960
961         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_DVSEC);
962         if (!pos)
963                 return 0;
964
965         while (pos) {
966                 u16 vendor, id;
967
968                 pci_read_config_word(pdev, pos + PCI_DVSEC_HEADER1, &vendor);
969                 pci_read_config_word(pdev, pos + PCI_DVSEC_HEADER2, &id);
970                 if (vendor == PCI_DVSEC_VENDOR_ID_CXL && dvsec == id)
971                         return pos;
972
973                 pos = pci_find_next_ext_capability(pdev, pos,
974                                                    PCI_EXT_CAP_ID_DVSEC);
975         }
976
977         return 0;
978 }
979
980 static int cxl_probe_regs(struct cxl_mem *cxlm, void __iomem *base,
981                           struct cxl_register_map *map)
982 {
983         struct pci_dev *pdev = cxlm->pdev;
984         struct device *dev = &pdev->dev;
985         struct cxl_component_reg_map *comp_map;
986         struct cxl_device_reg_map *dev_map;
987
988         switch (map->reg_type) {
989         case CXL_REGLOC_RBI_COMPONENT:
990                 comp_map = &map->component_map;
991                 cxl_probe_component_regs(dev, base, comp_map);
992                 if (!comp_map->hdm_decoder.valid) {
993                         dev_err(dev, "HDM decoder registers not found\n");
994                         return -ENXIO;
995                 }
996
997                 dev_dbg(dev, "Set up component registers\n");
998                 break;
999         case CXL_REGLOC_RBI_MEMDEV:
1000                 dev_map = &map->device_map;
1001                 cxl_probe_device_regs(dev, base, dev_map);
1002                 if (!dev_map->status.valid || !dev_map->mbox.valid ||
1003                     !dev_map->memdev.valid) {
1004                         dev_err(dev, "registers not found: %s%s%s\n",
1005                                 !dev_map->status.valid ? "status " : "",
1006                                 !dev_map->mbox.valid ? "status " : "",
1007                                 !dev_map->memdev.valid ? "status " : "");
1008                         return -ENXIO;
1009                 }
1010
1011                 dev_dbg(dev, "Probing device registers...\n");
1012                 break;
1013         default:
1014                 break;
1015         }
1016
1017         return 0;
1018 }
1019
1020 static int cxl_map_regs(struct cxl_mem *cxlm, struct cxl_register_map *map)
1021 {
1022         struct pci_dev *pdev = cxlm->pdev;
1023         struct device *dev = &pdev->dev;
1024
1025         switch (map->reg_type) {
1026         case CXL_REGLOC_RBI_COMPONENT:
1027                 cxl_map_component_regs(pdev, &cxlm->regs.component, map);
1028                 dev_dbg(dev, "Mapping component registers...\n");
1029                 break;
1030         case CXL_REGLOC_RBI_MEMDEV:
1031                 cxl_map_device_regs(pdev, &cxlm->regs.device_regs, map);
1032                 dev_dbg(dev, "Probing device registers...\n");
1033                 break;
1034         default:
1035                 break;
1036         }
1037
1038         return 0;
1039 }
1040
1041 static void cxl_decode_register_block(u32 reg_lo, u32 reg_hi,
1042                                       u8 *bar, u64 *offset, u8 *reg_type)
1043 {
1044         *offset = ((u64)reg_hi << 32) | (reg_lo & CXL_REGLOC_ADDR_MASK);
1045         *bar = FIELD_GET(CXL_REGLOC_BIR_MASK, reg_lo);
1046         *reg_type = FIELD_GET(CXL_REGLOC_RBI_MASK, reg_lo);
1047 }
1048
1049 /**
1050  * cxl_mem_setup_regs() - Setup necessary MMIO.
1051  * @cxlm: The CXL memory device to communicate with.
1052  *
1053  * Return: 0 if all necessary registers mapped.
1054  *
1055  * A memory device is required by spec to implement a certain set of MMIO
1056  * regions. The purpose of this function is to enumerate and map those
1057  * registers.
1058  */
1059 static int cxl_mem_setup_regs(struct cxl_mem *cxlm)
1060 {
1061         struct pci_dev *pdev = cxlm->pdev;
1062         struct device *dev = &pdev->dev;
1063         u32 regloc_size, regblocks;
1064         void __iomem *base;
1065         int regloc, i;
1066         struct cxl_register_map *map, *n;
1067         LIST_HEAD(register_maps);
1068         int ret = 0;
1069
1070         regloc = cxl_mem_dvsec(pdev, PCI_DVSEC_ID_CXL_REGLOC_OFFSET);
1071         if (!regloc) {
1072                 dev_err(dev, "register location dvsec not found\n");
1073                 return -ENXIO;
1074         }
1075
1076         if (pci_request_mem_regions(pdev, pci_name(pdev)))
1077                 return -ENODEV;
1078
1079         /* Get the size of the Register Locator DVSEC */
1080         pci_read_config_dword(pdev, regloc + PCI_DVSEC_HEADER1, &regloc_size);
1081         regloc_size = FIELD_GET(PCI_DVSEC_HEADER1_LENGTH_MASK, regloc_size);
1082
1083         regloc += PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET;
1084         regblocks = (regloc_size - PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET) / 8;
1085
1086         for (i = 0; i < regblocks; i++, regloc += 8) {
1087                 u32 reg_lo, reg_hi;
1088                 u8 reg_type;
1089                 u64 offset;
1090                 u8 bar;
1091
1092                 map = kzalloc(sizeof(*map), GFP_KERNEL);
1093                 if (!map) {
1094                         ret = -ENOMEM;
1095                         goto free_maps;
1096                 }
1097
1098                 list_add(&map->list, &register_maps);
1099
1100                 pci_read_config_dword(pdev, regloc, &reg_lo);
1101                 pci_read_config_dword(pdev, regloc + 4, &reg_hi);
1102
1103                 cxl_decode_register_block(reg_lo, reg_hi, &bar, &offset,
1104                                           &reg_type);
1105
1106                 dev_dbg(dev, "Found register block in bar %u @ 0x%llx of type %u\n",
1107                         bar, offset, reg_type);
1108
1109                 base = cxl_mem_map_regblock(cxlm, bar, offset);
1110                 if (!base) {
1111                         ret = -ENOMEM;
1112                         goto free_maps;
1113                 }
1114
1115                 map->barno = bar;
1116                 map->block_offset = offset;
1117                 map->reg_type = reg_type;
1118
1119                 ret = cxl_probe_regs(cxlm, base + offset, map);
1120
1121                 /* Always unmap the regblock regardless of probe success */
1122                 cxl_mem_unmap_regblock(cxlm, base);
1123
1124                 if (ret)
1125                         goto free_maps;
1126         }
1127
1128         pci_release_mem_regions(pdev);
1129
1130         list_for_each_entry(map, &register_maps, list) {
1131                 ret = cxl_map_regs(cxlm, map);
1132                 if (ret)
1133                         goto free_maps;
1134         }
1135
1136 free_maps:
1137         list_for_each_entry_safe(map, n, &register_maps, list) {
1138                 list_del(&map->list);
1139                 kfree(map);
1140         }
1141
1142         return ret;
1143 }
1144
1145 static struct cxl_memdev *to_cxl_memdev(struct device *dev)
1146 {
1147         return container_of(dev, struct cxl_memdev, dev);
1148 }
1149
1150 static void cxl_memdev_release(struct device *dev)
1151 {
1152         struct cxl_memdev *cxlmd = to_cxl_memdev(dev);
1153
1154         ida_free(&cxl_memdev_ida, cxlmd->id);
1155         kfree(cxlmd);
1156 }
1157
1158 static char *cxl_memdev_devnode(struct device *dev, umode_t *mode, kuid_t *uid,
1159                                 kgid_t *gid)
1160 {
1161         return kasprintf(GFP_KERNEL, "cxl/%s", dev_name(dev));
1162 }
1163
1164 static ssize_t firmware_version_show(struct device *dev,
1165                                      struct device_attribute *attr, char *buf)
1166 {
1167         struct cxl_memdev *cxlmd = to_cxl_memdev(dev);
1168         struct cxl_mem *cxlm = cxlmd->cxlm;
1169
1170         return sysfs_emit(buf, "%.16s\n", cxlm->firmware_version);
1171 }
1172 static DEVICE_ATTR_RO(firmware_version);
1173
1174 static ssize_t payload_max_show(struct device *dev,
1175                                 struct device_attribute *attr, char *buf)
1176 {
1177         struct cxl_memdev *cxlmd = to_cxl_memdev(dev);
1178         struct cxl_mem *cxlm = cxlmd->cxlm;
1179
1180         return sysfs_emit(buf, "%zu\n", cxlm->payload_size);
1181 }
1182 static DEVICE_ATTR_RO(payload_max);
1183
1184 static ssize_t label_storage_size_show(struct device *dev,
1185                                 struct device_attribute *attr, char *buf)
1186 {
1187         struct cxl_memdev *cxlmd = to_cxl_memdev(dev);
1188         struct cxl_mem *cxlm = cxlmd->cxlm;
1189
1190         return sysfs_emit(buf, "%zu\n", cxlm->lsa_size);
1191 }
1192 static DEVICE_ATTR_RO(label_storage_size);
1193
1194 static ssize_t ram_size_show(struct device *dev, struct device_attribute *attr,
1195                              char *buf)
1196 {
1197         struct cxl_memdev *cxlmd = to_cxl_memdev(dev);
1198         struct cxl_mem *cxlm = cxlmd->cxlm;
1199         unsigned long long len = range_len(&cxlm->ram_range);
1200
1201         return sysfs_emit(buf, "%#llx\n", len);
1202 }
1203
1204 static struct device_attribute dev_attr_ram_size =
1205         __ATTR(size, 0444, ram_size_show, NULL);
1206
1207 static ssize_t pmem_size_show(struct device *dev, struct device_attribute *attr,
1208                               char *buf)
1209 {
1210         struct cxl_memdev *cxlmd = to_cxl_memdev(dev);
1211         struct cxl_mem *cxlm = cxlmd->cxlm;
1212         unsigned long long len = range_len(&cxlm->pmem_range);
1213
1214         return sysfs_emit(buf, "%#llx\n", len);
1215 }
1216
1217 static struct device_attribute dev_attr_pmem_size =
1218         __ATTR(size, 0444, pmem_size_show, NULL);
1219
1220 static struct attribute *cxl_memdev_attributes[] = {
1221         &dev_attr_firmware_version.attr,
1222         &dev_attr_payload_max.attr,
1223         &dev_attr_label_storage_size.attr,
1224         NULL,
1225 };
1226
1227 static struct attribute *cxl_memdev_pmem_attributes[] = {
1228         &dev_attr_pmem_size.attr,
1229         NULL,
1230 };
1231
1232 static struct attribute *cxl_memdev_ram_attributes[] = {
1233         &dev_attr_ram_size.attr,
1234         NULL,
1235 };
1236
1237 static struct attribute_group cxl_memdev_attribute_group = {
1238         .attrs = cxl_memdev_attributes,
1239 };
1240
1241 static struct attribute_group cxl_memdev_ram_attribute_group = {
1242         .name = "ram",
1243         .attrs = cxl_memdev_ram_attributes,
1244 };
1245
1246 static struct attribute_group cxl_memdev_pmem_attribute_group = {
1247         .name = "pmem",
1248         .attrs = cxl_memdev_pmem_attributes,
1249 };
1250
1251 static const struct attribute_group *cxl_memdev_attribute_groups[] = {
1252         &cxl_memdev_attribute_group,
1253         &cxl_memdev_ram_attribute_group,
1254         &cxl_memdev_pmem_attribute_group,
1255         NULL,
1256 };
1257
1258 static const struct device_type cxl_memdev_type = {
1259         .name = "cxl_memdev",
1260         .release = cxl_memdev_release,
1261         .devnode = cxl_memdev_devnode,
1262         .groups = cxl_memdev_attribute_groups,
1263 };
1264
1265 static void cxl_memdev_shutdown(struct cxl_memdev *cxlmd)
1266 {
1267         down_write(&cxl_memdev_rwsem);
1268         cxlmd->cxlm = NULL;
1269         up_write(&cxl_memdev_rwsem);
1270 }
1271
1272 static void cxl_memdev_unregister(void *_cxlmd)
1273 {
1274         struct cxl_memdev *cxlmd = _cxlmd;
1275         struct device *dev = &cxlmd->dev;
1276
1277         cdev_device_del(&cxlmd->cdev, dev);
1278         cxl_memdev_shutdown(cxlmd);
1279         put_device(dev);
1280 }
1281
1282 static struct cxl_memdev *cxl_memdev_alloc(struct cxl_mem *cxlm)
1283 {
1284         struct pci_dev *pdev = cxlm->pdev;
1285         struct cxl_memdev *cxlmd;
1286         struct device *dev;
1287         struct cdev *cdev;
1288         int rc;
1289
1290         cxlmd = kzalloc(sizeof(*cxlmd), GFP_KERNEL);
1291         if (!cxlmd)
1292                 return ERR_PTR(-ENOMEM);
1293
1294         rc = ida_alloc_range(&cxl_memdev_ida, 0, CXL_MEM_MAX_DEVS, GFP_KERNEL);
1295         if (rc < 0)
1296                 goto err;
1297         cxlmd->id = rc;
1298
1299         dev = &cxlmd->dev;
1300         device_initialize(dev);
1301         dev->parent = &pdev->dev;
1302         dev->bus = &cxl_bus_type;
1303         dev->devt = MKDEV(cxl_mem_major, cxlmd->id);
1304         dev->type = &cxl_memdev_type;
1305         device_set_pm_not_required(dev);
1306
1307         cdev = &cxlmd->cdev;
1308         cdev_init(cdev, &cxl_memdev_fops);
1309         return cxlmd;
1310
1311 err:
1312         kfree(cxlmd);
1313         return ERR_PTR(rc);
1314 }
1315
1316 static int cxl_mem_add_memdev(struct cxl_mem *cxlm)
1317 {
1318         struct cxl_memdev *cxlmd;
1319         struct device *dev;
1320         struct cdev *cdev;
1321         int rc;
1322
1323         cxlmd = cxl_memdev_alloc(cxlm);
1324         if (IS_ERR(cxlmd))
1325                 return PTR_ERR(cxlmd);
1326
1327         dev = &cxlmd->dev;
1328         rc = dev_set_name(dev, "mem%d", cxlmd->id);
1329         if (rc)
1330                 goto err;
1331
1332         /*
1333          * Activate ioctl operations, no cxl_memdev_rwsem manipulation
1334          * needed as this is ordered with cdev_add() publishing the device.
1335          */
1336         cxlmd->cxlm = cxlm;
1337
1338         cdev = &cxlmd->cdev;
1339         rc = cdev_device_add(cdev, dev);
1340         if (rc)
1341                 goto err;
1342
1343         return devm_add_action_or_reset(dev->parent, cxl_memdev_unregister,
1344                                         cxlmd);
1345
1346 err:
1347         /*
1348          * The cdev was briefly live, shutdown any ioctl operations that
1349          * saw that state.
1350          */
1351         cxl_memdev_shutdown(cxlmd);
1352         put_device(dev);
1353         return rc;
1354 }
1355
1356 static int cxl_xfer_log(struct cxl_mem *cxlm, uuid_t *uuid, u32 size, u8 *out)
1357 {
1358         u32 remaining = size;
1359         u32 offset = 0;
1360
1361         while (remaining) {
1362                 u32 xfer_size = min_t(u32, remaining, cxlm->payload_size);
1363                 struct cxl_mbox_get_log {
1364                         uuid_t uuid;
1365                         __le32 offset;
1366                         __le32 length;
1367                 } __packed log = {
1368                         .uuid = *uuid,
1369                         .offset = cpu_to_le32(offset),
1370                         .length = cpu_to_le32(xfer_size)
1371                 };
1372                 int rc;
1373
1374                 rc = cxl_mem_mbox_send_cmd(cxlm, CXL_MBOX_OP_GET_LOG, &log,
1375                                            sizeof(log), out, xfer_size);
1376                 if (rc < 0)
1377                         return rc;
1378
1379                 out += xfer_size;
1380                 remaining -= xfer_size;
1381                 offset += xfer_size;
1382         }
1383
1384         return 0;
1385 }
1386
1387 /**
1388  * cxl_walk_cel() - Walk through the Command Effects Log.
1389  * @cxlm: Device.
1390  * @size: Length of the Command Effects Log.
1391  * @cel: CEL
1392  *
1393  * Iterate over each entry in the CEL and determine if the driver supports the
1394  * command. If so, the command is enabled for the device and can be used later.
1395  */
1396 static void cxl_walk_cel(struct cxl_mem *cxlm, size_t size, u8 *cel)
1397 {
1398         struct cel_entry {
1399                 __le16 opcode;
1400                 __le16 effect;
1401         } __packed * cel_entry;
1402         const int cel_entries = size / sizeof(*cel_entry);
1403         int i;
1404
1405         cel_entry = (struct cel_entry *)cel;
1406
1407         for (i = 0; i < cel_entries; i++) {
1408                 u16 opcode = le16_to_cpu(cel_entry[i].opcode);
1409                 struct cxl_mem_command *cmd = cxl_mem_find_command(opcode);
1410
1411                 if (!cmd) {
1412                         dev_dbg(&cxlm->pdev->dev,
1413                                 "Opcode 0x%04x unsupported by driver", opcode);
1414                         continue;
1415                 }
1416
1417                 set_bit(cmd->info.id, cxlm->enabled_cmds);
1418         }
1419 }
1420
1421 struct cxl_mbox_get_supported_logs {
1422         __le16 entries;
1423         u8 rsvd[6];
1424         struct gsl_entry {
1425                 uuid_t uuid;
1426                 __le32 size;
1427         } __packed entry[];
1428 } __packed;
1429
1430 static struct cxl_mbox_get_supported_logs *cxl_get_gsl(struct cxl_mem *cxlm)
1431 {
1432         struct cxl_mbox_get_supported_logs *ret;
1433         int rc;
1434
1435         ret = kvmalloc(cxlm->payload_size, GFP_KERNEL);
1436         if (!ret)
1437                 return ERR_PTR(-ENOMEM);
1438
1439         rc = cxl_mem_mbox_send_cmd(cxlm, CXL_MBOX_OP_GET_SUPPORTED_LOGS, NULL,
1440                                    0, ret, cxlm->payload_size);
1441         if (rc < 0) {
1442                 kvfree(ret);
1443                 return ERR_PTR(rc);
1444         }
1445
1446         return ret;
1447 }
1448
1449 /**
1450  * cxl_mem_enumerate_cmds() - Enumerate commands for a device.
1451  * @cxlm: The device.
1452  *
1453  * Returns 0 if enumerate completed successfully.
1454  *
1455  * CXL devices have optional support for certain commands. This function will
1456  * determine the set of supported commands for the hardware and update the
1457  * enabled_cmds bitmap in the @cxlm.
1458  */
1459 static int cxl_mem_enumerate_cmds(struct cxl_mem *cxlm)
1460 {
1461         struct cxl_mbox_get_supported_logs *gsl;
1462         struct device *dev = &cxlm->pdev->dev;
1463         struct cxl_mem_command *cmd;
1464         int i, rc;
1465
1466         gsl = cxl_get_gsl(cxlm);
1467         if (IS_ERR(gsl))
1468                 return PTR_ERR(gsl);
1469
1470         rc = -ENOENT;
1471         for (i = 0; i < le16_to_cpu(gsl->entries); i++) {
1472                 u32 size = le32_to_cpu(gsl->entry[i].size);
1473                 uuid_t uuid = gsl->entry[i].uuid;
1474                 u8 *log;
1475
1476                 dev_dbg(dev, "Found LOG type %pU of size %d", &uuid, size);
1477
1478                 if (!uuid_equal(&uuid, &log_uuid[CEL_UUID]))
1479                         continue;
1480
1481                 log = kvmalloc(size, GFP_KERNEL);
1482                 if (!log) {
1483                         rc = -ENOMEM;
1484                         goto out;
1485                 }
1486
1487                 rc = cxl_xfer_log(cxlm, &uuid, size, log);
1488                 if (rc) {
1489                         kvfree(log);
1490                         goto out;
1491                 }
1492
1493                 cxl_walk_cel(cxlm, size, log);
1494                 kvfree(log);
1495
1496                 /* In case CEL was bogus, enable some default commands. */
1497                 cxl_for_each_cmd(cmd)
1498                         if (cmd->flags & CXL_CMD_FLAG_FORCE_ENABLE)
1499                                 set_bit(cmd->info.id, cxlm->enabled_cmds);
1500
1501                 /* Found the required CEL */
1502                 rc = 0;
1503         }
1504
1505 out:
1506         kvfree(gsl);
1507         return rc;
1508 }
1509
1510 /**
1511  * cxl_mem_identify() - Send the IDENTIFY command to the device.
1512  * @cxlm: The device to identify.
1513  *
1514  * Return: 0 if identify was executed successfully.
1515  *
1516  * This will dispatch the identify command to the device and on success populate
1517  * structures to be exported to sysfs.
1518  */
1519 static int cxl_mem_identify(struct cxl_mem *cxlm)
1520 {
1521         /* See CXL 2.0 Table 175 Identify Memory Device Output Payload */
1522         struct cxl_mbox_identify {
1523                 char fw_revision[0x10];
1524                 __le64 total_capacity;
1525                 __le64 volatile_capacity;
1526                 __le64 persistent_capacity;
1527                 __le64 partition_align;
1528                 __le16 info_event_log_size;
1529                 __le16 warning_event_log_size;
1530                 __le16 failure_event_log_size;
1531                 __le16 fatal_event_log_size;
1532                 __le32 lsa_size;
1533                 u8 poison_list_max_mer[3];
1534                 __le16 inject_poison_limit;
1535                 u8 poison_caps;
1536                 u8 qos_telemetry_caps;
1537         } __packed id;
1538         int rc;
1539
1540         rc = cxl_mem_mbox_send_cmd(cxlm, CXL_MBOX_OP_IDENTIFY, NULL, 0, &id,
1541                                    sizeof(id));
1542         if (rc < 0)
1543                 return rc;
1544
1545         /*
1546          * TODO: enumerate DPA map, as 'ram' and 'pmem' do not alias.
1547          * For now, only the capacity is exported in sysfs
1548          */
1549         cxlm->ram_range.start = 0;
1550         cxlm->ram_range.end = le64_to_cpu(id.volatile_capacity) * SZ_256M - 1;
1551
1552         cxlm->pmem_range.start = 0;
1553         cxlm->pmem_range.end =
1554                 le64_to_cpu(id.persistent_capacity) * SZ_256M - 1;
1555
1556         cxlm->lsa_size = le32_to_cpu(id.lsa_size);
1557         memcpy(cxlm->firmware_version, id.fw_revision, sizeof(id.fw_revision));
1558
1559         return 0;
1560 }
1561
1562 static int cxl_mem_probe(struct pci_dev *pdev, const struct pci_device_id *id)
1563 {
1564         struct cxl_mem *cxlm;
1565         int rc;
1566
1567         rc = pcim_enable_device(pdev);
1568         if (rc)
1569                 return rc;
1570
1571         cxlm = cxl_mem_create(pdev);
1572         if (IS_ERR(cxlm))
1573                 return PTR_ERR(cxlm);
1574
1575         rc = cxl_mem_setup_regs(cxlm);
1576         if (rc)
1577                 return rc;
1578
1579         rc = cxl_mem_setup_mailbox(cxlm);
1580         if (rc)
1581                 return rc;
1582
1583         rc = cxl_mem_enumerate_cmds(cxlm);
1584         if (rc)
1585                 return rc;
1586
1587         rc = cxl_mem_identify(cxlm);
1588         if (rc)
1589                 return rc;
1590
1591         return cxl_mem_add_memdev(cxlm);
1592 }
1593
1594 static const struct pci_device_id cxl_mem_pci_tbl[] = {
1595         /* PCI class code for CXL.mem Type-3 Devices */
1596         { PCI_DEVICE_CLASS((PCI_CLASS_MEMORY_CXL << 8 | CXL_MEMORY_PROGIF), ~0)},
1597         { /* terminate list */ },
1598 };
1599 MODULE_DEVICE_TABLE(pci, cxl_mem_pci_tbl);
1600
1601 static struct pci_driver cxl_mem_driver = {
1602         .name                   = KBUILD_MODNAME,
1603         .id_table               = cxl_mem_pci_tbl,
1604         .probe                  = cxl_mem_probe,
1605         .driver = {
1606                 .probe_type     = PROBE_PREFER_ASYNCHRONOUS,
1607         },
1608 };
1609
1610 static __init int cxl_mem_init(void)
1611 {
1612         struct dentry *mbox_debugfs;
1613         dev_t devt;
1614         int rc;
1615
1616         /* Double check the anonymous union trickery in struct cxl_regs */
1617         BUILD_BUG_ON(offsetof(struct cxl_regs, memdev) !=
1618                      offsetof(struct cxl_regs, device_regs.memdev));
1619
1620         rc = alloc_chrdev_region(&devt, 0, CXL_MEM_MAX_DEVS, "cxl");
1621         if (rc)
1622                 return rc;
1623
1624         cxl_mem_major = MAJOR(devt);
1625
1626         rc = pci_register_driver(&cxl_mem_driver);
1627         if (rc) {
1628                 unregister_chrdev_region(MKDEV(cxl_mem_major, 0),
1629                                          CXL_MEM_MAX_DEVS);
1630                 return rc;
1631         }
1632
1633         cxl_debugfs = debugfs_create_dir("cxl", NULL);
1634         mbox_debugfs = debugfs_create_dir("mbox", cxl_debugfs);
1635         debugfs_create_bool("raw_allow_all", 0600, mbox_debugfs,
1636                             &cxl_raw_allow_all);
1637
1638         return 0;
1639 }
1640
1641 static __exit void cxl_mem_exit(void)
1642 {
1643         debugfs_remove_recursive(cxl_debugfs);
1644         pci_unregister_driver(&cxl_mem_driver);
1645         unregister_chrdev_region(MKDEV(cxl_mem_major, 0), CXL_MEM_MAX_DEVS);
1646 }
1647
1648 MODULE_LICENSE("GPL v2");
1649 module_init(cxl_mem_init);
1650 module_exit(cxl_mem_exit);
1651 MODULE_IMPORT_NS(CXL);