cxl/pci: Reserve all device regions at once
[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,
926                                           u8 bar, u64 offset)
927 {
928         struct pci_dev *pdev = cxlm->pdev;
929         struct device *dev = &pdev->dev;
930         void __iomem *addr;
931
932         /* Basic sanity check that BAR is big enough */
933         if (pci_resource_len(pdev, bar) < offset) {
934                 dev_err(dev, "BAR%d: %pr: too small (offset: %#llx)\n", bar,
935                         &pdev->resource[bar], (unsigned long long)offset);
936                 return IOMEM_ERR_PTR(-ENXIO);
937         }
938
939         addr = pcim_iomap(pdev, bar, 0);
940         if (!addr) {
941                 dev_err(dev, "failed to map registers\n");
942                 return addr;
943         }
944
945         dev_dbg(dev, "Mapped CXL Memory Device resource bar %u @ %#llx\n",
946                 bar, offset);
947
948         return pcim_iomap_table(pdev)[bar] + offset;
949 }
950
951 static int cxl_mem_dvsec(struct pci_dev *pdev, int dvsec)
952 {
953         int pos;
954
955         pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_DVSEC);
956         if (!pos)
957                 return 0;
958
959         while (pos) {
960                 u16 vendor, id;
961
962                 pci_read_config_word(pdev, pos + PCI_DVSEC_HEADER1, &vendor);
963                 pci_read_config_word(pdev, pos + PCI_DVSEC_HEADER2, &id);
964                 if (vendor == PCI_DVSEC_VENDOR_ID_CXL && dvsec == id)
965                         return pos;
966
967                 pos = pci_find_next_ext_capability(pdev, pos,
968                                                    PCI_EXT_CAP_ID_DVSEC);
969         }
970
971         return 0;
972 }
973
974 static void cxl_decode_register_block(u32 reg_lo, u32 reg_hi,
975                                       u8 *bar, u64 *offset, u8 *reg_type)
976 {
977         *offset = ((u64)reg_hi << 32) | (reg_lo & CXL_REGLOC_ADDR_MASK);
978         *bar = FIELD_GET(CXL_REGLOC_BIR_MASK, reg_lo);
979         *reg_type = FIELD_GET(CXL_REGLOC_RBI_MASK, reg_lo);
980 }
981
982 /**
983  * cxl_mem_setup_regs() - Setup necessary MMIO.
984  * @cxlm: The CXL memory device to communicate with.
985  *
986  * Return: 0 if all necessary registers mapped.
987  *
988  * A memory device is required by spec to implement a certain set of MMIO
989  * regions. The purpose of this function is to enumerate and map those
990  * registers.
991  */
992 static int cxl_mem_setup_regs(struct cxl_mem *cxlm)
993 {
994         struct cxl_regs *regs = &cxlm->regs;
995         struct pci_dev *pdev = cxlm->pdev;
996         struct device *dev = &pdev->dev;
997         u32 regloc_size, regblocks;
998         void __iomem *base;
999         int regloc, i;
1000
1001         regloc = cxl_mem_dvsec(pdev, PCI_DVSEC_ID_CXL_REGLOC_OFFSET);
1002         if (!regloc) {
1003                 dev_err(dev, "register location dvsec not found\n");
1004                 return -ENXIO;
1005         }
1006
1007         if (pci_request_mem_regions(pdev, pci_name(pdev)))
1008                 return -ENODEV;
1009
1010         /* Get the size of the Register Locator DVSEC */
1011         pci_read_config_dword(pdev, regloc + PCI_DVSEC_HEADER1, &regloc_size);
1012         regloc_size = FIELD_GET(PCI_DVSEC_HEADER1_LENGTH_MASK, regloc_size);
1013
1014         regloc += PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET;
1015         regblocks = (regloc_size - PCI_DVSEC_ID_CXL_REGLOC_BLOCK1_OFFSET) / 8;
1016
1017         for (i = 0; i < regblocks; i++, regloc += 8) {
1018                 u32 reg_lo, reg_hi;
1019                 u8 reg_type;
1020                 u64 offset;
1021                 u8 bar;
1022
1023                 /* "register low and high" contain other bits */
1024                 pci_read_config_dword(pdev, regloc, &reg_lo);
1025                 pci_read_config_dword(pdev, regloc + 4, &reg_hi);
1026
1027                 cxl_decode_register_block(reg_lo, reg_hi, &bar, &offset,
1028                                           &reg_type);
1029
1030                 dev_dbg(dev, "Found register block in bar %u @ 0x%llx of type %u\n",
1031                         bar, offset, reg_type);
1032
1033                 if (reg_type == CXL_REGLOC_RBI_MEMDEV) {
1034                         base = cxl_mem_map_regblock(cxlm, bar, offset);
1035                         if (!base)
1036                                 return -ENOMEM;
1037                         break;
1038                 }
1039         }
1040
1041         if (i == regblocks) {
1042                 dev_err(dev, "Missing register locator for device registers\n");
1043                 return -ENXIO;
1044         }
1045
1046         cxl_setup_device_regs(dev, base, &regs->device_regs);
1047
1048         if (!regs->status || !regs->mbox || !regs->memdev) {
1049                 dev_err(dev, "registers not found: %s%s%s\n",
1050                         !regs->status ? "status " : "",
1051                         !regs->mbox ? "mbox " : "",
1052                         !regs->memdev ? "memdev" : "");
1053                 return -ENXIO;
1054         }
1055
1056         return 0;
1057 }
1058
1059 static struct cxl_memdev *to_cxl_memdev(struct device *dev)
1060 {
1061         return container_of(dev, struct cxl_memdev, dev);
1062 }
1063
1064 static void cxl_memdev_release(struct device *dev)
1065 {
1066         struct cxl_memdev *cxlmd = to_cxl_memdev(dev);
1067
1068         ida_free(&cxl_memdev_ida, cxlmd->id);
1069         kfree(cxlmd);
1070 }
1071
1072 static char *cxl_memdev_devnode(struct device *dev, umode_t *mode, kuid_t *uid,
1073                                 kgid_t *gid)
1074 {
1075         return kasprintf(GFP_KERNEL, "cxl/%s", dev_name(dev));
1076 }
1077
1078 static ssize_t firmware_version_show(struct device *dev,
1079                                      struct device_attribute *attr, char *buf)
1080 {
1081         struct cxl_memdev *cxlmd = to_cxl_memdev(dev);
1082         struct cxl_mem *cxlm = cxlmd->cxlm;
1083
1084         return sysfs_emit(buf, "%.16s\n", cxlm->firmware_version);
1085 }
1086 static DEVICE_ATTR_RO(firmware_version);
1087
1088 static ssize_t payload_max_show(struct device *dev,
1089                                 struct device_attribute *attr, char *buf)
1090 {
1091         struct cxl_memdev *cxlmd = to_cxl_memdev(dev);
1092         struct cxl_mem *cxlm = cxlmd->cxlm;
1093
1094         return sysfs_emit(buf, "%zu\n", cxlm->payload_size);
1095 }
1096 static DEVICE_ATTR_RO(payload_max);
1097
1098 static ssize_t label_storage_size_show(struct device *dev,
1099                                 struct device_attribute *attr, char *buf)
1100 {
1101         struct cxl_memdev *cxlmd = to_cxl_memdev(dev);
1102         struct cxl_mem *cxlm = cxlmd->cxlm;
1103
1104         return sysfs_emit(buf, "%zu\n", cxlm->lsa_size);
1105 }
1106 static DEVICE_ATTR_RO(label_storage_size);
1107
1108 static ssize_t ram_size_show(struct device *dev, struct device_attribute *attr,
1109                              char *buf)
1110 {
1111         struct cxl_memdev *cxlmd = to_cxl_memdev(dev);
1112         struct cxl_mem *cxlm = cxlmd->cxlm;
1113         unsigned long long len = range_len(&cxlm->ram_range);
1114
1115         return sysfs_emit(buf, "%#llx\n", len);
1116 }
1117
1118 static struct device_attribute dev_attr_ram_size =
1119         __ATTR(size, 0444, ram_size_show, NULL);
1120
1121 static ssize_t pmem_size_show(struct device *dev, struct device_attribute *attr,
1122                               char *buf)
1123 {
1124         struct cxl_memdev *cxlmd = to_cxl_memdev(dev);
1125         struct cxl_mem *cxlm = cxlmd->cxlm;
1126         unsigned long long len = range_len(&cxlm->pmem_range);
1127
1128         return sysfs_emit(buf, "%#llx\n", len);
1129 }
1130
1131 static struct device_attribute dev_attr_pmem_size =
1132         __ATTR(size, 0444, pmem_size_show, NULL);
1133
1134 static struct attribute *cxl_memdev_attributes[] = {
1135         &dev_attr_firmware_version.attr,
1136         &dev_attr_payload_max.attr,
1137         &dev_attr_label_storage_size.attr,
1138         NULL,
1139 };
1140
1141 static struct attribute *cxl_memdev_pmem_attributes[] = {
1142         &dev_attr_pmem_size.attr,
1143         NULL,
1144 };
1145
1146 static struct attribute *cxl_memdev_ram_attributes[] = {
1147         &dev_attr_ram_size.attr,
1148         NULL,
1149 };
1150
1151 static struct attribute_group cxl_memdev_attribute_group = {
1152         .attrs = cxl_memdev_attributes,
1153 };
1154
1155 static struct attribute_group cxl_memdev_ram_attribute_group = {
1156         .name = "ram",
1157         .attrs = cxl_memdev_ram_attributes,
1158 };
1159
1160 static struct attribute_group cxl_memdev_pmem_attribute_group = {
1161         .name = "pmem",
1162         .attrs = cxl_memdev_pmem_attributes,
1163 };
1164
1165 static const struct attribute_group *cxl_memdev_attribute_groups[] = {
1166         &cxl_memdev_attribute_group,
1167         &cxl_memdev_ram_attribute_group,
1168         &cxl_memdev_pmem_attribute_group,
1169         NULL,
1170 };
1171
1172 static const struct device_type cxl_memdev_type = {
1173         .name = "cxl_memdev",
1174         .release = cxl_memdev_release,
1175         .devnode = cxl_memdev_devnode,
1176         .groups = cxl_memdev_attribute_groups,
1177 };
1178
1179 static void cxl_memdev_shutdown(struct cxl_memdev *cxlmd)
1180 {
1181         down_write(&cxl_memdev_rwsem);
1182         cxlmd->cxlm = NULL;
1183         up_write(&cxl_memdev_rwsem);
1184 }
1185
1186 static void cxl_memdev_unregister(void *_cxlmd)
1187 {
1188         struct cxl_memdev *cxlmd = _cxlmd;
1189         struct device *dev = &cxlmd->dev;
1190
1191         cdev_device_del(&cxlmd->cdev, dev);
1192         cxl_memdev_shutdown(cxlmd);
1193         put_device(dev);
1194 }
1195
1196 static struct cxl_memdev *cxl_memdev_alloc(struct cxl_mem *cxlm)
1197 {
1198         struct pci_dev *pdev = cxlm->pdev;
1199         struct cxl_memdev *cxlmd;
1200         struct device *dev;
1201         struct cdev *cdev;
1202         int rc;
1203
1204         cxlmd = kzalloc(sizeof(*cxlmd), GFP_KERNEL);
1205         if (!cxlmd)
1206                 return ERR_PTR(-ENOMEM);
1207
1208         rc = ida_alloc_range(&cxl_memdev_ida, 0, CXL_MEM_MAX_DEVS, GFP_KERNEL);
1209         if (rc < 0)
1210                 goto err;
1211         cxlmd->id = rc;
1212
1213         dev = &cxlmd->dev;
1214         device_initialize(dev);
1215         dev->parent = &pdev->dev;
1216         dev->bus = &cxl_bus_type;
1217         dev->devt = MKDEV(cxl_mem_major, cxlmd->id);
1218         dev->type = &cxl_memdev_type;
1219         device_set_pm_not_required(dev);
1220
1221         cdev = &cxlmd->cdev;
1222         cdev_init(cdev, &cxl_memdev_fops);
1223         return cxlmd;
1224
1225 err:
1226         kfree(cxlmd);
1227         return ERR_PTR(rc);
1228 }
1229
1230 static int cxl_mem_add_memdev(struct cxl_mem *cxlm)
1231 {
1232         struct cxl_memdev *cxlmd;
1233         struct device *dev;
1234         struct cdev *cdev;
1235         int rc;
1236
1237         cxlmd = cxl_memdev_alloc(cxlm);
1238         if (IS_ERR(cxlmd))
1239                 return PTR_ERR(cxlmd);
1240
1241         dev = &cxlmd->dev;
1242         rc = dev_set_name(dev, "mem%d", cxlmd->id);
1243         if (rc)
1244                 goto err;
1245
1246         /*
1247          * Activate ioctl operations, no cxl_memdev_rwsem manipulation
1248          * needed as this is ordered with cdev_add() publishing the device.
1249          */
1250         cxlmd->cxlm = cxlm;
1251
1252         cdev = &cxlmd->cdev;
1253         rc = cdev_device_add(cdev, dev);
1254         if (rc)
1255                 goto err;
1256
1257         return devm_add_action_or_reset(dev->parent, cxl_memdev_unregister,
1258                                         cxlmd);
1259
1260 err:
1261         /*
1262          * The cdev was briefly live, shutdown any ioctl operations that
1263          * saw that state.
1264          */
1265         cxl_memdev_shutdown(cxlmd);
1266         put_device(dev);
1267         return rc;
1268 }
1269
1270 static int cxl_xfer_log(struct cxl_mem *cxlm, uuid_t *uuid, u32 size, u8 *out)
1271 {
1272         u32 remaining = size;
1273         u32 offset = 0;
1274
1275         while (remaining) {
1276                 u32 xfer_size = min_t(u32, remaining, cxlm->payload_size);
1277                 struct cxl_mbox_get_log {
1278                         uuid_t uuid;
1279                         __le32 offset;
1280                         __le32 length;
1281                 } __packed log = {
1282                         .uuid = *uuid,
1283                         .offset = cpu_to_le32(offset),
1284                         .length = cpu_to_le32(xfer_size)
1285                 };
1286                 int rc;
1287
1288                 rc = cxl_mem_mbox_send_cmd(cxlm, CXL_MBOX_OP_GET_LOG, &log,
1289                                            sizeof(log), out, xfer_size);
1290                 if (rc < 0)
1291                         return rc;
1292
1293                 out += xfer_size;
1294                 remaining -= xfer_size;
1295                 offset += xfer_size;
1296         }
1297
1298         return 0;
1299 }
1300
1301 /**
1302  * cxl_walk_cel() - Walk through the Command Effects Log.
1303  * @cxlm: Device.
1304  * @size: Length of the Command Effects Log.
1305  * @cel: CEL
1306  *
1307  * Iterate over each entry in the CEL and determine if the driver supports the
1308  * command. If so, the command is enabled for the device and can be used later.
1309  */
1310 static void cxl_walk_cel(struct cxl_mem *cxlm, size_t size, u8 *cel)
1311 {
1312         struct cel_entry {
1313                 __le16 opcode;
1314                 __le16 effect;
1315         } __packed * cel_entry;
1316         const int cel_entries = size / sizeof(*cel_entry);
1317         int i;
1318
1319         cel_entry = (struct cel_entry *)cel;
1320
1321         for (i = 0; i < cel_entries; i++) {
1322                 u16 opcode = le16_to_cpu(cel_entry[i].opcode);
1323                 struct cxl_mem_command *cmd = cxl_mem_find_command(opcode);
1324
1325                 if (!cmd) {
1326                         dev_dbg(&cxlm->pdev->dev,
1327                                 "Opcode 0x%04x unsupported by driver", opcode);
1328                         continue;
1329                 }
1330
1331                 set_bit(cmd->info.id, cxlm->enabled_cmds);
1332         }
1333 }
1334
1335 struct cxl_mbox_get_supported_logs {
1336         __le16 entries;
1337         u8 rsvd[6];
1338         struct gsl_entry {
1339                 uuid_t uuid;
1340                 __le32 size;
1341         } __packed entry[];
1342 } __packed;
1343
1344 static struct cxl_mbox_get_supported_logs *cxl_get_gsl(struct cxl_mem *cxlm)
1345 {
1346         struct cxl_mbox_get_supported_logs *ret;
1347         int rc;
1348
1349         ret = kvmalloc(cxlm->payload_size, GFP_KERNEL);
1350         if (!ret)
1351                 return ERR_PTR(-ENOMEM);
1352
1353         rc = cxl_mem_mbox_send_cmd(cxlm, CXL_MBOX_OP_GET_SUPPORTED_LOGS, NULL,
1354                                    0, ret, cxlm->payload_size);
1355         if (rc < 0) {
1356                 kvfree(ret);
1357                 return ERR_PTR(rc);
1358         }
1359
1360         return ret;
1361 }
1362
1363 /**
1364  * cxl_mem_enumerate_cmds() - Enumerate commands for a device.
1365  * @cxlm: The device.
1366  *
1367  * Returns 0 if enumerate completed successfully.
1368  *
1369  * CXL devices have optional support for certain commands. This function will
1370  * determine the set of supported commands for the hardware and update the
1371  * enabled_cmds bitmap in the @cxlm.
1372  */
1373 static int cxl_mem_enumerate_cmds(struct cxl_mem *cxlm)
1374 {
1375         struct cxl_mbox_get_supported_logs *gsl;
1376         struct device *dev = &cxlm->pdev->dev;
1377         struct cxl_mem_command *cmd;
1378         int i, rc;
1379
1380         gsl = cxl_get_gsl(cxlm);
1381         if (IS_ERR(gsl))
1382                 return PTR_ERR(gsl);
1383
1384         rc = -ENOENT;
1385         for (i = 0; i < le16_to_cpu(gsl->entries); i++) {
1386                 u32 size = le32_to_cpu(gsl->entry[i].size);
1387                 uuid_t uuid = gsl->entry[i].uuid;
1388                 u8 *log;
1389
1390                 dev_dbg(dev, "Found LOG type %pU of size %d", &uuid, size);
1391
1392                 if (!uuid_equal(&uuid, &log_uuid[CEL_UUID]))
1393                         continue;
1394
1395                 log = kvmalloc(size, GFP_KERNEL);
1396                 if (!log) {
1397                         rc = -ENOMEM;
1398                         goto out;
1399                 }
1400
1401                 rc = cxl_xfer_log(cxlm, &uuid, size, log);
1402                 if (rc) {
1403                         kvfree(log);
1404                         goto out;
1405                 }
1406
1407                 cxl_walk_cel(cxlm, size, log);
1408                 kvfree(log);
1409
1410                 /* In case CEL was bogus, enable some default commands. */
1411                 cxl_for_each_cmd(cmd)
1412                         if (cmd->flags & CXL_CMD_FLAG_FORCE_ENABLE)
1413                                 set_bit(cmd->info.id, cxlm->enabled_cmds);
1414
1415                 /* Found the required CEL */
1416                 rc = 0;
1417         }
1418
1419 out:
1420         kvfree(gsl);
1421         return rc;
1422 }
1423
1424 /**
1425  * cxl_mem_identify() - Send the IDENTIFY command to the device.
1426  * @cxlm: The device to identify.
1427  *
1428  * Return: 0 if identify was executed successfully.
1429  *
1430  * This will dispatch the identify command to the device and on success populate
1431  * structures to be exported to sysfs.
1432  */
1433 static int cxl_mem_identify(struct cxl_mem *cxlm)
1434 {
1435         /* See CXL 2.0 Table 175 Identify Memory Device Output Payload */
1436         struct cxl_mbox_identify {
1437                 char fw_revision[0x10];
1438                 __le64 total_capacity;
1439                 __le64 volatile_capacity;
1440                 __le64 persistent_capacity;
1441                 __le64 partition_align;
1442                 __le16 info_event_log_size;
1443                 __le16 warning_event_log_size;
1444                 __le16 failure_event_log_size;
1445                 __le16 fatal_event_log_size;
1446                 __le32 lsa_size;
1447                 u8 poison_list_max_mer[3];
1448                 __le16 inject_poison_limit;
1449                 u8 poison_caps;
1450                 u8 qos_telemetry_caps;
1451         } __packed id;
1452         int rc;
1453
1454         rc = cxl_mem_mbox_send_cmd(cxlm, CXL_MBOX_OP_IDENTIFY, NULL, 0, &id,
1455                                    sizeof(id));
1456         if (rc < 0)
1457                 return rc;
1458
1459         /*
1460          * TODO: enumerate DPA map, as 'ram' and 'pmem' do not alias.
1461          * For now, only the capacity is exported in sysfs
1462          */
1463         cxlm->ram_range.start = 0;
1464         cxlm->ram_range.end = le64_to_cpu(id.volatile_capacity) * SZ_256M - 1;
1465
1466         cxlm->pmem_range.start = 0;
1467         cxlm->pmem_range.end =
1468                 le64_to_cpu(id.persistent_capacity) * SZ_256M - 1;
1469
1470         cxlm->lsa_size = le32_to_cpu(id.lsa_size);
1471         memcpy(cxlm->firmware_version, id.fw_revision, sizeof(id.fw_revision));
1472
1473         return 0;
1474 }
1475
1476 static int cxl_mem_probe(struct pci_dev *pdev, const struct pci_device_id *id)
1477 {
1478         struct cxl_mem *cxlm;
1479         int rc;
1480
1481         rc = pcim_enable_device(pdev);
1482         if (rc)
1483                 return rc;
1484
1485         cxlm = cxl_mem_create(pdev);
1486         if (IS_ERR(cxlm))
1487                 return PTR_ERR(cxlm);
1488
1489         rc = cxl_mem_setup_regs(cxlm);
1490         if (rc)
1491                 return rc;
1492
1493         rc = cxl_mem_setup_mailbox(cxlm);
1494         if (rc)
1495                 return rc;
1496
1497         rc = cxl_mem_enumerate_cmds(cxlm);
1498         if (rc)
1499                 return rc;
1500
1501         rc = cxl_mem_identify(cxlm);
1502         if (rc)
1503                 return rc;
1504
1505         return cxl_mem_add_memdev(cxlm);
1506 }
1507
1508 static const struct pci_device_id cxl_mem_pci_tbl[] = {
1509         /* PCI class code for CXL.mem Type-3 Devices */
1510         { PCI_DEVICE_CLASS((PCI_CLASS_MEMORY_CXL << 8 | CXL_MEMORY_PROGIF), ~0)},
1511         { /* terminate list */ },
1512 };
1513 MODULE_DEVICE_TABLE(pci, cxl_mem_pci_tbl);
1514
1515 static struct pci_driver cxl_mem_driver = {
1516         .name                   = KBUILD_MODNAME,
1517         .id_table               = cxl_mem_pci_tbl,
1518         .probe                  = cxl_mem_probe,
1519         .driver = {
1520                 .probe_type     = PROBE_PREFER_ASYNCHRONOUS,
1521         },
1522 };
1523
1524 static __init int cxl_mem_init(void)
1525 {
1526         struct dentry *mbox_debugfs;
1527         dev_t devt;
1528         int rc;
1529
1530         /* Double check the anonymous union trickery in struct cxl_regs */
1531         BUILD_BUG_ON(offsetof(struct cxl_regs, memdev) !=
1532                      offsetof(struct cxl_regs, device_regs.memdev));
1533
1534         rc = alloc_chrdev_region(&devt, 0, CXL_MEM_MAX_DEVS, "cxl");
1535         if (rc)
1536                 return rc;
1537
1538         cxl_mem_major = MAJOR(devt);
1539
1540         rc = pci_register_driver(&cxl_mem_driver);
1541         if (rc) {
1542                 unregister_chrdev_region(MKDEV(cxl_mem_major, 0),
1543                                          CXL_MEM_MAX_DEVS);
1544                 return rc;
1545         }
1546
1547         cxl_debugfs = debugfs_create_dir("cxl", NULL);
1548         mbox_debugfs = debugfs_create_dir("mbox", cxl_debugfs);
1549         debugfs_create_bool("raw_allow_all", 0600, mbox_debugfs,
1550                             &cxl_raw_allow_all);
1551
1552         return 0;
1553 }
1554
1555 static __exit void cxl_mem_exit(void)
1556 {
1557         debugfs_remove_recursive(cxl_debugfs);
1558         pci_unregister_driver(&cxl_mem_driver);
1559         unregister_chrdev_region(MKDEV(cxl_mem_major, 0), CXL_MEM_MAX_DEVS);
1560 }
1561
1562 MODULE_LICENSE("GPL v2");
1563 module_init(cxl_mem_init);
1564 module_exit(cxl_mem_exit);
1565 MODULE_IMPORT_NS(CXL);