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/file.h>
17 #include <linux/syscalls.h>
18 #include <misc/cxl.h>
19 #include <asm/unaligned.h>
20 
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>
26 
27 #include "sislite.h"
28 #include "common.h"
29 #include "vlun.h"
30 #include "superpipe.h"
31 
32 struct cxlflash_global global;
33 
34 /**
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.
38  */
39 static void marshal_rele_to_resize(struct dk_cxlflash_release *release,
40 				   struct dk_cxlflash_resize *resize)
41 {
42 	resize->hdr = release->hdr;
43 	resize->context_id = release->context_id;
44 	resize->rsrc_handle = release->rsrc_handle;
45 }
46 
47 /**
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.
51  */
52 static void marshal_det_to_rele(struct dk_cxlflash_detach *detach,
53 				struct dk_cxlflash_release *release)
54 {
55 	release->hdr = detach->hdr;
56 	release->context_id = detach->context_id;
57 }
58 
59 /**
60  * cxlflash_free_errpage() - frees resources associated with global error page
61  */
62 void cxlflash_free_errpage(void)
63 {
64 
65 	mutex_lock(&global.mutex);
66 	if (global.err_page) {
67 		__free_page(global.err_page);
68 		global.err_page = NULL;
69 	}
70 	mutex_unlock(&global.mutex);
71 }
72 
73 /**
74  * cxlflash_stop_term_user_contexts() - stops/terminates known user contexts
75  * @cfg:	Internal structure associated with the host.
76  *
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.
81  *
82  * Note that the main loop in this routine will always execute at least once
83  * to flush the reset_waitq.
84  */
85 void cxlflash_stop_term_user_contexts(struct cxlflash_cfg *cfg)
86 {
87 	struct device *dev = &cfg->dev->dev;
88 	int i, found = true;
89 
90 	cxlflash_mark_contexts_error(cfg);
91 
92 	while (true) {
93 		for (i = 0; i < MAX_CONTEXT; i++)
94 			if (cfg->ctx_tbl[i]) {
95 				found = true;
96 				break;
97 			}
98 
99 		if (!found && list_empty(&cfg->ctx_err_recovery))
100 			return;
101 
102 		dev_dbg(dev, "%s: Wait for user contexts to quiesce...\n",
103 			__func__);
104 		wake_up_all(&cfg->reset_waitq);
105 		ssleep(1);
106 		found = false;
107 	}
108 }
109 
110 /**
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.
115  *
116  * Return: Found context on success, NULL on failure
117  */
118 static struct ctx_info *find_error_context(struct cxlflash_cfg *cfg, u64 rctxid,
119 					   struct file *file)
120 {
121 	struct ctx_info *ctxi;
122 
123 	list_for_each_entry(ctxi, &cfg->ctx_err_recovery, list)
124 		if ((ctxi->ctxid == rctxid) || (ctxi->file == file))
125 			return ctxi;
126 
127 	return NULL;
128 }
129 
130 /**
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.
136  *
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.
142  *
143  * Return: Validated context on success, NULL on failure
144  */
145 struct ctx_info *get_context(struct cxlflash_cfg *cfg, u64 rctxid,
146 			     void *arg, enum ctx_ctrl ctx_ctrl)
147 {
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);
154 	int rc;
155 	pid_t pid = current->tgid, ctxpid = 0;
156 
157 	if (ctx_ctrl & CTX_CTRL_FILE) {
158 		lli = NULL;
159 		file = (struct file *)arg;
160 	}
161 
162 	if (ctx_ctrl & CTX_CTRL_CLONE)
163 		pid = current->parent->tgid;
164 
165 	if (likely(ctxid < MAX_CONTEXT)) {
166 		while (true) {
167 			mutex_lock(&cfg->ctx_tbl_list_mutex);
168 			ctxi = cfg->ctx_tbl[ctxid];
169 			if (ctxi)
170 				if ((file && (ctxi->file != file)) ||
171 				    (!file && (ctxi->ctxid != rctxid)))
172 					ctxi = NULL;
173 
174 			if ((ctx_ctrl & CTX_CTRL_ERR) ||
175 			    (!ctxi && (ctx_ctrl & CTX_CTRL_ERR_FALLBACK)))
176 				ctxi = find_error_context(cfg, rctxid, file);
177 			if (!ctxi) {
178 				mutex_unlock(&cfg->ctx_tbl_list_mutex);
179 				goto out;
180 			}
181 
182 			/*
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.
187 			 *
188 			 * Note that the lock order is:
189 			 *
190 			 *	cfg->ctx_tbl_list_mutex -> ctxi->mutex
191 			 *
192 			 * Therefore release ctx_tbl_list_mutex before retrying.
193 			 */
194 			rc = mutex_trylock(&ctxi->mutex);
195 			mutex_unlock(&cfg->ctx_tbl_list_mutex);
196 			if (rc)
197 				break; /* got the context's lock! */
198 		}
199 
200 		if (ctxi->unavail)
201 			goto denied;
202 
203 		ctxpid = ctxi->pid;
204 		if (likely(!(ctx_ctrl & CTX_CTRL_NOPID)))
205 			if (pid != ctxpid)
206 				goto denied;
207 
208 		if (lli) {
209 			list_for_each_entry(lun_access, &ctxi->luns, list)
210 				if (lun_access->lli == lli)
211 					goto out;
212 			goto denied;
213 		}
214 	}
215 
216 out:
217 	dev_dbg(dev, "%s: rctxid=%016llx ctxinfo=%p ctxpid=%u pid=%u "
218 		"ctx_ctrl=%u\n", __func__, rctxid, ctxi, ctxpid, pid,
219 		ctx_ctrl);
220 
221 	return ctxi;
222 
223 denied:
224 	mutex_unlock(&ctxi->mutex);
225 	ctxi = NULL;
226 	goto out;
227 }
228 
229 /**
230  * put_context() - release a context that was retrieved from get_context()
231  * @ctxi:	Context to release.
232  *
233  * For now, releasing the context equates to unlocking it's mutex.
234  */
235 void put_context(struct ctx_info *ctxi)
236 {
237 	mutex_unlock(&ctxi->mutex);
238 }
239 
240 /**
241  * afu_attach() - attach a context to the AFU
242  * @cfg:	Internal structure associated with the host.
243  * @ctxi:	Context to attach.
244  *
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.
248  *
249  * Return: 0 on success, -errno on failure
250  */
251 static int afu_attach(struct cxlflash_cfg *cfg, struct ctx_info *ctxi)
252 {
253 	struct device *dev = &cfg->dev->dev;
254 	struct afu *afu = cfg->afu;
255 	struct sisl_ctrl_map __iomem *ctrl_map = ctxi->ctrl_map;
256 	int rc = 0;
257 	struct hwq *hwq = get_hwq(afu, PRIMARY_HWQ);
258 	u64 val;
259 
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",
267 			__func__, val);
268 		rc = -EAGAIN;
269 		goto out;
270 	}
271 
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);
276 out:
277 	dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
278 	return rc;
279 }
280 
281 /**
282  * read_cap16() - issues a SCSI READ_CAP16 command
283  * @sdev:	SCSI device associated with LUN.
284  * @lli:	LUN destined for capacity request.
285  *
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
299  * to continue.
300  *
301  * Note that the above puts a requirement on this routine to only be called on
302  * an ioctl thread.
303  *
304  * Return: 0 on success, -errno on failure
305  */
306 static int read_cap16(struct scsi_device *sdev, struct llun_info *lli)
307 {
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;
312 	u8 *cmd_buf = NULL;
313 	u8 *scsi_cmd = NULL;
314 	u8 *sense_buf = NULL;
315 	int rc = 0;
316 	int result = 0;
317 	int retry_cnt = 0;
318 	u32 to = CMD_TIMEOUT * HZ;
319 
320 retry:
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)) {
325 		rc = -ENOMEM;
326 		goto out;
327 	}
328 
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]);
332 
333 	dev_dbg(dev, "%s: %ssending cmd(%02x)\n", __func__,
334 		retry_cnt ? "re" : "", scsi_cmd[0]);
335 
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,
340 			      0, 0, NULL);
341 	down_read(&cfg->ioctl_rwsem);
342 	rc = check_state(cfg);
343 	if (rc) {
344 		dev_err(dev, "%s: Failed state result=%08x\n",
345 			__func__, result);
346 		rc = -ENODEV;
347 		goto out;
348 	}
349 
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) {
354 			case NO_SENSE:
355 			case RECOVERED_ERROR:
356 				/* fall through */
357 			case NOT_READY:
358 				result &= ~SAM_STAT_CHECK_CONDITION;
359 				break;
360 			case UNIT_ATTENTION:
361 				switch (sshdr.asc) {
362 				case 0x29: /* Power on Reset or Device Reset */
363 					/* fall through */
364 				case 0x2A: /* Device capacity changed */
365 				case 0x3F: /* Report LUNs changed */
366 					/* Retry the command once more */
367 					if (retry_cnt++ < 1) {
368 						kfree(cmd_buf);
369 						kfree(scsi_cmd);
370 						kfree(sense_buf);
371 						goto retry;
372 					}
373 				}
374 				break;
375 			default:
376 				break;
377 			}
378 		}
379 	}
380 
381 	if (result) {
382 		dev_err(dev, "%s: command failed, result=%08x\n",
383 			__func__, result);
384 		rc = -EIO;
385 		goto out;
386 	}
387 
388 	/*
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.
392 	 */
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);
397 
398 out:
399 	kfree(cmd_buf);
400 	kfree(scsi_cmd);
401 	kfree(sense_buf);
402 
403 	dev_dbg(dev, "%s: maxlba=%lld blklen=%d rc=%d\n",
404 		__func__, gli->max_lba, gli->blk_len, rc);
405 	return rc;
406 }
407 
408 /**
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.
413  *
414  * Return: Validated RHTE on success, NULL on failure
415  */
416 struct sisl_rht_entry *get_rhte(struct ctx_info *ctxi, res_hndl_t rhndl,
417 				struct llun_info *lli)
418 {
419 	struct cxlflash_cfg *cfg = ctxi->cfg;
420 	struct device *dev = &cfg->dev->dev;
421 	struct sisl_rht_entry *rhte = NULL;
422 
423 	if (unlikely(!ctxi->rht_start)) {
424 		dev_dbg(dev, "%s: Context does not have allocated RHT\n",
425 			 __func__);
426 		goto out;
427 	}
428 
429 	if (unlikely(rhndl >= MAX_RHT_PER_CONTEXT)) {
430 		dev_dbg(dev, "%s: Bad resource handle rhndl=%d\n",
431 			__func__, rhndl);
432 		goto out;
433 	}
434 
435 	if (unlikely(ctxi->rht_lun[rhndl] != lli)) {
436 		dev_dbg(dev, "%s: Bad resource handle LUN rhndl=%d\n",
437 			__func__, rhndl);
438 		goto out;
439 	}
440 
441 	rhte = &ctxi->rht_start[rhndl];
442 	if (unlikely(rhte->nmask == 0)) {
443 		dev_dbg(dev, "%s: Unopened resource handle rhndl=%d\n",
444 			__func__, rhndl);
445 		rhte = NULL;
446 		goto out;
447 	}
448 
449 out:
450 	return rhte;
451 }
452 
453 /**
454  * rhte_checkout() - obtains free/empty resource handle table entry
455  * @ctxi:	Context owning the resource handle.
456  * @lli:	LUN associated with request.
457  *
458  * Return: Free RHTE on success, NULL on failure
459  */
460 struct sisl_rht_entry *rhte_checkout(struct ctx_info *ctxi,
461 				     struct llun_info *lli)
462 {
463 	struct cxlflash_cfg *cfg = ctxi->cfg;
464 	struct device *dev = &cfg->dev->dev;
465 	struct sisl_rht_entry *rhte = NULL;
466 	int i;
467 
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];
472 			ctxi->rht_out++;
473 			break;
474 		}
475 
476 	if (likely(rhte))
477 		ctxi->rht_lun[i] = lli;
478 
479 	dev_dbg(dev, "%s: returning rhte=%p index=%d\n", __func__, rhte, i);
480 	return rhte;
481 }
482 
483 /**
484  * rhte_checkin() - releases a resource handle table entry
485  * @ctxi:	Context owning the resource handle.
486  * @rhte:	RHTE to release.
487  */
488 void rhte_checkin(struct ctx_info *ctxi,
489 		  struct sisl_rht_entry *rhte)
490 {
491 	u32 rsrc_handle = rhte - ctxi->rht_start;
492 
493 	rhte->nmask = 0;
494 	rhte->fp = 0;
495 	ctxi->rht_out--;
496 	ctxi->rht_lun[rsrc_handle] = NULL;
497 	ctxi->rht_needs_ws[rsrc_handle] = false;
498 }
499 
500 /**
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
506  */
507 static void rht_format1(struct sisl_rht_entry *rhte, u64 lun_id, u32 perm,
508 			u32 port_sel)
509 {
510 	/*
511 	 * Populate the Format 1 RHT entry for direct access (physical
512 	 * LUN) using the synchronization sequence defined in the
513 	 * SISLite specification.
514 	 */
515 	struct sisl_rht_entry_f1 dummy = { 0 };
516 	struct sisl_rht_entry_f1 *rhte_f1 = (struct sisl_rht_entry_f1 *)rhte;
517 
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 */
521 
522 	rhte_f1->lun_id = lun_id;
523 	dma_wmb(); /* Make setting of LUN id visible */
524 
525 	/*
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).
529 	 */
530 	dummy.valid = 0x80;
531 	dummy.fp = SISL_RHT_FP(1U, perm);
532 	dummy.port_sel = port_sel;
533 	rhte_f1->dw = dummy.dw;
534 
535 	dma_wmb(); /* Make remaining RHT entry fields visible */
536 }
537 
538 /**
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.
543  *
544  * Return: 0 on success, -errno on failure
545  */
546 int cxlflash_lun_attach(struct glun_info *gli, enum lun_mode mode, bool locked)
547 {
548 	int rc = 0;
549 
550 	if (!locked)
551 		mutex_lock(&gli->mutex);
552 
553 	if (gli->mode == MODE_NONE)
554 		gli->mode = mode;
555 	else if (gli->mode != mode) {
556 		pr_debug("%s: gli_mode=%d requested_mode=%d\n",
557 			 __func__, gli->mode, mode);
558 		rc = -EINVAL;
559 		goto out;
560 	}
561 
562 	gli->users++;
563 	WARN_ON(gli->users <= 0);
564 out:
565 	pr_debug("%s: Returning rc=%d gli->mode=%u gli->users=%u\n",
566 		 __func__, rc, gli->mode, gli->users);
567 	if (!locked)
568 		mutex_unlock(&gli->mutex);
569 	return rc;
570 }
571 
572 /**
573  * cxlflash_lun_detach() - detaches a user from a LUN and resets the LUN's mode
574  * @gli:	LUN to detach.
575  *
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
580  * virtual mode).
581  */
582 void cxlflash_lun_detach(struct glun_info *gli)
583 {
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);
589 	}
590 	pr_debug("%s: gli->users=%u\n", __func__, gli->users);
591 	WARN_ON(gli->users < 0);
592 	mutex_unlock(&gli->mutex);
593 }
594 
595 /**
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.
600  *
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.
607  *
608  * Return: 0 on success, -errno on failure
609  */
610 int _cxlflash_disk_release(struct scsi_device *sdev,
611 			   struct ctx_info *ctxi,
612 			   struct dk_cxlflash_release *release)
613 {
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;
620 
621 	struct dk_cxlflash_resize size;
622 	res_hndl_t rhndl = release->rsrc_handle;
623 
624 	int rc = 0;
625 	u64 ctxid = DECODE_CTXID(release->context_id),
626 	    rctxid = release->context_id;
627 
628 	struct sisl_rht_entry *rhte;
629 	struct sisl_rht_entry_f1 *rhte_f1;
630 
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);
633 
634 	if (!ctxi) {
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",
638 				__func__, ctxid);
639 			rc = -EINVAL;
640 			goto out;
641 		}
642 
643 		put_ctx = true;
644 	}
645 
646 	rhte = get_rhte(ctxi, rhndl, lli);
647 	if (unlikely(!rhte)) {
648 		dev_dbg(dev, "%s: Bad resource handle rhndl=%d\n",
649 			__func__, rhndl);
650 		rc = -EINVAL;
651 		goto out;
652 	}
653 
654 	/*
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.
658 	 *
659 	 * Afterwards we clear the remaining fields.
660 	 */
661 	switch (gli->mode) {
662 	case MODE_VIRTUAL:
663 		marshal_rele_to_resize(release, &size);
664 		size.req_size = 0;
665 		rc = _cxlflash_vlun_resize(sdev, ctxi, &size);
666 		if (rc) {
667 			dev_dbg(dev, "%s: resize failed rc %d\n", __func__, rc);
668 			goto out;
669 		}
670 
671 		break;
672 	case MODE_PHYSICAL:
673 		/*
674 		 * Clear the Format 1 RHT entry for direct access
675 		 * (physical LUN) using the synchronization sequence
676 		 * defined in the SISLite specification.
677 		 */
678 		rhte_f1 = (struct sisl_rht_entry_f1 *)rhte;
679 
680 		rhte_f1->valid = 0;
681 		dma_wmb(); /* Make revocation of RHT entry visible */
682 
683 		rhte_f1->lun_id = 0;
684 		dma_wmb(); /* Make clearing of LUN id visible */
685 
686 		rhte_f1->dw = 0;
687 		dma_wmb(); /* Make RHT entry bottom-half clearing visible */
688 
689 		if (!ctxi->err_recovery_active)
690 			cxlflash_afu_sync(afu, ctxid, rhndl, AFU_HW_SYNC);
691 		break;
692 	default:
693 		WARN(1, "Unsupported LUN mode!");
694 		goto out;
695 	}
696 
697 	rhte_checkin(ctxi, rhte);
698 	cxlflash_lun_detach(gli);
699 
700 out:
701 	if (put_ctx)
702 		put_context(ctxi);
703 	dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
704 	return rc;
705 }
706 
707 int cxlflash_disk_release(struct scsi_device *sdev,
708 			  struct dk_cxlflash_release *release)
709 {
710 	return _cxlflash_disk_release(sdev, NULL, release);
711 }
712 
713 /**
714  * destroy_context() - releases a context
715  * @cfg:	Internal structure associated with the host.
716  * @ctxi:	Context to release.
717  *
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).
725  */
726 static void destroy_context(struct cxlflash_cfg *cfg,
727 			    struct ctx_info *ctxi)
728 {
729 	struct afu *afu = cfg->afu;
730 
731 	if (ctxi->initialized) {
732 		WARN_ON(!list_empty(&ctxi->luns));
733 
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);
739 		}
740 	}
741 
742 	/* Free memory associated with context */
743 	free_page((ulong)ctxi->rht_start);
744 	kfree(ctxi->rht_needs_ws);
745 	kfree(ctxi->rht_lun);
746 	kfree(ctxi);
747 }
748 
749 /**
750  * create_context() - allocates and initializes a context
751  * @cfg:	Internal structure associated with the host.
752  *
753  * Return: Allocated context on success, NULL on failure
754  */
755 static struct ctx_info *create_context(struct cxlflash_cfg *cfg)
756 {
757 	struct device *dev = &cfg->dev->dev;
758 	struct ctx_info *ctxi = NULL;
759 	struct llun_info **lli = NULL;
760 	u8 *ws = NULL;
761 	struct sisl_rht_entry *rhte;
762 
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__);
768 		goto err;
769 	}
770 
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__);
774 		goto err;
775 	}
776 
777 	ctxi->rht_lun = lli;
778 	ctxi->rht_needs_ws = ws;
779 	ctxi->rht_start = rhte;
780 out:
781 	return ctxi;
782 
783 err:
784 	kfree(ws);
785 	kfree(lli);
786 	kfree(ctxi);
787 	ctxi = NULL;
788 	goto out;
789 }
790 
791 /**
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.
799  */
800 static void init_context(struct ctx_info *ctxi, struct cxlflash_cfg *cfg,
801 			 struct cxl_context *ctx, int ctxid, struct file *file,
802 			 u32 perms)
803 {
804 	struct afu *afu = cfg->afu;
805 
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 */
810 	ctxi->ctx = ctx;
811 	ctxi->cfg = cfg;
812 	ctxi->file = file;
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() */
818 }
819 
820 /**
821  * remove_context() - context kref release handler
822  * @kref:	Kernel reference associated with context to be removed.
823  *
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.
827  */
828 static void remove_context(struct kref *kref)
829 {
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);
833 
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);
840 
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);
846 
847 	/* Context now completely uncoupled/unreachable */
848 	destroy_context(cfg, ctxi);
849 }
850 
851 /**
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.
856  *
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.
860  *
861  * Return: 0 on success, -errno on failure
862  */
863 static int _cxlflash_disk_detach(struct scsi_device *sdev,
864 				 struct ctx_info *ctxi,
865 				 struct dk_cxlflash_detach *detach)
866 {
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;
873 
874 	int i;
875 	int rc = 0;
876 	u64 ctxid = DECODE_CTXID(detach->context_id),
877 	    rctxid = detach->context_id;
878 
879 	dev_dbg(dev, "%s: ctxid=%llu\n", __func__, ctxid);
880 
881 	if (!ctxi) {
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",
885 				__func__, ctxid);
886 			rc = -EINVAL;
887 			goto out;
888 		}
889 
890 		put_ctx = true;
891 	}
892 
893 	/* Cleanup outstanding resources tied to this LUN */
894 	if (ctxi->rht_out) {
895 		marshal_det_to_rele(detach, &rel);
896 		for (i = 0; i < MAX_RHT_PER_CONTEXT; i++) {
897 			if (ctxi->rht_lun[i] == lli) {
898 				rel.rsrc_handle = i;
899 				_cxlflash_disk_release(sdev, ctxi, &rel);
900 			}
901 
902 			/* No need to loop further if we're done */
903 			if (ctxi->rht_out == 0)
904 				break;
905 		}
906 	}
907 
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);
912 			kfree(lun_access);
913 			lun_access = NULL;
914 			break;
915 		}
916 
917 	/*
918 	 * Release the context reference and the sdev reference that
919 	 * bound this LUN to the context.
920 	 */
921 	if (kref_put(&ctxi->kref, remove_context))
922 		put_ctx = false;
923 	scsi_device_put(sdev);
924 out:
925 	if (put_ctx)
926 		put_context(ctxi);
927 	dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
928 	return rc;
929 }
930 
931 static int cxlflash_disk_detach(struct scsi_device *sdev,
932 				struct dk_cxlflash_detach *detach)
933 {
934 	return _cxlflash_disk_detach(sdev, NULL, detach);
935 }
936 
937 /**
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.
941  *
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.
949  *
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.
956  *
957  * Return: 0 on success
958  */
959 static int cxlflash_cxl_release(struct inode *inode, struct file *file)
960 {
961 	struct cxl_context *ctx = cxl_fops_get_context(file);
962 	struct cxlflash_cfg *cfg = container_of(file->f_op, struct cxlflash_cfg,
963 						cxl_fops);
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;
969 	int ctxid;
970 
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);
975 		goto out;
976 	}
977 
978 	ctxi = get_context(cfg, ctxid, file, ctrl);
979 	if (unlikely(!ctxi)) {
980 		ctxi = get_context(cfg, ctxid, file, ctrl | CTX_CTRL_CLONE);
981 		if (!ctxi) {
982 			dev_dbg(dev, "%s: ctxid=%d already free\n",
983 				__func__, ctxid);
984 			goto out_release;
985 		}
986 
987 		dev_dbg(dev, "%s: Another process owns ctxid=%d\n",
988 			__func__, ctxid);
989 		put_context(ctxi);
990 		goto out;
991 	}
992 
993 	dev_dbg(dev, "%s: close for ctxid=%d\n", __func__, ctxid);
994 
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);
998 out_release:
999 	cxl_fd_release(inode, file);
1000 out:
1001 	dev_dbg(dev, "%s: returning\n", __func__);
1002 	return 0;
1003 }
1004 
1005 /**
1006  * unmap_context() - clears a previously established mapping
1007  * @ctxi:	Context owning the mapping.
1008  *
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
1011  * fault handler).
1012  */
1013 static void unmap_context(struct ctx_info *ctxi)
1014 {
1015 	unmap_mapping_range(ctxi->file->f_mapping, 0, 0, 1);
1016 }
1017 
1018 /**
1019  * get_err_page() - obtains and allocates the error notification page
1020  * @cfg:	Internal structure associated with the host.
1021  *
1022  * Return: error notification page on success, NULL on failure
1023  */
1024 static struct page *get_err_page(struct cxlflash_cfg *cfg)
1025 {
1026 	struct page *err_page = global.err_page;
1027 	struct device *dev = &cfg->dev->dev;
1028 
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",
1033 				__func__);
1034 			goto out;
1035 		}
1036 
1037 		memset(page_address(err_page), -1, PAGE_SIZE);
1038 
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;
1043 		else {
1044 			__free_page(err_page);
1045 			err_page = global.err_page;
1046 		}
1047 		mutex_unlock(&global.mutex);
1048 	}
1049 
1050 out:
1051 	dev_dbg(dev, "%s: returning err_page=%p\n", __func__, err_page);
1052 	return err_page;
1053 }
1054 
1055 /**
1056  * cxlflash_mmap_fault() - mmap fault handler for adapter file descriptor
1057  * @vmf:	VM fault associated with current fault.
1058  *
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.
1067  *
1068  * Return: 0 on success, VM_FAULT_SIGBUS on failure
1069  */
1070 static int cxlflash_mmap_fault(struct vm_fault *vmf)
1071 {
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,
1076 						cxl_fops);
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;
1081 	int rc = 0;
1082 	int ctxid;
1083 
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);
1088 		goto err;
1089 	}
1090 
1091 	ctxi = get_context(cfg, ctxid, file, ctrl);
1092 	if (unlikely(!ctxi)) {
1093 		dev_dbg(dev, "%s: Bad context ctxid=%d\n", __func__, ctxid);
1094 		goto err;
1095 	}
1096 
1097 	dev_dbg(dev, "%s: fault for context %d\n", __func__, ctxid);
1098 
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);
1102 	} else {
1103 		dev_dbg(dev, "%s: err recovery active, use err_page\n",
1104 			__func__);
1105 
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;
1110 			goto out;
1111 		}
1112 
1113 		get_page(err_page);
1114 		vmf->page = err_page;
1115 		vma->vm_page_prot = pgprot_cached(vma->vm_page_prot);
1116 	}
1117 
1118 out:
1119 	if (likely(ctxi))
1120 		put_context(ctxi);
1121 	dev_dbg(dev, "%s: returning rc=%d\n", __func__, rc);
1122 	return rc;
1123 
1124 err:
1125 	rc = VM_FAULT_SIGBUS;
1126 	goto out;
1127 }
1128 
1129 /*
1130  * Local MMAP vmops to 'catch' faults
1131  */
1132 static const struct vm_operations_struct cxlflash_mmap_vmops = {
1133 	.fault = cxlflash_mmap_fault,
1134 };
1135 
1136 /**
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.
1140  *
1141  * Installs local mmap vmops to 'catch' faults for error notification support.
1142  *
1143  * Return: 0 on success, -errno on failure
1144  */
1145 static int cxlflash_cxl_mmap(struct file *file, struct vm_area_struct *vma)
1146 {
1147 	struct cxl_context *ctx = cxl_fops_get_context(file);
1148 	struct cxlflash_cfg *cfg = container_of(file->f_op, struct cxlflash_cfg,
1149 						cxl_fops);
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;
1153 	int ctxid;
1154 	int rc = 0;
1155 
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);
1160 		rc = -EIO;
1161 		goto out;
1162 	}
1163 
1164 	ctxi = get_context(cfg, ctxid, file, ctrl);
1165 	if (unlikely(!ctxi)) {
1166 		dev_dbg(dev, "%s: Bad context ctxid=%d\n", __func__, ctxid);
1167 		rc = -EIO;
1168 		goto out;
1169 	}
1170 
1171 	dev_dbg(dev, "%s: mmap for context %d\n", __func__, ctxid);
1172 
1173 	rc = cxl_fd_mmap(file, vma);
1174 	if (likely(!rc)) {
1175 		/* Insert ourself in the mmap fault handler path */
1176 		ctxi->cxl_mmap_vmops = vma->vm_ops;
1177 		vma->vm_ops = &cxlflash_mmap_vmops;
1178 	}
1179 
1180 out:
1181 	if (likely(ctxi))
1182 		put_context(ctxi);
1183 	return rc;
1184 }
1185 
1186 const struct file_operations cxlflash_cxl_fops = {
1187 	.owner = THIS_MODULE,
1188 	.mmap = cxlflash_cxl_mmap,
1189 	.release = cxlflash_cxl_release,
1190 };
1191 
1192 /**
1193  * cxlflash_mark_contexts_error() - move contexts to error state and list
1194  * @cfg:	Internal structure associated with the host.
1195  *
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.
1198  *
1199  * Return: 0 on success, -errno on failure
1200  */
1201 int cxlflash_mark_contexts_error(struct cxlflash_cfg *cfg)
1202 {
1203 	int i, rc = 0;
1204 	struct ctx_info *ctxi = NULL;
1205 
1206 	mutex_lock(&cfg->ctx_tbl_list_mutex);
1207 
1208 	for (i = 0; i < MAX_CONTEXT; i++) {
1209 		ctxi = cfg->ctx_tbl[i];
1210 		if (ctxi) {
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);
1218 		}
1219 	}
1220 
1221 	mutex_unlock(&cfg->ctx_tbl_list_mutex);
1222 	return rc;
1223 }
1224 
1225 /*
1226  * Dummy NULL fops
1227  */
1228 static const struct file_operations null_fops = {
1229 	.owner = THIS_MODULE,
1230 };
1231 
1232 /**
1233  * check_state() - checks and responds to the current adapter state
1234  * @cfg:	Internal structure associated with the host.
1235  *
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.
1242  *
1243  * Return: 0 on success, -errno on failure
1244  */
1245 int check_state(struct cxlflash_cfg *cfg)
1246 {
1247 	struct device *dev = &cfg->dev->dev;
1248 	int rc = 0;
1249 
1250 retry:
1251 	switch (cfg->state) {
1252 	case STATE_RESET:
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);
1258 		if (unlikely(rc))
1259 			break;
1260 		goto retry;
1261 	case STATE_FAILTERM:
1262 		dev_dbg(dev, "%s: Failed/Terminating\n", __func__);
1263 		rc = -ENODEV;
1264 		break;
1265 	default:
1266 		break;
1267 	}
1268 
1269 	return rc;
1270 }
1271 
1272 /**
1273  * cxlflash_disk_attach() - attach a LUN to a context
1274  * @sdev:	SCSI device associated with LUN.
1275  * @attach:	Attach ioctl data structure.
1276  *
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.
1281  *
1282  * Return: 0 on success, -errno on failure
1283  */
1284 static int cxlflash_disk_attach(struct scsi_device *sdev,
1285 				struct dk_cxlflash_attach *attach)
1286 {
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;
1295 	int rc = 0;
1296 	u32 perms;
1297 	int ctxid = -1;
1298 	u64 flags = 0UL;
1299 	u64 rctxid = 0UL;
1300 	struct file *file = NULL;
1301 
1302 	struct cxl_context *ctx = NULL;
1303 
1304 	int fd = -1;
1305 
1306 	if (attach->num_interrupts > 4) {
1307 		dev_dbg(dev, "%s: Cannot support this many interrupts %llu\n",
1308 			__func__, attach->num_interrupts);
1309 		rc = -EINVAL;
1310 		goto out;
1311 	}
1312 
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);
1317 		if (rc) {
1318 			dev_err(dev, "%s: Invalid device rc=%d\n",
1319 				__func__, rc);
1320 			rc = -ENODEV;
1321 			goto out;
1322 		}
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);
1325 	}
1326 
1327 	if (attach->hdr.flags & DK_CXLFLASH_ATTACH_REUSE_CONTEXT) {
1328 		rctxid = attach->context_id;
1329 		ctxi = get_context(cfg, rctxid, NULL, 0);
1330 		if (!ctxi) {
1331 			dev_dbg(dev, "%s: Bad context rctxid=%016llx\n",
1332 				__func__, rctxid);
1333 			rc = -EINVAL;
1334 			goto out;
1335 		}
1336 
1337 		list_for_each_entry(lun_access, &ctxi->luns, list)
1338 			if (lun_access->lli == lli) {
1339 				dev_dbg(dev, "%s: Already attached\n",
1340 					__func__);
1341 				rc = -EINVAL;
1342 				goto out;
1343 			}
1344 	}
1345 
1346 	rc = scsi_device_get(sdev);
1347 	if (unlikely(rc)) {
1348 		dev_err(dev, "%s: Unable to get sdev reference\n", __func__);
1349 		goto out;
1350 	}
1351 
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__);
1355 		rc = -ENOMEM;
1356 		goto err;
1357 	}
1358 
1359 	lun_access->lli = lli;
1360 	lun_access->sdev = sdev;
1361 
1362 	/* Non-NULL context indicates reuse (another context reference) */
1363 	if (ctxi) {
1364 		dev_dbg(dev, "%s: Reusing context for LUN rctxid=%016llx\n",
1365 			__func__, rctxid);
1366 		kref_get(&ctxi->kref);
1367 		list_add(&lun_access->list, &ctxi->luns);
1368 		goto out_attach;
1369 	}
1370 
1371 	ctxi = create_context(cfg);
1372 	if (unlikely(!ctxi)) {
1373 		dev_err(dev, "%s: Failed to create context ctxid=%d\n",
1374 			__func__, ctxid);
1375 		goto err;
1376 	}
1377 
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",
1381 			__func__, ctx);
1382 		rc = -ENODEV;
1383 		goto err;
1384 	}
1385 
1386 	work = &ctxi->work;
1387 	work->num_interrupts = attach->num_interrupts;
1388 	work->flags = CXL_START_WORK_NUM_IRQS;
1389 
1390 	rc = cxl_start_work(ctx, work);
1391 	if (unlikely(rc)) {
1392 		dev_dbg(dev, "%s: Could not start context rc=%d\n",
1393 			__func__, rc);
1394 		goto err;
1395 	}
1396 
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);
1400 		rc = -EPERM;
1401 		goto err;
1402 	}
1403 
1404 	file = cxl_get_fd(ctx, &cfg->cxl_fops, &fd);
1405 	if (unlikely(fd < 0)) {
1406 		rc = -ENODEV;
1407 		dev_err(dev, "%s: Could not get file descriptor\n", __func__);
1408 		goto err;
1409 	}
1410 
1411 	/* Translate read/write O_* flags from fcntl.h to AFU permission bits */
1412 	perms = SISL_RHT_PERM(attach->hdr.flags + 1);
1413 
1414 	/* Context mutex is locked upon return */
1415 	init_context(ctxi, cfg, ctx, ctxid, file, perms);
1416 
1417 	rc = afu_attach(cfg, ctxi);
1418 	if (unlikely(rc)) {
1419 		dev_err(dev, "%s: Could not attach AFU rc %d\n", __func__, rc);
1420 		goto err;
1421 	}
1422 
1423 	/*
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.
1428 	 */
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);
1435 
1436 out_attach:
1437 	if (fd != -1)
1438 		flags |= DK_CXLFLASH_APP_CLOSE_ADAP_FD;
1439 	if (afu_is_sq_cmd_mode(afu))
1440 		flags |= DK_CXLFLASH_CONTEXT_SQ_CMD_MODE;
1441 
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;
1449 
1450 out:
1451 	attach->adap_fd = fd;
1452 
1453 	if (ctxi)
1454 		put_context(ctxi);
1455 
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);
1458 	return rc;
1459 
1460 err:
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);
1465 		ctx = NULL;
1466 	}
1467 
1468 	/*
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
1473 	 * issue here.
1474 	 */
1475 	if (fd > 0) {
1476 		file->f_op = &null_fops;
1477 		fput(file);
1478 		put_unused_fd(fd);
1479 		fd = -1;
1480 		file = NULL;
1481 	}
1482 
1483 	/* Cleanup our context */
1484 	if (ctxi) {
1485 		destroy_context(cfg, ctxi);
1486 		ctxi = NULL;
1487 	}
1488 
1489 	kfree(lun_access);
1490 	scsi_device_put(sdev);
1491 	goto out;
1492 }
1493 
1494 /**
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.
1499  *
1500  * Restablishes the state for a context-in-error.
1501  *
1502  * Return: 0 on success, -errno on failure
1503  */
1504 static int recover_context(struct cxlflash_cfg *cfg,
1505 			   struct ctx_info *ctxi,
1506 			   int *adap_fd)
1507 {
1508 	struct device *dev = &cfg->dev->dev;
1509 	int rc = 0;
1510 	int fd = -1;
1511 	int ctxid = -1;
1512 	struct file *file;
1513 	struct cxl_context *ctx;
1514 	struct afu *afu = cfg->afu;
1515 
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",
1519 			__func__, ctx);
1520 		rc = -ENODEV;
1521 		goto out;
1522 	}
1523 
1524 	rc = cxl_start_work(ctx, &ctxi->work);
1525 	if (unlikely(rc)) {
1526 		dev_dbg(dev, "%s: Could not start context rc=%d\n",
1527 			__func__, rc);
1528 		goto err1;
1529 	}
1530 
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);
1534 		rc = -EPERM;
1535 		goto err2;
1536 	}
1537 
1538 	file = cxl_get_fd(ctx, &cfg->cxl_fops, &fd);
1539 	if (unlikely(fd < 0)) {
1540 		rc = -ENODEV;
1541 		dev_err(dev, "%s: Could not get file descriptor\n", __func__);
1542 		goto err2;
1543 	}
1544 
1545 	/* Update with new MMIO area based on updated context id */
1546 	ctxi->ctrl_map = &afu->afu_map->ctrls[ctxid].ctrl;
1547 
1548 	rc = afu_attach(cfg, ctxi);
1549 	if (rc) {
1550 		dev_err(dev, "%s: Could not attach AFU rc %d\n", __func__, rc);
1551 		goto err3;
1552 	}
1553 
1554 	/*
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.
1557 	 */
1558 	ctxi->ctxid = ENCODE_CTXID(ctxi, ctxid);
1559 	ctxi->ctx = ctx;
1560 	ctxi->file = file;
1561 
1562 	/*
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.
1567 	 */
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);
1575 	*adap_fd = fd;
1576 out:
1577 	dev_dbg(dev, "%s: returning ctxid=%d fd=%d rc=%d\n",
1578 		__func__, ctxid, fd, rc);
1579 	return rc;
1580 
1581 err3:
1582 	fput(file);
1583 	put_unused_fd(fd);
1584 err2:
1585 	cxl_stop_context(ctx);
1586 err1:
1587 	cxl_release_context(ctx);
1588 	goto out;
1589 }
1590 
1591 /**
1592  * cxlflash_afu_recover() - initiates AFU recovery
1593  * @sdev:	SCSI device associated with LUN.
1594  * @recover:	Recover ioctl data structure.
1595  *
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.
1602  *
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
1608  * parallel.
1609  *
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().
1618  *
1619  * Return: 0 on success, -errno on failure
1620  */
1621 static int cxlflash_afu_recover(struct scsi_device *sdev,
1622 				struct dk_cxlflash_recover_afu *recover)
1623 {
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);
1631 	u64 flags;
1632 	u64 ctxid = DECODE_CTXID(recover->context_id),
1633 	    rctxid = recover->context_id;
1634 	long reg;
1635 	int lretry = 20; /* up to 2 seconds */
1636 	int new_adap_fd = -1;
1637 	int rc = 0;
1638 
1639 	atomic_inc(&cfg->recovery_threads);
1640 	up_read(&cfg->ioctl_rwsem);
1641 	rc = mutex_lock_interruptible(mutex);
1642 	down_read(&cfg->ioctl_rwsem);
1643 	if (rc)
1644 		goto out;
1645 	rc = check_state(cfg);
1646 	if (rc) {
1647 		dev_err(dev, "%s: Failed state rc=%d\n", __func__, rc);
1648 		rc = -ENODEV;
1649 		goto out;
1650 	}
1651 
1652 	dev_dbg(dev, "%s: reason=%016llx rctxid=%016llx\n",
1653 		__func__, recover->reason, rctxid);
1654 
1655 retry:
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);
1660 		rc = -EINVAL;
1661 		goto out;
1662 	}
1663 
1664 	if (ctxi->err_recovery_active) {
1665 retry_recover:
1666 		rc = recover_context(cfg, ctxi, &new_adap_fd);
1667 		if (unlikely(rc)) {
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) ||
1672 			     (lretry--))) {
1673 				dev_dbg(dev, "%s: Going to try again\n",
1674 					__func__);
1675 				mutex_unlock(mutex);
1676 				msleep(100);
1677 				rc = mutex_lock_interruptible(mutex);
1678 				if (rc)
1679 					goto out;
1680 				goto retry_recover;
1681 			}
1682 
1683 			goto out;
1684 		}
1685 
1686 		ctxi->err_recovery_active = false;
1687 
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;
1692 
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);
1697 		goto out;
1698 	}
1699 
1700 	/* Test if in error state */
1701 	reg = readq_be(&hwq->ctrl_map->mbox_r);
1702 	if (reg == -1) {
1703 		dev_dbg(dev, "%s: MMIO fail, wait for recovery.\n", __func__);
1704 
1705 		/*
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).
1709 		 */
1710 		put_context(ctxi);
1711 		ctxi = NULL;
1712 		ssleep(1);
1713 		rc = check_state(cfg);
1714 		if (unlikely(rc))
1715 			goto out;
1716 		goto retry;
1717 	}
1718 
1719 	dev_dbg(dev, "%s: MMIO working, no recovery required\n", __func__);
1720 out:
1721 	if (likely(ctxi))
1722 		put_context(ctxi);
1723 	mutex_unlock(mutex);
1724 	atomic_dec_if_positive(&cfg->recovery_threads);
1725 	return rc;
1726 }
1727 
1728 /**
1729  * process_sense() - evaluates and processes sense data
1730  * @sdev:	SCSI device associated with LUN.
1731  * @verify:	Verify ioctl data structure.
1732  *
1733  * Return: 0 on success, -errno on failure
1734  */
1735 static int process_sense(struct scsi_device *sdev,
1736 			 struct dk_cxlflash_verify *verify)
1737 {
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 };
1744 	int rc = 0;
1745 
1746 	rc = scsi_normalize_sense((const u8 *)&verify->sense_data,
1747 				  DK_CXLFLASH_VERIFY_SENSE_LEN, &sshdr);
1748 	if (!rc) {
1749 		dev_err(dev, "%s: Failed to normalize sense data\n", __func__);
1750 		rc = -EINVAL;
1751 		goto out;
1752 	}
1753 
1754 	switch (sshdr.sense_key) {
1755 	case NO_SENSE:
1756 	case RECOVERED_ERROR:
1757 		/* fall through */
1758 	case NOT_READY:
1759 		break;
1760 	case UNIT_ATTENTION:
1761 		switch (sshdr.asc) {
1762 		case 0x29: /* Power on Reset or Device Reset */
1763 			/* fall through */
1764 		case 0x2A: /* Device settings/capacity changed */
1765 			rc = read_cap16(sdev, lli);
1766 			if (rc) {
1767 				rc = -ENODEV;
1768 				break;
1769 			}
1770 			if (prev_lba != gli->max_lba)
1771 				dev_dbg(dev, "%s: Capacity changed old=%lld "
1772 					"new=%lld\n", __func__, prev_lba,
1773 					gli->max_lba);
1774 			break;
1775 		case 0x3F: /* Report LUNs changed, Rescan. */
1776 			scsi_scan_host(cfg->host);
1777 			break;
1778 		default:
1779 			rc = -EIO;
1780 			break;
1781 		}
1782 		break;
1783 	default:
1784 		rc = -EIO;
1785 		break;
1786 	}
1787 out:
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);
1790 	return rc;
1791 }
1792 
1793 /**
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.
1797  *
1798  * Return: 0 on success, -errno on failure
1799  */
1800 static int cxlflash_disk_verify(struct scsi_device *sdev,
1801 				struct dk_cxlflash_verify *verify)
1802 {
1803 	int rc = 0;
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;
1813 	u64 last_lba = 0;
1814 
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);
1818 
1819 	ctxi = get_context(cfg, rctxid, lli, 0);
1820 	if (unlikely(!ctxi)) {
1821 		dev_dbg(dev, "%s: Bad context ctxid=%llu\n", __func__, ctxid);
1822 		rc = -EINVAL;
1823 		goto out;
1824 	}
1825 
1826 	rhte = get_rhte(ctxi, rhndl, lli);
1827 	if (unlikely(!rhte)) {
1828 		dev_dbg(dev, "%s: Bad resource handle rhndl=%d\n",
1829 			__func__, rhndl);
1830 		rc = -EINVAL;
1831 		goto out;
1832 	}
1833 
1834 	/*
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).
1837 	 */
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.
1841 		 */
1842 		ctxi->unavail = true;
1843 		mutex_unlock(&ctxi->mutex);
1844 		rc = process_sense(sdev, verify);
1845 		if (unlikely(rc)) {
1846 			dev_err(dev, "%s: Failed to validate sense data (%d)\n",
1847 				__func__, rc);
1848 			mutex_lock(&ctxi->mutex);
1849 			ctxi->unavail = false;
1850 			goto out;
1851 		}
1852 		mutex_lock(&ctxi->mutex);
1853 		ctxi->unavail = false;
1854 	}
1855 
1856 	switch (gli->mode) {
1857 	case MODE_PHYSICAL:
1858 		last_lba = gli->max_lba;
1859 		break;
1860 	case MODE_VIRTUAL:
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;
1864 		last_lba--;
1865 		break;
1866 	default:
1867 		WARN(1, "Unsupported LUN mode!");
1868 	}
1869 
1870 	verify->last_lba = last_lba;
1871 
1872 out:
1873 	if (likely(ctxi))
1874 		put_context(ctxi);
1875 	dev_dbg(dev, "%s: returning rc=%d llba=%llx\n",
1876 		__func__, rc, verify->last_lba);
1877 	return rc;
1878 }
1879 
1880 /**
1881  * decode_ioctl() - translates an encoded ioctl to an easily identifiable string
1882  * @cmd:	The ioctl command to decode.
1883  *
1884  * Return: A string identifying the decoded ioctl.
1885  */
1886 static char *decode_ioctl(int cmd)
1887 {
1888 	switch (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);
1909 	}
1910 
1911 	return "UNKNOWN";
1912 }
1913 
1914 /**
1915  * cxlflash_disk_direct_open() - opens a direct (physical) disk
1916  * @sdev:	SCSI device associated with LUN.
1917  * @arg:	UDirect ioctl data structure.
1918  *
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.
1922  *
1923  * Return: 0 on success, -errno on failure
1924  */
1925 static int cxlflash_disk_direct_open(struct scsi_device *sdev, void *arg)
1926 {
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;
1932 
1933 	struct dk_cxlflash_udirect *pphys = (struct dk_cxlflash_udirect *)arg;
1934 
1935 	u64 ctxid = DECODE_CTXID(pphys->context_id),
1936 	    rctxid = pphys->context_id;
1937 	u64 lun_size = 0;
1938 	u64 last_lba = 0;
1939 	u64 rsrc_handle = -1;
1940 	u32 port = CHAN2PORTMASK(sdev->channel);
1941 
1942 	int rc = 0;
1943 
1944 	struct ctx_info *ctxi = NULL;
1945 	struct sisl_rht_entry *rhte = NULL;
1946 
1947 	dev_dbg(dev, "%s: ctxid=%llu ls=%llu\n", __func__, ctxid, lun_size);
1948 
1949 	rc = cxlflash_lun_attach(gli, MODE_PHYSICAL, false);
1950 	if (unlikely(rc)) {
1951 		dev_dbg(dev, "%s: Failed attach to LUN (PHYSICAL)\n", __func__);
1952 		goto out;
1953 	}
1954 
1955 	ctxi = get_context(cfg, rctxid, lli, 0);
1956 	if (unlikely(!ctxi)) {
1957 		dev_dbg(dev, "%s: Bad context ctxid=%llu\n", __func__, ctxid);
1958 		rc = -EINVAL;
1959 		goto err1;
1960 	}
1961 
1962 	rhte = rhte_checkout(ctxi, lli);
1963 	if (unlikely(!rhte)) {
1964 		dev_dbg(dev, "%s: Too many opens ctxid=%lld\n",
1965 			__func__, ctxid);
1966 		rc = -EMFILE;	/* too many opens  */
1967 		goto err1;
1968 	}
1969 
1970 	rsrc_handle = (rhte - ctxi->rht_start);
1971 
1972 	rht_format1(rhte, lli->lun_id[sdev->channel], ctxi->rht_perms, port);
1973 	cxlflash_afu_sync(afu, ctxid, rsrc_handle, AFU_LW_SYNC);
1974 
1975 	last_lba = gli->max_lba;
1976 	pphys->hdr.return_flags = 0;
1977 	pphys->last_lba = last_lba;
1978 	pphys->rsrc_handle = rsrc_handle;
1979 
1980 out:
1981 	if (likely(ctxi))
1982 		put_context(ctxi);
1983 	dev_dbg(dev, "%s: returning handle=%llu rc=%d llba=%llu\n",
1984 		__func__, rsrc_handle, rc, last_lba);
1985 	return rc;
1986 
1987 err1:
1988 	cxlflash_lun_detach(gli);
1989 	goto out;
1990 }
1991 
1992 /**
1993  * ioctl_common() - common IOCTL handler for driver
1994  * @sdev:	SCSI device associated with LUN.
1995  * @cmd:	IOCTL command.
1996  *
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.
2000  *
2001  * Return: 0 on success, -errno on failure
2002  */
2003 static int ioctl_common(struct scsi_device *sdev, int cmd)
2004 {
2005 	struct cxlflash_cfg *cfg = shost_priv(sdev->host);
2006 	struct device *dev = &cfg->dev->dev;
2007 	struct llun_info *lli = sdev->hostdata;
2008 	int rc = 0;
2009 
2010 	if (unlikely(!lli)) {
2011 		dev_dbg(dev, "%s: Unknown LUN\n", __func__);
2012 		rc = -EINVAL;
2013 		goto out;
2014 	}
2015 
2016 	rc = check_state(cfg);
2017 	if (unlikely(rc) && (cfg->state == STATE_FAILTERM)) {
2018 		switch (cmd) {
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",
2023 				__func__, rc);
2024 			rc = 0;
2025 			break;
2026 		}
2027 	}
2028 out:
2029 	return rc;
2030 }
2031 
2032 /**
2033  * cxlflash_ioctl() - IOCTL handler for driver
2034  * @sdev:	SCSI device associated with LUN.
2035  * @cmd:	IOCTL command.
2036  * @arg:	Userspace ioctl data structure.
2037  *
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.
2045  *
2046  * Return: 0 on success, -errno on failure
2047  */
2048 int cxlflash_ioctl(struct scsi_device *sdev, int cmd, void __user *arg)
2049 {
2050 	typedef int (*sioctl) (struct scsi_device *, void *);
2051 
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)];
2057 	size_t size = 0;
2058 	bool known_ioctl = false;
2059 	int idx;
2060 	int rc = 0;
2061 	struct Scsi_Host *shost = sdev->host;
2062 	sioctl do_ioctl = NULL;
2063 
2064 	static const struct {
2065 		size_t size;
2066 		sioctl ioctl;
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},
2078 	};
2079 
2080 	/* Hold read semaphore so we can drain if needed */
2081 	down_read(&cfg->ioctl_rwsem);
2082 
2083 	/* Restrict command set to physical support only for internal LUN */
2084 	if (afu->internal_lun)
2085 		switch (cmd) {
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);
2092 			rc = -EINVAL;
2093 			goto cxlflash_ioctl_exit;
2094 		}
2095 
2096 	switch (cmd) {
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);
2110 		if (unlikely(rc))
2111 			goto cxlflash_ioctl_exit;
2112 
2113 		/* fall through */
2114 
2115 	case DK_CXLFLASH_MANAGE_LUN:
2116 		known_ioctl = true;
2117 		idx = _IOC_NR(cmd) - _IOC_NR(DK_CXLFLASH_ATTACH);
2118 		size = ioctl_tbl[idx].size;
2119 		do_ioctl = ioctl_tbl[idx].ioctl;
2120 
2121 		if (likely(do_ioctl))
2122 			break;
2123 
2124 		/* fall through */
2125 	default:
2126 		rc = -EINVAL;
2127 		goto cxlflash_ioctl_exit;
2128 	}
2129 
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);
2134 		rc = -EFAULT;
2135 		goto cxlflash_ioctl_exit;
2136 	}
2137 
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));
2142 		rc = -EINVAL;
2143 		goto cxlflash_ioctl_exit;
2144 	}
2145 
2146 	if (hdr->rsvd[0] || hdr->rsvd[1] || hdr->rsvd[2] || hdr->return_flags) {
2147 		dev_dbg(dev, "%s: Reserved/rflags populated\n", __func__);
2148 		rc = -EINVAL;
2149 		goto cxlflash_ioctl_exit;
2150 	}
2151 
2152 	rc = do_ioctl(sdev, (void *)&buf);
2153 	if (likely(!rc))
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);
2158 			rc = -EFAULT;
2159 		}
2160 
2161 	/* fall through to exit */
2162 
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);
2170 	else
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,
2174 			sdev->lun, rc);
2175 	return rc;
2176 }
2177