GNU Linux-libre 4.14.251-gnu1
[releases.git] / drivers / scsi / cxlflash / main.c
1 /*
2  * CXL Flash Device Driver
3  *
4  * Written by: Manoj N. Kumar <manoj@linux.vnet.ibm.com>, IBM Corporation
5  *             Matthew R. Ochs <mrochs@linux.vnet.ibm.com>, IBM Corporation
6  *
7  * Copyright (C) 2015 IBM Corporation
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; either version
12  * 2 of the License, or (at your option) any later version.
13  */
14
15 #include <linux/delay.h>
16 #include <linux/list.h>
17 #include <linux/module.h>
18 #include <linux/pci.h>
19
20 #include <asm/unaligned.h>
21
22 #include <misc/cxl.h>
23
24 #include <scsi/scsi_cmnd.h>
25 #include <scsi/scsi_host.h>
26 #include <uapi/scsi/cxlflash_ioctl.h>
27
28 #include "main.h"
29 #include "sislite.h"
30 #include "common.h"
31
32 MODULE_DESCRIPTION(CXLFLASH_ADAPTER_NAME);
33 MODULE_AUTHOR("Manoj N. Kumar <manoj@linux.vnet.ibm.com>");
34 MODULE_AUTHOR("Matthew R. Ochs <mrochs@linux.vnet.ibm.com>");
35 MODULE_LICENSE("GPL");
36
37 static struct class *cxlflash_class;
38 static u32 cxlflash_major;
39 static DECLARE_BITMAP(cxlflash_minor, CXLFLASH_MAX_ADAPTERS);
40
41 /**
42  * process_cmd_err() - command error handler
43  * @cmd:        AFU command that experienced the error.
44  * @scp:        SCSI command associated with the AFU command in error.
45  *
46  * Translates error bits from AFU command to SCSI command results.
47  */
48 static void process_cmd_err(struct afu_cmd *cmd, struct scsi_cmnd *scp)
49 {
50         struct afu *afu = cmd->parent;
51         struct cxlflash_cfg *cfg = afu->parent;
52         struct device *dev = &cfg->dev->dev;
53         struct sisl_ioarcb *ioarcb;
54         struct sisl_ioasa *ioasa;
55         u32 resid;
56
57         if (unlikely(!cmd))
58                 return;
59
60         ioarcb = &(cmd->rcb);
61         ioasa = &(cmd->sa);
62
63         if (ioasa->rc.flags & SISL_RC_FLAGS_UNDERRUN) {
64                 resid = ioasa->resid;
65                 scsi_set_resid(scp, resid);
66                 dev_dbg(dev, "%s: cmd underrun cmd = %p scp = %p, resid = %d\n",
67                         __func__, cmd, scp, resid);
68         }
69
70         if (ioasa->rc.flags & SISL_RC_FLAGS_OVERRUN) {
71                 dev_dbg(dev, "%s: cmd underrun cmd = %p scp = %p\n",
72                         __func__, cmd, scp);
73                 scp->result = (DID_ERROR << 16);
74         }
75
76         dev_dbg(dev, "%s: cmd failed afu_rc=%02x scsi_rc=%02x fc_rc=%02x "
77                 "afu_extra=%02x scsi_extra=%02x fc_extra=%02x\n", __func__,
78                 ioasa->rc.afu_rc, ioasa->rc.scsi_rc, ioasa->rc.fc_rc,
79                 ioasa->afu_extra, ioasa->scsi_extra, ioasa->fc_extra);
80
81         if (ioasa->rc.scsi_rc) {
82                 /* We have a SCSI status */
83                 if (ioasa->rc.flags & SISL_RC_FLAGS_SENSE_VALID) {
84                         memcpy(scp->sense_buffer, ioasa->sense_data,
85                                SISL_SENSE_DATA_LEN);
86                         scp->result = ioasa->rc.scsi_rc;
87                 } else
88                         scp->result = ioasa->rc.scsi_rc | (DID_ERROR << 16);
89         }
90
91         /*
92          * We encountered an error. Set scp->result based on nature
93          * of error.
94          */
95         if (ioasa->rc.fc_rc) {
96                 /* We have an FC status */
97                 switch (ioasa->rc.fc_rc) {
98                 case SISL_FC_RC_LINKDOWN:
99                         scp->result = (DID_REQUEUE << 16);
100                         break;
101                 case SISL_FC_RC_RESID:
102                         /* This indicates an FCP resid underrun */
103                         if (!(ioasa->rc.flags & SISL_RC_FLAGS_OVERRUN)) {
104                                 /* If the SISL_RC_FLAGS_OVERRUN flag was set,
105                                  * then we will handle this error else where.
106                                  * If not then we must handle it here.
107                                  * This is probably an AFU bug.
108                                  */
109                                 scp->result = (DID_ERROR << 16);
110                         }
111                         break;
112                 case SISL_FC_RC_RESIDERR:
113                         /* Resid mismatch between adapter and device */
114                 case SISL_FC_RC_TGTABORT:
115                 case SISL_FC_RC_ABORTOK:
116                 case SISL_FC_RC_ABORTFAIL:
117                 case SISL_FC_RC_NOLOGI:
118                 case SISL_FC_RC_ABORTPEND:
119                 case SISL_FC_RC_WRABORTPEND:
120                 case SISL_FC_RC_NOEXP:
121                 case SISL_FC_RC_INUSE:
122                         scp->result = (DID_ERROR << 16);
123                         break;
124                 }
125         }
126
127         if (ioasa->rc.afu_rc) {
128                 /* We have an AFU error */
129                 switch (ioasa->rc.afu_rc) {
130                 case SISL_AFU_RC_NO_CHANNELS:
131                         scp->result = (DID_NO_CONNECT << 16);
132                         break;
133                 case SISL_AFU_RC_DATA_DMA_ERR:
134                         switch (ioasa->afu_extra) {
135                         case SISL_AFU_DMA_ERR_PAGE_IN:
136                                 /* Retry */
137                                 scp->result = (DID_IMM_RETRY << 16);
138                                 break;
139                         case SISL_AFU_DMA_ERR_INVALID_EA:
140                         default:
141                                 scp->result = (DID_ERROR << 16);
142                         }
143                         break;
144                 case SISL_AFU_RC_OUT_OF_DATA_BUFS:
145                         /* Retry */
146                         scp->result = (DID_ALLOC_FAILURE << 16);
147                         break;
148                 default:
149                         scp->result = (DID_ERROR << 16);
150                 }
151         }
152 }
153
154 /**
155  * cmd_complete() - command completion handler
156  * @cmd:        AFU command that has completed.
157  *
158  * For SCSI commands this routine prepares and submits commands that have
159  * either completed or timed out to the SCSI stack. For internal commands
160  * (TMF or AFU), this routine simply notifies the originator that the
161  * command has completed.
162  */
163 static void cmd_complete(struct afu_cmd *cmd)
164 {
165         struct scsi_cmnd *scp;
166         ulong lock_flags;
167         struct afu *afu = cmd->parent;
168         struct cxlflash_cfg *cfg = afu->parent;
169         struct device *dev = &cfg->dev->dev;
170         struct hwq *hwq = get_hwq(afu, cmd->hwq_index);
171
172         spin_lock_irqsave(&hwq->hsq_slock, lock_flags);
173         list_del(&cmd->list);
174         spin_unlock_irqrestore(&hwq->hsq_slock, lock_flags);
175
176         if (cmd->scp) {
177                 scp = cmd->scp;
178                 if (unlikely(cmd->sa.ioasc))
179                         process_cmd_err(cmd, scp);
180                 else
181                         scp->result = (DID_OK << 16);
182
183                 dev_dbg_ratelimited(dev, "%s:scp=%p result=%08x ioasc=%08x\n",
184                                     __func__, scp, scp->result, cmd->sa.ioasc);
185                 scp->scsi_done(scp);
186         } else if (cmd->cmd_tmf) {
187                 spin_lock_irqsave(&cfg->tmf_slock, lock_flags);
188                 cfg->tmf_active = false;
189                 wake_up_all_locked(&cfg->tmf_waitq);
190                 spin_unlock_irqrestore(&cfg->tmf_slock, lock_flags);
191         } else
192                 complete(&cmd->cevent);
193 }
194
195 /**
196  * flush_pending_cmds() - flush all pending commands on this hardware queue
197  * @hwq:        Hardware queue to flush.
198  *
199  * The hardware send queue lock associated with this hardware queue must be
200  * held when calling this routine.
201  */
202 static void flush_pending_cmds(struct hwq *hwq)
203 {
204         struct cxlflash_cfg *cfg = hwq->afu->parent;
205         struct afu_cmd *cmd, *tmp;
206         struct scsi_cmnd *scp;
207         ulong lock_flags;
208
209         list_for_each_entry_safe(cmd, tmp, &hwq->pending_cmds, list) {
210                 /* Bypass command when on a doneq, cmd_complete() will handle */
211                 if (!list_empty(&cmd->queue))
212                         continue;
213
214                 list_del(&cmd->list);
215
216                 if (cmd->scp) {
217                         scp = cmd->scp;
218                         scp->result = (DID_IMM_RETRY << 16);
219                         scp->scsi_done(scp);
220                 } else {
221                         cmd->cmd_aborted = true;
222
223                         if (cmd->cmd_tmf) {
224                                 spin_lock_irqsave(&cfg->tmf_slock, lock_flags);
225                                 cfg->tmf_active = false;
226                                 wake_up_all_locked(&cfg->tmf_waitq);
227                                 spin_unlock_irqrestore(&cfg->tmf_slock,
228                                                        lock_flags);
229                         } else
230                                 complete(&cmd->cevent);
231                 }
232         }
233 }
234
235 /**
236  * context_reset() - reset context via specified register
237  * @hwq:        Hardware queue owning the context to be reset.
238  * @reset_reg:  MMIO register to perform reset.
239  *
240  * When the reset is successful, the SISLite specification guarantees that
241  * the AFU has aborted all currently pending I/O. Accordingly, these commands
242  * must be flushed.
243  *
244  * Return: 0 on success, -errno on failure
245  */
246 static int context_reset(struct hwq *hwq, __be64 __iomem *reset_reg)
247 {
248         struct cxlflash_cfg *cfg = hwq->afu->parent;
249         struct device *dev = &cfg->dev->dev;
250         int rc = -ETIMEDOUT;
251         int nretry = 0;
252         u64 val = 0x1;
253         ulong lock_flags;
254
255         dev_dbg(dev, "%s: hwq=%p\n", __func__, hwq);
256
257         spin_lock_irqsave(&hwq->hsq_slock, lock_flags);
258
259         writeq_be(val, reset_reg);
260         do {
261                 val = readq_be(reset_reg);
262                 if ((val & 0x1) == 0x0) {
263                         rc = 0;
264                         break;
265                 }
266
267                 /* Double delay each time */
268                 udelay(1 << nretry);
269         } while (nretry++ < MC_ROOM_RETRY_CNT);
270
271         if (!rc)
272                 flush_pending_cmds(hwq);
273
274         spin_unlock_irqrestore(&hwq->hsq_slock, lock_flags);
275
276         dev_dbg(dev, "%s: returning rc=%d, val=%016llx nretry=%d\n",
277                 __func__, rc, val, nretry);
278         return rc;
279 }
280
281 /**
282  * context_reset_ioarrin() - reset context via IOARRIN register
283  * @hwq:        Hardware queue owning the context to be reset.
284  *
285  * Return: 0 on success, -errno on failure
286  */
287 static int context_reset_ioarrin(struct hwq *hwq)
288 {
289         return context_reset(hwq, &hwq->host_map->ioarrin);
290 }
291
292 /**
293  * context_reset_sq() - reset context via SQ_CONTEXT_RESET register
294  * @hwq:        Hardware queue owning the context to be reset.
295  *
296  * Return: 0 on success, -errno on failure
297  */
298 static int context_reset_sq(struct hwq *hwq)
299 {
300         return context_reset(hwq, &hwq->host_map->sq_ctx_reset);
301 }
302
303 /**
304  * send_cmd_ioarrin() - sends an AFU command via IOARRIN register
305  * @afu:        AFU associated with the host.
306  * @cmd:        AFU command to send.
307  *
308  * Return:
309  *      0 on success, SCSI_MLQUEUE_HOST_BUSY on failure
310  */
311 static int send_cmd_ioarrin(struct afu *afu, struct afu_cmd *cmd)
312 {
313         struct cxlflash_cfg *cfg = afu->parent;
314         struct device *dev = &cfg->dev->dev;
315         struct hwq *hwq = get_hwq(afu, cmd->hwq_index);
316         int rc = 0;
317         s64 room;
318         ulong lock_flags;
319
320         /*
321          * To avoid the performance penalty of MMIO, spread the update of
322          * 'room' over multiple commands.
323          */
324         spin_lock_irqsave(&hwq->hsq_slock, lock_flags);
325         if (--hwq->room < 0) {
326                 room = readq_be(&hwq->host_map->cmd_room);
327                 if (room <= 0) {
328                         dev_dbg_ratelimited(dev, "%s: no cmd_room to send "
329                                             "0x%02X, room=0x%016llX\n",
330                                             __func__, cmd->rcb.cdb[0], room);
331                         hwq->room = 0;
332                         rc = SCSI_MLQUEUE_HOST_BUSY;
333                         goto out;
334                 }
335                 hwq->room = room - 1;
336         }
337
338         list_add(&cmd->list, &hwq->pending_cmds);
339         writeq_be((u64)&cmd->rcb, &hwq->host_map->ioarrin);
340 out:
341         spin_unlock_irqrestore(&hwq->hsq_slock, lock_flags);
342         dev_dbg(dev, "%s: cmd=%p len=%u ea=%016llx rc=%d\n", __func__,
343                 cmd, cmd->rcb.data_len, cmd->rcb.data_ea, rc);
344         return rc;
345 }
346
347 /**
348  * send_cmd_sq() - sends an AFU command via SQ ring
349  * @afu:        AFU associated with the host.
350  * @cmd:        AFU command to send.
351  *
352  * Return:
353  *      0 on success, SCSI_MLQUEUE_HOST_BUSY on failure
354  */
355 static int send_cmd_sq(struct afu *afu, struct afu_cmd *cmd)
356 {
357         struct cxlflash_cfg *cfg = afu->parent;
358         struct device *dev = &cfg->dev->dev;
359         struct hwq *hwq = get_hwq(afu, cmd->hwq_index);
360         int rc = 0;
361         int newval;
362         ulong lock_flags;
363
364         newval = atomic_dec_if_positive(&hwq->hsq_credits);
365         if (newval <= 0) {
366                 rc = SCSI_MLQUEUE_HOST_BUSY;
367                 goto out;
368         }
369
370         cmd->rcb.ioasa = &cmd->sa;
371
372         spin_lock_irqsave(&hwq->hsq_slock, lock_flags);
373
374         *hwq->hsq_curr = cmd->rcb;
375         if (hwq->hsq_curr < hwq->hsq_end)
376                 hwq->hsq_curr++;
377         else
378                 hwq->hsq_curr = hwq->hsq_start;
379
380         list_add(&cmd->list, &hwq->pending_cmds);
381         writeq_be((u64)hwq->hsq_curr, &hwq->host_map->sq_tail);
382
383         spin_unlock_irqrestore(&hwq->hsq_slock, lock_flags);
384 out:
385         dev_dbg(dev, "%s: cmd=%p len=%u ea=%016llx ioasa=%p rc=%d curr=%p "
386                "head=%016llx tail=%016llx\n", __func__, cmd, cmd->rcb.data_len,
387                cmd->rcb.data_ea, cmd->rcb.ioasa, rc, hwq->hsq_curr,
388                readq_be(&hwq->host_map->sq_head),
389                readq_be(&hwq->host_map->sq_tail));
390         return rc;
391 }
392
393 /**
394  * wait_resp() - polls for a response or timeout to a sent AFU command
395  * @afu:        AFU associated with the host.
396  * @cmd:        AFU command that was sent.
397  *
398  * Return: 0 on success, -errno on failure
399  */
400 static int wait_resp(struct afu *afu, struct afu_cmd *cmd)
401 {
402         struct cxlflash_cfg *cfg = afu->parent;
403         struct device *dev = &cfg->dev->dev;
404         int rc = 0;
405         ulong timeout = msecs_to_jiffies(cmd->rcb.timeout * 2 * 1000);
406
407         timeout = wait_for_completion_timeout(&cmd->cevent, timeout);
408         if (!timeout)
409                 rc = -ETIMEDOUT;
410
411         if (cmd->cmd_aborted)
412                 rc = -EAGAIN;
413
414         if (unlikely(cmd->sa.ioasc != 0)) {
415                 dev_err(dev, "%s: cmd %02x failed, ioasc=%08x\n",
416                         __func__, cmd->rcb.cdb[0], cmd->sa.ioasc);
417                 rc = -EIO;
418         }
419
420         return rc;
421 }
422
423 /**
424  * cmd_to_target_hwq() - selects a target hardware queue for a SCSI command
425  * @host:       SCSI host associated with device.
426  * @scp:        SCSI command to send.
427  * @afu:        SCSI command to send.
428  *
429  * Hashes a command based upon the hardware queue mode.
430  *
431  * Return: Trusted index of target hardware queue
432  */
433 static u32 cmd_to_target_hwq(struct Scsi_Host *host, struct scsi_cmnd *scp,
434                              struct afu *afu)
435 {
436         u32 tag;
437         u32 hwq = 0;
438
439         if (afu->num_hwqs == 1)
440                 return 0;
441
442         switch (afu->hwq_mode) {
443         case HWQ_MODE_RR:
444                 hwq = afu->hwq_rr_count++ % afu->num_hwqs;
445                 break;
446         case HWQ_MODE_TAG:
447                 tag = blk_mq_unique_tag(scp->request);
448                 hwq = blk_mq_unique_tag_to_hwq(tag);
449                 break;
450         case HWQ_MODE_CPU:
451                 hwq = smp_processor_id() % afu->num_hwqs;
452                 break;
453         default:
454                 WARN_ON_ONCE(1);
455         }
456
457         return hwq;
458 }
459
460 /**
461  * send_tmf() - sends a Task Management Function (TMF)
462  * @cfg:        Internal structure associated with the host.
463  * @sdev:       SCSI device destined for TMF.
464  * @tmfcmd:     TMF command to send.
465  *
466  * Return:
467  *      0 on success, SCSI_MLQUEUE_HOST_BUSY or -errno on failure
468  */
469 static int send_tmf(struct cxlflash_cfg *cfg, struct scsi_device *sdev,
470                     u64 tmfcmd)
471 {
472         struct afu *afu = cfg->afu;
473         struct afu_cmd *cmd = NULL;
474         struct device *dev = &cfg->dev->dev;
475         struct hwq *hwq = get_hwq(afu, PRIMARY_HWQ);
476         char *buf = NULL;
477         ulong lock_flags;
478         int rc = 0;
479         ulong to;
480
481         buf = kzalloc(sizeof(*cmd) + __alignof__(*cmd) - 1, GFP_KERNEL);
482         if (unlikely(!buf)) {
483                 dev_err(dev, "%s: no memory for command\n", __func__);
484                 rc = -ENOMEM;
485                 goto out;
486         }
487
488         cmd = (struct afu_cmd *)PTR_ALIGN(buf, __alignof__(*cmd));
489         INIT_LIST_HEAD(&cmd->queue);
490
491         /* When Task Management Function is active do not send another */
492         spin_lock_irqsave(&cfg->tmf_slock, lock_flags);
493         if (cfg->tmf_active)
494                 wait_event_interruptible_lock_irq(cfg->tmf_waitq,
495                                                   !cfg->tmf_active,
496                                                   cfg->tmf_slock);
497         cfg->tmf_active = true;
498         spin_unlock_irqrestore(&cfg->tmf_slock, lock_flags);
499
500         cmd->parent = afu;
501         cmd->cmd_tmf = true;
502         cmd->hwq_index = hwq->index;
503
504         cmd->rcb.ctx_id = hwq->ctx_hndl;
505         cmd->rcb.msi = SISL_MSI_RRQ_UPDATED;
506         cmd->rcb.port_sel = CHAN2PORTMASK(sdev->channel);
507         cmd->rcb.lun_id = lun_to_lunid(sdev->lun);
508         cmd->rcb.req_flags = (SISL_REQ_FLAGS_PORT_LUN_ID |
509                               SISL_REQ_FLAGS_SUP_UNDERRUN |
510                               SISL_REQ_FLAGS_TMF_CMD);
511         memcpy(cmd->rcb.cdb, &tmfcmd, sizeof(tmfcmd));
512
513         rc = afu->send_cmd(afu, cmd);
514         if (unlikely(rc)) {
515                 spin_lock_irqsave(&cfg->tmf_slock, lock_flags);
516                 cfg->tmf_active = false;
517                 spin_unlock_irqrestore(&cfg->tmf_slock, lock_flags);
518                 goto out;
519         }
520
521         spin_lock_irqsave(&cfg->tmf_slock, lock_flags);
522         to = msecs_to_jiffies(5000);
523         to = wait_event_interruptible_lock_irq_timeout(cfg->tmf_waitq,
524                                                        !cfg->tmf_active,
525                                                        cfg->tmf_slock,
526                                                        to);
527         if (!to) {
528                 dev_err(dev, "%s: TMF timed out\n", __func__);
529                 rc = -ETIMEDOUT;
530         } else if (cmd->cmd_aborted) {
531                 dev_err(dev, "%s: TMF aborted\n", __func__);
532                 rc = -EAGAIN;
533         } else if (cmd->sa.ioasc) {
534                 dev_err(dev, "%s: TMF failed ioasc=%08x\n",
535                         __func__, cmd->sa.ioasc);
536                 rc = -EIO;
537         }
538         cfg->tmf_active = false;
539         spin_unlock_irqrestore(&cfg->tmf_slock, lock_flags);
540 out:
541         kfree(buf);
542         return rc;
543 }
544
545 /**
546  * cxlflash_driver_info() - information handler for this host driver
547  * @host:       SCSI host associated with device.
548  *
549  * Return: A string describing the device.
550  */
551 static const char *cxlflash_driver_info(struct Scsi_Host *host)
552 {
553         return CXLFLASH_ADAPTER_NAME;
554 }
555
556 /**
557  * cxlflash_queuecommand() - sends a mid-layer request
558  * @host:       SCSI host associated with device.
559  * @scp:        SCSI command to send.
560  *
561  * Return: 0 on success, SCSI_MLQUEUE_HOST_BUSY on failure
562  */
563 static int cxlflash_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *scp)
564 {
565         struct cxlflash_cfg *cfg = shost_priv(host);
566         struct afu *afu = cfg->afu;
567         struct device *dev = &cfg->dev->dev;
568         struct afu_cmd *cmd = sc_to_afuci(scp);
569         struct scatterlist *sg = scsi_sglist(scp);
570         int hwq_index = cmd_to_target_hwq(host, scp, afu);
571         struct hwq *hwq = get_hwq(afu, hwq_index);
572         u16 req_flags = SISL_REQ_FLAGS_SUP_UNDERRUN;
573         ulong lock_flags;
574         int rc = 0;
575
576         dev_dbg_ratelimited(dev, "%s: (scp=%p) %d/%d/%d/%llu "
577                             "cdb=(%08x-%08x-%08x-%08x)\n",
578                             __func__, scp, host->host_no, scp->device->channel,
579                             scp->device->id, scp->device->lun,
580                             get_unaligned_be32(&((u32 *)scp->cmnd)[0]),
581                             get_unaligned_be32(&((u32 *)scp->cmnd)[1]),
582                             get_unaligned_be32(&((u32 *)scp->cmnd)[2]),
583                             get_unaligned_be32(&((u32 *)scp->cmnd)[3]));
584
585         /*
586          * If a Task Management Function is active, wait for it to complete
587          * before continuing with regular commands.
588          */
589         spin_lock_irqsave(&cfg->tmf_slock, lock_flags);
590         if (cfg->tmf_active) {
591                 spin_unlock_irqrestore(&cfg->tmf_slock, lock_flags);
592                 rc = SCSI_MLQUEUE_HOST_BUSY;
593                 goto out;
594         }
595         spin_unlock_irqrestore(&cfg->tmf_slock, lock_flags);
596
597         switch (cfg->state) {
598         case STATE_PROBING:
599         case STATE_PROBED:
600         case STATE_RESET:
601                 dev_dbg_ratelimited(dev, "%s: device is in reset\n", __func__);
602                 rc = SCSI_MLQUEUE_HOST_BUSY;
603                 goto out;
604         case STATE_FAILTERM:
605                 dev_dbg_ratelimited(dev, "%s: device has failed\n", __func__);
606                 scp->result = (DID_NO_CONNECT << 16);
607                 scp->scsi_done(scp);
608                 rc = 0;
609                 goto out;
610         default:
611                 break;
612         }
613
614         if (likely(sg)) {
615                 cmd->rcb.data_len = sg->length;
616                 cmd->rcb.data_ea = (uintptr_t)sg_virt(sg);
617         }
618
619         cmd->scp = scp;
620         cmd->parent = afu;
621         cmd->hwq_index = hwq_index;
622
623         cmd->sa.ioasc = 0;
624         cmd->rcb.ctx_id = hwq->ctx_hndl;
625         cmd->rcb.msi = SISL_MSI_RRQ_UPDATED;
626         cmd->rcb.port_sel = CHAN2PORTMASK(scp->device->channel);
627         cmd->rcb.lun_id = lun_to_lunid(scp->device->lun);
628
629         if (scp->sc_data_direction == DMA_TO_DEVICE)
630                 req_flags |= SISL_REQ_FLAGS_HOST_WRITE;
631
632         cmd->rcb.req_flags = req_flags;
633         memcpy(cmd->rcb.cdb, scp->cmnd, sizeof(cmd->rcb.cdb));
634
635         rc = afu->send_cmd(afu, cmd);
636 out:
637         return rc;
638 }
639
640 /**
641  * cxlflash_wait_for_pci_err_recovery() - wait for error recovery during probe
642  * @cfg:        Internal structure associated with the host.
643  */
644 static void cxlflash_wait_for_pci_err_recovery(struct cxlflash_cfg *cfg)
645 {
646         struct pci_dev *pdev = cfg->dev;
647
648         if (pci_channel_offline(pdev))
649                 wait_event_timeout(cfg->reset_waitq,
650                                    !pci_channel_offline(pdev),
651                                    CXLFLASH_PCI_ERROR_RECOVERY_TIMEOUT);
652 }
653
654 /**
655  * free_mem() - free memory associated with the AFU
656  * @cfg:        Internal structure associated with the host.
657  */
658 static void free_mem(struct cxlflash_cfg *cfg)
659 {
660         struct afu *afu = cfg->afu;
661
662         if (cfg->afu) {
663                 free_pages((ulong)afu, get_order(sizeof(struct afu)));
664                 cfg->afu = NULL;
665         }
666 }
667
668 /**
669  * cxlflash_reset_sync() - synchronizing point for asynchronous resets
670  * @cfg:        Internal structure associated with the host.
671  */
672 static void cxlflash_reset_sync(struct cxlflash_cfg *cfg)
673 {
674         if (cfg->async_reset_cookie == 0)
675                 return;
676
677         /* Wait until all async calls prior to this cookie have completed */
678         async_synchronize_cookie(cfg->async_reset_cookie + 1);
679         cfg->async_reset_cookie = 0;
680 }
681
682 /**
683  * stop_afu() - stops the AFU command timers and unmaps the MMIO space
684  * @cfg:        Internal structure associated with the host.
685  *
686  * Safe to call with AFU in a partially allocated/initialized state.
687  *
688  * Cancels scheduled worker threads, waits for any active internal AFU
689  * commands to timeout, disables IRQ polling and then unmaps the MMIO space.
690  */
691 static void stop_afu(struct cxlflash_cfg *cfg)
692 {
693         struct afu *afu = cfg->afu;
694         struct hwq *hwq;
695         int i;
696
697         cancel_work_sync(&cfg->work_q);
698         if (!current_is_async())
699                 cxlflash_reset_sync(cfg);
700
701         if (likely(afu)) {
702                 while (atomic_read(&afu->cmds_active))
703                         ssleep(1);
704
705                 if (afu_is_irqpoll_enabled(afu)) {
706                         for (i = 0; i < afu->num_hwqs; i++) {
707                                 hwq = get_hwq(afu, i);
708
709                                 irq_poll_disable(&hwq->irqpoll);
710                         }
711                 }
712
713                 if (likely(afu->afu_map)) {
714                         cxl_psa_unmap((void __iomem *)afu->afu_map);
715                         afu->afu_map = NULL;
716                 }
717         }
718 }
719
720 /**
721  * term_intr() - disables all AFU interrupts
722  * @cfg:        Internal structure associated with the host.
723  * @level:      Depth of allocation, where to begin waterfall tear down.
724  * @index:      Index of the hardware queue.
725  *
726  * Safe to call with AFU/MC in partially allocated/initialized state.
727  */
728 static void term_intr(struct cxlflash_cfg *cfg, enum undo_level level,
729                       u32 index)
730 {
731         struct afu *afu = cfg->afu;
732         struct device *dev = &cfg->dev->dev;
733         struct hwq *hwq;
734
735         if (!afu) {
736                 dev_err(dev, "%s: returning with NULL afu\n", __func__);
737                 return;
738         }
739
740         hwq = get_hwq(afu, index);
741
742         if (!hwq->ctx) {
743                 dev_err(dev, "%s: returning with NULL MC\n", __func__);
744                 return;
745         }
746
747         switch (level) {
748         case UNMAP_THREE:
749                 /* SISL_MSI_ASYNC_ERROR is setup only for the primary HWQ */
750                 if (index == PRIMARY_HWQ)
751                         cxl_unmap_afu_irq(hwq->ctx, 3, hwq);
752         case UNMAP_TWO:
753                 cxl_unmap_afu_irq(hwq->ctx, 2, hwq);
754         case UNMAP_ONE:
755                 cxl_unmap_afu_irq(hwq->ctx, 1, hwq);
756         case FREE_IRQ:
757                 cxl_free_afu_irqs(hwq->ctx);
758                 /* fall through */
759         case UNDO_NOOP:
760                 /* No action required */
761                 break;
762         }
763 }
764
765 /**
766  * term_mc() - terminates the master context
767  * @cfg:        Internal structure associated with the host.
768  * @index:      Index of the hardware queue.
769  *
770  * Safe to call with AFU/MC in partially allocated/initialized state.
771  */
772 static void term_mc(struct cxlflash_cfg *cfg, u32 index)
773 {
774         struct afu *afu = cfg->afu;
775         struct device *dev = &cfg->dev->dev;
776         struct hwq *hwq;
777         ulong lock_flags;
778
779         if (!afu) {
780                 dev_err(dev, "%s: returning with NULL afu\n", __func__);
781                 return;
782         }
783
784         hwq = get_hwq(afu, index);
785
786         if (!hwq->ctx) {
787                 dev_err(dev, "%s: returning with NULL MC\n", __func__);
788                 return;
789         }
790
791         WARN_ON(cxl_stop_context(hwq->ctx));
792         if (index != PRIMARY_HWQ)
793                 WARN_ON(cxl_release_context(hwq->ctx));
794         hwq->ctx = NULL;
795
796         spin_lock_irqsave(&hwq->hsq_slock, lock_flags);
797         flush_pending_cmds(hwq);
798         spin_unlock_irqrestore(&hwq->hsq_slock, lock_flags);
799 }
800
801 /**
802  * term_afu() - terminates the AFU
803  * @cfg:        Internal structure associated with the host.
804  *
805  * Safe to call with AFU/MC in partially allocated/initialized state.
806  */
807 static void term_afu(struct cxlflash_cfg *cfg)
808 {
809         struct device *dev = &cfg->dev->dev;
810         int k;
811
812         /*
813          * Tear down is carefully orchestrated to ensure
814          * no interrupts can come in when the problem state
815          * area is unmapped.
816          *
817          * 1) Disable all AFU interrupts for each master
818          * 2) Unmap the problem state area
819          * 3) Stop each master context
820          */
821         for (k = cfg->afu->num_hwqs - 1; k >= 0; k--)
822                 term_intr(cfg, UNMAP_THREE, k);
823
824         stop_afu(cfg);
825
826         for (k = cfg->afu->num_hwqs - 1; k >= 0; k--)
827                 term_mc(cfg, k);
828
829         dev_dbg(dev, "%s: returning\n", __func__);
830 }
831
832 /**
833  * notify_shutdown() - notifies device of pending shutdown
834  * @cfg:        Internal structure associated with the host.
835  * @wait:       Whether to wait for shutdown processing to complete.
836  *
837  * This function will notify the AFU that the adapter is being shutdown
838  * and will wait for shutdown processing to complete if wait is true.
839  * This notification should flush pending I/Os to the device and halt
840  * further I/Os until the next AFU reset is issued and device restarted.
841  */
842 static void notify_shutdown(struct cxlflash_cfg *cfg, bool wait)
843 {
844         struct afu *afu = cfg->afu;
845         struct device *dev = &cfg->dev->dev;
846         struct dev_dependent_vals *ddv;
847         __be64 __iomem *fc_port_regs;
848         u64 reg, status;
849         int i, retry_cnt = 0;
850
851         ddv = (struct dev_dependent_vals *)cfg->dev_id->driver_data;
852         if (!(ddv->flags & CXLFLASH_NOTIFY_SHUTDOWN))
853                 return;
854
855         if (!afu || !afu->afu_map) {
856                 dev_dbg(dev, "%s: Problem state area not mapped\n", __func__);
857                 return;
858         }
859
860         /* Notify AFU */
861         for (i = 0; i < cfg->num_fc_ports; i++) {
862                 fc_port_regs = get_fc_port_regs(cfg, i);
863
864                 reg = readq_be(&fc_port_regs[FC_CONFIG2 / 8]);
865                 reg |= SISL_FC_SHUTDOWN_NORMAL;
866                 writeq_be(reg, &fc_port_regs[FC_CONFIG2 / 8]);
867         }
868
869         if (!wait)
870                 return;
871
872         /* Wait up to 1.5 seconds for shutdown processing to complete */
873         for (i = 0; i < cfg->num_fc_ports; i++) {
874                 fc_port_regs = get_fc_port_regs(cfg, i);
875                 retry_cnt = 0;
876
877                 while (true) {
878                         status = readq_be(&fc_port_regs[FC_STATUS / 8]);
879                         if (status & SISL_STATUS_SHUTDOWN_COMPLETE)
880                                 break;
881                         if (++retry_cnt >= MC_RETRY_CNT) {
882                                 dev_dbg(dev, "%s: port %d shutdown processing "
883                                         "not yet completed\n", __func__, i);
884                                 break;
885                         }
886                         msleep(100 * retry_cnt);
887                 }
888         }
889 }
890
891 /**
892  * cxlflash_get_minor() - gets the first available minor number
893  *
894  * Return: Unique minor number that can be used to create the character device.
895  */
896 static int cxlflash_get_minor(void)
897 {
898         int minor;
899         long bit;
900
901         bit = find_first_zero_bit(cxlflash_minor, CXLFLASH_MAX_ADAPTERS);
902         if (bit >= CXLFLASH_MAX_ADAPTERS)
903                 return -1;
904
905         minor = bit & MINORMASK;
906         set_bit(minor, cxlflash_minor);
907         return minor;
908 }
909
910 /**
911  * cxlflash_put_minor() - releases the minor number
912  * @minor:      Minor number that is no longer needed.
913  */
914 static void cxlflash_put_minor(int minor)
915 {
916         clear_bit(minor, cxlflash_minor);
917 }
918
919 /**
920  * cxlflash_release_chrdev() - release the character device for the host
921  * @cfg:        Internal structure associated with the host.
922  */
923 static void cxlflash_release_chrdev(struct cxlflash_cfg *cfg)
924 {
925         device_unregister(cfg->chardev);
926         cfg->chardev = NULL;
927         cdev_del(&cfg->cdev);
928         cxlflash_put_minor(MINOR(cfg->cdev.dev));
929 }
930
931 /**
932  * cxlflash_remove() - PCI entry point to tear down host
933  * @pdev:       PCI device associated with the host.
934  *
935  * Safe to use as a cleanup in partially allocated/initialized state. Note that
936  * the reset_waitq is flushed as part of the stop/termination of user contexts.
937  */
938 static void cxlflash_remove(struct pci_dev *pdev)
939 {
940         struct cxlflash_cfg *cfg = pci_get_drvdata(pdev);
941         struct device *dev = &pdev->dev;
942         ulong lock_flags;
943
944         if (!pci_is_enabled(pdev)) {
945                 dev_dbg(dev, "%s: Device is disabled\n", __func__);
946                 return;
947         }
948
949         /* Yield to running recovery threads before continuing with remove */
950         wait_event(cfg->reset_waitq, cfg->state != STATE_RESET &&
951                                      cfg->state != STATE_PROBING);
952         spin_lock_irqsave(&cfg->tmf_slock, lock_flags);
953         if (cfg->tmf_active)
954                 wait_event_interruptible_lock_irq(cfg->tmf_waitq,
955                                                   !cfg->tmf_active,
956                                                   cfg->tmf_slock);
957         spin_unlock_irqrestore(&cfg->tmf_slock, lock_flags);
958
959         /* Notify AFU and wait for shutdown processing to complete */
960         notify_shutdown(cfg, true);
961
962         cfg->state = STATE_FAILTERM;
963         cxlflash_stop_term_user_contexts(cfg);
964
965         switch (cfg->init_state) {
966         case INIT_STATE_CDEV:
967                 cxlflash_release_chrdev(cfg);
968         case INIT_STATE_SCSI:
969                 cxlflash_term_local_luns(cfg);
970                 scsi_remove_host(cfg->host);
971         case INIT_STATE_AFU:
972                 term_afu(cfg);
973         case INIT_STATE_PCI:
974                 pci_disable_device(pdev);
975         case INIT_STATE_NONE:
976                 free_mem(cfg);
977                 scsi_host_put(cfg->host);
978                 break;
979         }
980
981         dev_dbg(dev, "%s: returning\n", __func__);
982 }
983
984 /**
985  * alloc_mem() - allocates the AFU and its command pool
986  * @cfg:        Internal structure associated with the host.
987  *
988  * A partially allocated state remains on failure.
989  *
990  * Return:
991  *      0 on success
992  *      -ENOMEM on failure to allocate memory
993  */
994 static int alloc_mem(struct cxlflash_cfg *cfg)
995 {
996         int rc = 0;
997         struct device *dev = &cfg->dev->dev;
998
999         /* AFU is ~28k, i.e. only one 64k page or up to seven 4k pages */
1000         cfg->afu = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO,
1001                                             get_order(sizeof(struct afu)));
1002         if (unlikely(!cfg->afu)) {
1003                 dev_err(dev, "%s: cannot get %d free pages\n",
1004                         __func__, get_order(sizeof(struct afu)));
1005                 rc = -ENOMEM;
1006                 goto out;
1007         }
1008         cfg->afu->parent = cfg;
1009         cfg->afu->desired_hwqs = CXLFLASH_DEF_HWQS;
1010         cfg->afu->afu_map = NULL;
1011 out:
1012         return rc;
1013 }
1014
1015 /**
1016  * init_pci() - initializes the host as a PCI device
1017  * @cfg:        Internal structure associated with the host.
1018  *
1019  * Return: 0 on success, -errno on failure
1020  */
1021 static int init_pci(struct cxlflash_cfg *cfg)
1022 {
1023         struct pci_dev *pdev = cfg->dev;
1024         struct device *dev = &cfg->dev->dev;
1025         int rc = 0;
1026
1027         rc = pci_enable_device(pdev);
1028         if (rc || pci_channel_offline(pdev)) {
1029                 if (pci_channel_offline(pdev)) {
1030                         cxlflash_wait_for_pci_err_recovery(cfg);
1031                         rc = pci_enable_device(pdev);
1032                 }
1033
1034                 if (rc) {
1035                         dev_err(dev, "%s: Cannot enable adapter\n", __func__);
1036                         cxlflash_wait_for_pci_err_recovery(cfg);
1037                         goto out;
1038                 }
1039         }
1040
1041 out:
1042         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
1043         return rc;
1044 }
1045
1046 /**
1047  * init_scsi() - adds the host to the SCSI stack and kicks off host scan
1048  * @cfg:        Internal structure associated with the host.
1049  *
1050  * Return: 0 on success, -errno on failure
1051  */
1052 static int init_scsi(struct cxlflash_cfg *cfg)
1053 {
1054         struct pci_dev *pdev = cfg->dev;
1055         struct device *dev = &cfg->dev->dev;
1056         int rc = 0;
1057
1058         rc = scsi_add_host(cfg->host, &pdev->dev);
1059         if (rc) {
1060                 dev_err(dev, "%s: scsi_add_host failed rc=%d\n", __func__, rc);
1061                 goto out;
1062         }
1063
1064         scsi_scan_host(cfg->host);
1065
1066 out:
1067         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
1068         return rc;
1069 }
1070
1071 /**
1072  * set_port_online() - transitions the specified host FC port to online state
1073  * @fc_regs:    Top of MMIO region defined for specified port.
1074  *
1075  * The provided MMIO region must be mapped prior to call. Online state means
1076  * that the FC link layer has synced, completed the handshaking process, and
1077  * is ready for login to start.
1078  */
1079 static void set_port_online(__be64 __iomem *fc_regs)
1080 {
1081         u64 cmdcfg;
1082
1083         cmdcfg = readq_be(&fc_regs[FC_MTIP_CMDCONFIG / 8]);
1084         cmdcfg &= (~FC_MTIP_CMDCONFIG_OFFLINE); /* clear OFF_LINE */
1085         cmdcfg |= (FC_MTIP_CMDCONFIG_ONLINE);   /* set ON_LINE */
1086         writeq_be(cmdcfg, &fc_regs[FC_MTIP_CMDCONFIG / 8]);
1087 }
1088
1089 /**
1090  * set_port_offline() - transitions the specified host FC port to offline state
1091  * @fc_regs:    Top of MMIO region defined for specified port.
1092  *
1093  * The provided MMIO region must be mapped prior to call.
1094  */
1095 static void set_port_offline(__be64 __iomem *fc_regs)
1096 {
1097         u64 cmdcfg;
1098
1099         cmdcfg = readq_be(&fc_regs[FC_MTIP_CMDCONFIG / 8]);
1100         cmdcfg &= (~FC_MTIP_CMDCONFIG_ONLINE);  /* clear ON_LINE */
1101         cmdcfg |= (FC_MTIP_CMDCONFIG_OFFLINE);  /* set OFF_LINE */
1102         writeq_be(cmdcfg, &fc_regs[FC_MTIP_CMDCONFIG / 8]);
1103 }
1104
1105 /**
1106  * wait_port_online() - waits for the specified host FC port come online
1107  * @fc_regs:    Top of MMIO region defined for specified port.
1108  * @delay_us:   Number of microseconds to delay between reading port status.
1109  * @nretry:     Number of cycles to retry reading port status.
1110  *
1111  * The provided MMIO region must be mapped prior to call. This will timeout
1112  * when the cable is not plugged in.
1113  *
1114  * Return:
1115  *      TRUE (1) when the specified port is online
1116  *      FALSE (0) when the specified port fails to come online after timeout
1117  */
1118 static bool wait_port_online(__be64 __iomem *fc_regs, u32 delay_us, u32 nretry)
1119 {
1120         u64 status;
1121
1122         WARN_ON(delay_us < 1000);
1123
1124         do {
1125                 msleep(delay_us / 1000);
1126                 status = readq_be(&fc_regs[FC_MTIP_STATUS / 8]);
1127                 if (status == U64_MAX)
1128                         nretry /= 2;
1129         } while ((status & FC_MTIP_STATUS_MASK) != FC_MTIP_STATUS_ONLINE &&
1130                  nretry--);
1131
1132         return ((status & FC_MTIP_STATUS_MASK) == FC_MTIP_STATUS_ONLINE);
1133 }
1134
1135 /**
1136  * wait_port_offline() - waits for the specified host FC port go offline
1137  * @fc_regs:    Top of MMIO region defined for specified port.
1138  * @delay_us:   Number of microseconds to delay between reading port status.
1139  * @nretry:     Number of cycles to retry reading port status.
1140  *
1141  * The provided MMIO region must be mapped prior to call.
1142  *
1143  * Return:
1144  *      TRUE (1) when the specified port is offline
1145  *      FALSE (0) when the specified port fails to go offline after timeout
1146  */
1147 static bool wait_port_offline(__be64 __iomem *fc_regs, u32 delay_us, u32 nretry)
1148 {
1149         u64 status;
1150
1151         WARN_ON(delay_us < 1000);
1152
1153         do {
1154                 msleep(delay_us / 1000);
1155                 status = readq_be(&fc_regs[FC_MTIP_STATUS / 8]);
1156                 if (status == U64_MAX)
1157                         nretry /= 2;
1158         } while ((status & FC_MTIP_STATUS_MASK) != FC_MTIP_STATUS_OFFLINE &&
1159                  nretry--);
1160
1161         return ((status & FC_MTIP_STATUS_MASK) == FC_MTIP_STATUS_OFFLINE);
1162 }
1163
1164 /**
1165  * afu_set_wwpn() - configures the WWPN for the specified host FC port
1166  * @afu:        AFU associated with the host that owns the specified FC port.
1167  * @port:       Port number being configured.
1168  * @fc_regs:    Top of MMIO region defined for specified port.
1169  * @wwpn:       The world-wide-port-number previously discovered for port.
1170  *
1171  * The provided MMIO region must be mapped prior to call. As part of the
1172  * sequence to configure the WWPN, the port is toggled offline and then back
1173  * online. This toggling action can cause this routine to delay up to a few
1174  * seconds. When configured to use the internal LUN feature of the AFU, a
1175  * failure to come online is overridden.
1176  */
1177 static void afu_set_wwpn(struct afu *afu, int port, __be64 __iomem *fc_regs,
1178                          u64 wwpn)
1179 {
1180         struct cxlflash_cfg *cfg = afu->parent;
1181         struct device *dev = &cfg->dev->dev;
1182
1183         set_port_offline(fc_regs);
1184         if (!wait_port_offline(fc_regs, FC_PORT_STATUS_RETRY_INTERVAL_US,
1185                                FC_PORT_STATUS_RETRY_CNT)) {
1186                 dev_dbg(dev, "%s: wait on port %d to go offline timed out\n",
1187                         __func__, port);
1188         }
1189
1190         writeq_be(wwpn, &fc_regs[FC_PNAME / 8]);
1191
1192         set_port_online(fc_regs);
1193         if (!wait_port_online(fc_regs, FC_PORT_STATUS_RETRY_INTERVAL_US,
1194                               FC_PORT_STATUS_RETRY_CNT)) {
1195                 dev_dbg(dev, "%s: wait on port %d to go online timed out\n",
1196                         __func__, port);
1197         }
1198 }
1199
1200 /**
1201  * afu_link_reset() - resets the specified host FC port
1202  * @afu:        AFU associated with the host that owns the specified FC port.
1203  * @port:       Port number being configured.
1204  * @fc_regs:    Top of MMIO region defined for specified port.
1205  *
1206  * The provided MMIO region must be mapped prior to call. The sequence to
1207  * reset the port involves toggling it offline and then back online. This
1208  * action can cause this routine to delay up to a few seconds. An effort
1209  * is made to maintain link with the device by switching to host to use
1210  * the alternate port exclusively while the reset takes place.
1211  * failure to come online is overridden.
1212  */
1213 static void afu_link_reset(struct afu *afu, int port, __be64 __iomem *fc_regs)
1214 {
1215         struct cxlflash_cfg *cfg = afu->parent;
1216         struct device *dev = &cfg->dev->dev;
1217         u64 port_sel;
1218
1219         /* first switch the AFU to the other links, if any */
1220         port_sel = readq_be(&afu->afu_map->global.regs.afu_port_sel);
1221         port_sel &= ~(1ULL << port);
1222         writeq_be(port_sel, &afu->afu_map->global.regs.afu_port_sel);
1223         cxlflash_afu_sync(afu, 0, 0, AFU_GSYNC);
1224
1225         set_port_offline(fc_regs);
1226         if (!wait_port_offline(fc_regs, FC_PORT_STATUS_RETRY_INTERVAL_US,
1227                                FC_PORT_STATUS_RETRY_CNT))
1228                 dev_err(dev, "%s: wait on port %d to go offline timed out\n",
1229                         __func__, port);
1230
1231         set_port_online(fc_regs);
1232         if (!wait_port_online(fc_regs, FC_PORT_STATUS_RETRY_INTERVAL_US,
1233                               FC_PORT_STATUS_RETRY_CNT))
1234                 dev_err(dev, "%s: wait on port %d to go online timed out\n",
1235                         __func__, port);
1236
1237         /* switch back to include this port */
1238         port_sel |= (1ULL << port);
1239         writeq_be(port_sel, &afu->afu_map->global.regs.afu_port_sel);
1240         cxlflash_afu_sync(afu, 0, 0, AFU_GSYNC);
1241
1242         dev_dbg(dev, "%s: returning port_sel=%016llx\n", __func__, port_sel);
1243 }
1244
1245 /**
1246  * afu_err_intr_init() - clears and initializes the AFU for error interrupts
1247  * @afu:        AFU associated with the host.
1248  */
1249 static void afu_err_intr_init(struct afu *afu)
1250 {
1251         struct cxlflash_cfg *cfg = afu->parent;
1252         __be64 __iomem *fc_port_regs;
1253         int i;
1254         struct hwq *hwq = get_hwq(afu, PRIMARY_HWQ);
1255         u64 reg;
1256
1257         /* global async interrupts: AFU clears afu_ctrl on context exit
1258          * if async interrupts were sent to that context. This prevents
1259          * the AFU form sending further async interrupts when
1260          * there is
1261          * nobody to receive them.
1262          */
1263
1264         /* mask all */
1265         writeq_be(-1ULL, &afu->afu_map->global.regs.aintr_mask);
1266         /* set LISN# to send and point to primary master context */
1267         reg = ((u64) (((hwq->ctx_hndl << 8) | SISL_MSI_ASYNC_ERROR)) << 40);
1268
1269         if (afu->internal_lun)
1270                 reg |= 1;       /* Bit 63 indicates local lun */
1271         writeq_be(reg, &afu->afu_map->global.regs.afu_ctrl);
1272         /* clear all */
1273         writeq_be(-1ULL, &afu->afu_map->global.regs.aintr_clear);
1274         /* unmask bits that are of interest */
1275         /* note: afu can send an interrupt after this step */
1276         writeq_be(SISL_ASTATUS_MASK, &afu->afu_map->global.regs.aintr_mask);
1277         /* clear again in case a bit came on after previous clear but before */
1278         /* unmask */
1279         writeq_be(-1ULL, &afu->afu_map->global.regs.aintr_clear);
1280
1281         /* Clear/Set internal lun bits */
1282         fc_port_regs = get_fc_port_regs(cfg, 0);
1283         reg = readq_be(&fc_port_regs[FC_CONFIG2 / 8]);
1284         reg &= SISL_FC_INTERNAL_MASK;
1285         if (afu->internal_lun)
1286                 reg |= ((u64)(afu->internal_lun - 1) << SISL_FC_INTERNAL_SHIFT);
1287         writeq_be(reg, &fc_port_regs[FC_CONFIG2 / 8]);
1288
1289         /* now clear FC errors */
1290         for (i = 0; i < cfg->num_fc_ports; i++) {
1291                 fc_port_regs = get_fc_port_regs(cfg, i);
1292
1293                 writeq_be(0xFFFFFFFFU, &fc_port_regs[FC_ERROR / 8]);
1294                 writeq_be(0, &fc_port_regs[FC_ERRCAP / 8]);
1295         }
1296
1297         /* sync interrupts for master's IOARRIN write */
1298         /* note that unlike asyncs, there can be no pending sync interrupts */
1299         /* at this time (this is a fresh context and master has not written */
1300         /* IOARRIN yet), so there is nothing to clear. */
1301
1302         /* set LISN#, it is always sent to the context that wrote IOARRIN */
1303         for (i = 0; i < afu->num_hwqs; i++) {
1304                 hwq = get_hwq(afu, i);
1305
1306                 reg = readq_be(&hwq->host_map->ctx_ctrl);
1307                 WARN_ON((reg & SISL_CTX_CTRL_LISN_MASK) != 0);
1308                 reg |= SISL_MSI_SYNC_ERROR;
1309                 writeq_be(reg, &hwq->host_map->ctx_ctrl);
1310                 writeq_be(SISL_ISTATUS_MASK, &hwq->host_map->intr_mask);
1311         }
1312 }
1313
1314 /**
1315  * cxlflash_sync_err_irq() - interrupt handler for synchronous errors
1316  * @irq:        Interrupt number.
1317  * @data:       Private data provided at interrupt registration, the AFU.
1318  *
1319  * Return: Always return IRQ_HANDLED.
1320  */
1321 static irqreturn_t cxlflash_sync_err_irq(int irq, void *data)
1322 {
1323         struct hwq *hwq = (struct hwq *)data;
1324         struct cxlflash_cfg *cfg = hwq->afu->parent;
1325         struct device *dev = &cfg->dev->dev;
1326         u64 reg;
1327         u64 reg_unmasked;
1328
1329         reg = readq_be(&hwq->host_map->intr_status);
1330         reg_unmasked = (reg & SISL_ISTATUS_UNMASK);
1331
1332         if (reg_unmasked == 0UL) {
1333                 dev_err(dev, "%s: spurious interrupt, intr_status=%016llx\n",
1334                         __func__, reg);
1335                 goto cxlflash_sync_err_irq_exit;
1336         }
1337
1338         dev_err(dev, "%s: unexpected interrupt, intr_status=%016llx\n",
1339                 __func__, reg);
1340
1341         writeq_be(reg_unmasked, &hwq->host_map->intr_clear);
1342
1343 cxlflash_sync_err_irq_exit:
1344         return IRQ_HANDLED;
1345 }
1346
1347 /**
1348  * process_hrrq() - process the read-response queue
1349  * @afu:        AFU associated with the host.
1350  * @doneq:      Queue of commands harvested from the RRQ.
1351  * @budget:     Threshold of RRQ entries to process.
1352  *
1353  * This routine must be called holding the disabled RRQ spin lock.
1354  *
1355  * Return: The number of entries processed.
1356  */
1357 static int process_hrrq(struct hwq *hwq, struct list_head *doneq, int budget)
1358 {
1359         struct afu *afu = hwq->afu;
1360         struct afu_cmd *cmd;
1361         struct sisl_ioasa *ioasa;
1362         struct sisl_ioarcb *ioarcb;
1363         bool toggle = hwq->toggle;
1364         int num_hrrq = 0;
1365         u64 entry,
1366             *hrrq_start = hwq->hrrq_start,
1367             *hrrq_end = hwq->hrrq_end,
1368             *hrrq_curr = hwq->hrrq_curr;
1369
1370         /* Process ready RRQ entries up to the specified budget (if any) */
1371         while (true) {
1372                 entry = *hrrq_curr;
1373
1374                 if ((entry & SISL_RESP_HANDLE_T_BIT) != toggle)
1375                         break;
1376
1377                 entry &= ~SISL_RESP_HANDLE_T_BIT;
1378
1379                 if (afu_is_sq_cmd_mode(afu)) {
1380                         ioasa = (struct sisl_ioasa *)entry;
1381                         cmd = container_of(ioasa, struct afu_cmd, sa);
1382                 } else {
1383                         ioarcb = (struct sisl_ioarcb *)entry;
1384                         cmd = container_of(ioarcb, struct afu_cmd, rcb);
1385                 }
1386
1387                 list_add_tail(&cmd->queue, doneq);
1388
1389                 /* Advance to next entry or wrap and flip the toggle bit */
1390                 if (hrrq_curr < hrrq_end)
1391                         hrrq_curr++;
1392                 else {
1393                         hrrq_curr = hrrq_start;
1394                         toggle ^= SISL_RESP_HANDLE_T_BIT;
1395                 }
1396
1397                 atomic_inc(&hwq->hsq_credits);
1398                 num_hrrq++;
1399
1400                 if (budget > 0 && num_hrrq >= budget)
1401                         break;
1402         }
1403
1404         hwq->hrrq_curr = hrrq_curr;
1405         hwq->toggle = toggle;
1406
1407         return num_hrrq;
1408 }
1409
1410 /**
1411  * process_cmd_doneq() - process a queue of harvested RRQ commands
1412  * @doneq:      Queue of completed commands.
1413  *
1414  * Note that upon return the queue can no longer be trusted.
1415  */
1416 static void process_cmd_doneq(struct list_head *doneq)
1417 {
1418         struct afu_cmd *cmd, *tmp;
1419
1420         WARN_ON(list_empty(doneq));
1421
1422         list_for_each_entry_safe(cmd, tmp, doneq, queue)
1423                 cmd_complete(cmd);
1424 }
1425
1426 /**
1427  * cxlflash_irqpoll() - process a queue of harvested RRQ commands
1428  * @irqpoll:    IRQ poll structure associated with queue to poll.
1429  * @budget:     Threshold of RRQ entries to process per poll.
1430  *
1431  * Return: The number of entries processed.
1432  */
1433 static int cxlflash_irqpoll(struct irq_poll *irqpoll, int budget)
1434 {
1435         struct hwq *hwq = container_of(irqpoll, struct hwq, irqpoll);
1436         unsigned long hrrq_flags;
1437         LIST_HEAD(doneq);
1438         int num_entries = 0;
1439
1440         spin_lock_irqsave(&hwq->hrrq_slock, hrrq_flags);
1441
1442         num_entries = process_hrrq(hwq, &doneq, budget);
1443         if (num_entries < budget)
1444                 irq_poll_complete(irqpoll);
1445
1446         spin_unlock_irqrestore(&hwq->hrrq_slock, hrrq_flags);
1447
1448         process_cmd_doneq(&doneq);
1449         return num_entries;
1450 }
1451
1452 /**
1453  * cxlflash_rrq_irq() - interrupt handler for read-response queue (normal path)
1454  * @irq:        Interrupt number.
1455  * @data:       Private data provided at interrupt registration, the AFU.
1456  *
1457  * Return: IRQ_HANDLED or IRQ_NONE when no ready entries found.
1458  */
1459 static irqreturn_t cxlflash_rrq_irq(int irq, void *data)
1460 {
1461         struct hwq *hwq = (struct hwq *)data;
1462         struct afu *afu = hwq->afu;
1463         unsigned long hrrq_flags;
1464         LIST_HEAD(doneq);
1465         int num_entries = 0;
1466
1467         spin_lock_irqsave(&hwq->hrrq_slock, hrrq_flags);
1468
1469         if (afu_is_irqpoll_enabled(afu)) {
1470                 irq_poll_sched(&hwq->irqpoll);
1471                 spin_unlock_irqrestore(&hwq->hrrq_slock, hrrq_flags);
1472                 return IRQ_HANDLED;
1473         }
1474
1475         num_entries = process_hrrq(hwq, &doneq, -1);
1476         spin_unlock_irqrestore(&hwq->hrrq_slock, hrrq_flags);
1477
1478         if (num_entries == 0)
1479                 return IRQ_NONE;
1480
1481         process_cmd_doneq(&doneq);
1482         return IRQ_HANDLED;
1483 }
1484
1485 /*
1486  * Asynchronous interrupt information table
1487  *
1488  * NOTE:
1489  *      - Order matters here as this array is indexed by bit position.
1490  *
1491  *      - The checkpatch script considers the BUILD_SISL_ASTATUS_FC_PORT macro
1492  *        as complex and complains due to a lack of parentheses/braces.
1493  */
1494 #define ASTATUS_FC(_a, _b, _c, _d)                                       \
1495         { SISL_ASTATUS_FC##_a##_##_b, _c, _a, (_d) }
1496
1497 #define BUILD_SISL_ASTATUS_FC_PORT(_a)                                   \
1498         ASTATUS_FC(_a, LINK_UP, "link up", 0),                           \
1499         ASTATUS_FC(_a, LINK_DN, "link down", 0),                         \
1500         ASTATUS_FC(_a, LOGI_S, "login succeeded", SCAN_HOST),            \
1501         ASTATUS_FC(_a, LOGI_F, "login failed", CLR_FC_ERROR),            \
1502         ASTATUS_FC(_a, LOGI_R, "login timed out, retrying", LINK_RESET), \
1503         ASTATUS_FC(_a, CRC_T, "CRC threshold exceeded", LINK_RESET),     \
1504         ASTATUS_FC(_a, LOGO, "target initiated LOGO", 0),                \
1505         ASTATUS_FC(_a, OTHER, "other error", CLR_FC_ERROR | LINK_RESET)
1506
1507 static const struct asyc_intr_info ainfo[] = {
1508         BUILD_SISL_ASTATUS_FC_PORT(1),
1509         BUILD_SISL_ASTATUS_FC_PORT(0),
1510         BUILD_SISL_ASTATUS_FC_PORT(3),
1511         BUILD_SISL_ASTATUS_FC_PORT(2)
1512 };
1513
1514 /**
1515  * cxlflash_async_err_irq() - interrupt handler for asynchronous errors
1516  * @irq:        Interrupt number.
1517  * @data:       Private data provided at interrupt registration, the AFU.
1518  *
1519  * Return: Always return IRQ_HANDLED.
1520  */
1521 static irqreturn_t cxlflash_async_err_irq(int irq, void *data)
1522 {
1523         struct hwq *hwq = (struct hwq *)data;
1524         struct afu *afu = hwq->afu;
1525         struct cxlflash_cfg *cfg = afu->parent;
1526         struct device *dev = &cfg->dev->dev;
1527         const struct asyc_intr_info *info;
1528         struct sisl_global_map __iomem *global = &afu->afu_map->global;
1529         __be64 __iomem *fc_port_regs;
1530         u64 reg_unmasked;
1531         u64 reg;
1532         u64 bit;
1533         u8 port;
1534
1535         reg = readq_be(&global->regs.aintr_status);
1536         reg_unmasked = (reg & SISL_ASTATUS_UNMASK);
1537
1538         if (unlikely(reg_unmasked == 0)) {
1539                 dev_err(dev, "%s: spurious interrupt, aintr_status=%016llx\n",
1540                         __func__, reg);
1541                 goto out;
1542         }
1543
1544         /* FYI, it is 'okay' to clear AFU status before FC_ERROR */
1545         writeq_be(reg_unmasked, &global->regs.aintr_clear);
1546
1547         /* Check each bit that is on */
1548         for_each_set_bit(bit, (ulong *)&reg_unmasked, BITS_PER_LONG) {
1549                 if (unlikely(bit >= ARRAY_SIZE(ainfo))) {
1550                         WARN_ON_ONCE(1);
1551                         continue;
1552                 }
1553
1554                 info = &ainfo[bit];
1555                 if (unlikely(info->status != 1ULL << bit)) {
1556                         WARN_ON_ONCE(1);
1557                         continue;
1558                 }
1559
1560                 port = info->port;
1561                 fc_port_regs = get_fc_port_regs(cfg, port);
1562
1563                 dev_err(dev, "%s: FC Port %d -> %s, fc_status=%016llx\n",
1564                         __func__, port, info->desc,
1565                        readq_be(&fc_port_regs[FC_STATUS / 8]));
1566
1567                 /*
1568                  * Do link reset first, some OTHER errors will set FC_ERROR
1569                  * again if cleared before or w/o a reset
1570                  */
1571                 if (info->action & LINK_RESET) {
1572                         dev_err(dev, "%s: FC Port %d: resetting link\n",
1573                                 __func__, port);
1574                         cfg->lr_state = LINK_RESET_REQUIRED;
1575                         cfg->lr_port = port;
1576                         schedule_work(&cfg->work_q);
1577                 }
1578
1579                 if (info->action & CLR_FC_ERROR) {
1580                         reg = readq_be(&fc_port_regs[FC_ERROR / 8]);
1581
1582                         /*
1583                          * Since all errors are unmasked, FC_ERROR and FC_ERRCAP
1584                          * should be the same and tracing one is sufficient.
1585                          */
1586
1587                         dev_err(dev, "%s: fc %d: clearing fc_error=%016llx\n",
1588                                 __func__, port, reg);
1589
1590                         writeq_be(reg, &fc_port_regs[FC_ERROR / 8]);
1591                         writeq_be(0, &fc_port_regs[FC_ERRCAP / 8]);
1592                 }
1593
1594                 if (info->action & SCAN_HOST) {
1595                         atomic_inc(&cfg->scan_host_needed);
1596                         schedule_work(&cfg->work_q);
1597                 }
1598         }
1599
1600 out:
1601         return IRQ_HANDLED;
1602 }
1603
1604 /**
1605  * start_context() - starts the master context
1606  * @cfg:        Internal structure associated with the host.
1607  * @index:      Index of the hardware queue.
1608  *
1609  * Return: A success or failure value from CXL services.
1610  */
1611 static int start_context(struct cxlflash_cfg *cfg, u32 index)
1612 {
1613         struct device *dev = &cfg->dev->dev;
1614         struct hwq *hwq = get_hwq(cfg->afu, index);
1615         int rc = 0;
1616
1617         rc = cxl_start_context(hwq->ctx,
1618                                hwq->work.work_element_descriptor,
1619                                NULL);
1620
1621         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
1622         return rc;
1623 }
1624
1625 /**
1626  * read_vpd() - obtains the WWPNs from VPD
1627  * @cfg:        Internal structure associated with the host.
1628  * @wwpn:       Array of size MAX_FC_PORTS to pass back WWPNs
1629  *
1630  * Return: 0 on success, -errno on failure
1631  */
1632 static int read_vpd(struct cxlflash_cfg *cfg, u64 wwpn[])
1633 {
1634         struct device *dev = &cfg->dev->dev;
1635         struct pci_dev *pdev = cfg->dev;
1636         int rc = 0;
1637         int ro_start, ro_size, i, j, k;
1638         ssize_t vpd_size;
1639         char vpd_data[CXLFLASH_VPD_LEN];
1640         char tmp_buf[WWPN_BUF_LEN] = { 0 };
1641         char *wwpn_vpd_tags[MAX_FC_PORTS] = { "V5", "V6", "V7", "V8" };
1642
1643         /* Get the VPD data from the device */
1644         vpd_size = cxl_read_adapter_vpd(pdev, vpd_data, sizeof(vpd_data));
1645         if (unlikely(vpd_size <= 0)) {
1646                 dev_err(dev, "%s: Unable to read VPD (size = %ld)\n",
1647                         __func__, vpd_size);
1648                 rc = -ENODEV;
1649                 goto out;
1650         }
1651
1652         /* Get the read only section offset */
1653         ro_start = pci_vpd_find_tag(vpd_data, 0, vpd_size,
1654                                     PCI_VPD_LRDT_RO_DATA);
1655         if (unlikely(ro_start < 0)) {
1656                 dev_err(dev, "%s: VPD Read-only data not found\n", __func__);
1657                 rc = -ENODEV;
1658                 goto out;
1659         }
1660
1661         /* Get the read only section size, cap when extends beyond read VPD */
1662         ro_size = pci_vpd_lrdt_size(&vpd_data[ro_start]);
1663         j = ro_size;
1664         i = ro_start + PCI_VPD_LRDT_TAG_SIZE;
1665         if (unlikely((i + j) > vpd_size)) {
1666                 dev_dbg(dev, "%s: Might need to read more VPD (%d > %ld)\n",
1667                         __func__, (i + j), vpd_size);
1668                 ro_size = vpd_size - i;
1669         }
1670
1671         /*
1672          * Find the offset of the WWPN tag within the read only
1673          * VPD data and validate the found field (partials are
1674          * no good to us). Convert the ASCII data to an integer
1675          * value. Note that we must copy to a temporary buffer
1676          * because the conversion service requires that the ASCII
1677          * string be terminated.
1678          */
1679         for (k = 0; k < cfg->num_fc_ports; k++) {
1680                 j = ro_size;
1681                 i = ro_start + PCI_VPD_LRDT_TAG_SIZE;
1682
1683                 i = pci_vpd_find_info_keyword(vpd_data, i, j, wwpn_vpd_tags[k]);
1684                 if (unlikely(i < 0)) {
1685                         dev_err(dev, "%s: Port %d WWPN not found in VPD\n",
1686                                 __func__, k);
1687                         rc = -ENODEV;
1688                         goto out;
1689                 }
1690
1691                 j = pci_vpd_info_field_size(&vpd_data[i]);
1692                 i += PCI_VPD_INFO_FLD_HDR_SIZE;
1693                 if (unlikely((i + j > vpd_size) || (j != WWPN_LEN))) {
1694                         dev_err(dev, "%s: Port %d WWPN incomplete or bad VPD\n",
1695                                 __func__, k);
1696                         rc = -ENODEV;
1697                         goto out;
1698                 }
1699
1700                 memcpy(tmp_buf, &vpd_data[i], WWPN_LEN);
1701                 rc = kstrtoul(tmp_buf, WWPN_LEN, (ulong *)&wwpn[k]);
1702                 if (unlikely(rc)) {
1703                         dev_err(dev, "%s: WWPN conversion failed for port %d\n",
1704                                 __func__, k);
1705                         rc = -ENODEV;
1706                         goto out;
1707                 }
1708
1709                 dev_dbg(dev, "%s: wwpn%d=%016llx\n", __func__, k, wwpn[k]);
1710         }
1711
1712 out:
1713         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
1714         return rc;
1715 }
1716
1717 /**
1718  * init_pcr() - initialize the provisioning and control registers
1719  * @cfg:        Internal structure associated with the host.
1720  *
1721  * Also sets up fast access to the mapped registers and initializes AFU
1722  * command fields that never change.
1723  */
1724 static void init_pcr(struct cxlflash_cfg *cfg)
1725 {
1726         struct afu *afu = cfg->afu;
1727         struct sisl_ctrl_map __iomem *ctrl_map;
1728         struct hwq *hwq;
1729         int i;
1730
1731         for (i = 0; i < MAX_CONTEXT; i++) {
1732                 ctrl_map = &afu->afu_map->ctrls[i].ctrl;
1733                 /* Disrupt any clients that could be running */
1734                 /* e.g. clients that survived a master restart */
1735                 writeq_be(0, &ctrl_map->rht_start);
1736                 writeq_be(0, &ctrl_map->rht_cnt_id);
1737                 writeq_be(0, &ctrl_map->ctx_cap);
1738         }
1739
1740         /* Copy frequently used fields into hwq */
1741         for (i = 0; i < afu->num_hwqs; i++) {
1742                 hwq = get_hwq(afu, i);
1743
1744                 hwq->ctx_hndl = (u16) cxl_process_element(hwq->ctx);
1745                 hwq->host_map = &afu->afu_map->hosts[hwq->ctx_hndl].host;
1746                 hwq->ctrl_map = &afu->afu_map->ctrls[hwq->ctx_hndl].ctrl;
1747
1748                 /* Program the Endian Control for the master context */
1749                 writeq_be(SISL_ENDIAN_CTRL, &hwq->host_map->endian_ctrl);
1750         }
1751 }
1752
1753 /**
1754  * init_global() - initialize AFU global registers
1755  * @cfg:        Internal structure associated with the host.
1756  */
1757 static int init_global(struct cxlflash_cfg *cfg)
1758 {
1759         struct afu *afu = cfg->afu;
1760         struct device *dev = &cfg->dev->dev;
1761         struct hwq *hwq;
1762         struct sisl_host_map __iomem *hmap;
1763         __be64 __iomem *fc_port_regs;
1764         u64 wwpn[MAX_FC_PORTS]; /* wwpn of AFU ports */
1765         int i = 0, num_ports = 0;
1766         int rc = 0;
1767         u64 reg;
1768
1769         rc = read_vpd(cfg, &wwpn[0]);
1770         if (rc) {
1771                 dev_err(dev, "%s: could not read vpd rc=%d\n", __func__, rc);
1772                 goto out;
1773         }
1774
1775         /* Set up RRQ and SQ in HWQ for master issued cmds */
1776         for (i = 0; i < afu->num_hwqs; i++) {
1777                 hwq = get_hwq(afu, i);
1778                 hmap = hwq->host_map;
1779
1780                 writeq_be((u64) hwq->hrrq_start, &hmap->rrq_start);
1781                 writeq_be((u64) hwq->hrrq_end, &hmap->rrq_end);
1782
1783                 if (afu_is_sq_cmd_mode(afu)) {
1784                         writeq_be((u64)hwq->hsq_start, &hmap->sq_start);
1785                         writeq_be((u64)hwq->hsq_end, &hmap->sq_end);
1786                 }
1787         }
1788
1789         /* AFU configuration */
1790         reg = readq_be(&afu->afu_map->global.regs.afu_config);
1791         reg |= SISL_AFUCONF_AR_ALL|SISL_AFUCONF_ENDIAN;
1792         /* enable all auto retry options and control endianness */
1793         /* leave others at default: */
1794         /* CTX_CAP write protected, mbox_r does not clear on read and */
1795         /* checker on if dual afu */
1796         writeq_be(reg, &afu->afu_map->global.regs.afu_config);
1797
1798         /* Global port select: select either port */
1799         if (afu->internal_lun) {
1800                 /* Only use port 0 */
1801                 writeq_be(PORT0, &afu->afu_map->global.regs.afu_port_sel);
1802                 num_ports = 0;
1803         } else {
1804                 writeq_be(PORT_MASK(cfg->num_fc_ports),
1805                           &afu->afu_map->global.regs.afu_port_sel);
1806                 num_ports = cfg->num_fc_ports;
1807         }
1808
1809         for (i = 0; i < num_ports; i++) {
1810                 fc_port_regs = get_fc_port_regs(cfg, i);
1811
1812                 /* Unmask all errors (but they are still masked at AFU) */
1813                 writeq_be(0, &fc_port_regs[FC_ERRMSK / 8]);
1814                 /* Clear CRC error cnt & set a threshold */
1815                 (void)readq_be(&fc_port_regs[FC_CNT_CRCERR / 8]);
1816                 writeq_be(MC_CRC_THRESH, &fc_port_regs[FC_CRC_THRESH / 8]);
1817
1818                 /* Set WWPNs. If already programmed, wwpn[i] is 0 */
1819                 if (wwpn[i] != 0)
1820                         afu_set_wwpn(afu, i, &fc_port_regs[0], wwpn[i]);
1821                 /* Programming WWPN back to back causes additional
1822                  * offline/online transitions and a PLOGI
1823                  */
1824                 msleep(100);
1825         }
1826
1827         /* Set up master's own CTX_CAP to allow real mode, host translation */
1828         /* tables, afu cmds and read/write GSCSI cmds. */
1829         /* First, unlock ctx_cap write by reading mbox */
1830         for (i = 0; i < afu->num_hwqs; i++) {
1831                 hwq = get_hwq(afu, i);
1832
1833                 (void)readq_be(&hwq->ctrl_map->mbox_r); /* unlock ctx_cap */
1834                 writeq_be((SISL_CTX_CAP_REAL_MODE | SISL_CTX_CAP_HOST_XLATE |
1835                         SISL_CTX_CAP_READ_CMD | SISL_CTX_CAP_WRITE_CMD |
1836                         SISL_CTX_CAP_AFU_CMD | SISL_CTX_CAP_GSCSI_CMD),
1837                         &hwq->ctrl_map->ctx_cap);
1838         }
1839
1840         /*
1841          * Determine write-same unmap support for host by evaluating the unmap
1842          * sector support bit of the context control register associated with
1843          * the primary hardware queue. Note that while this status is reflected
1844          * in a context register, the outcome can be assumed to be host-wide.
1845          */
1846         hwq = get_hwq(afu, PRIMARY_HWQ);
1847         reg = readq_be(&hwq->host_map->ctx_ctrl);
1848         if (reg & SISL_CTX_CTRL_UNMAP_SECTOR)
1849                 cfg->ws_unmap = true;
1850
1851         /* Initialize heartbeat */
1852         afu->hb = readq_be(&afu->afu_map->global.regs.afu_hb);
1853 out:
1854         return rc;
1855 }
1856
1857 /**
1858  * start_afu() - initializes and starts the AFU
1859  * @cfg:        Internal structure associated with the host.
1860  */
1861 static int start_afu(struct cxlflash_cfg *cfg)
1862 {
1863         struct afu *afu = cfg->afu;
1864         struct device *dev = &cfg->dev->dev;
1865         struct hwq *hwq;
1866         int rc = 0;
1867         int i;
1868
1869         init_pcr(cfg);
1870
1871         /* Initialize each HWQ */
1872         for (i = 0; i < afu->num_hwqs; i++) {
1873                 hwq = get_hwq(afu, i);
1874
1875                 /* After an AFU reset, RRQ entries are stale, clear them */
1876                 memset(&hwq->rrq_entry, 0, sizeof(hwq->rrq_entry));
1877
1878                 /* Initialize RRQ pointers */
1879                 hwq->hrrq_start = &hwq->rrq_entry[0];
1880                 hwq->hrrq_end = &hwq->rrq_entry[NUM_RRQ_ENTRY - 1];
1881                 hwq->hrrq_curr = hwq->hrrq_start;
1882                 hwq->toggle = 1;
1883
1884                 /* Initialize spin locks */
1885                 spin_lock_init(&hwq->hrrq_slock);
1886                 spin_lock_init(&hwq->hsq_slock);
1887
1888                 /* Initialize SQ */
1889                 if (afu_is_sq_cmd_mode(afu)) {
1890                         memset(&hwq->sq, 0, sizeof(hwq->sq));
1891                         hwq->hsq_start = &hwq->sq[0];
1892                         hwq->hsq_end = &hwq->sq[NUM_SQ_ENTRY - 1];
1893                         hwq->hsq_curr = hwq->hsq_start;
1894
1895                         atomic_set(&hwq->hsq_credits, NUM_SQ_ENTRY - 1);
1896                 }
1897
1898                 /* Initialize IRQ poll */
1899                 if (afu_is_irqpoll_enabled(afu))
1900                         irq_poll_init(&hwq->irqpoll, afu->irqpoll_weight,
1901                                       cxlflash_irqpoll);
1902
1903         }
1904
1905         rc = init_global(cfg);
1906
1907         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
1908         return rc;
1909 }
1910
1911 /**
1912  * init_intr() - setup interrupt handlers for the master context
1913  * @cfg:        Internal structure associated with the host.
1914  * @hwq:        Hardware queue to initialize.
1915  *
1916  * Return: 0 on success, -errno on failure
1917  */
1918 static enum undo_level init_intr(struct cxlflash_cfg *cfg,
1919                                  struct hwq *hwq)
1920 {
1921         struct device *dev = &cfg->dev->dev;
1922         struct cxl_context *ctx = hwq->ctx;
1923         int rc = 0;
1924         enum undo_level level = UNDO_NOOP;
1925         bool is_primary_hwq = (hwq->index == PRIMARY_HWQ);
1926         int num_irqs = is_primary_hwq ? 3 : 2;
1927
1928         rc = cxl_allocate_afu_irqs(ctx, num_irqs);
1929         if (unlikely(rc)) {
1930                 dev_err(dev, "%s: allocate_afu_irqs failed rc=%d\n",
1931                         __func__, rc);
1932                 level = UNDO_NOOP;
1933                 goto out;
1934         }
1935
1936         rc = cxl_map_afu_irq(ctx, 1, cxlflash_sync_err_irq, hwq,
1937                              "SISL_MSI_SYNC_ERROR");
1938         if (unlikely(rc <= 0)) {
1939                 dev_err(dev, "%s: SISL_MSI_SYNC_ERROR map failed\n", __func__);
1940                 level = FREE_IRQ;
1941                 goto out;
1942         }
1943
1944         rc = cxl_map_afu_irq(ctx, 2, cxlflash_rrq_irq, hwq,
1945                              "SISL_MSI_RRQ_UPDATED");
1946         if (unlikely(rc <= 0)) {
1947                 dev_err(dev, "%s: SISL_MSI_RRQ_UPDATED map failed\n", __func__);
1948                 level = UNMAP_ONE;
1949                 goto out;
1950         }
1951
1952         /* SISL_MSI_ASYNC_ERROR is setup only for the primary HWQ */
1953         if (!is_primary_hwq)
1954                 goto out;
1955
1956         rc = cxl_map_afu_irq(ctx, 3, cxlflash_async_err_irq, hwq,
1957                              "SISL_MSI_ASYNC_ERROR");
1958         if (unlikely(rc <= 0)) {
1959                 dev_err(dev, "%s: SISL_MSI_ASYNC_ERROR map failed\n", __func__);
1960                 level = UNMAP_TWO;
1961                 goto out;
1962         }
1963 out:
1964         return level;
1965 }
1966
1967 /**
1968  * init_mc() - create and register as the master context
1969  * @cfg:        Internal structure associated with the host.
1970  * index:       HWQ Index of the master context.
1971  *
1972  * Return: 0 on success, -errno on failure
1973  */
1974 static int init_mc(struct cxlflash_cfg *cfg, u32 index)
1975 {
1976         struct cxl_context *ctx;
1977         struct device *dev = &cfg->dev->dev;
1978         struct hwq *hwq = get_hwq(cfg->afu, index);
1979         int rc = 0;
1980         enum undo_level level;
1981
1982         hwq->afu = cfg->afu;
1983         hwq->index = index;
1984         INIT_LIST_HEAD(&hwq->pending_cmds);
1985
1986         if (index == PRIMARY_HWQ)
1987                 ctx = cxl_get_context(cfg->dev);
1988         else
1989                 ctx = cxl_dev_context_init(cfg->dev);
1990         if (unlikely(!ctx)) {
1991                 rc = -ENOMEM;
1992                 goto err1;
1993         }
1994
1995         WARN_ON(hwq->ctx);
1996         hwq->ctx = ctx;
1997
1998         /* Set it up as a master with the CXL */
1999         cxl_set_master(ctx);
2000
2001         /* Reset AFU when initializing primary context */
2002         if (index == PRIMARY_HWQ) {
2003                 rc = cxl_afu_reset(ctx);
2004                 if (unlikely(rc)) {
2005                         dev_err(dev, "%s: AFU reset failed rc=%d\n",
2006                                       __func__, rc);
2007                         goto err1;
2008                 }
2009         }
2010
2011         level = init_intr(cfg, hwq);
2012         if (unlikely(level)) {
2013                 dev_err(dev, "%s: interrupt init failed rc=%d\n", __func__, rc);
2014                 goto err2;
2015         }
2016
2017         /* This performs the equivalent of the CXL_IOCTL_START_WORK.
2018          * The CXL_IOCTL_GET_PROCESS_ELEMENT is implicit in the process
2019          * element (pe) that is embedded in the context (ctx)
2020          */
2021         rc = start_context(cfg, index);
2022         if (unlikely(rc)) {
2023                 dev_err(dev, "%s: start context failed rc=%d\n", __func__, rc);
2024                 level = UNMAP_THREE;
2025                 goto err2;
2026         }
2027
2028 out:
2029         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
2030         return rc;
2031 err2:
2032         term_intr(cfg, level, index);
2033         if (index != PRIMARY_HWQ)
2034                 cxl_release_context(ctx);
2035 err1:
2036         hwq->ctx = NULL;
2037         goto out;
2038 }
2039
2040 /**
2041  * get_num_afu_ports() - determines and configures the number of AFU ports
2042  * @cfg:        Internal structure associated with the host.
2043  *
2044  * This routine determines the number of AFU ports by converting the global
2045  * port selection mask. The converted value is only valid following an AFU
2046  * reset (explicit or power-on). This routine must be invoked shortly after
2047  * mapping as other routines are dependent on the number of ports during the
2048  * initialization sequence.
2049  *
2050  * To support legacy AFUs that might not have reflected an initial global
2051  * port mask (value read is 0), default to the number of ports originally
2052  * supported by the cxlflash driver (2) before hardware with other port
2053  * offerings was introduced.
2054  */
2055 static void get_num_afu_ports(struct cxlflash_cfg *cfg)
2056 {
2057         struct afu *afu = cfg->afu;
2058         struct device *dev = &cfg->dev->dev;
2059         u64 port_mask;
2060         int num_fc_ports = LEGACY_FC_PORTS;
2061
2062         port_mask = readq_be(&afu->afu_map->global.regs.afu_port_sel);
2063         if (port_mask != 0ULL)
2064                 num_fc_ports = min(ilog2(port_mask) + 1, MAX_FC_PORTS);
2065
2066         dev_dbg(dev, "%s: port_mask=%016llx num_fc_ports=%d\n",
2067                 __func__, port_mask, num_fc_ports);
2068
2069         cfg->num_fc_ports = num_fc_ports;
2070         cfg->host->max_channel = PORTNUM2CHAN(num_fc_ports);
2071 }
2072
2073 /**
2074  * init_afu() - setup as master context and start AFU
2075  * @cfg:        Internal structure associated with the host.
2076  *
2077  * This routine is a higher level of control for configuring the
2078  * AFU on probe and reset paths.
2079  *
2080  * Return: 0 on success, -errno on failure
2081  */
2082 static int init_afu(struct cxlflash_cfg *cfg)
2083 {
2084         u64 reg;
2085         int rc = 0;
2086         struct afu *afu = cfg->afu;
2087         struct device *dev = &cfg->dev->dev;
2088         struct hwq *hwq;
2089         int i;
2090
2091         cxl_perst_reloads_same_image(cfg->cxl_afu, true);
2092
2093         afu->num_hwqs = afu->desired_hwqs;
2094         for (i = 0; i < afu->num_hwqs; i++) {
2095                 rc = init_mc(cfg, i);
2096                 if (rc) {
2097                         dev_err(dev, "%s: init_mc failed rc=%d index=%d\n",
2098                                 __func__, rc, i);
2099                         goto err1;
2100                 }
2101         }
2102
2103         /* Map the entire MMIO space of the AFU using the first context */
2104         hwq = get_hwq(afu, PRIMARY_HWQ);
2105         afu->afu_map = cxl_psa_map(hwq->ctx);
2106         if (!afu->afu_map) {
2107                 dev_err(dev, "%s: cxl_psa_map failed\n", __func__);
2108                 rc = -ENOMEM;
2109                 goto err1;
2110         }
2111
2112         /* No byte reverse on reading afu_version or string will be backwards */
2113         reg = readq(&afu->afu_map->global.regs.afu_version);
2114         memcpy(afu->version, &reg, sizeof(reg));
2115         afu->interface_version =
2116             readq_be(&afu->afu_map->global.regs.interface_version);
2117         if ((afu->interface_version + 1) == 0) {
2118                 dev_err(dev, "Back level AFU, please upgrade. AFU version %s "
2119                         "interface version %016llx\n", afu->version,
2120                        afu->interface_version);
2121                 rc = -EINVAL;
2122                 goto err1;
2123         }
2124
2125         if (afu_is_sq_cmd_mode(afu)) {
2126                 afu->send_cmd = send_cmd_sq;
2127                 afu->context_reset = context_reset_sq;
2128         } else {
2129                 afu->send_cmd = send_cmd_ioarrin;
2130                 afu->context_reset = context_reset_ioarrin;
2131         }
2132
2133         dev_dbg(dev, "%s: afu_ver=%s interface_ver=%016llx\n", __func__,
2134                 afu->version, afu->interface_version);
2135
2136         get_num_afu_ports(cfg);
2137
2138         rc = start_afu(cfg);
2139         if (rc) {
2140                 dev_err(dev, "%s: start_afu failed, rc=%d\n", __func__, rc);
2141                 goto err1;
2142         }
2143
2144         afu_err_intr_init(cfg->afu);
2145         for (i = 0; i < afu->num_hwqs; i++) {
2146                 hwq = get_hwq(afu, i);
2147
2148                 hwq->room = readq_be(&hwq->host_map->cmd_room);
2149         }
2150
2151         /* Restore the LUN mappings */
2152         cxlflash_restore_luntable(cfg);
2153 out:
2154         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
2155         return rc;
2156
2157 err1:
2158         for (i = afu->num_hwqs - 1; i >= 0; i--) {
2159                 term_intr(cfg, UNMAP_THREE, i);
2160                 term_mc(cfg, i);
2161         }
2162         goto out;
2163 }
2164
2165 /**
2166  * afu_reset() - resets the AFU
2167  * @cfg:        Internal structure associated with the host.
2168  *
2169  * Return: 0 on success, -errno on failure
2170  */
2171 static int afu_reset(struct cxlflash_cfg *cfg)
2172 {
2173         struct device *dev = &cfg->dev->dev;
2174         int rc = 0;
2175
2176         /* Stop the context before the reset. Since the context is
2177          * no longer available restart it after the reset is complete
2178          */
2179         term_afu(cfg);
2180
2181         rc = init_afu(cfg);
2182
2183         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
2184         return rc;
2185 }
2186
2187 /**
2188  * drain_ioctls() - wait until all currently executing ioctls have completed
2189  * @cfg:        Internal structure associated with the host.
2190  *
2191  * Obtain write access to read/write semaphore that wraps ioctl
2192  * handling to 'drain' ioctls currently executing.
2193  */
2194 static void drain_ioctls(struct cxlflash_cfg *cfg)
2195 {
2196         down_write(&cfg->ioctl_rwsem);
2197         up_write(&cfg->ioctl_rwsem);
2198 }
2199
2200 /**
2201  * cxlflash_async_reset_host() - asynchronous host reset handler
2202  * @data:       Private data provided while scheduling reset.
2203  * @cookie:     Cookie that can be used for checkpointing.
2204  */
2205 static void cxlflash_async_reset_host(void *data, async_cookie_t cookie)
2206 {
2207         struct cxlflash_cfg *cfg = data;
2208         struct device *dev = &cfg->dev->dev;
2209         int rc = 0;
2210
2211         if (cfg->state != STATE_RESET) {
2212                 dev_dbg(dev, "%s: Not performing a reset, state=%d\n",
2213                         __func__, cfg->state);
2214                 goto out;
2215         }
2216
2217         drain_ioctls(cfg);
2218         cxlflash_mark_contexts_error(cfg);
2219         rc = afu_reset(cfg);
2220         if (rc)
2221                 cfg->state = STATE_FAILTERM;
2222         else
2223                 cfg->state = STATE_NORMAL;
2224         wake_up_all(&cfg->reset_waitq);
2225
2226 out:
2227         scsi_unblock_requests(cfg->host);
2228 }
2229
2230 /**
2231  * cxlflash_schedule_async_reset() - schedule an asynchronous host reset
2232  * @cfg:        Internal structure associated with the host.
2233  */
2234 static void cxlflash_schedule_async_reset(struct cxlflash_cfg *cfg)
2235 {
2236         struct device *dev = &cfg->dev->dev;
2237
2238         if (cfg->state != STATE_NORMAL) {
2239                 dev_dbg(dev, "%s: Not performing reset state=%d\n",
2240                         __func__, cfg->state);
2241                 return;
2242         }
2243
2244         cfg->state = STATE_RESET;
2245         scsi_block_requests(cfg->host);
2246         cfg->async_reset_cookie = async_schedule(cxlflash_async_reset_host,
2247                                                  cfg);
2248 }
2249
2250 /**
2251  * send_afu_cmd() - builds and sends an internal AFU command
2252  * @afu:        AFU associated with the host.
2253  * @rcb:        Pre-populated IOARCB describing command to send.
2254  *
2255  * The AFU can only take one internal AFU command at a time. This limitation is
2256  * enforced by using a mutex to provide exclusive access to the AFU during the
2257  * operation. This design point requires calling threads to not be on interrupt
2258  * context due to the possibility of sleeping during concurrent AFU operations.
2259  *
2260  * The command status is optionally passed back to the caller when the caller
2261  * populates the IOASA field of the IOARCB with a pointer to an IOASA structure.
2262  *
2263  * Return:
2264  *      0 on success, -errno on failure
2265  */
2266 static int send_afu_cmd(struct afu *afu, struct sisl_ioarcb *rcb)
2267 {
2268         struct cxlflash_cfg *cfg = afu->parent;
2269         struct device *dev = &cfg->dev->dev;
2270         struct afu_cmd *cmd = NULL;
2271         struct hwq *hwq = get_hwq(afu, PRIMARY_HWQ);
2272         char *buf = NULL;
2273         int rc = 0;
2274         int nretry = 0;
2275         static DEFINE_MUTEX(sync_active);
2276
2277         if (cfg->state != STATE_NORMAL) {
2278                 dev_dbg(dev, "%s: Sync not required state=%u\n",
2279                         __func__, cfg->state);
2280                 return 0;
2281         }
2282
2283         mutex_lock(&sync_active);
2284         atomic_inc(&afu->cmds_active);
2285         buf = kmalloc(sizeof(*cmd) + __alignof__(*cmd) - 1, GFP_KERNEL);
2286         if (unlikely(!buf)) {
2287                 dev_err(dev, "%s: no memory for command\n", __func__);
2288                 rc = -ENOMEM;
2289                 goto out;
2290         }
2291
2292         cmd = (struct afu_cmd *)PTR_ALIGN(buf, __alignof__(*cmd));
2293
2294 retry:
2295         memset(cmd, 0, sizeof(*cmd));
2296         memcpy(&cmd->rcb, rcb, sizeof(*rcb));
2297         INIT_LIST_HEAD(&cmd->queue);
2298         init_completion(&cmd->cevent);
2299         cmd->parent = afu;
2300         cmd->hwq_index = hwq->index;
2301         cmd->rcb.ctx_id = hwq->ctx_hndl;
2302
2303         dev_dbg(dev, "%s: afu=%p cmd=%p type=%02x nretry=%d\n",
2304                 __func__, afu, cmd, cmd->rcb.cdb[0], nretry);
2305
2306         rc = afu->send_cmd(afu, cmd);
2307         if (unlikely(rc)) {
2308                 rc = -ENOBUFS;
2309                 goto out;
2310         }
2311
2312         rc = wait_resp(afu, cmd);
2313         switch (rc) {
2314         case -ETIMEDOUT:
2315                 rc = afu->context_reset(hwq);
2316                 if (rc) {
2317                         cxlflash_schedule_async_reset(cfg);
2318                         break;
2319                 }
2320                 /* fall through to retry */
2321         case -EAGAIN:
2322                 if (++nretry < 2)
2323                         goto retry;
2324                 /* fall through to exit */
2325         default:
2326                 break;
2327         }
2328
2329         if (rcb->ioasa)
2330                 *rcb->ioasa = cmd->sa;
2331 out:
2332         atomic_dec(&afu->cmds_active);
2333         mutex_unlock(&sync_active);
2334         kfree(buf);
2335         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
2336         return rc;
2337 }
2338
2339 /**
2340  * cxlflash_afu_sync() - builds and sends an AFU sync command
2341  * @afu:        AFU associated with the host.
2342  * @ctx:        Identifies context requesting sync.
2343  * @res:        Identifies resource requesting sync.
2344  * @mode:       Type of sync to issue (lightweight, heavyweight, global).
2345  *
2346  * AFU sync operations are only necessary and allowed when the device is
2347  * operating normally. When not operating normally, sync requests can occur as
2348  * part of cleaning up resources associated with an adapter prior to removal.
2349  * In this scenario, these requests are simply ignored (safe due to the AFU
2350  * going away).
2351  *
2352  * Return:
2353  *      0 on success, -errno on failure
2354  */
2355 int cxlflash_afu_sync(struct afu *afu, ctx_hndl_t ctx, res_hndl_t res, u8 mode)
2356 {
2357         struct cxlflash_cfg *cfg = afu->parent;
2358         struct device *dev = &cfg->dev->dev;
2359         struct sisl_ioarcb rcb = { 0 };
2360
2361         dev_dbg(dev, "%s: afu=%p ctx=%u res=%u mode=%u\n",
2362                 __func__, afu, ctx, res, mode);
2363
2364         rcb.req_flags = SISL_REQ_FLAGS_AFU_CMD;
2365         rcb.msi = SISL_MSI_RRQ_UPDATED;
2366         rcb.timeout = MC_AFU_SYNC_TIMEOUT;
2367
2368         rcb.cdb[0] = SISL_AFU_CMD_SYNC;
2369         rcb.cdb[1] = mode;
2370         put_unaligned_be16(ctx, &rcb.cdb[2]);
2371         put_unaligned_be32(res, &rcb.cdb[4]);
2372
2373         return send_afu_cmd(afu, &rcb);
2374 }
2375
2376 /**
2377  * cxlflash_eh_abort_handler() - abort a SCSI command
2378  * @scp:        SCSI command to abort.
2379  *
2380  * CXL Flash devices do not support a single command abort. Reset the context
2381  * as per SISLite specification. Flush any pending commands in the hardware
2382  * queue before the reset.
2383  *
2384  * Return: SUCCESS/FAILED as defined in scsi/scsi.h
2385  */
2386 static int cxlflash_eh_abort_handler(struct scsi_cmnd *scp)
2387 {
2388         int rc = FAILED;
2389         struct Scsi_Host *host = scp->device->host;
2390         struct cxlflash_cfg *cfg = shost_priv(host);
2391         struct afu_cmd *cmd = sc_to_afuc(scp);
2392         struct device *dev = &cfg->dev->dev;
2393         struct afu *afu = cfg->afu;
2394         struct hwq *hwq = get_hwq(afu, cmd->hwq_index);
2395
2396         dev_dbg(dev, "%s: (scp=%p) %d/%d/%d/%llu "
2397                 "cdb=(%08x-%08x-%08x-%08x)\n", __func__, scp, host->host_no,
2398                 scp->device->channel, scp->device->id, scp->device->lun,
2399                 get_unaligned_be32(&((u32 *)scp->cmnd)[0]),
2400                 get_unaligned_be32(&((u32 *)scp->cmnd)[1]),
2401                 get_unaligned_be32(&((u32 *)scp->cmnd)[2]),
2402                 get_unaligned_be32(&((u32 *)scp->cmnd)[3]));
2403
2404         /* When the state is not normal, another reset/reload is in progress.
2405          * Return failed and the mid-layer will invoke host reset handler.
2406          */
2407         if (cfg->state != STATE_NORMAL) {
2408                 dev_dbg(dev, "%s: Invalid state for abort, state=%d\n",
2409                         __func__, cfg->state);
2410                 goto out;
2411         }
2412
2413         rc = afu->context_reset(hwq);
2414         if (unlikely(rc))
2415                 goto out;
2416
2417         rc = SUCCESS;
2418
2419 out:
2420         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
2421         return rc;
2422 }
2423
2424 /**
2425  * cxlflash_eh_device_reset_handler() - reset a single LUN
2426  * @scp:        SCSI command to send.
2427  *
2428  * Return:
2429  *      SUCCESS as defined in scsi/scsi.h
2430  *      FAILED as defined in scsi/scsi.h
2431  */
2432 static int cxlflash_eh_device_reset_handler(struct scsi_cmnd *scp)
2433 {
2434         int rc = SUCCESS;
2435         struct scsi_device *sdev = scp->device;
2436         struct Scsi_Host *host = sdev->host;
2437         struct cxlflash_cfg *cfg = shost_priv(host);
2438         struct device *dev = &cfg->dev->dev;
2439         int rcr = 0;
2440
2441         dev_dbg(dev, "%s: %d/%d/%d/%llu\n", __func__,
2442                 host->host_no, sdev->channel, sdev->id, sdev->lun);
2443 retry:
2444         switch (cfg->state) {
2445         case STATE_NORMAL:
2446                 rcr = send_tmf(cfg, sdev, TMF_LUN_RESET);
2447                 if (unlikely(rcr))
2448                         rc = FAILED;
2449                 break;
2450         case STATE_RESET:
2451                 wait_event(cfg->reset_waitq, cfg->state != STATE_RESET);
2452                 goto retry;
2453         default:
2454                 rc = FAILED;
2455                 break;
2456         }
2457
2458         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
2459         return rc;
2460 }
2461
2462 /**
2463  * cxlflash_eh_host_reset_handler() - reset the host adapter
2464  * @scp:        SCSI command from stack identifying host.
2465  *
2466  * Following a reset, the state is evaluated again in case an EEH occurred
2467  * during the reset. In such a scenario, the host reset will either yield
2468  * until the EEH recovery is complete or return success or failure based
2469  * upon the current device state.
2470  *
2471  * Return:
2472  *      SUCCESS as defined in scsi/scsi.h
2473  *      FAILED as defined in scsi/scsi.h
2474  */
2475 static int cxlflash_eh_host_reset_handler(struct scsi_cmnd *scp)
2476 {
2477         int rc = SUCCESS;
2478         int rcr = 0;
2479         struct Scsi_Host *host = scp->device->host;
2480         struct cxlflash_cfg *cfg = shost_priv(host);
2481         struct device *dev = &cfg->dev->dev;
2482
2483         dev_dbg(dev, "%s: %d\n", __func__, host->host_no);
2484
2485         switch (cfg->state) {
2486         case STATE_NORMAL:
2487                 cfg->state = STATE_RESET;
2488                 drain_ioctls(cfg);
2489                 cxlflash_mark_contexts_error(cfg);
2490                 rcr = afu_reset(cfg);
2491                 if (rcr) {
2492                         rc = FAILED;
2493                         cfg->state = STATE_FAILTERM;
2494                 } else
2495                         cfg->state = STATE_NORMAL;
2496                 wake_up_all(&cfg->reset_waitq);
2497                 ssleep(1);
2498                 /* fall through */
2499         case STATE_RESET:
2500                 wait_event(cfg->reset_waitq, cfg->state != STATE_RESET);
2501                 if (cfg->state == STATE_NORMAL)
2502                         break;
2503                 /* fall through */
2504         default:
2505                 rc = FAILED;
2506                 break;
2507         }
2508
2509         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
2510         return rc;
2511 }
2512
2513 /**
2514  * cxlflash_change_queue_depth() - change the queue depth for the device
2515  * @sdev:       SCSI device destined for queue depth change.
2516  * @qdepth:     Requested queue depth value to set.
2517  *
2518  * The requested queue depth is capped to the maximum supported value.
2519  *
2520  * Return: The actual queue depth set.
2521  */
2522 static int cxlflash_change_queue_depth(struct scsi_device *sdev, int qdepth)
2523 {
2524
2525         if (qdepth > CXLFLASH_MAX_CMDS_PER_LUN)
2526                 qdepth = CXLFLASH_MAX_CMDS_PER_LUN;
2527
2528         scsi_change_queue_depth(sdev, qdepth);
2529         return sdev->queue_depth;
2530 }
2531
2532 /**
2533  * cxlflash_show_port_status() - queries and presents the current port status
2534  * @port:       Desired port for status reporting.
2535  * @cfg:        Internal structure associated with the host.
2536  * @buf:        Buffer of length PAGE_SIZE to report back port status in ASCII.
2537  *
2538  * Return: The size of the ASCII string returned in @buf or -EINVAL.
2539  */
2540 static ssize_t cxlflash_show_port_status(u32 port,
2541                                          struct cxlflash_cfg *cfg,
2542                                          char *buf)
2543 {
2544         struct device *dev = &cfg->dev->dev;
2545         char *disp_status;
2546         u64 status;
2547         __be64 __iomem *fc_port_regs;
2548
2549         WARN_ON(port >= MAX_FC_PORTS);
2550
2551         if (port >= cfg->num_fc_ports) {
2552                 dev_info(dev, "%s: Port %d not supported on this card.\n",
2553                         __func__, port);
2554                 return -EINVAL;
2555         }
2556
2557         fc_port_regs = get_fc_port_regs(cfg, port);
2558         status = readq_be(&fc_port_regs[FC_MTIP_STATUS / 8]);
2559         status &= FC_MTIP_STATUS_MASK;
2560
2561         if (status == FC_MTIP_STATUS_ONLINE)
2562                 disp_status = "online";
2563         else if (status == FC_MTIP_STATUS_OFFLINE)
2564                 disp_status = "offline";
2565         else
2566                 disp_status = "unknown";
2567
2568         return scnprintf(buf, PAGE_SIZE, "%s\n", disp_status);
2569 }
2570
2571 /**
2572  * port0_show() - queries and presents the current status of port 0
2573  * @dev:        Generic device associated with the host owning the port.
2574  * @attr:       Device attribute representing the port.
2575  * @buf:        Buffer of length PAGE_SIZE to report back port status in ASCII.
2576  *
2577  * Return: The size of the ASCII string returned in @buf.
2578  */
2579 static ssize_t port0_show(struct device *dev,
2580                           struct device_attribute *attr,
2581                           char *buf)
2582 {
2583         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
2584
2585         return cxlflash_show_port_status(0, cfg, buf);
2586 }
2587
2588 /**
2589  * port1_show() - queries and presents the current status of port 1
2590  * @dev:        Generic device associated with the host owning the port.
2591  * @attr:       Device attribute representing the port.
2592  * @buf:        Buffer of length PAGE_SIZE to report back port status in ASCII.
2593  *
2594  * Return: The size of the ASCII string returned in @buf.
2595  */
2596 static ssize_t port1_show(struct device *dev,
2597                           struct device_attribute *attr,
2598                           char *buf)
2599 {
2600         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
2601
2602         return cxlflash_show_port_status(1, cfg, buf);
2603 }
2604
2605 /**
2606  * port2_show() - queries and presents the current status of port 2
2607  * @dev:        Generic device associated with the host owning the port.
2608  * @attr:       Device attribute representing the port.
2609  * @buf:        Buffer of length PAGE_SIZE to report back port status in ASCII.
2610  *
2611  * Return: The size of the ASCII string returned in @buf.
2612  */
2613 static ssize_t port2_show(struct device *dev,
2614                           struct device_attribute *attr,
2615                           char *buf)
2616 {
2617         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
2618
2619         return cxlflash_show_port_status(2, cfg, buf);
2620 }
2621
2622 /**
2623  * port3_show() - queries and presents the current status of port 3
2624  * @dev:        Generic device associated with the host owning the port.
2625  * @attr:       Device attribute representing the port.
2626  * @buf:        Buffer of length PAGE_SIZE to report back port status in ASCII.
2627  *
2628  * Return: The size of the ASCII string returned in @buf.
2629  */
2630 static ssize_t port3_show(struct device *dev,
2631                           struct device_attribute *attr,
2632                           char *buf)
2633 {
2634         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
2635
2636         return cxlflash_show_port_status(3, cfg, buf);
2637 }
2638
2639 /**
2640  * lun_mode_show() - presents the current LUN mode of the host
2641  * @dev:        Generic device associated with the host.
2642  * @attr:       Device attribute representing the LUN mode.
2643  * @buf:        Buffer of length PAGE_SIZE to report back the LUN mode in ASCII.
2644  *
2645  * Return: The size of the ASCII string returned in @buf.
2646  */
2647 static ssize_t lun_mode_show(struct device *dev,
2648                              struct device_attribute *attr, char *buf)
2649 {
2650         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
2651         struct afu *afu = cfg->afu;
2652
2653         return scnprintf(buf, PAGE_SIZE, "%u\n", afu->internal_lun);
2654 }
2655
2656 /**
2657  * lun_mode_store() - sets the LUN mode of the host
2658  * @dev:        Generic device associated with the host.
2659  * @attr:       Device attribute representing the LUN mode.
2660  * @buf:        Buffer of length PAGE_SIZE containing the LUN mode in ASCII.
2661  * @count:      Length of data resizing in @buf.
2662  *
2663  * The CXL Flash AFU supports a dummy LUN mode where the external
2664  * links and storage are not required. Space on the FPGA is used
2665  * to create 1 or 2 small LUNs which are presented to the system
2666  * as if they were a normal storage device. This feature is useful
2667  * during development and also provides manufacturing with a way
2668  * to test the AFU without an actual device.
2669  *
2670  * 0 = external LUN[s] (default)
2671  * 1 = internal LUN (1 x 64K, 512B blocks, id 0)
2672  * 2 = internal LUN (1 x 64K, 4K blocks, id 0)
2673  * 3 = internal LUN (2 x 32K, 512B blocks, ids 0,1)
2674  * 4 = internal LUN (2 x 32K, 4K blocks, ids 0,1)
2675  *
2676  * Return: The size of the ASCII string returned in @buf.
2677  */
2678 static ssize_t lun_mode_store(struct device *dev,
2679                               struct device_attribute *attr,
2680                               const char *buf, size_t count)
2681 {
2682         struct Scsi_Host *shost = class_to_shost(dev);
2683         struct cxlflash_cfg *cfg = shost_priv(shost);
2684         struct afu *afu = cfg->afu;
2685         int rc;
2686         u32 lun_mode;
2687
2688         rc = kstrtouint(buf, 10, &lun_mode);
2689         if (!rc && (lun_mode < 5) && (lun_mode != afu->internal_lun)) {
2690                 afu->internal_lun = lun_mode;
2691
2692                 /*
2693                  * When configured for internal LUN, there is only one channel,
2694                  * channel number 0, else there will be one less than the number
2695                  * of fc ports for this card.
2696                  */
2697                 if (afu->internal_lun)
2698                         shost->max_channel = 0;
2699                 else
2700                         shost->max_channel = PORTNUM2CHAN(cfg->num_fc_ports);
2701
2702                 afu_reset(cfg);
2703                 scsi_scan_host(cfg->host);
2704         }
2705
2706         return count;
2707 }
2708
2709 /**
2710  * ioctl_version_show() - presents the current ioctl version of the host
2711  * @dev:        Generic device associated with the host.
2712  * @attr:       Device attribute representing the ioctl version.
2713  * @buf:        Buffer of length PAGE_SIZE to report back the ioctl version.
2714  *
2715  * Return: The size of the ASCII string returned in @buf.
2716  */
2717 static ssize_t ioctl_version_show(struct device *dev,
2718                                   struct device_attribute *attr, char *buf)
2719 {
2720         ssize_t bytes = 0;
2721
2722         bytes = scnprintf(buf, PAGE_SIZE,
2723                           "disk: %u\n", DK_CXLFLASH_VERSION_0);
2724         bytes += scnprintf(buf + bytes, PAGE_SIZE - bytes,
2725                            "host: %u\n", HT_CXLFLASH_VERSION_0);
2726
2727         return bytes;
2728 }
2729
2730 /**
2731  * cxlflash_show_port_lun_table() - queries and presents the port LUN table
2732  * @port:       Desired port for status reporting.
2733  * @cfg:        Internal structure associated with the host.
2734  * @buf:        Buffer of length PAGE_SIZE to report back port status in ASCII.
2735  *
2736  * Return: The size of the ASCII string returned in @buf or -EINVAL.
2737  */
2738 static ssize_t cxlflash_show_port_lun_table(u32 port,
2739                                             struct cxlflash_cfg *cfg,
2740                                             char *buf)
2741 {
2742         struct device *dev = &cfg->dev->dev;
2743         __be64 __iomem *fc_port_luns;
2744         int i;
2745         ssize_t bytes = 0;
2746
2747         WARN_ON(port >= MAX_FC_PORTS);
2748
2749         if (port >= cfg->num_fc_ports) {
2750                 dev_info(dev, "%s: Port %d not supported on this card.\n",
2751                         __func__, port);
2752                 return -EINVAL;
2753         }
2754
2755         fc_port_luns = get_fc_port_luns(cfg, port);
2756
2757         for (i = 0; i < CXLFLASH_NUM_VLUNS; i++)
2758                 bytes += scnprintf(buf + bytes, PAGE_SIZE - bytes,
2759                                    "%03d: %016llx\n",
2760                                    i, readq_be(&fc_port_luns[i]));
2761         return bytes;
2762 }
2763
2764 /**
2765  * port0_lun_table_show() - presents the current LUN table of port 0
2766  * @dev:        Generic device associated with the host owning the port.
2767  * @attr:       Device attribute representing the port.
2768  * @buf:        Buffer of length PAGE_SIZE to report back port status in ASCII.
2769  *
2770  * Return: The size of the ASCII string returned in @buf.
2771  */
2772 static ssize_t port0_lun_table_show(struct device *dev,
2773                                     struct device_attribute *attr,
2774                                     char *buf)
2775 {
2776         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
2777
2778         return cxlflash_show_port_lun_table(0, cfg, buf);
2779 }
2780
2781 /**
2782  * port1_lun_table_show() - presents the current LUN table of port 1
2783  * @dev:        Generic device associated with the host owning the port.
2784  * @attr:       Device attribute representing the port.
2785  * @buf:        Buffer of length PAGE_SIZE to report back port status in ASCII.
2786  *
2787  * Return: The size of the ASCII string returned in @buf.
2788  */
2789 static ssize_t port1_lun_table_show(struct device *dev,
2790                                     struct device_attribute *attr,
2791                                     char *buf)
2792 {
2793         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
2794
2795         return cxlflash_show_port_lun_table(1, cfg, buf);
2796 }
2797
2798 /**
2799  * port2_lun_table_show() - presents the current LUN table of port 2
2800  * @dev:        Generic device associated with the host owning the port.
2801  * @attr:       Device attribute representing the port.
2802  * @buf:        Buffer of length PAGE_SIZE to report back port status in ASCII.
2803  *
2804  * Return: The size of the ASCII string returned in @buf.
2805  */
2806 static ssize_t port2_lun_table_show(struct device *dev,
2807                                     struct device_attribute *attr,
2808                                     char *buf)
2809 {
2810         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
2811
2812         return cxlflash_show_port_lun_table(2, cfg, buf);
2813 }
2814
2815 /**
2816  * port3_lun_table_show() - presents the current LUN table of port 3
2817  * @dev:        Generic device associated with the host owning the port.
2818  * @attr:       Device attribute representing the port.
2819  * @buf:        Buffer of length PAGE_SIZE to report back port status in ASCII.
2820  *
2821  * Return: The size of the ASCII string returned in @buf.
2822  */
2823 static ssize_t port3_lun_table_show(struct device *dev,
2824                                     struct device_attribute *attr,
2825                                     char *buf)
2826 {
2827         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
2828
2829         return cxlflash_show_port_lun_table(3, cfg, buf);
2830 }
2831
2832 /**
2833  * irqpoll_weight_show() - presents the current IRQ poll weight for the host
2834  * @dev:        Generic device associated with the host.
2835  * @attr:       Device attribute representing the IRQ poll weight.
2836  * @buf:        Buffer of length PAGE_SIZE to report back the current IRQ poll
2837  *              weight in ASCII.
2838  *
2839  * An IRQ poll weight of 0 indicates polling is disabled.
2840  *
2841  * Return: The size of the ASCII string returned in @buf.
2842  */
2843 static ssize_t irqpoll_weight_show(struct device *dev,
2844                                    struct device_attribute *attr, char *buf)
2845 {
2846         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
2847         struct afu *afu = cfg->afu;
2848
2849         return scnprintf(buf, PAGE_SIZE, "%u\n", afu->irqpoll_weight);
2850 }
2851
2852 /**
2853  * irqpoll_weight_store() - sets the current IRQ poll weight for the host
2854  * @dev:        Generic device associated with the host.
2855  * @attr:       Device attribute representing the IRQ poll weight.
2856  * @buf:        Buffer of length PAGE_SIZE containing the desired IRQ poll
2857  *              weight in ASCII.
2858  * @count:      Length of data resizing in @buf.
2859  *
2860  * An IRQ poll weight of 0 indicates polling is disabled.
2861  *
2862  * Return: The size of the ASCII string returned in @buf.
2863  */
2864 static ssize_t irqpoll_weight_store(struct device *dev,
2865                                     struct device_attribute *attr,
2866                                     const char *buf, size_t count)
2867 {
2868         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
2869         struct device *cfgdev = &cfg->dev->dev;
2870         struct afu *afu = cfg->afu;
2871         struct hwq *hwq;
2872         u32 weight;
2873         int rc, i;
2874
2875         rc = kstrtouint(buf, 10, &weight);
2876         if (rc)
2877                 return -EINVAL;
2878
2879         if (weight > 256) {
2880                 dev_info(cfgdev,
2881                          "Invalid IRQ poll weight. It must be 256 or less.\n");
2882                 return -EINVAL;
2883         }
2884
2885         if (weight == afu->irqpoll_weight) {
2886                 dev_info(cfgdev,
2887                          "Current IRQ poll weight has the same weight.\n");
2888                 return -EINVAL;
2889         }
2890
2891         if (afu_is_irqpoll_enabled(afu)) {
2892                 for (i = 0; i < afu->num_hwqs; i++) {
2893                         hwq = get_hwq(afu, i);
2894
2895                         irq_poll_disable(&hwq->irqpoll);
2896                 }
2897         }
2898
2899         afu->irqpoll_weight = weight;
2900
2901         if (weight > 0) {
2902                 for (i = 0; i < afu->num_hwqs; i++) {
2903                         hwq = get_hwq(afu, i);
2904
2905                         irq_poll_init(&hwq->irqpoll, weight, cxlflash_irqpoll);
2906                 }
2907         }
2908
2909         return count;
2910 }
2911
2912 /**
2913  * num_hwqs_show() - presents the number of hardware queues for the host
2914  * @dev:        Generic device associated with the host.
2915  * @attr:       Device attribute representing the number of hardware queues.
2916  * @buf:        Buffer of length PAGE_SIZE to report back the number of hardware
2917  *              queues in ASCII.
2918  *
2919  * Return: The size of the ASCII string returned in @buf.
2920  */
2921 static ssize_t num_hwqs_show(struct device *dev,
2922                              struct device_attribute *attr, char *buf)
2923 {
2924         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
2925         struct afu *afu = cfg->afu;
2926
2927         return scnprintf(buf, PAGE_SIZE, "%u\n", afu->num_hwqs);
2928 }
2929
2930 /**
2931  * num_hwqs_store() - sets the number of hardware queues for the host
2932  * @dev:        Generic device associated with the host.
2933  * @attr:       Device attribute representing the number of hardware queues.
2934  * @buf:        Buffer of length PAGE_SIZE containing the number of hardware
2935  *              queues in ASCII.
2936  * @count:      Length of data resizing in @buf.
2937  *
2938  * n > 0: num_hwqs = n
2939  * n = 0: num_hwqs = num_online_cpus()
2940  * n < 0: num_online_cpus() / abs(n)
2941  *
2942  * Return: The size of the ASCII string returned in @buf.
2943  */
2944 static ssize_t num_hwqs_store(struct device *dev,
2945                               struct device_attribute *attr,
2946                               const char *buf, size_t count)
2947 {
2948         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
2949         struct afu *afu = cfg->afu;
2950         int rc;
2951         int nhwqs, num_hwqs;
2952
2953         rc = kstrtoint(buf, 10, &nhwqs);
2954         if (rc)
2955                 return -EINVAL;
2956
2957         if (nhwqs >= 1)
2958                 num_hwqs = nhwqs;
2959         else if (nhwqs == 0)
2960                 num_hwqs = num_online_cpus();
2961         else
2962                 num_hwqs = num_online_cpus() / abs(nhwqs);
2963
2964         afu->desired_hwqs = min(num_hwqs, CXLFLASH_MAX_HWQS);
2965         WARN_ON_ONCE(afu->desired_hwqs == 0);
2966
2967 retry:
2968         switch (cfg->state) {
2969         case STATE_NORMAL:
2970                 cfg->state = STATE_RESET;
2971                 drain_ioctls(cfg);
2972                 cxlflash_mark_contexts_error(cfg);
2973                 rc = afu_reset(cfg);
2974                 if (rc)
2975                         cfg->state = STATE_FAILTERM;
2976                 else
2977                         cfg->state = STATE_NORMAL;
2978                 wake_up_all(&cfg->reset_waitq);
2979                 break;
2980         case STATE_RESET:
2981                 wait_event(cfg->reset_waitq, cfg->state != STATE_RESET);
2982                 if (cfg->state == STATE_NORMAL)
2983                         goto retry;
2984         default:
2985                 /* Ideally should not happen */
2986                 dev_err(dev, "%s: Device is not ready, state=%d\n",
2987                         __func__, cfg->state);
2988                 break;
2989         }
2990
2991         return count;
2992 }
2993
2994 static const char *hwq_mode_name[MAX_HWQ_MODE] = { "rr", "tag", "cpu" };
2995
2996 /**
2997  * hwq_mode_show() - presents the HWQ steering mode for the host
2998  * @dev:        Generic device associated with the host.
2999  * @attr:       Device attribute representing the HWQ steering mode.
3000  * @buf:        Buffer of length PAGE_SIZE to report back the HWQ steering mode
3001  *              as a character string.
3002  *
3003  * Return: The size of the ASCII string returned in @buf.
3004  */
3005 static ssize_t hwq_mode_show(struct device *dev,
3006                              struct device_attribute *attr, char *buf)
3007 {
3008         struct cxlflash_cfg *cfg = shost_priv(class_to_shost(dev));
3009         struct afu *afu = cfg->afu;
3010
3011         return scnprintf(buf, PAGE_SIZE, "%s\n", hwq_mode_name[afu->hwq_mode]);
3012 }
3013
3014 /**
3015  * hwq_mode_store() - sets the HWQ steering mode for the host
3016  * @dev:        Generic device associated with the host.
3017  * @attr:       Device attribute representing the HWQ steering mode.
3018  * @buf:        Buffer of length PAGE_SIZE containing the HWQ steering mode
3019  *              as a character string.
3020  * @count:      Length of data resizing in @buf.
3021  *
3022  * rr = Round-Robin
3023  * tag = Block MQ Tagging
3024  * cpu = CPU Affinity
3025  *
3026  * Return: The size of the ASCII string returned in @buf.
3027  */
3028 static ssize_t hwq_mode_store(struct device *dev,
3029                               struct device_attribute *attr,
3030                               const char *buf, size_t count)
3031 {
3032         struct Scsi_Host *shost = class_to_shost(dev);
3033         struct cxlflash_cfg *cfg = shost_priv(shost);
3034         struct device *cfgdev = &cfg->dev->dev;
3035         struct afu *afu = cfg->afu;
3036         int i;
3037         u32 mode = MAX_HWQ_MODE;
3038
3039         for (i = 0; i < MAX_HWQ_MODE; i++) {
3040                 if (!strncmp(hwq_mode_name[i], buf, strlen(hwq_mode_name[i]))) {
3041                         mode = i;
3042                         break;
3043                 }
3044         }
3045
3046         if (mode >= MAX_HWQ_MODE) {
3047                 dev_info(cfgdev, "Invalid HWQ steering mode.\n");
3048                 return -EINVAL;
3049         }
3050
3051         if ((mode == HWQ_MODE_TAG) && !shost_use_blk_mq(shost)) {
3052                 dev_info(cfgdev, "SCSI-MQ is not enabled, use a different "
3053                          "HWQ steering mode.\n");
3054                 return -EINVAL;
3055         }
3056
3057         afu->hwq_mode = mode;
3058
3059         return count;
3060 }
3061
3062 /**
3063  * mode_show() - presents the current mode of the device
3064  * @dev:        Generic device associated with the device.
3065  * @attr:       Device attribute representing the device mode.
3066  * @buf:        Buffer of length PAGE_SIZE to report back the dev mode in ASCII.
3067  *
3068  * Return: The size of the ASCII string returned in @buf.
3069  */
3070 static ssize_t mode_show(struct device *dev,
3071                          struct device_attribute *attr, char *buf)
3072 {
3073         struct scsi_device *sdev = to_scsi_device(dev);
3074
3075         return scnprintf(buf, PAGE_SIZE, "%s\n",
3076                          sdev->hostdata ? "superpipe" : "legacy");
3077 }
3078
3079 /*
3080  * Host attributes
3081  */
3082 static DEVICE_ATTR_RO(port0);
3083 static DEVICE_ATTR_RO(port1);
3084 static DEVICE_ATTR_RO(port2);
3085 static DEVICE_ATTR_RO(port3);
3086 static DEVICE_ATTR_RW(lun_mode);
3087 static DEVICE_ATTR_RO(ioctl_version);
3088 static DEVICE_ATTR_RO(port0_lun_table);
3089 static DEVICE_ATTR_RO(port1_lun_table);
3090 static DEVICE_ATTR_RO(port2_lun_table);
3091 static DEVICE_ATTR_RO(port3_lun_table);
3092 static DEVICE_ATTR_RW(irqpoll_weight);
3093 static DEVICE_ATTR_RW(num_hwqs);
3094 static DEVICE_ATTR_RW(hwq_mode);
3095
3096 static struct device_attribute *cxlflash_host_attrs[] = {
3097         &dev_attr_port0,
3098         &dev_attr_port1,
3099         &dev_attr_port2,
3100         &dev_attr_port3,
3101         &dev_attr_lun_mode,
3102         &dev_attr_ioctl_version,
3103         &dev_attr_port0_lun_table,
3104         &dev_attr_port1_lun_table,
3105         &dev_attr_port2_lun_table,
3106         &dev_attr_port3_lun_table,
3107         &dev_attr_irqpoll_weight,
3108         &dev_attr_num_hwqs,
3109         &dev_attr_hwq_mode,
3110         NULL
3111 };
3112
3113 /*
3114  * Device attributes
3115  */
3116 static DEVICE_ATTR_RO(mode);
3117
3118 static struct device_attribute *cxlflash_dev_attrs[] = {
3119         &dev_attr_mode,
3120         NULL
3121 };
3122
3123 /*
3124  * Host template
3125  */
3126 static struct scsi_host_template driver_template = {
3127         .module = THIS_MODULE,
3128         .name = CXLFLASH_ADAPTER_NAME,
3129         .info = cxlflash_driver_info,
3130         .ioctl = cxlflash_ioctl,
3131         .proc_name = CXLFLASH_NAME,
3132         .queuecommand = cxlflash_queuecommand,
3133         .eh_abort_handler = cxlflash_eh_abort_handler,
3134         .eh_device_reset_handler = cxlflash_eh_device_reset_handler,
3135         .eh_host_reset_handler = cxlflash_eh_host_reset_handler,
3136         .change_queue_depth = cxlflash_change_queue_depth,
3137         .cmd_per_lun = CXLFLASH_MAX_CMDS_PER_LUN,
3138         .can_queue = CXLFLASH_MAX_CMDS,
3139         .cmd_size = sizeof(struct afu_cmd) + __alignof__(struct afu_cmd) - 1,
3140         .this_id = -1,
3141         .sg_tablesize = 1,      /* No scatter gather support */
3142         .max_sectors = CXLFLASH_MAX_SECTORS,
3143         .use_clustering = ENABLE_CLUSTERING,
3144         .shost_attrs = cxlflash_host_attrs,
3145         .sdev_attrs = cxlflash_dev_attrs,
3146 };
3147
3148 /*
3149  * Device dependent values
3150  */
3151 static struct dev_dependent_vals dev_corsa_vals = { CXLFLASH_MAX_SECTORS,
3152                                         0ULL };
3153 static struct dev_dependent_vals dev_flash_gt_vals = { CXLFLASH_MAX_SECTORS,
3154                                         CXLFLASH_NOTIFY_SHUTDOWN };
3155 static struct dev_dependent_vals dev_briard_vals = { CXLFLASH_MAX_SECTORS,
3156                                         CXLFLASH_NOTIFY_SHUTDOWN };
3157
3158 /*
3159  * PCI device binding table
3160  */
3161 static struct pci_device_id cxlflash_pci_table[] = {
3162         {PCI_VENDOR_ID_IBM, PCI_DEVICE_ID_IBM_CORSA,
3163          PCI_ANY_ID, PCI_ANY_ID, 0, 0, (kernel_ulong_t)&dev_corsa_vals},
3164         {PCI_VENDOR_ID_IBM, PCI_DEVICE_ID_IBM_FLASH_GT,
3165          PCI_ANY_ID, PCI_ANY_ID, 0, 0, (kernel_ulong_t)&dev_flash_gt_vals},
3166         {PCI_VENDOR_ID_IBM, PCI_DEVICE_ID_IBM_BRIARD,
3167          PCI_ANY_ID, PCI_ANY_ID, 0, 0, (kernel_ulong_t)&dev_briard_vals},
3168         {}
3169 };
3170
3171 MODULE_DEVICE_TABLE(pci, cxlflash_pci_table);
3172
3173 /**
3174  * cxlflash_worker_thread() - work thread handler for the AFU
3175  * @work:       Work structure contained within cxlflash associated with host.
3176  *
3177  * Handles the following events:
3178  * - Link reset which cannot be performed on interrupt context due to
3179  * blocking up to a few seconds
3180  * - Rescan the host
3181  */
3182 static void cxlflash_worker_thread(struct work_struct *work)
3183 {
3184         struct cxlflash_cfg *cfg = container_of(work, struct cxlflash_cfg,
3185                                                 work_q);
3186         struct afu *afu = cfg->afu;
3187         struct device *dev = &cfg->dev->dev;
3188         __be64 __iomem *fc_port_regs;
3189         int port;
3190         ulong lock_flags;
3191
3192         /* Avoid MMIO if the device has failed */
3193
3194         if (cfg->state != STATE_NORMAL)
3195                 return;
3196
3197         spin_lock_irqsave(cfg->host->host_lock, lock_flags);
3198
3199         if (cfg->lr_state == LINK_RESET_REQUIRED) {
3200                 port = cfg->lr_port;
3201                 if (port < 0)
3202                         dev_err(dev, "%s: invalid port index %d\n",
3203                                 __func__, port);
3204                 else {
3205                         spin_unlock_irqrestore(cfg->host->host_lock,
3206                                                lock_flags);
3207
3208                         /* The reset can block... */
3209                         fc_port_regs = get_fc_port_regs(cfg, port);
3210                         afu_link_reset(afu, port, fc_port_regs);
3211                         spin_lock_irqsave(cfg->host->host_lock, lock_flags);
3212                 }
3213
3214                 cfg->lr_state = LINK_RESET_COMPLETE;
3215         }
3216
3217         spin_unlock_irqrestore(cfg->host->host_lock, lock_flags);
3218
3219         if (atomic_dec_if_positive(&cfg->scan_host_needed) >= 0)
3220                 scsi_scan_host(cfg->host);
3221 }
3222
3223 /**
3224  * cxlflash_chr_open() - character device open handler
3225  * @inode:      Device inode associated with this character device.
3226  * @file:       File pointer for this device.
3227  *
3228  * Only users with admin privileges are allowed to open the character device.
3229  *
3230  * Return: 0 on success, -errno on failure
3231  */
3232 static int cxlflash_chr_open(struct inode *inode, struct file *file)
3233 {
3234         struct cxlflash_cfg *cfg;
3235
3236         if (!capable(CAP_SYS_ADMIN))
3237                 return -EACCES;
3238
3239         cfg = container_of(inode->i_cdev, struct cxlflash_cfg, cdev);
3240         file->private_data = cfg;
3241
3242         return 0;
3243 }
3244
3245 /**
3246  * decode_hioctl() - translates encoded host ioctl to easily identifiable string
3247  * @cmd:        The host ioctl command to decode.
3248  *
3249  * Return: A string identifying the decoded host ioctl.
3250  */
3251 static char *decode_hioctl(int cmd)
3252 {
3253         switch (cmd) {
3254         case HT_CXLFLASH_LUN_PROVISION:
3255                 return __stringify_1(HT_CXLFLASH_LUN_PROVISION);
3256         }
3257
3258         return "UNKNOWN";
3259 }
3260
3261 /**
3262  * cxlflash_lun_provision() - host LUN provisioning handler
3263  * @cfg:        Internal structure associated with the host.
3264  * @arg:        Kernel copy of userspace ioctl data structure.
3265  *
3266  * Return: 0 on success, -errno on failure
3267  */
3268 static int cxlflash_lun_provision(struct cxlflash_cfg *cfg,
3269                                   struct ht_cxlflash_lun_provision *lunprov)
3270 {
3271         struct afu *afu = cfg->afu;
3272         struct device *dev = &cfg->dev->dev;
3273         struct sisl_ioarcb rcb;
3274         struct sisl_ioasa asa;
3275         __be64 __iomem *fc_port_regs;
3276         u16 port = lunprov->port;
3277         u16 scmd = lunprov->hdr.subcmd;
3278         u16 type;
3279         u64 reg;
3280         u64 size;
3281         u64 lun_id;
3282         int rc = 0;
3283
3284         if (!afu_is_lun_provision(afu)) {
3285                 rc = -ENOTSUPP;
3286                 goto out;
3287         }
3288
3289         if (port >= cfg->num_fc_ports) {
3290                 rc = -EINVAL;
3291                 goto out;
3292         }
3293
3294         switch (scmd) {
3295         case HT_CXLFLASH_LUN_PROVISION_SUBCMD_CREATE_LUN:
3296                 type = SISL_AFU_LUN_PROVISION_CREATE;
3297                 size = lunprov->size;
3298                 lun_id = 0;
3299                 break;
3300         case HT_CXLFLASH_LUN_PROVISION_SUBCMD_DELETE_LUN:
3301                 type = SISL_AFU_LUN_PROVISION_DELETE;
3302                 size = 0;
3303                 lun_id = lunprov->lun_id;
3304                 break;
3305         case HT_CXLFLASH_LUN_PROVISION_SUBCMD_QUERY_PORT:
3306                 fc_port_regs = get_fc_port_regs(cfg, port);
3307
3308                 reg = readq_be(&fc_port_regs[FC_MAX_NUM_LUNS / 8]);
3309                 lunprov->max_num_luns = reg;
3310                 reg = readq_be(&fc_port_regs[FC_CUR_NUM_LUNS / 8]);
3311                 lunprov->cur_num_luns = reg;
3312                 reg = readq_be(&fc_port_regs[FC_MAX_CAP_PORT / 8]);
3313                 lunprov->max_cap_port = reg;
3314                 reg = readq_be(&fc_port_regs[FC_CUR_CAP_PORT / 8]);
3315                 lunprov->cur_cap_port = reg;
3316
3317                 goto out;
3318         default:
3319                 rc = -EINVAL;
3320                 goto out;
3321         }
3322
3323         memset(&rcb, 0, sizeof(rcb));
3324         memset(&asa, 0, sizeof(asa));
3325         rcb.req_flags = SISL_REQ_FLAGS_AFU_CMD;
3326         rcb.lun_id = lun_id;
3327         rcb.msi = SISL_MSI_RRQ_UPDATED;
3328         rcb.timeout = MC_LUN_PROV_TIMEOUT;
3329         rcb.ioasa = &asa;
3330
3331         rcb.cdb[0] = SISL_AFU_CMD_LUN_PROVISION;
3332         rcb.cdb[1] = type;
3333         rcb.cdb[2] = port;
3334         put_unaligned_be64(size, &rcb.cdb[8]);
3335
3336         rc = send_afu_cmd(afu, &rcb);
3337         if (rc) {
3338                 dev_err(dev, "%s: send_afu_cmd failed rc=%d asc=%08x afux=%x\n",
3339                         __func__, rc, asa.ioasc, asa.afu_extra);
3340                 goto out;
3341         }
3342
3343         if (scmd == HT_CXLFLASH_LUN_PROVISION_SUBCMD_CREATE_LUN) {
3344                 lunprov->lun_id = (u64)asa.lunid_hi << 32 | asa.lunid_lo;
3345                 memcpy(lunprov->wwid, asa.wwid, sizeof(lunprov->wwid));
3346         }
3347 out:
3348         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
3349         return rc;
3350 }
3351
3352 /**
3353  * cxlflash_afu_debug() - host AFU debug handler
3354  * @cfg:        Internal structure associated with the host.
3355  * @arg:        Kernel copy of userspace ioctl data structure.
3356  *
3357  * For debug requests requiring a data buffer, always provide an aligned
3358  * (cache line) buffer to the AFU to appease any alignment requirements.
3359  *
3360  * Return: 0 on success, -errno on failure
3361  */
3362 static int cxlflash_afu_debug(struct cxlflash_cfg *cfg,
3363                               struct ht_cxlflash_afu_debug *afu_dbg)
3364 {
3365         struct afu *afu = cfg->afu;
3366         struct device *dev = &cfg->dev->dev;
3367         struct sisl_ioarcb rcb;
3368         struct sisl_ioasa asa;
3369         char *buf = NULL;
3370         char *kbuf = NULL;
3371         void __user *ubuf = (__force void __user *)afu_dbg->data_ea;
3372         u16 req_flags = SISL_REQ_FLAGS_AFU_CMD;
3373         u32 ulen = afu_dbg->data_len;
3374         bool is_write = afu_dbg->hdr.flags & HT_CXLFLASH_HOST_WRITE;
3375         int rc = 0;
3376
3377         if (!afu_is_afu_debug(afu)) {
3378                 rc = -ENOTSUPP;
3379                 goto out;
3380         }
3381
3382         if (ulen) {
3383                 req_flags |= SISL_REQ_FLAGS_SUP_UNDERRUN;
3384
3385                 if (ulen > HT_CXLFLASH_AFU_DEBUG_MAX_DATA_LEN) {
3386                         rc = -EINVAL;
3387                         goto out;
3388                 }
3389
3390                 if (unlikely(!access_ok(is_write ? VERIFY_READ : VERIFY_WRITE,
3391                                         ubuf, ulen))) {
3392                         rc = -EFAULT;
3393                         goto out;
3394                 }
3395
3396                 buf = kmalloc(ulen + cache_line_size() - 1, GFP_KERNEL);
3397                 if (unlikely(!buf)) {
3398                         rc = -ENOMEM;
3399                         goto out;
3400                 }
3401
3402                 kbuf = PTR_ALIGN(buf, cache_line_size());
3403
3404                 if (is_write) {
3405                         req_flags |= SISL_REQ_FLAGS_HOST_WRITE;
3406
3407                         if (copy_from_user(kbuf, ubuf, ulen)) {
3408                                 rc = -EFAULT;
3409                                 goto out;
3410                         }
3411                 }
3412         }
3413
3414         memset(&rcb, 0, sizeof(rcb));
3415         memset(&asa, 0, sizeof(asa));
3416
3417         rcb.req_flags = req_flags;
3418         rcb.msi = SISL_MSI_RRQ_UPDATED;
3419         rcb.timeout = MC_AFU_DEBUG_TIMEOUT;
3420         rcb.ioasa = &asa;
3421
3422         if (ulen) {
3423                 rcb.data_len = ulen;
3424                 rcb.data_ea = (uintptr_t)kbuf;
3425         }
3426
3427         rcb.cdb[0] = SISL_AFU_CMD_DEBUG;
3428         memcpy(&rcb.cdb[4], afu_dbg->afu_subcmd,
3429                HT_CXLFLASH_AFU_DEBUG_SUBCMD_LEN);
3430
3431         rc = send_afu_cmd(afu, &rcb);
3432         if (rc) {
3433                 dev_err(dev, "%s: send_afu_cmd failed rc=%d asc=%08x afux=%x\n",
3434                         __func__, rc, asa.ioasc, asa.afu_extra);
3435                 goto out;
3436         }
3437
3438         if (ulen && !is_write) {
3439                 if (copy_to_user(ubuf, kbuf, ulen))
3440                         rc = -EFAULT;
3441         }
3442 out:
3443         kfree(buf);
3444         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
3445         return rc;
3446 }
3447
3448 /**
3449  * cxlflash_chr_ioctl() - character device IOCTL handler
3450  * @file:       File pointer for this device.
3451  * @cmd:        IOCTL command.
3452  * @arg:        Userspace ioctl data structure.
3453  *
3454  * A read/write semaphore is used to implement a 'drain' of currently
3455  * running ioctls. The read semaphore is taken at the beginning of each
3456  * ioctl thread and released upon concluding execution. Additionally the
3457  * semaphore should be released and then reacquired in any ioctl execution
3458  * path which will wait for an event to occur that is outside the scope of
3459  * the ioctl (i.e. an adapter reset). To drain the ioctls currently running,
3460  * a thread simply needs to acquire the write semaphore.
3461  *
3462  * Return: 0 on success, -errno on failure
3463  */
3464 static long cxlflash_chr_ioctl(struct file *file, unsigned int cmd,
3465                                unsigned long arg)
3466 {
3467         typedef int (*hioctl) (struct cxlflash_cfg *, void *);
3468
3469         struct cxlflash_cfg *cfg = file->private_data;
3470         struct device *dev = &cfg->dev->dev;
3471         char buf[sizeof(union cxlflash_ht_ioctls)];
3472         void __user *uarg = (void __user *)arg;
3473         struct ht_cxlflash_hdr *hdr;
3474         size_t size = 0;
3475         bool known_ioctl = false;
3476         int idx = 0;
3477         int rc = 0;
3478         hioctl do_ioctl = NULL;
3479
3480         static const struct {
3481                 size_t size;
3482                 hioctl ioctl;
3483         } ioctl_tbl[] = {       /* NOTE: order matters here */
3484         { sizeof(struct ht_cxlflash_lun_provision),
3485                 (hioctl)cxlflash_lun_provision },
3486         { sizeof(struct ht_cxlflash_afu_debug),
3487                 (hioctl)cxlflash_afu_debug },
3488         };
3489
3490         /* Hold read semaphore so we can drain if needed */
3491         down_read(&cfg->ioctl_rwsem);
3492
3493         dev_dbg(dev, "%s: cmd=%u idx=%d tbl_size=%lu\n",
3494                 __func__, cmd, idx, sizeof(ioctl_tbl));
3495
3496         switch (cmd) {
3497         case HT_CXLFLASH_LUN_PROVISION:
3498         case HT_CXLFLASH_AFU_DEBUG:
3499                 known_ioctl = true;
3500                 idx = _IOC_NR(HT_CXLFLASH_LUN_PROVISION) - _IOC_NR(cmd);
3501                 size = ioctl_tbl[idx].size;
3502                 do_ioctl = ioctl_tbl[idx].ioctl;
3503
3504                 if (likely(do_ioctl))
3505                         break;
3506
3507                 /* fall through */
3508         default:
3509                 rc = -EINVAL;
3510                 goto out;
3511         }
3512
3513         if (unlikely(copy_from_user(&buf, uarg, size))) {
3514                 dev_err(dev, "%s: copy_from_user() fail "
3515                         "size=%lu cmd=%d (%s) uarg=%p\n",
3516                         __func__, size, cmd, decode_hioctl(cmd), uarg);
3517                 rc = -EFAULT;
3518                 goto out;
3519         }
3520
3521         hdr = (struct ht_cxlflash_hdr *)&buf;
3522         if (hdr->version != HT_CXLFLASH_VERSION_0) {
3523                 dev_dbg(dev, "%s: Version %u not supported for %s\n",
3524                         __func__, hdr->version, decode_hioctl(cmd));
3525                 rc = -EINVAL;
3526                 goto out;
3527         }
3528
3529         if (hdr->rsvd[0] || hdr->rsvd[1] || hdr->return_flags) {
3530                 dev_dbg(dev, "%s: Reserved/rflags populated\n", __func__);
3531                 rc = -EINVAL;
3532                 goto out;
3533         }
3534
3535         rc = do_ioctl(cfg, (void *)&buf);
3536         if (likely(!rc))
3537                 if (unlikely(copy_to_user(uarg, &buf, size))) {
3538                         dev_err(dev, "%s: copy_to_user() fail "
3539                                 "size=%lu cmd=%d (%s) uarg=%p\n",
3540                                 __func__, size, cmd, decode_hioctl(cmd), uarg);
3541                         rc = -EFAULT;
3542                 }
3543
3544         /* fall through to exit */
3545
3546 out:
3547         up_read(&cfg->ioctl_rwsem);
3548         if (unlikely(rc && known_ioctl))
3549                 dev_err(dev, "%s: ioctl %s (%08X) returned rc=%d\n",
3550                         __func__, decode_hioctl(cmd), cmd, rc);
3551         else
3552                 dev_dbg(dev, "%s: ioctl %s (%08X) returned rc=%d\n",
3553                         __func__, decode_hioctl(cmd), cmd, rc);
3554         return rc;
3555 }
3556
3557 /*
3558  * Character device file operations
3559  */
3560 static const struct file_operations cxlflash_chr_fops = {
3561         .owner          = THIS_MODULE,
3562         .open           = cxlflash_chr_open,
3563         .unlocked_ioctl = cxlflash_chr_ioctl,
3564         .compat_ioctl   = cxlflash_chr_ioctl,
3565 };
3566
3567 /**
3568  * init_chrdev() - initialize the character device for the host
3569  * @cfg:        Internal structure associated with the host.
3570  *
3571  * Return: 0 on success, -errno on failure
3572  */
3573 static int init_chrdev(struct cxlflash_cfg *cfg)
3574 {
3575         struct device *dev = &cfg->dev->dev;
3576         struct device *char_dev;
3577         dev_t devno;
3578         int minor;
3579         int rc = 0;
3580
3581         minor = cxlflash_get_minor();
3582         if (unlikely(minor < 0)) {
3583                 dev_err(dev, "%s: Exhausted allowed adapters\n", __func__);
3584                 rc = -ENOSPC;
3585                 goto out;
3586         }
3587
3588         devno = MKDEV(cxlflash_major, minor);
3589         cdev_init(&cfg->cdev, &cxlflash_chr_fops);
3590
3591         rc = cdev_add(&cfg->cdev, devno, 1);
3592         if (rc) {
3593                 dev_err(dev, "%s: cdev_add failed rc=%d\n", __func__, rc);
3594                 goto err1;
3595         }
3596
3597         char_dev = device_create(cxlflash_class, NULL, devno,
3598                                  NULL, "cxlflash%d", minor);
3599         if (IS_ERR(char_dev)) {
3600                 rc = PTR_ERR(char_dev);
3601                 dev_err(dev, "%s: device_create failed rc=%d\n",
3602                         __func__, rc);
3603                 goto err2;
3604         }
3605
3606         cfg->chardev = char_dev;
3607 out:
3608         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
3609         return rc;
3610 err2:
3611         cdev_del(&cfg->cdev);
3612 err1:
3613         cxlflash_put_minor(minor);
3614         goto out;
3615 }
3616
3617 /**
3618  * cxlflash_probe() - PCI entry point to add host
3619  * @pdev:       PCI device associated with the host.
3620  * @dev_id:     PCI device id associated with device.
3621  *
3622  * The device will initially start out in a 'probing' state and
3623  * transition to the 'normal' state at the end of a successful
3624  * probe. Should an EEH event occur during probe, the notification
3625  * thread (error_detected()) will wait until the probe handler
3626  * is nearly complete. At that time, the device will be moved to
3627  * a 'probed' state and the EEH thread woken up to drive the slot
3628  * reset and recovery (device moves to 'normal' state). Meanwhile,
3629  * the probe will be allowed to exit successfully.
3630  *
3631  * Return: 0 on success, -errno on failure
3632  */
3633 static int cxlflash_probe(struct pci_dev *pdev,
3634                           const struct pci_device_id *dev_id)
3635 {
3636         struct Scsi_Host *host;
3637         struct cxlflash_cfg *cfg = NULL;
3638         struct device *dev = &pdev->dev;
3639         struct dev_dependent_vals *ddv;
3640         int rc = 0;
3641         int k;
3642
3643         dev_dbg(&pdev->dev, "%s: Found CXLFLASH with IRQ: %d\n",
3644                 __func__, pdev->irq);
3645
3646         ddv = (struct dev_dependent_vals *)dev_id->driver_data;
3647         driver_template.max_sectors = ddv->max_sectors;
3648
3649         host = scsi_host_alloc(&driver_template, sizeof(struct cxlflash_cfg));
3650         if (!host) {
3651                 dev_err(dev, "%s: scsi_host_alloc failed\n", __func__);
3652                 rc = -ENOMEM;
3653                 goto out;
3654         }
3655
3656         host->max_id = CXLFLASH_MAX_NUM_TARGETS_PER_BUS;
3657         host->max_lun = CXLFLASH_MAX_NUM_LUNS_PER_TARGET;
3658         host->unique_id = host->host_no;
3659         host->max_cmd_len = CXLFLASH_MAX_CDB_LEN;
3660
3661         cfg = shost_priv(host);
3662         cfg->state = STATE_PROBING;
3663         cfg->host = host;
3664         rc = alloc_mem(cfg);
3665         if (rc) {
3666                 dev_err(dev, "%s: alloc_mem failed\n", __func__);
3667                 rc = -ENOMEM;
3668                 scsi_host_put(cfg->host);
3669                 goto out;
3670         }
3671
3672         cfg->init_state = INIT_STATE_NONE;
3673         cfg->dev = pdev;
3674         cfg->cxl_fops = cxlflash_cxl_fops;
3675
3676         /*
3677          * Promoted LUNs move to the top of the LUN table. The rest stay on
3678          * the bottom half. The bottom half grows from the end (index = 255),
3679          * whereas the top half grows from the beginning (index = 0).
3680          *
3681          * Initialize the last LUN index for all possible ports.
3682          */
3683         cfg->promote_lun_index = 0;
3684
3685         for (k = 0; k < MAX_FC_PORTS; k++)
3686                 cfg->last_lun_index[k] = CXLFLASH_NUM_VLUNS/2 - 1;
3687
3688         cfg->dev_id = (struct pci_device_id *)dev_id;
3689
3690         init_waitqueue_head(&cfg->tmf_waitq);
3691         init_waitqueue_head(&cfg->reset_waitq);
3692
3693         INIT_WORK(&cfg->work_q, cxlflash_worker_thread);
3694         cfg->lr_state = LINK_RESET_INVALID;
3695         cfg->lr_port = -1;
3696         spin_lock_init(&cfg->tmf_slock);
3697         mutex_init(&cfg->ctx_tbl_list_mutex);
3698         mutex_init(&cfg->ctx_recovery_mutex);
3699         init_rwsem(&cfg->ioctl_rwsem);
3700         INIT_LIST_HEAD(&cfg->ctx_err_recovery);
3701         INIT_LIST_HEAD(&cfg->lluns);
3702
3703         pci_set_drvdata(pdev, cfg);
3704
3705         cfg->cxl_afu = cxl_pci_to_afu(pdev);
3706
3707         rc = init_pci(cfg);
3708         if (rc) {
3709                 dev_err(dev, "%s: init_pci failed rc=%d\n", __func__, rc);
3710                 goto out_remove;
3711         }
3712         cfg->init_state = INIT_STATE_PCI;
3713
3714         rc = init_afu(cfg);
3715         if (rc && !wq_has_sleeper(&cfg->reset_waitq)) {
3716                 dev_err(dev, "%s: init_afu failed rc=%d\n", __func__, rc);
3717                 goto out_remove;
3718         }
3719         cfg->init_state = INIT_STATE_AFU;
3720
3721         rc = init_scsi(cfg);
3722         if (rc) {
3723                 dev_err(dev, "%s: init_scsi failed rc=%d\n", __func__, rc);
3724                 goto out_remove;
3725         }
3726         cfg->init_state = INIT_STATE_SCSI;
3727
3728         rc = init_chrdev(cfg);
3729         if (rc) {
3730                 dev_err(dev, "%s: init_chrdev failed rc=%d\n", __func__, rc);
3731                 goto out_remove;
3732         }
3733         cfg->init_state = INIT_STATE_CDEV;
3734
3735         if (wq_has_sleeper(&cfg->reset_waitq)) {
3736                 cfg->state = STATE_PROBED;
3737                 wake_up_all(&cfg->reset_waitq);
3738         } else
3739                 cfg->state = STATE_NORMAL;
3740 out:
3741         dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
3742         return rc;
3743
3744 out_remove:
3745         cfg->state = STATE_PROBED;
3746         cxlflash_remove(pdev);
3747         goto out;
3748 }
3749
3750 /**
3751  * cxlflash_pci_error_detected() - called when a PCI error is detected
3752  * @pdev:       PCI device struct.
3753  * @state:      PCI channel state.
3754  *
3755  * When an EEH occurs during an active reset, wait until the reset is
3756  * complete and then take action based upon the device state.
3757  *
3758  * Return: PCI_ERS_RESULT_NEED_RESET or PCI_ERS_RESULT_DISCONNECT
3759  */
3760 static pci_ers_result_t cxlflash_pci_error_detected(struct pci_dev *pdev,
3761                                                     pci_channel_state_t state)
3762 {
3763         int rc = 0;
3764         struct cxlflash_cfg *cfg = pci_get_drvdata(pdev);
3765         struct device *dev = &cfg->dev->dev;
3766
3767         dev_dbg(dev, "%s: pdev=%p state=%u\n", __func__, pdev, state);
3768
3769         switch (state) {
3770         case pci_channel_io_frozen:
3771                 wait_event(cfg->reset_waitq, cfg->state != STATE_RESET &&
3772                                              cfg->state != STATE_PROBING);
3773                 if (cfg->state == STATE_FAILTERM)
3774                         return PCI_ERS_RESULT_DISCONNECT;
3775
3776                 cfg->state = STATE_RESET;
3777                 scsi_block_requests(cfg->host);
3778                 drain_ioctls(cfg);
3779                 rc = cxlflash_mark_contexts_error(cfg);
3780                 if (unlikely(rc))
3781                         dev_err(dev, "%s: Failed to mark user contexts rc=%d\n",
3782                                 __func__, rc);
3783                 term_afu(cfg);
3784                 return PCI_ERS_RESULT_NEED_RESET;
3785         case pci_channel_io_perm_failure:
3786                 cfg->state = STATE_FAILTERM;
3787                 wake_up_all(&cfg->reset_waitq);
3788                 scsi_unblock_requests(cfg->host);
3789                 return PCI_ERS_RESULT_DISCONNECT;
3790         default:
3791                 break;
3792         }
3793         return PCI_ERS_RESULT_NEED_RESET;
3794 }
3795
3796 /**
3797  * cxlflash_pci_slot_reset() - called when PCI slot has been reset
3798  * @pdev:       PCI device struct.
3799  *
3800  * This routine is called by the pci error recovery code after the PCI
3801  * slot has been reset, just before we should resume normal operations.
3802  *
3803  * Return: PCI_ERS_RESULT_RECOVERED or PCI_ERS_RESULT_DISCONNECT
3804  */
3805 static pci_ers_result_t cxlflash_pci_slot_reset(struct pci_dev *pdev)
3806 {
3807         int rc = 0;
3808         struct cxlflash_cfg *cfg = pci_get_drvdata(pdev);
3809         struct device *dev = &cfg->dev->dev;
3810
3811         dev_dbg(dev, "%s: pdev=%p\n", __func__, pdev);
3812
3813         rc = init_afu(cfg);
3814         if (unlikely(rc)) {
3815                 dev_err(dev, "%s: EEH recovery failed rc=%d\n", __func__, rc);
3816                 return PCI_ERS_RESULT_DISCONNECT;
3817         }
3818
3819         return PCI_ERS_RESULT_RECOVERED;
3820 }
3821
3822 /**
3823  * cxlflash_pci_resume() - called when normal operation can resume
3824  * @pdev:       PCI device struct
3825  */
3826 static void cxlflash_pci_resume(struct pci_dev *pdev)
3827 {
3828         struct cxlflash_cfg *cfg = pci_get_drvdata(pdev);
3829         struct device *dev = &cfg->dev->dev;
3830
3831         dev_dbg(dev, "%s: pdev=%p\n", __func__, pdev);
3832
3833         cfg->state = STATE_NORMAL;
3834         wake_up_all(&cfg->reset_waitq);
3835         scsi_unblock_requests(cfg->host);
3836 }
3837
3838 /**
3839  * cxlflash_devnode() - provides devtmpfs for devices in the cxlflash class
3840  * @dev:        Character device.
3841  * @mode:       Mode that can be used to verify access.
3842  *
3843  * Return: Allocated string describing the devtmpfs structure.
3844  */
3845 static char *cxlflash_devnode(struct device *dev, umode_t *mode)
3846 {
3847         return kasprintf(GFP_KERNEL, "cxlflash/%s", dev_name(dev));
3848 }
3849
3850 /**
3851  * cxlflash_class_init() - create character device class
3852  *
3853  * Return: 0 on success, -errno on failure
3854  */
3855 static int cxlflash_class_init(void)
3856 {
3857         dev_t devno;
3858         int rc = 0;
3859
3860         rc = alloc_chrdev_region(&devno, 0, CXLFLASH_MAX_ADAPTERS, "cxlflash");
3861         if (unlikely(rc)) {
3862                 pr_err("%s: alloc_chrdev_region failed rc=%d\n", __func__, rc);
3863                 goto out;
3864         }
3865
3866         cxlflash_major = MAJOR(devno);
3867
3868         cxlflash_class = class_create(THIS_MODULE, "cxlflash");
3869         if (IS_ERR(cxlflash_class)) {
3870                 rc = PTR_ERR(cxlflash_class);
3871                 pr_err("%s: class_create failed rc=%d\n", __func__, rc);
3872                 goto err;
3873         }
3874
3875         cxlflash_class->devnode = cxlflash_devnode;
3876 out:
3877         pr_debug("%s: returning rc=%d\n", __func__, rc);
3878         return rc;
3879 err:
3880         unregister_chrdev_region(devno, CXLFLASH_MAX_ADAPTERS);
3881         goto out;
3882 }
3883
3884 /**
3885  * cxlflash_class_exit() - destroy character device class
3886  */
3887 static void cxlflash_class_exit(void)
3888 {
3889         dev_t devno = MKDEV(cxlflash_major, 0);
3890
3891         class_destroy(cxlflash_class);
3892         unregister_chrdev_region(devno, CXLFLASH_MAX_ADAPTERS);
3893 }
3894
3895 static const struct pci_error_handlers cxlflash_err_handler = {
3896         .error_detected = cxlflash_pci_error_detected,
3897         .slot_reset = cxlflash_pci_slot_reset,
3898         .resume = cxlflash_pci_resume,
3899 };
3900
3901 /*
3902  * PCI device structure
3903  */
3904 static struct pci_driver cxlflash_driver = {
3905         .name = CXLFLASH_NAME,
3906         .id_table = cxlflash_pci_table,
3907         .probe = cxlflash_probe,
3908         .remove = cxlflash_remove,
3909         .shutdown = cxlflash_remove,
3910         .err_handler = &cxlflash_err_handler,
3911 };
3912
3913 /**
3914  * init_cxlflash() - module entry point
3915  *
3916  * Return: 0 on success, -errno on failure
3917  */
3918 static int __init init_cxlflash(void)
3919 {
3920         int rc;
3921
3922         check_sizes();
3923         cxlflash_list_init();
3924         rc = cxlflash_class_init();
3925         if (unlikely(rc))
3926                 goto out;
3927
3928         rc = pci_register_driver(&cxlflash_driver);
3929         if (unlikely(rc))
3930                 goto err;
3931 out:
3932         pr_debug("%s: returning rc=%d\n", __func__, rc);
3933         return rc;
3934 err:
3935         cxlflash_class_exit();
3936         goto out;
3937 }
3938
3939 /**
3940  * exit_cxlflash() - module exit point
3941  */
3942 static void __exit exit_cxlflash(void)
3943 {
3944         cxlflash_term_global_luns();
3945         cxlflash_free_errpage();
3946
3947         pci_unregister_driver(&cxlflash_driver);
3948         cxlflash_class_exit();
3949 }
3950
3951 module_init(init_cxlflash);
3952 module_exit(exit_cxlflash);