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