2 * CXL Flash Device Driver
4 * Written by: Manoj N. Kumar <manoj@linux.vnet.ibm.com>, IBM Corporation
5 * Matthew R. Ochs <mrochs@linux.vnet.ibm.com>, IBM Corporation
7 * Copyright (C) 2015 IBM Corporation
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.
15 #include <linux/delay.h>
16 #include <linux/file.h>
17 #include <linux/syscalls.h>
19 #include <asm/unaligned.h>
21 #include <scsi/scsi.h>
22 #include <scsi/scsi_host.h>
23 #include <scsi/scsi_cmnd.h>
24 #include <scsi/scsi_eh.h>
25 #include <uapi/scsi/cxlflash_ioctl.h>
30 #include "superpipe.h"
32 struct cxlflash_global global;
35 * marshal_rele_to_resize() - translate release to resize structure
36 * @rele: Source structure from which to translate/copy.
37 * @resize: Destination structure for the translate/copy.
39 static void marshal_rele_to_resize(struct dk_cxlflash_release *release,
40 struct dk_cxlflash_resize *resize)
42 resize->hdr = release->hdr;
43 resize->context_id = release->context_id;
44 resize->rsrc_handle = release->rsrc_handle;
48 * marshal_det_to_rele() - translate detach to release structure
49 * @detach: Destination structure for the translate/copy.
50 * @rele: Source structure from which to translate/copy.
52 static void marshal_det_to_rele(struct dk_cxlflash_detach *detach,
53 struct dk_cxlflash_release *release)
55 release->hdr = detach->hdr;
56 release->context_id = detach->context_id;
60 * cxlflash_free_errpage() - frees resources associated with global error page
62 void cxlflash_free_errpage(void)
65 mutex_lock(&global.mutex);
66 if (global.err_page) {
67 __free_page(global.err_page);
68 global.err_page = NULL;
70 mutex_unlock(&global.mutex);
74 * cxlflash_stop_term_user_contexts() - stops/terminates known user contexts
75 * @cfg: Internal structure associated with the host.
77 * When the host needs to go down, all users must be quiesced and their
78 * memory freed. This is accomplished by putting the contexts in error
79 * state which will notify the user and let them 'drive' the tear down.
80 * Meanwhile, this routine camps until all user contexts have been removed.
82 * Note that the main loop in this routine will always execute at least once
83 * to flush the reset_waitq.
85 void cxlflash_stop_term_user_contexts(struct cxlflash_cfg *cfg)
87 struct device *dev = &cfg->dev->dev;
90 cxlflash_mark_contexts_error(cfg);
93 for (i = 0; i < MAX_CONTEXT; i++)
94 if (cfg->ctx_tbl[i]) {
99 if (!found && list_empty(&cfg->ctx_err_recovery))
102 dev_dbg(dev, "%s: Wait for user contexts to quiesce...\n",
104 wake_up_all(&cfg->reset_waitq);
111 * find_error_context() - locates a context by cookie on the error recovery list
112 * @cfg: Internal structure associated with the host.
113 * @rctxid: Desired context by id.
114 * @file: Desired context by file.
116 * Return: Found context on success, NULL on failure
118 static struct ctx_info *find_error_context(struct cxlflash_cfg *cfg, u64 rctxid,
121 struct ctx_info *ctxi;
123 list_for_each_entry(ctxi, &cfg->ctx_err_recovery, list)
124 if ((ctxi->ctxid == rctxid) || (ctxi->file == file))
131 * get_context() - obtains a validated and locked context reference
132 * @cfg: Internal structure associated with the host.
133 * @rctxid: Desired context (raw, un-decoded format).
134 * @arg: LUN information or file associated with request.
135 * @ctx_ctrl: Control information to 'steer' desired lookup.
137 * NOTE: despite the name pid, in linux, current->pid actually refers
138 * to the lightweight process id (tid) and can change if the process is
139 * multi threaded. The tgid remains constant for the process and only changes
140 * when the process of fork. For all intents and purposes, think of tgid
141 * as a pid in the traditional sense.
143 * Return: Validated context on success, NULL on failure
145 struct ctx_info *get_context(struct cxlflash_cfg *cfg, u64 rctxid,
146 void *arg, enum ctx_ctrl ctx_ctrl)
148 struct device *dev = &cfg->dev->dev;
149 struct ctx_info *ctxi = NULL;
150 struct lun_access *lun_access = NULL;
151 struct file *file = NULL;
152 struct llun_info *lli = arg;
153 u64 ctxid = DECODE_CTXID(rctxid);
155 pid_t pid = current->tgid, ctxpid = 0;
157 if (ctx_ctrl & CTX_CTRL_FILE) {
159 file = (struct file *)arg;
162 if (ctx_ctrl & CTX_CTRL_CLONE)
163 pid = current->parent->tgid;
165 if (likely(ctxid < MAX_CONTEXT)) {
167 mutex_lock(&cfg->ctx_tbl_list_mutex);
168 ctxi = cfg->ctx_tbl[ctxid];
170 if ((file && (ctxi->file != file)) ||
171 (!file && (ctxi->ctxid != rctxid)))
174 if ((ctx_ctrl & CTX_CTRL_ERR) ||
175 (!ctxi && (ctx_ctrl & CTX_CTRL_ERR_FALLBACK)))
176 ctxi = find_error_context(cfg, rctxid, file);
178 mutex_unlock(&cfg->ctx_tbl_list_mutex);
183 * Need to acquire ownership of the context while still
184 * under the table/list lock to serialize with a remove
185 * thread. Use the 'try' to avoid stalling the
186 * table/list lock for a single context.
188 * Note that the lock order is:
190 * cfg->ctx_tbl_list_mutex -> ctxi->mutex
192 * Therefore release ctx_tbl_list_mutex before retrying.
194 rc = mutex_trylock(&ctxi->mutex);
195 mutex_unlock(&cfg->ctx_tbl_list_mutex);
197 break; /* got the context's lock! */
204 if (likely(!(ctx_ctrl & CTX_CTRL_NOPID)))
209 list_for_each_entry(lun_access, &ctxi->luns, list)
210 if (lun_access->lli == lli)
217 dev_dbg(dev, "%s: rctxid=%016llx ctxinfo=%p ctxpid=%u pid=%u "
218 "ctx_ctrl=%u\n", __func__, rctxid, ctxi, ctxpid, pid,
224 mutex_unlock(&ctxi->mutex);
230 * put_context() - release a context that was retrieved from get_context()
231 * @ctxi: Context to release.
233 * For now, releasing the context equates to unlocking it's mutex.
235 void put_context(struct ctx_info *ctxi)
237 mutex_unlock(&ctxi->mutex);
241 * afu_attach() - attach a context to the AFU
242 * @cfg: Internal structure associated with the host.
243 * @ctxi: Context to attach.
245 * Upon setting the context capabilities, they must be confirmed with
246 * a read back operation as the context might have been closed since
247 * the mailbox was unlocked. When this occurs, registration is failed.
249 * Return: 0 on success, -errno on failure
251 static int afu_attach(struct cxlflash_cfg *cfg, struct ctx_info *ctxi)
253 struct device *dev = &cfg->dev->dev;
254 struct afu *afu = cfg->afu;
255 struct sisl_ctrl_map __iomem *ctrl_map = ctxi->ctrl_map;
257 struct hwq *hwq = get_hwq(afu, PRIMARY_HWQ);
260 /* Unlock cap and restrict user to read/write cmds in translated mode */
261 readq_be(&ctrl_map->mbox_r);
262 val = (SISL_CTX_CAP_READ_CMD | SISL_CTX_CAP_WRITE_CMD);
263 writeq_be(val, &ctrl_map->ctx_cap);
264 val = readq_be(&ctrl_map->ctx_cap);
265 if (val != (SISL_CTX_CAP_READ_CMD | SISL_CTX_CAP_WRITE_CMD)) {
266 dev_err(dev, "%s: ctx may be closed val=%016llx\n",
272 /* Set up MMIO registers pointing to the RHT */
273 writeq_be((u64)ctxi->rht_start, &ctrl_map->rht_start);
274 val = SISL_RHT_CNT_ID((u64)MAX_RHT_PER_CONTEXT, (u64)(hwq->ctx_hndl));
275 writeq_be(val, &ctrl_map->rht_cnt_id);
277 dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
282 * read_cap16() - issues a SCSI READ_CAP16 command
283 * @sdev: SCSI device associated with LUN.
284 * @lli: LUN destined for capacity request.
286 * The READ_CAP16 can take quite a while to complete. Should an EEH occur while
287 * in scsi_execute(), the EEH handler will attempt to recover. As part of the
288 * recovery, the handler drains all currently running ioctls, waiting until they
289 * have completed before proceeding with a reset. As this routine is used on the
290 * ioctl path, this can create a condition where the EEH handler becomes stuck,
291 * infinitely waiting for this ioctl thread. To avoid this behavior, temporarily
292 * unmark this thread as an ioctl thread by releasing the ioctl read semaphore.
293 * This will allow the EEH handler to proceed with a recovery while this thread
294 * is still running. Once the scsi_execute() returns, reacquire the ioctl read
295 * semaphore and check the adapter state in case it changed while inside of
296 * scsi_execute(). The state check will wait if the adapter is still being
297 * recovered or return a failure if the recovery failed. In the event that the
298 * adapter reset failed, simply return the failure as the ioctl would be unable
301 * Note that the above puts a requirement on this routine to only be called on
304 * Return: 0 on success, -errno on failure
306 static int read_cap16(struct scsi_device *sdev, struct llun_info *lli)
308 struct cxlflash_cfg *cfg = shost_priv(sdev->host);
309 struct device *dev = &cfg->dev->dev;
310 struct glun_info *gli = lli->parent;
311 struct scsi_sense_hdr sshdr;
314 u8 *sense_buf = NULL;
318 u32 to = CMD_TIMEOUT * HZ;
321 cmd_buf = kzalloc(CMD_BUFSIZE, GFP_KERNEL);
322 scsi_cmd = kzalloc(MAX_COMMAND_SIZE, GFP_KERNEL);
323 sense_buf = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
324 if (unlikely(!cmd_buf || !scsi_cmd || !sense_buf)) {
329 scsi_cmd[0] = SERVICE_ACTION_IN_16; /* read cap(16) */
330 scsi_cmd[1] = SAI_READ_CAPACITY_16; /* service action */
331 put_unaligned_be32(CMD_BUFSIZE, &scsi_cmd[10]);
333 dev_dbg(dev, "%s: %ssending cmd(%02x)\n", __func__,
334 retry_cnt ? "re" : "", scsi_cmd[0]);
336 /* Drop the ioctl read semahpore across lengthy call */
337 up_read(&cfg->ioctl_rwsem);
338 result = scsi_execute(sdev, scsi_cmd, DMA_FROM_DEVICE, cmd_buf,
339 CMD_BUFSIZE, sense_buf, &sshdr, to, CMD_RETRIES,
341 down_read(&cfg->ioctl_rwsem);
342 rc = check_state(cfg);
344 dev_err(dev, "%s: Failed state result=%08x\n",
350 if (driver_byte(result) == DRIVER_SENSE) {
351 result &= ~(0xFF<<24); /* DRIVER_SENSE is not an error */
352 if (result & SAM_STAT_CHECK_CONDITION) {
353 switch (sshdr.sense_key) {
355 case RECOVERED_ERROR:
358 result &= ~SAM_STAT_CHECK_CONDITION;
362 case 0x29: /* Power on Reset or Device Reset */
364 case 0x2A: /* Device capacity changed */
365 case 0x3F: /* Report LUNs changed */
366 /* Retry the command once more */
367 if (retry_cnt++ < 1) {
382 dev_err(dev, "%s: command failed, result=%08x\n",
389 * Read cap was successful, grab values from the buffer;
390 * note that we don't need to worry about unaligned access
391 * as the buffer is allocated on an aligned boundary.
393 mutex_lock(&gli->mutex);
394 gli->max_lba = be64_to_cpu(*((__be64 *)&cmd_buf[0]));
395 gli->blk_len = be32_to_cpu(*((__be32 *)&cmd_buf[8]));
396 mutex_unlock(&gli->mutex);
403 dev_dbg(dev, "%s: maxlba=%lld blklen=%d rc=%d\n",
404 __func__, gli->max_lba, gli->blk_len, rc);
409 * get_rhte() - obtains validated resource handle table entry reference
410 * @ctxi: Context owning the resource handle.
411 * @rhndl: Resource handle associated with entry.
412 * @lli: LUN associated with request.
414 * Return: Validated RHTE on success, NULL on failure
416 struct sisl_rht_entry *get_rhte(struct ctx_info *ctxi, res_hndl_t rhndl,
417 struct llun_info *lli)
419 struct cxlflash_cfg *cfg = ctxi->cfg;
420 struct device *dev = &cfg->dev->dev;
421 struct sisl_rht_entry *rhte = NULL;
423 if (unlikely(!ctxi->rht_start)) {
424 dev_dbg(dev, "%s: Context does not have allocated RHT\n",
429 if (unlikely(rhndl >= MAX_RHT_PER_CONTEXT)) {
430 dev_dbg(dev, "%s: Bad resource handle rhndl=%d\n",
435 if (unlikely(ctxi->rht_lun[rhndl] != lli)) {
436 dev_dbg(dev, "%s: Bad resource handle LUN rhndl=%d\n",
441 rhte = &ctxi->rht_start[rhndl];
442 if (unlikely(rhte->nmask == 0)) {
443 dev_dbg(dev, "%s: Unopened resource handle rhndl=%d\n",
454 * rhte_checkout() - obtains free/empty resource handle table entry
455 * @ctxi: Context owning the resource handle.
456 * @lli: LUN associated with request.
458 * Return: Free RHTE on success, NULL on failure
460 struct sisl_rht_entry *rhte_checkout(struct ctx_info *ctxi,
461 struct llun_info *lli)
463 struct cxlflash_cfg *cfg = ctxi->cfg;
464 struct device *dev = &cfg->dev->dev;
465 struct sisl_rht_entry *rhte = NULL;
468 /* Find a free RHT entry */
469 for (i = 0; i < MAX_RHT_PER_CONTEXT; i++)
470 if (ctxi->rht_start[i].nmask == 0) {
471 rhte = &ctxi->rht_start[i];
477 ctxi->rht_lun[i] = lli;
479 dev_dbg(dev, "%s: returning rhte=%p index=%d\n", __func__, rhte, i);
484 * rhte_checkin() - releases a resource handle table entry
485 * @ctxi: Context owning the resource handle.
486 * @rhte: RHTE to release.
488 void rhte_checkin(struct ctx_info *ctxi,
489 struct sisl_rht_entry *rhte)
491 u32 rsrc_handle = rhte - ctxi->rht_start;
496 ctxi->rht_lun[rsrc_handle] = NULL;
497 ctxi->rht_needs_ws[rsrc_handle] = false;
501 * rhte_format1() - populates a RHTE for format 1
502 * @rhte: RHTE to populate.
503 * @lun_id: LUN ID of LUN associated with RHTE.
504 * @perm: Desired permissions for RHTE.
505 * @port_sel: Port selection mask
507 static void rht_format1(struct sisl_rht_entry *rhte, u64 lun_id, u32 perm,
511 * Populate the Format 1 RHT entry for direct access (physical
512 * LUN) using the synchronization sequence defined in the
513 * SISLite specification.
515 struct sisl_rht_entry_f1 dummy = { 0 };
516 struct sisl_rht_entry_f1 *rhte_f1 = (struct sisl_rht_entry_f1 *)rhte;
518 memset(rhte_f1, 0, sizeof(*rhte_f1));
519 rhte_f1->fp = SISL_RHT_FP(1U, 0);
520 dma_wmb(); /* Make setting of format bit visible */
522 rhte_f1->lun_id = lun_id;
523 dma_wmb(); /* Make setting of LUN id visible */
526 * Use a dummy RHT Format 1 entry to build the second dword
527 * of the entry that must be populated in a single write when
528 * enabled (valid bit set to TRUE).
531 dummy.fp = SISL_RHT_FP(1U, perm);
532 dummy.port_sel = port_sel;
533 rhte_f1->dw = dummy.dw;
535 dma_wmb(); /* Make remaining RHT entry fields visible */
539 * cxlflash_lun_attach() - attaches a user to a LUN and manages the LUN's mode
540 * @gli: LUN to attach.
541 * @mode: Desired mode of the LUN.
542 * @locked: Mutex status on current thread.
544 * Return: 0 on success, -errno on failure
546 int cxlflash_lun_attach(struct glun_info *gli, enum lun_mode mode, bool locked)
551 mutex_lock(&gli->mutex);
553 if (gli->mode == MODE_NONE)
555 else if (gli->mode != mode) {
556 pr_debug("%s: gli_mode=%d requested_mode=%d\n",
557 __func__, gli->mode, mode);
563 WARN_ON(gli->users <= 0);
565 pr_debug("%s: Returning rc=%d gli->mode=%u gli->users=%u\n",
566 __func__, rc, gli->mode, gli->users);
568 mutex_unlock(&gli->mutex);
573 * cxlflash_lun_detach() - detaches a user from a LUN and resets the LUN's mode
574 * @gli: LUN to detach.
576 * When resetting the mode, terminate block allocation resources as they
577 * are no longer required (service is safe to call even when block allocation
578 * resources were not present - such as when transitioning from physical mode).
579 * These resources will be reallocated when needed (subsequent transition to
582 void cxlflash_lun_detach(struct glun_info *gli)
584 mutex_lock(&gli->mutex);
585 WARN_ON(gli->mode == MODE_NONE);
586 if (--gli->users == 0) {
587 gli->mode = MODE_NONE;
588 cxlflash_ba_terminate(&gli->blka.ba_lun);
590 pr_debug("%s: gli->users=%u\n", __func__, gli->users);
591 WARN_ON(gli->users < 0);
592 mutex_unlock(&gli->mutex);
596 * _cxlflash_disk_release() - releases the specified resource entry
597 * @sdev: SCSI device associated with LUN.
598 * @ctxi: Context owning resources.
599 * @release: Release ioctl data structure.
601 * For LUNs in virtual mode, the virtual LUN associated with the specified
602 * resource handle is resized to 0 prior to releasing the RHTE. Note that the
603 * AFU sync should _not_ be performed when the context is sitting on the error
604 * recovery list. A context on the error recovery list is not known to the AFU
605 * due to reset. When the context is recovered, it will be reattached and made
606 * known again to the AFU.
608 * Return: 0 on success, -errno on failure
610 int _cxlflash_disk_release(struct scsi_device *sdev,
611 struct ctx_info *ctxi,
612 struct dk_cxlflash_release *release)
614 struct cxlflash_cfg *cfg = shost_priv(sdev->host);
615 struct device *dev = &cfg->dev->dev;
616 struct llun_info *lli = sdev->hostdata;
617 struct glun_info *gli = lli->parent;
618 struct afu *afu = cfg->afu;
619 bool put_ctx = false;
621 struct dk_cxlflash_resize size;
622 res_hndl_t rhndl = release->rsrc_handle;
625 u64 ctxid = DECODE_CTXID(release->context_id),
626 rctxid = release->context_id;
628 struct sisl_rht_entry *rhte;
629 struct sisl_rht_entry_f1 *rhte_f1;
631 dev_dbg(dev, "%s: ctxid=%llu rhndl=%llu gli->mode=%u gli->users=%u\n",
632 __func__, ctxid, release->rsrc_handle, gli->mode, gli->users);
635 ctxi = get_context(cfg, rctxid, lli, CTX_CTRL_ERR_FALLBACK);
636 if (unlikely(!ctxi)) {
637 dev_dbg(dev, "%s: Bad context ctxid=%llu\n",
646 rhte = get_rhte(ctxi, rhndl, lli);
647 if (unlikely(!rhte)) {
648 dev_dbg(dev, "%s: Bad resource handle rhndl=%d\n",
655 * Resize to 0 for virtual LUNS by setting the size
656 * to 0. This will clear LXT_START and LXT_CNT fields
657 * in the RHT entry and properly sync with the AFU.
659 * Afterwards we clear the remaining fields.
663 marshal_rele_to_resize(release, &size);
665 rc = _cxlflash_vlun_resize(sdev, ctxi, &size);
667 dev_dbg(dev, "%s: resize failed rc %d\n", __func__, rc);
674 * Clear the Format 1 RHT entry for direct access
675 * (physical LUN) using the synchronization sequence
676 * defined in the SISLite specification.
678 rhte_f1 = (struct sisl_rht_entry_f1 *)rhte;
681 dma_wmb(); /* Make revocation of RHT entry visible */
684 dma_wmb(); /* Make clearing of LUN id visible */
687 dma_wmb(); /* Make RHT entry bottom-half clearing visible */
689 if (!ctxi->err_recovery_active)
690 cxlflash_afu_sync(afu, ctxid, rhndl, AFU_HW_SYNC);
693 WARN(1, "Unsupported LUN mode!");
697 rhte_checkin(ctxi, rhte);
698 cxlflash_lun_detach(gli);
703 dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
707 int cxlflash_disk_release(struct scsi_device *sdev,
708 struct dk_cxlflash_release *release)
710 return _cxlflash_disk_release(sdev, NULL, release);
714 * destroy_context() - releases a context
715 * @cfg: Internal structure associated with the host.
716 * @ctxi: Context to release.
718 * This routine is safe to be called with a a non-initialized context.
719 * Also note that the routine conditionally checks for the existence
720 * of the context control map before clearing the RHT registers and
721 * context capabilities because it is possible to destroy a context
722 * while the context is in the error state (previous mapping was
723 * removed [so there is no need to worry about clearing] and context
724 * is waiting for a new mapping).
726 static void destroy_context(struct cxlflash_cfg *cfg,
727 struct ctx_info *ctxi)
729 struct afu *afu = cfg->afu;
731 if (ctxi->initialized) {
732 WARN_ON(!list_empty(&ctxi->luns));
734 /* Clear RHT registers and drop all capabilities for context */
735 if (afu->afu_map && ctxi->ctrl_map) {
736 writeq_be(0, &ctxi->ctrl_map->rht_start);
737 writeq_be(0, &ctxi->ctrl_map->rht_cnt_id);
738 writeq_be(0, &ctxi->ctrl_map->ctx_cap);
742 /* Free memory associated with context */
743 free_page((ulong)ctxi->rht_start);
744 kfree(ctxi->rht_needs_ws);
745 kfree(ctxi->rht_lun);
750 * create_context() - allocates and initializes a context
751 * @cfg: Internal structure associated with the host.
753 * Return: Allocated context on success, NULL on failure
755 static struct ctx_info *create_context(struct cxlflash_cfg *cfg)
757 struct device *dev = &cfg->dev->dev;
758 struct ctx_info *ctxi = NULL;
759 struct llun_info **lli = NULL;
761 struct sisl_rht_entry *rhte;
763 ctxi = kzalloc(sizeof(*ctxi), GFP_KERNEL);
764 lli = kzalloc((MAX_RHT_PER_CONTEXT * sizeof(*lli)), GFP_KERNEL);
765 ws = kzalloc((MAX_RHT_PER_CONTEXT * sizeof(*ws)), GFP_KERNEL);
766 if (unlikely(!ctxi || !lli || !ws)) {
767 dev_err(dev, "%s: Unable to allocate context\n", __func__);
771 rhte = (struct sisl_rht_entry *)get_zeroed_page(GFP_KERNEL);
772 if (unlikely(!rhte)) {
773 dev_err(dev, "%s: Unable to allocate RHT\n", __func__);
778 ctxi->rht_needs_ws = ws;
779 ctxi->rht_start = rhte;
792 * init_context() - initializes a previously allocated context
793 * @ctxi: Previously allocated context
794 * @cfg: Internal structure associated with the host.
795 * @ctx: Previously obtained CXL context reference.
796 * @ctxid: Previously obtained process element associated with CXL context.
797 * @file: Previously obtained file associated with CXL context.
798 * @perms: User-specified permissions.
800 static void init_context(struct ctx_info *ctxi, struct cxlflash_cfg *cfg,
801 struct cxl_context *ctx, int ctxid, struct file *file,
804 struct afu *afu = cfg->afu;
806 ctxi->rht_perms = perms;
807 ctxi->ctrl_map = &afu->afu_map->ctrls[ctxid].ctrl;
808 ctxi->ctxid = ENCODE_CTXID(ctxi, ctxid);
809 ctxi->pid = current->tgid; /* tgid = pid */
813 ctxi->initialized = true;
814 mutex_init(&ctxi->mutex);
815 kref_init(&ctxi->kref);
816 INIT_LIST_HEAD(&ctxi->luns);
817 INIT_LIST_HEAD(&ctxi->list); /* initialize for list_empty() */
821 * remove_context() - context kref release handler
822 * @kref: Kernel reference associated with context to be removed.
824 * When a context no longer has any references it can safely be removed
825 * from global access and destroyed. Note that it is assumed the thread
826 * relinquishing access to the context holds its mutex.
828 static void remove_context(struct kref *kref)
830 struct ctx_info *ctxi = container_of(kref, struct ctx_info, kref);
831 struct cxlflash_cfg *cfg = ctxi->cfg;
832 u64 ctxid = DECODE_CTXID(ctxi->ctxid);
834 /* Remove context from table/error list */
835 WARN_ON(!mutex_is_locked(&ctxi->mutex));
836 ctxi->unavail = true;
837 mutex_unlock(&ctxi->mutex);
838 mutex_lock(&cfg->ctx_tbl_list_mutex);
839 mutex_lock(&ctxi->mutex);
841 if (!list_empty(&ctxi->list))
842 list_del(&ctxi->list);
843 cfg->ctx_tbl[ctxid] = NULL;
844 mutex_unlock(&cfg->ctx_tbl_list_mutex);
845 mutex_unlock(&ctxi->mutex);
847 /* Context now completely uncoupled/unreachable */
848 destroy_context(cfg, ctxi);
852 * _cxlflash_disk_detach() - detaches a LUN from a context
853 * @sdev: SCSI device associated with LUN.
854 * @ctxi: Context owning resources.
855 * @detach: Detach ioctl data structure.
857 * As part of the detach, all per-context resources associated with the LUN
858 * are cleaned up. When detaching the last LUN for a context, the context
859 * itself is cleaned up and released.
861 * Return: 0 on success, -errno on failure
863 static int _cxlflash_disk_detach(struct scsi_device *sdev,
864 struct ctx_info *ctxi,
865 struct dk_cxlflash_detach *detach)
867 struct cxlflash_cfg *cfg = shost_priv(sdev->host);
868 struct device *dev = &cfg->dev->dev;
869 struct llun_info *lli = sdev->hostdata;
870 struct lun_access *lun_access, *t;
871 struct dk_cxlflash_release rel;
872 bool put_ctx = false;
876 u64 ctxid = DECODE_CTXID(detach->context_id),
877 rctxid = detach->context_id;
879 dev_dbg(dev, "%s: ctxid=%llu\n", __func__, ctxid);
882 ctxi = get_context(cfg, rctxid, lli, CTX_CTRL_ERR_FALLBACK);
883 if (unlikely(!ctxi)) {
884 dev_dbg(dev, "%s: Bad context ctxid=%llu\n",
893 /* Cleanup outstanding resources tied to this LUN */
895 marshal_det_to_rele(detach, &rel);
896 for (i = 0; i < MAX_RHT_PER_CONTEXT; i++) {
897 if (ctxi->rht_lun[i] == lli) {
899 _cxlflash_disk_release(sdev, ctxi, &rel);
902 /* No need to loop further if we're done */
903 if (ctxi->rht_out == 0)
908 /* Take our LUN out of context, free the node */
909 list_for_each_entry_safe(lun_access, t, &ctxi->luns, list)
910 if (lun_access->lli == lli) {
911 list_del(&lun_access->list);
918 * Release the context reference and the sdev reference that
919 * bound this LUN to the context.
921 if (kref_put(&ctxi->kref, remove_context))
923 scsi_device_put(sdev);
927 dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
931 static int cxlflash_disk_detach(struct scsi_device *sdev,
932 struct dk_cxlflash_detach *detach)
934 return _cxlflash_disk_detach(sdev, NULL, detach);
938 * cxlflash_cxl_release() - release handler for adapter file descriptor
939 * @inode: File-system inode associated with fd.
940 * @file: File installed with adapter file descriptor.
942 * This routine is the release handler for the fops registered with
943 * the CXL services on an initial attach for a context. It is called
944 * when a close (explicity by the user or as part of a process tear
945 * down) is performed on the adapter file descriptor returned to the
946 * user. The user should be aware that explicitly performing a close
947 * considered catastrophic and subsequent usage of the superpipe API
948 * with previously saved off tokens will fail.
950 * This routine derives the context reference and calls detach for
951 * each LUN associated with the context.The final detach operation
952 * causes the context itself to be freed. With exception to when the
953 * CXL process element (context id) lookup fails (a case that should
954 * theoretically never occur), every call into this routine results
955 * in a complete freeing of a context.
957 * Return: 0 on success
959 static int cxlflash_cxl_release(struct inode *inode, struct file *file)
961 struct cxl_context *ctx = cxl_fops_get_context(file);
962 struct cxlflash_cfg *cfg = container_of(file->f_op, struct cxlflash_cfg,
964 struct device *dev = &cfg->dev->dev;
965 struct ctx_info *ctxi = NULL;
966 struct dk_cxlflash_detach detach = { { 0 }, 0 };
967 struct lun_access *lun_access, *t;
968 enum ctx_ctrl ctrl = CTX_CTRL_ERR_FALLBACK | CTX_CTRL_FILE;
971 ctxid = cxl_process_element(ctx);
972 if (unlikely(ctxid < 0)) {
973 dev_err(dev, "%s: Context %p was closed ctxid=%d\n",
974 __func__, ctx, ctxid);
978 ctxi = get_context(cfg, ctxid, file, ctrl);
979 if (unlikely(!ctxi)) {
980 ctxi = get_context(cfg, ctxid, file, ctrl | CTX_CTRL_CLONE);
982 dev_dbg(dev, "%s: ctxid=%d already free\n",
987 dev_dbg(dev, "%s: Another process owns ctxid=%d\n",
993 dev_dbg(dev, "%s: close for ctxid=%d\n", __func__, ctxid);
995 detach.context_id = ctxi->ctxid;
996 list_for_each_entry_safe(lun_access, t, &ctxi->luns, list)
997 _cxlflash_disk_detach(lun_access->sdev, ctxi, &detach);
999 cxl_fd_release(inode, file);
1001 dev_dbg(dev, "%s: returning\n", __func__);
1006 * unmap_context() - clears a previously established mapping
1007 * @ctxi: Context owning the mapping.
1009 * This routine is used to switch between the error notification page
1010 * (dummy page of all 1's) and the real mapping (established by the CXL
1013 static void unmap_context(struct ctx_info *ctxi)
1015 unmap_mapping_range(ctxi->file->f_mapping, 0, 0, 1);
1019 * get_err_page() - obtains and allocates the error notification page
1020 * @cfg: Internal structure associated with the host.
1022 * Return: error notification page on success, NULL on failure
1024 static struct page *get_err_page(struct cxlflash_cfg *cfg)
1026 struct page *err_page = global.err_page;
1027 struct device *dev = &cfg->dev->dev;
1029 if (unlikely(!err_page)) {
1030 err_page = alloc_page(GFP_KERNEL);
1031 if (unlikely(!err_page)) {
1032 dev_err(dev, "%s: Unable to allocate err_page\n",
1037 memset(page_address(err_page), -1, PAGE_SIZE);
1039 /* Serialize update w/ other threads to avoid a leak */
1040 mutex_lock(&global.mutex);
1041 if (likely(!global.err_page))
1042 global.err_page = err_page;
1044 __free_page(err_page);
1045 err_page = global.err_page;
1047 mutex_unlock(&global.mutex);
1051 dev_dbg(dev, "%s: returning err_page=%p\n", __func__, err_page);
1056 * cxlflash_mmap_fault() - mmap fault handler for adapter file descriptor
1057 * @vmf: VM fault associated with current fault.
1059 * To support error notification via MMIO, faults are 'caught' by this routine
1060 * that was inserted before passing back the adapter file descriptor on attach.
1061 * When a fault occurs, this routine evaluates if error recovery is active and
1062 * if so, installs the error page to 'notify' the user about the error state.
1063 * During normal operation, the fault is simply handled by the original fault
1064 * handler that was installed by CXL services as part of initializing the
1065 * adapter file descriptor. The VMA's page protection bits are toggled to
1066 * indicate cached/not-cached depending on the memory backing the fault.
1068 * Return: 0 on success, VM_FAULT_SIGBUS on failure
1070 static int cxlflash_mmap_fault(struct vm_fault *vmf)
1072 struct vm_area_struct *vma = vmf->vma;
1073 struct file *file = vma->vm_file;
1074 struct cxl_context *ctx = cxl_fops_get_context(file);
1075 struct cxlflash_cfg *cfg = container_of(file->f_op, struct cxlflash_cfg,
1077 struct device *dev = &cfg->dev->dev;
1078 struct ctx_info *ctxi = NULL;
1079 struct page *err_page = NULL;
1080 enum ctx_ctrl ctrl = CTX_CTRL_ERR_FALLBACK | CTX_CTRL_FILE;
1084 ctxid = cxl_process_element(ctx);
1085 if (unlikely(ctxid < 0)) {
1086 dev_err(dev, "%s: Context %p was closed ctxid=%d\n",
1087 __func__, ctx, ctxid);
1091 ctxi = get_context(cfg, ctxid, file, ctrl);
1092 if (unlikely(!ctxi)) {
1093 dev_dbg(dev, "%s: Bad context ctxid=%d\n", __func__, ctxid);
1097 dev_dbg(dev, "%s: fault for context %d\n", __func__, ctxid);
1099 if (likely(!ctxi->err_recovery_active)) {
1100 vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
1101 rc = ctxi->cxl_mmap_vmops->fault(vmf);
1103 dev_dbg(dev, "%s: err recovery active, use err_page\n",
1106 err_page = get_err_page(cfg);
1107 if (unlikely(!err_page)) {
1108 dev_err(dev, "%s: Could not get err_page\n", __func__);
1109 rc = VM_FAULT_RETRY;
1114 vmf->page = err_page;
1115 vma->vm_page_prot = pgprot_cached(vma->vm_page_prot);
1121 dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
1125 rc = VM_FAULT_SIGBUS;
1130 * Local MMAP vmops to 'catch' faults
1132 static const struct vm_operations_struct cxlflash_mmap_vmops = {
1133 .fault = cxlflash_mmap_fault,
1137 * cxlflash_cxl_mmap() - mmap handler for adapter file descriptor
1138 * @file: File installed with adapter file descriptor.
1139 * @vma: VM area associated with mapping.
1141 * Installs local mmap vmops to 'catch' faults for error notification support.
1143 * Return: 0 on success, -errno on failure
1145 static int cxlflash_cxl_mmap(struct file *file, struct vm_area_struct *vma)
1147 struct cxl_context *ctx = cxl_fops_get_context(file);
1148 struct cxlflash_cfg *cfg = container_of(file->f_op, struct cxlflash_cfg,
1150 struct device *dev = &cfg->dev->dev;
1151 struct ctx_info *ctxi = NULL;
1152 enum ctx_ctrl ctrl = CTX_CTRL_ERR_FALLBACK | CTX_CTRL_FILE;
1156 ctxid = cxl_process_element(ctx);
1157 if (unlikely(ctxid < 0)) {
1158 dev_err(dev, "%s: Context %p was closed ctxid=%d\n",
1159 __func__, ctx, ctxid);
1164 ctxi = get_context(cfg, ctxid, file, ctrl);
1165 if (unlikely(!ctxi)) {
1166 dev_dbg(dev, "%s: Bad context ctxid=%d\n", __func__, ctxid);
1171 dev_dbg(dev, "%s: mmap for context %d\n", __func__, ctxid);
1173 rc = cxl_fd_mmap(file, vma);
1175 /* Insert ourself in the mmap fault handler path */
1176 ctxi->cxl_mmap_vmops = vma->vm_ops;
1177 vma->vm_ops = &cxlflash_mmap_vmops;
1186 const struct file_operations cxlflash_cxl_fops = {
1187 .owner = THIS_MODULE,
1188 .mmap = cxlflash_cxl_mmap,
1189 .release = cxlflash_cxl_release,
1193 * cxlflash_mark_contexts_error() - move contexts to error state and list
1194 * @cfg: Internal structure associated with the host.
1196 * A context is only moved over to the error list when there are no outstanding
1197 * references to it. This ensures that a running operation has completed.
1199 * Return: 0 on success, -errno on failure
1201 int cxlflash_mark_contexts_error(struct cxlflash_cfg *cfg)
1204 struct ctx_info *ctxi = NULL;
1206 mutex_lock(&cfg->ctx_tbl_list_mutex);
1208 for (i = 0; i < MAX_CONTEXT; i++) {
1209 ctxi = cfg->ctx_tbl[i];
1211 mutex_lock(&ctxi->mutex);
1212 cfg->ctx_tbl[i] = NULL;
1213 list_add(&ctxi->list, &cfg->ctx_err_recovery);
1214 ctxi->err_recovery_active = true;
1215 ctxi->ctrl_map = NULL;
1216 unmap_context(ctxi);
1217 mutex_unlock(&ctxi->mutex);
1221 mutex_unlock(&cfg->ctx_tbl_list_mutex);
1228 static const struct file_operations null_fops = {
1229 .owner = THIS_MODULE,
1233 * check_state() - checks and responds to the current adapter state
1234 * @cfg: Internal structure associated with the host.
1236 * This routine can block and should only be used on process context.
1237 * It assumes that the caller is an ioctl thread and holding the ioctl
1238 * read semaphore. This is temporarily let up across the wait to allow
1239 * for draining actively running ioctls. Also note that when waking up
1240 * from waiting in reset, the state is unknown and must be checked again
1241 * before proceeding.
1243 * Return: 0 on success, -errno on failure
1245 int check_state(struct cxlflash_cfg *cfg)
1247 struct device *dev = &cfg->dev->dev;
1251 switch (cfg->state) {
1253 dev_dbg(dev, "%s: Reset state, going to wait...\n", __func__);
1254 up_read(&cfg->ioctl_rwsem);
1255 rc = wait_event_interruptible(cfg->reset_waitq,
1256 cfg->state != STATE_RESET);
1257 down_read(&cfg->ioctl_rwsem);
1261 case STATE_FAILTERM:
1262 dev_dbg(dev, "%s: Failed/Terminating\n", __func__);
1273 * cxlflash_disk_attach() - attach a LUN to a context
1274 * @sdev: SCSI device associated with LUN.
1275 * @attach: Attach ioctl data structure.
1277 * Creates a context and attaches LUN to it. A LUN can only be attached
1278 * one time to a context (subsequent attaches for the same context/LUN pair
1279 * are not supported). Additional LUNs can be attached to a context by
1280 * specifying the 'reuse' flag defined in the cxlflash_ioctl.h header.
1282 * Return: 0 on success, -errno on failure
1284 static int cxlflash_disk_attach(struct scsi_device *sdev,
1285 struct dk_cxlflash_attach *attach)
1287 struct cxlflash_cfg *cfg = shost_priv(sdev->host);
1288 struct device *dev = &cfg->dev->dev;
1289 struct afu *afu = cfg->afu;
1290 struct llun_info *lli = sdev->hostdata;
1291 struct glun_info *gli = lli->parent;
1292 struct cxl_ioctl_start_work *work;
1293 struct ctx_info *ctxi = NULL;
1294 struct lun_access *lun_access = NULL;
1300 struct file *file = NULL;
1302 struct cxl_context *ctx = NULL;
1306 if (attach->num_interrupts > 4) {
1307 dev_dbg(dev, "%s: Cannot support this many interrupts %llu\n",
1308 __func__, attach->num_interrupts);
1313 if (gli->max_lba == 0) {
1314 dev_dbg(dev, "%s: No capacity info for LUN=%016llx\n",
1315 __func__, lli->lun_id[sdev->channel]);
1316 rc = read_cap16(sdev, lli);
1318 dev_err(dev, "%s: Invalid device rc=%d\n",
1323 dev_dbg(dev, "%s: LBA = %016llx\n", __func__, gli->max_lba);
1324 dev_dbg(dev, "%s: BLK_LEN = %08x\n", __func__, gli->blk_len);
1327 if (attach->hdr.flags & DK_CXLFLASH_ATTACH_REUSE_CONTEXT) {
1328 rctxid = attach->context_id;
1329 ctxi = get_context(cfg, rctxid, NULL, 0);
1331 dev_dbg(dev, "%s: Bad context rctxid=%016llx\n",
1337 list_for_each_entry(lun_access, &ctxi->luns, list)
1338 if (lun_access->lli == lli) {
1339 dev_dbg(dev, "%s: Already attached\n",
1346 rc = scsi_device_get(sdev);
1348 dev_err(dev, "%s: Unable to get sdev reference\n", __func__);
1352 lun_access = kzalloc(sizeof(*lun_access), GFP_KERNEL);
1353 if (unlikely(!lun_access)) {
1354 dev_err(dev, "%s: Unable to allocate lun_access\n", __func__);
1359 lun_access->lli = lli;
1360 lun_access->sdev = sdev;
1362 /* Non-NULL context indicates reuse (another context reference) */
1364 dev_dbg(dev, "%s: Reusing context for LUN rctxid=%016llx\n",
1366 kref_get(&ctxi->kref);
1367 list_add(&lun_access->list, &ctxi->luns);
1371 ctxi = create_context(cfg);
1372 if (unlikely(!ctxi)) {
1373 dev_err(dev, "%s: Failed to create context ctxid=%d\n",
1378 ctx = cxl_dev_context_init(cfg->dev);
1379 if (IS_ERR_OR_NULL(ctx)) {
1380 dev_err(dev, "%s: Could not initialize context %p\n",
1387 work->num_interrupts = attach->num_interrupts;
1388 work->flags = CXL_START_WORK_NUM_IRQS;
1390 rc = cxl_start_work(ctx, work);
1392 dev_dbg(dev, "%s: Could not start context rc=%d\n",
1397 ctxid = cxl_process_element(ctx);
1398 if (unlikely((ctxid >= MAX_CONTEXT) || (ctxid < 0))) {
1399 dev_err(dev, "%s: ctxid=%d invalid\n", __func__, ctxid);
1404 file = cxl_get_fd(ctx, &cfg->cxl_fops, &fd);
1405 if (unlikely(fd < 0)) {
1407 dev_err(dev, "%s: Could not get file descriptor\n", __func__);
1411 /* Translate read/write O_* flags from fcntl.h to AFU permission bits */
1412 perms = SISL_RHT_PERM(attach->hdr.flags + 1);
1414 /* Context mutex is locked upon return */
1415 init_context(ctxi, cfg, ctx, ctxid, file, perms);
1417 rc = afu_attach(cfg, ctxi);
1419 dev_err(dev, "%s: Could not attach AFU rc %d\n", __func__, rc);
1424 * No error paths after this point. Once the fd is installed it's
1425 * visible to user space and can't be undone safely on this thread.
1426 * There is no need to worry about a deadlock here because no one
1427 * knows about us yet; we can be the only one holding our mutex.
1429 list_add(&lun_access->list, &ctxi->luns);
1430 mutex_lock(&cfg->ctx_tbl_list_mutex);
1431 mutex_lock(&ctxi->mutex);
1432 cfg->ctx_tbl[ctxid] = ctxi;
1433 mutex_unlock(&cfg->ctx_tbl_list_mutex);
1434 fd_install(fd, file);
1438 flags |= DK_CXLFLASH_APP_CLOSE_ADAP_FD;
1439 if (afu_is_sq_cmd_mode(afu))
1440 flags |= DK_CXLFLASH_CONTEXT_SQ_CMD_MODE;
1442 attach->hdr.return_flags = flags;
1443 attach->context_id = ctxi->ctxid;
1444 attach->block_size = gli->blk_len;
1445 attach->mmio_size = sizeof(afu->afu_map->hosts[0].harea);
1446 attach->last_lba = gli->max_lba;
1447 attach->max_xfer = sdev->host->max_sectors * MAX_SECTOR_UNIT;
1448 attach->max_xfer /= gli->blk_len;
1451 attach->adap_fd = fd;
1456 dev_dbg(dev, "%s: returning ctxid=%d fd=%d bs=%lld rc=%d llba=%lld\n",
1457 __func__, ctxid, fd, attach->block_size, rc, attach->last_lba);
1461 /* Cleanup CXL context; okay to 'stop' even if it was not started */
1462 if (!IS_ERR_OR_NULL(ctx)) {
1463 cxl_stop_context(ctx);
1464 cxl_release_context(ctx);
1469 * Here, we're overriding the fops with a dummy all-NULL fops because
1470 * fput() calls the release fop, which will cause us to mistakenly
1471 * call into the CXL code. Rather than try to add yet more complexity
1472 * to that routine (cxlflash_cxl_release) we should try to fix the
1476 file->f_op = &null_fops;
1483 /* Cleanup our context */
1485 destroy_context(cfg, ctxi);
1490 scsi_device_put(sdev);
1495 * recover_context() - recovers a context in error
1496 * @cfg: Internal structure associated with the host.
1497 * @ctxi: Context to release.
1498 * @adap_fd: Adapter file descriptor associated with new/recovered context.
1500 * Restablishes the state for a context-in-error.
1502 * Return: 0 on success, -errno on failure
1504 static int recover_context(struct cxlflash_cfg *cfg,
1505 struct ctx_info *ctxi,
1508 struct device *dev = &cfg->dev->dev;
1513 struct cxl_context *ctx;
1514 struct afu *afu = cfg->afu;
1516 ctx = cxl_dev_context_init(cfg->dev);
1517 if (IS_ERR_OR_NULL(ctx)) {
1518 dev_err(dev, "%s: Could not initialize context %p\n",
1524 rc = cxl_start_work(ctx, &ctxi->work);
1526 dev_dbg(dev, "%s: Could not start context rc=%d\n",
1531 ctxid = cxl_process_element(ctx);
1532 if (unlikely((ctxid >= MAX_CONTEXT) || (ctxid < 0))) {
1533 dev_err(dev, "%s: ctxid=%d invalid\n", __func__, ctxid);
1538 file = cxl_get_fd(ctx, &cfg->cxl_fops, &fd);
1539 if (unlikely(fd < 0)) {
1541 dev_err(dev, "%s: Could not get file descriptor\n", __func__);
1545 /* Update with new MMIO area based on updated context id */
1546 ctxi->ctrl_map = &afu->afu_map->ctrls[ctxid].ctrl;
1548 rc = afu_attach(cfg, ctxi);
1550 dev_err(dev, "%s: Could not attach AFU rc %d\n", __func__, rc);
1555 * No error paths after this point. Once the fd is installed it's
1556 * visible to user space and can't be undone safely on this thread.
1558 ctxi->ctxid = ENCODE_CTXID(ctxi, ctxid);
1563 * Put context back in table (note the reinit of the context list);
1564 * we must first drop the context's mutex and then acquire it in
1565 * order with the table/list mutex to avoid a deadlock - safe to do
1566 * here because no one can find us at this moment in time.
1568 mutex_unlock(&ctxi->mutex);
1569 mutex_lock(&cfg->ctx_tbl_list_mutex);
1570 mutex_lock(&ctxi->mutex);
1571 list_del_init(&ctxi->list);
1572 cfg->ctx_tbl[ctxid] = ctxi;
1573 mutex_unlock(&cfg->ctx_tbl_list_mutex);
1574 fd_install(fd, file);
1577 dev_dbg(dev, "%s: returning ctxid=%d fd=%d rc=%d\n",
1578 __func__, ctxid, fd, rc);
1585 cxl_stop_context(ctx);
1587 cxl_release_context(ctx);
1592 * cxlflash_afu_recover() - initiates AFU recovery
1593 * @sdev: SCSI device associated with LUN.
1594 * @recover: Recover ioctl data structure.
1596 * Only a single recovery is allowed at a time to avoid exhausting CXL
1597 * resources (leading to recovery failure) in the event that we're up
1598 * against the maximum number of contexts limit. For similar reasons,
1599 * a context recovery is retried if there are multiple recoveries taking
1600 * place at the same time and the failure was due to CXL services being
1601 * unable to keep up.
1603 * As this routine is called on ioctl context, it holds the ioctl r/w
1604 * semaphore that is used to drain ioctls in recovery scenarios. The
1605 * implementation to achieve the pacing described above (a local mutex)
1606 * requires that the ioctl r/w semaphore be dropped and reacquired to
1607 * avoid a 3-way deadlock when multiple process recoveries operate in
1610 * Because a user can detect an error condition before the kernel, it is
1611 * quite possible for this routine to act as the kernel's EEH detection
1612 * source (MMIO read of mbox_r). Because of this, there is a window of
1613 * time where an EEH might have been detected but not yet 'serviced'
1614 * (callback invoked, causing the device to enter reset state). To avoid
1615 * looping in this routine during that window, a 1 second sleep is in place
1616 * between the time the MMIO failure is detected and the time a wait on the
1617 * reset wait queue is attempted via check_state().
1619 * Return: 0 on success, -errno on failure
1621 static int cxlflash_afu_recover(struct scsi_device *sdev,
1622 struct dk_cxlflash_recover_afu *recover)
1624 struct cxlflash_cfg *cfg = shost_priv(sdev->host);
1625 struct device *dev = &cfg->dev->dev;
1626 struct llun_info *lli = sdev->hostdata;
1627 struct afu *afu = cfg->afu;
1628 struct ctx_info *ctxi = NULL;
1629 struct mutex *mutex = &cfg->ctx_recovery_mutex;
1630 struct hwq *hwq = get_hwq(afu, PRIMARY_HWQ);
1632 u64 ctxid = DECODE_CTXID(recover->context_id),
1633 rctxid = recover->context_id;
1635 int lretry = 20; /* up to 2 seconds */
1636 int new_adap_fd = -1;
1639 atomic_inc(&cfg->recovery_threads);
1640 up_read(&cfg->ioctl_rwsem);
1641 rc = mutex_lock_interruptible(mutex);
1642 down_read(&cfg->ioctl_rwsem);
1645 rc = check_state(cfg);
1647 dev_err(dev, "%s: Failed state rc=%d\n", __func__, rc);
1652 dev_dbg(dev, "%s: reason=%016llx rctxid=%016llx\n",
1653 __func__, recover->reason, rctxid);
1656 /* Ensure that this process is attached to the context */
1657 ctxi = get_context(cfg, rctxid, lli, CTX_CTRL_ERR_FALLBACK);
1658 if (unlikely(!ctxi)) {
1659 dev_dbg(dev, "%s: Bad context ctxid=%llu\n", __func__, ctxid);
1664 if (ctxi->err_recovery_active) {
1666 rc = recover_context(cfg, ctxi, &new_adap_fd);
1668 dev_err(dev, "%s: Recovery failed ctxid=%llu rc=%d\n",
1669 __func__, ctxid, rc);
1670 if ((rc == -ENODEV) &&
1671 ((atomic_read(&cfg->recovery_threads) > 1) ||
1673 dev_dbg(dev, "%s: Going to try again\n",
1675 mutex_unlock(mutex);
1677 rc = mutex_lock_interruptible(mutex);
1686 ctxi->err_recovery_active = false;
1688 flags = DK_CXLFLASH_APP_CLOSE_ADAP_FD |
1689 DK_CXLFLASH_RECOVER_AFU_CONTEXT_RESET;
1690 if (afu_is_sq_cmd_mode(afu))
1691 flags |= DK_CXLFLASH_CONTEXT_SQ_CMD_MODE;
1693 recover->hdr.return_flags = flags;
1694 recover->context_id = ctxi->ctxid;
1695 recover->adap_fd = new_adap_fd;
1696 recover->mmio_size = sizeof(afu->afu_map->hosts[0].harea);
1700 /* Test if in error state */
1701 reg = readq_be(&hwq->ctrl_map->mbox_r);
1703 dev_dbg(dev, "%s: MMIO fail, wait for recovery.\n", __func__);
1706 * Before checking the state, put back the context obtained with
1707 * get_context() as it is no longer needed and sleep for a short
1708 * period of time (see prolog notes).
1713 rc = check_state(cfg);
1719 dev_dbg(dev, "%s: MMIO working, no recovery required\n", __func__);
1723 mutex_unlock(mutex);
1724 atomic_dec_if_positive(&cfg->recovery_threads);
1729 * process_sense() - evaluates and processes sense data
1730 * @sdev: SCSI device associated with LUN.
1731 * @verify: Verify ioctl data structure.
1733 * Return: 0 on success, -errno on failure
1735 static int process_sense(struct scsi_device *sdev,
1736 struct dk_cxlflash_verify *verify)
1738 struct cxlflash_cfg *cfg = shost_priv(sdev->host);
1739 struct device *dev = &cfg->dev->dev;
1740 struct llun_info *lli = sdev->hostdata;
1741 struct glun_info *gli = lli->parent;
1742 u64 prev_lba = gli->max_lba;
1743 struct scsi_sense_hdr sshdr = { 0 };
1746 rc = scsi_normalize_sense((const u8 *)&verify->sense_data,
1747 DK_CXLFLASH_VERIFY_SENSE_LEN, &sshdr);
1749 dev_err(dev, "%s: Failed to normalize sense data\n", __func__);
1754 switch (sshdr.sense_key) {
1756 case RECOVERED_ERROR:
1760 case UNIT_ATTENTION:
1761 switch (sshdr.asc) {
1762 case 0x29: /* Power on Reset or Device Reset */
1764 case 0x2A: /* Device settings/capacity changed */
1765 rc = read_cap16(sdev, lli);
1770 if (prev_lba != gli->max_lba)
1771 dev_dbg(dev, "%s: Capacity changed old=%lld "
1772 "new=%lld\n", __func__, prev_lba,
1775 case 0x3F: /* Report LUNs changed, Rescan. */
1776 scsi_scan_host(cfg->host);
1788 dev_dbg(dev, "%s: sense_key %x asc %x ascq %x rc %d\n", __func__,
1789 sshdr.sense_key, sshdr.asc, sshdr.ascq, rc);
1794 * cxlflash_disk_verify() - verifies a LUN is the same and handle size changes
1795 * @sdev: SCSI device associated with LUN.
1796 * @verify: Verify ioctl data structure.
1798 * Return: 0 on success, -errno on failure
1800 static int cxlflash_disk_verify(struct scsi_device *sdev,
1801 struct dk_cxlflash_verify *verify)
1804 struct ctx_info *ctxi = NULL;
1805 struct cxlflash_cfg *cfg = shost_priv(sdev->host);
1806 struct device *dev = &cfg->dev->dev;
1807 struct llun_info *lli = sdev->hostdata;
1808 struct glun_info *gli = lli->parent;
1809 struct sisl_rht_entry *rhte = NULL;
1810 res_hndl_t rhndl = verify->rsrc_handle;
1811 u64 ctxid = DECODE_CTXID(verify->context_id),
1812 rctxid = verify->context_id;
1815 dev_dbg(dev, "%s: ctxid=%llu rhndl=%016llx, hint=%016llx, "
1816 "flags=%016llx\n", __func__, ctxid, verify->rsrc_handle,
1817 verify->hint, verify->hdr.flags);
1819 ctxi = get_context(cfg, rctxid, lli, 0);
1820 if (unlikely(!ctxi)) {
1821 dev_dbg(dev, "%s: Bad context ctxid=%llu\n", __func__, ctxid);
1826 rhte = get_rhte(ctxi, rhndl, lli);
1827 if (unlikely(!rhte)) {
1828 dev_dbg(dev, "%s: Bad resource handle rhndl=%d\n",
1835 * Look at the hint/sense to see if it requires us to redrive
1836 * inquiry (i.e. the Unit attention is due to the WWN changing).
1838 if (verify->hint & DK_CXLFLASH_VERIFY_HINT_SENSE) {
1839 /* Can't hold mutex across process_sense/read_cap16,
1840 * since we could have an intervening EEH event.
1842 ctxi->unavail = true;
1843 mutex_unlock(&ctxi->mutex);
1844 rc = process_sense(sdev, verify);
1846 dev_err(dev, "%s: Failed to validate sense data (%d)\n",
1848 mutex_lock(&ctxi->mutex);
1849 ctxi->unavail = false;
1852 mutex_lock(&ctxi->mutex);
1853 ctxi->unavail = false;
1856 switch (gli->mode) {
1858 last_lba = gli->max_lba;
1861 /* Cast lxt_cnt to u64 for multiply to be treated as 64bit op */
1862 last_lba = ((u64)rhte->lxt_cnt * MC_CHUNK_SIZE * gli->blk_len);
1863 last_lba /= CXLFLASH_BLOCK_SIZE;
1867 WARN(1, "Unsupported LUN mode!");
1870 verify->last_lba = last_lba;
1875 dev_dbg(dev, "%s: returning rc=%d llba=%llx\n",
1876 __func__, rc, verify->last_lba);
1881 * decode_ioctl() - translates an encoded ioctl to an easily identifiable string
1882 * @cmd: The ioctl command to decode.
1884 * Return: A string identifying the decoded ioctl.
1886 static char *decode_ioctl(int cmd)
1889 case DK_CXLFLASH_ATTACH:
1890 return __stringify_1(DK_CXLFLASH_ATTACH);
1891 case DK_CXLFLASH_USER_DIRECT:
1892 return __stringify_1(DK_CXLFLASH_USER_DIRECT);
1893 case DK_CXLFLASH_USER_VIRTUAL:
1894 return __stringify_1(DK_CXLFLASH_USER_VIRTUAL);
1895 case DK_CXLFLASH_VLUN_RESIZE:
1896 return __stringify_1(DK_CXLFLASH_VLUN_RESIZE);
1897 case DK_CXLFLASH_RELEASE:
1898 return __stringify_1(DK_CXLFLASH_RELEASE);
1899 case DK_CXLFLASH_DETACH:
1900 return __stringify_1(DK_CXLFLASH_DETACH);
1901 case DK_CXLFLASH_VERIFY:
1902 return __stringify_1(DK_CXLFLASH_VERIFY);
1903 case DK_CXLFLASH_VLUN_CLONE:
1904 return __stringify_1(DK_CXLFLASH_VLUN_CLONE);
1905 case DK_CXLFLASH_RECOVER_AFU:
1906 return __stringify_1(DK_CXLFLASH_RECOVER_AFU);
1907 case DK_CXLFLASH_MANAGE_LUN:
1908 return __stringify_1(DK_CXLFLASH_MANAGE_LUN);
1915 * cxlflash_disk_direct_open() - opens a direct (physical) disk
1916 * @sdev: SCSI device associated with LUN.
1917 * @arg: UDirect ioctl data structure.
1919 * On successful return, the user is informed of the resource handle
1920 * to be used to identify the direct lun and the size (in blocks) of
1921 * the direct lun in last LBA format.
1923 * Return: 0 on success, -errno on failure
1925 static int cxlflash_disk_direct_open(struct scsi_device *sdev, void *arg)
1927 struct cxlflash_cfg *cfg = shost_priv(sdev->host);
1928 struct device *dev = &cfg->dev->dev;
1929 struct afu *afu = cfg->afu;
1930 struct llun_info *lli = sdev->hostdata;
1931 struct glun_info *gli = lli->parent;
1933 struct dk_cxlflash_udirect *pphys = (struct dk_cxlflash_udirect *)arg;
1935 u64 ctxid = DECODE_CTXID(pphys->context_id),
1936 rctxid = pphys->context_id;
1939 u64 rsrc_handle = -1;
1940 u32 port = CHAN2PORTMASK(sdev->channel);
1944 struct ctx_info *ctxi = NULL;
1945 struct sisl_rht_entry *rhte = NULL;
1947 dev_dbg(dev, "%s: ctxid=%llu ls=%llu\n", __func__, ctxid, lun_size);
1949 rc = cxlflash_lun_attach(gli, MODE_PHYSICAL, false);
1951 dev_dbg(dev, "%s: Failed attach to LUN (PHYSICAL)\n", __func__);
1955 ctxi = get_context(cfg, rctxid, lli, 0);
1956 if (unlikely(!ctxi)) {
1957 dev_dbg(dev, "%s: Bad context ctxid=%llu\n", __func__, ctxid);
1962 rhte = rhte_checkout(ctxi, lli);
1963 if (unlikely(!rhte)) {
1964 dev_dbg(dev, "%s: Too many opens ctxid=%lld\n",
1966 rc = -EMFILE; /* too many opens */
1970 rsrc_handle = (rhte - ctxi->rht_start);
1972 rht_format1(rhte, lli->lun_id[sdev->channel], ctxi->rht_perms, port);
1973 cxlflash_afu_sync(afu, ctxid, rsrc_handle, AFU_LW_SYNC);
1975 last_lba = gli->max_lba;
1976 pphys->hdr.return_flags = 0;
1977 pphys->last_lba = last_lba;
1978 pphys->rsrc_handle = rsrc_handle;
1983 dev_dbg(dev, "%s: returning handle=%llu rc=%d llba=%llu\n",
1984 __func__, rsrc_handle, rc, last_lba);
1988 cxlflash_lun_detach(gli);
1993 * ioctl_common() - common IOCTL handler for driver
1994 * @sdev: SCSI device associated with LUN.
1995 * @cmd: IOCTL command.
1997 * Handles common fencing operations that are valid for multiple ioctls. Always
1998 * allow through ioctls that are cleanup oriented in nature, even when operating
1999 * in a failed/terminating state.
2001 * Return: 0 on success, -errno on failure
2003 static int ioctl_common(struct scsi_device *sdev, int cmd)
2005 struct cxlflash_cfg *cfg = shost_priv(sdev->host);
2006 struct device *dev = &cfg->dev->dev;
2007 struct llun_info *lli = sdev->hostdata;
2010 if (unlikely(!lli)) {
2011 dev_dbg(dev, "%s: Unknown LUN\n", __func__);
2016 rc = check_state(cfg);
2017 if (unlikely(rc) && (cfg->state == STATE_FAILTERM)) {
2019 case DK_CXLFLASH_VLUN_RESIZE:
2020 case DK_CXLFLASH_RELEASE:
2021 case DK_CXLFLASH_DETACH:
2022 dev_dbg(dev, "%s: Command override rc=%d\n",
2033 * cxlflash_ioctl() - IOCTL handler for driver
2034 * @sdev: SCSI device associated with LUN.
2035 * @cmd: IOCTL command.
2036 * @arg: Userspace ioctl data structure.
2038 * A read/write semaphore is used to implement a 'drain' of currently
2039 * running ioctls. The read semaphore is taken at the beginning of each
2040 * ioctl thread and released upon concluding execution. Additionally the
2041 * semaphore should be released and then reacquired in any ioctl execution
2042 * path which will wait for an event to occur that is outside the scope of
2043 * the ioctl (i.e. an adapter reset). To drain the ioctls currently running,
2044 * a thread simply needs to acquire the write semaphore.
2046 * Return: 0 on success, -errno on failure
2048 int cxlflash_ioctl(struct scsi_device *sdev, int cmd, void __user *arg)
2050 typedef int (*sioctl) (struct scsi_device *, void *);
2052 struct cxlflash_cfg *cfg = shost_priv(sdev->host);
2053 struct device *dev = &cfg->dev->dev;
2054 struct afu *afu = cfg->afu;
2055 struct dk_cxlflash_hdr *hdr;
2056 char buf[sizeof(union cxlflash_ioctls)];
2058 bool known_ioctl = false;
2061 struct Scsi_Host *shost = sdev->host;
2062 sioctl do_ioctl = NULL;
2064 static const struct {
2067 } ioctl_tbl[] = { /* NOTE: order matters here */
2068 {sizeof(struct dk_cxlflash_attach), (sioctl)cxlflash_disk_attach},
2069 {sizeof(struct dk_cxlflash_udirect), cxlflash_disk_direct_open},
2070 {sizeof(struct dk_cxlflash_release), (sioctl)cxlflash_disk_release},
2071 {sizeof(struct dk_cxlflash_detach), (sioctl)cxlflash_disk_detach},
2072 {sizeof(struct dk_cxlflash_verify), (sioctl)cxlflash_disk_verify},
2073 {sizeof(struct dk_cxlflash_recover_afu), (sioctl)cxlflash_afu_recover},
2074 {sizeof(struct dk_cxlflash_manage_lun), (sioctl)cxlflash_manage_lun},
2075 {sizeof(struct dk_cxlflash_uvirtual), cxlflash_disk_virtual_open},
2076 {sizeof(struct dk_cxlflash_resize), (sioctl)cxlflash_vlun_resize},
2077 {sizeof(struct dk_cxlflash_clone), (sioctl)cxlflash_disk_clone},
2080 /* Hold read semaphore so we can drain if needed */
2081 down_read(&cfg->ioctl_rwsem);
2083 /* Restrict command set to physical support only for internal LUN */
2084 if (afu->internal_lun)
2086 case DK_CXLFLASH_RELEASE:
2087 case DK_CXLFLASH_USER_VIRTUAL:
2088 case DK_CXLFLASH_VLUN_RESIZE:
2089 case DK_CXLFLASH_VLUN_CLONE:
2090 dev_dbg(dev, "%s: %s not supported for lun_mode=%d\n",
2091 __func__, decode_ioctl(cmd), afu->internal_lun);
2093 goto cxlflash_ioctl_exit;
2097 case DK_CXLFLASH_ATTACH:
2098 case DK_CXLFLASH_USER_DIRECT:
2099 case DK_CXLFLASH_RELEASE:
2100 case DK_CXLFLASH_DETACH:
2101 case DK_CXLFLASH_VERIFY:
2102 case DK_CXLFLASH_RECOVER_AFU:
2103 case DK_CXLFLASH_USER_VIRTUAL:
2104 case DK_CXLFLASH_VLUN_RESIZE:
2105 case DK_CXLFLASH_VLUN_CLONE:
2106 dev_dbg(dev, "%s: %s (%08X) on dev(%d/%d/%d/%llu)\n",
2107 __func__, decode_ioctl(cmd), cmd, shost->host_no,
2108 sdev->channel, sdev->id, sdev->lun);
2109 rc = ioctl_common(sdev, cmd);
2111 goto cxlflash_ioctl_exit;
2115 case DK_CXLFLASH_MANAGE_LUN:
2117 idx = _IOC_NR(cmd) - _IOC_NR(DK_CXLFLASH_ATTACH);
2118 size = ioctl_tbl[idx].size;
2119 do_ioctl = ioctl_tbl[idx].ioctl;
2121 if (likely(do_ioctl))
2127 goto cxlflash_ioctl_exit;
2130 if (unlikely(copy_from_user(&buf, arg, size))) {
2131 dev_err(dev, "%s: copy_from_user() fail "
2132 "size=%lu cmd=%d (%s) arg=%p\n",
2133 __func__, size, cmd, decode_ioctl(cmd), arg);
2135 goto cxlflash_ioctl_exit;
2138 hdr = (struct dk_cxlflash_hdr *)&buf;
2139 if (hdr->version != DK_CXLFLASH_VERSION_0) {
2140 dev_dbg(dev, "%s: Version %u not supported for %s\n",
2141 __func__, hdr->version, decode_ioctl(cmd));
2143 goto cxlflash_ioctl_exit;
2146 if (hdr->rsvd[0] || hdr->rsvd[1] || hdr->rsvd[2] || hdr->return_flags) {
2147 dev_dbg(dev, "%s: Reserved/rflags populated\n", __func__);
2149 goto cxlflash_ioctl_exit;
2152 rc = do_ioctl(sdev, (void *)&buf);
2154 if (unlikely(copy_to_user(arg, &buf, size))) {
2155 dev_err(dev, "%s: copy_to_user() fail "
2156 "size=%lu cmd=%d (%s) arg=%p\n",
2157 __func__, size, cmd, decode_ioctl(cmd), arg);
2161 /* fall through to exit */
2163 cxlflash_ioctl_exit:
2164 up_read(&cfg->ioctl_rwsem);
2165 if (unlikely(rc && known_ioctl))
2166 dev_err(dev, "%s: ioctl %s (%08X) on dev(%d/%d/%d/%llu) "
2167 "returned rc %d\n", __func__,
2168 decode_ioctl(cmd), cmd, shost->host_no,
2169 sdev->channel, sdev->id, sdev->lun, rc);
2171 dev_dbg(dev, "%s: ioctl %s (%08X) on dev(%d/%d/%d/%llu) "
2172 "returned rc %d\n", __func__, decode_ioctl(cmd),
2173 cmd, shost->host_no, sdev->channel, sdev->id,