xref: /freebsd/sys/cam/ctl/ctl_tpc.c (revision c1eb4109f3b1d90a9c1538179ea6a52a191899b2)
1 /*-
2  * Copyright (c) 2014 Alexander Motin <mav@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/types.h>
34 #include <sys/lock.h>
35 #include <sys/module.h>
36 #include <sys/mutex.h>
37 #include <sys/condvar.h>
38 #include <sys/malloc.h>
39 #include <sys/conf.h>
40 #include <sys/queue.h>
41 #include <sys/sysctl.h>
42 #include <machine/atomic.h>
43 
44 #include <cam/cam.h>
45 #include <cam/scsi/scsi_all.h>
46 #include <cam/scsi/scsi_da.h>
47 #include <cam/ctl/ctl_io.h>
48 #include <cam/ctl/ctl.h>
49 #include <cam/ctl/ctl_frontend.h>
50 #include <cam/ctl/ctl_util.h>
51 #include <cam/ctl/ctl_backend.h>
52 #include <cam/ctl/ctl_ioctl.h>
53 #include <cam/ctl/ctl_ha.h>
54 #include <cam/ctl/ctl_private.h>
55 #include <cam/ctl/ctl_debug.h>
56 #include <cam/ctl/ctl_scsi_all.h>
57 #include <cam/ctl/ctl_tpc.h>
58 #include <cam/ctl/ctl_error.h>
59 
60 #define	TPC_MAX_CSCDS	64
61 #define	TPC_MAX_SEGS	64
62 #define	TPC_MAX_SEG	0
63 #define	TPC_MAX_LIST	8192
64 #define	TPC_MAX_INLINE	0
65 #define	TPC_MAX_LISTS	255
66 #define	TPC_MAX_IO_SIZE	(1024 * 1024)
67 #define	TPC_MAX_IOCHUNK_SIZE	(TPC_MAX_IO_SIZE * 16)
68 #define	TPC_MIN_TOKEN_TIMEOUT	1
69 #define	TPC_DFL_TOKEN_TIMEOUT	60
70 #define	TPC_MAX_TOKEN_TIMEOUT	600
71 
72 MALLOC_DEFINE(M_CTL_TPC, "ctltpc", "CTL TPC");
73 
74 typedef enum {
75 	TPC_ERR_RETRY		= 0x000,
76 	TPC_ERR_FAIL		= 0x001,
77 	TPC_ERR_MASK		= 0x0ff,
78 	TPC_ERR_NO_DECREMENT	= 0x100
79 } tpc_error_action;
80 
81 struct tpc_list;
82 TAILQ_HEAD(runl, tpc_io);
83 struct tpc_io {
84 	union ctl_io		*io;
85 	uint64_t		 lun;
86 	struct tpc_list		*list;
87 	struct runl		 run;
88 	TAILQ_ENTRY(tpc_io)	 rlinks;
89 	TAILQ_ENTRY(tpc_io)	 links;
90 };
91 
92 struct tpc_token {
93 	uint8_t			 token[512];
94 	uint64_t		 lun;
95 	uint32_t		 blocksize;
96 	uint8_t			*params;
97 	struct scsi_range_desc	*range;
98 	int			 nrange;
99 	int			 active;
100 	time_t			 last_active;
101 	uint32_t		 timeout;
102 	TAILQ_ENTRY(tpc_token)	 links;
103 };
104 
105 struct tpc_list {
106 	uint8_t			 service_action;
107 	int			 init_port;
108 	uint32_t		 init_idx;
109 	uint32_t		 list_id;
110 	uint8_t			 flags;
111 	uint8_t			*params;
112 	struct scsi_ec_cscd	*cscd;
113 	struct scsi_ec_segment	*seg[TPC_MAX_SEGS];
114 	uint8_t			*inl;
115 	int			 ncscd;
116 	int			 nseg;
117 	int			 leninl;
118 	struct tpc_token	*token;
119 	struct scsi_range_desc	*range;
120 	int			 nrange;
121 	off_t			 offset_into_rod;
122 
123 	int			 curseg;
124 	off_t			 cursectors;
125 	off_t			 curbytes;
126 	int			 curops;
127 	int			 stage;
128 	uint8_t			*buf;
129 	off_t			 segsectors;
130 	off_t			 segbytes;
131 	int			 tbdio;
132 	int			 error;
133 	int			 abort;
134 	int			 completed;
135 	time_t			 last_active;
136 	TAILQ_HEAD(, tpc_io)	 allio;
137 	struct scsi_sense_data	 sense_data;
138 	uint8_t			 sense_len;
139 	uint8_t			 scsi_status;
140 	struct ctl_scsiio	*ctsio;
141 	struct ctl_lun		*lun;
142 	int			 res_token_valid;
143 	uint8_t			 res_token[512];
144 	TAILQ_ENTRY(tpc_list)	 links;
145 };
146 
147 static void
148 tpc_timeout(void *arg)
149 {
150 	struct ctl_softc *softc = arg;
151 	struct ctl_lun *lun;
152 	struct tpc_token *token, *ttoken;
153 	struct tpc_list *list, *tlist;
154 
155 	/* Free completed lists with expired timeout. */
156 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
157 		mtx_lock(&lun->lun_lock);
158 		TAILQ_FOREACH_SAFE(list, &lun->tpc_lists, links, tlist) {
159 			if (!list->completed || time_uptime < list->last_active +
160 			    TPC_DFL_TOKEN_TIMEOUT)
161 				continue;
162 			TAILQ_REMOVE(&lun->tpc_lists, list, links);
163 			free(list, M_CTL);
164 		}
165 		mtx_unlock(&lun->lun_lock);
166 	}
167 
168 	/* Free inactive ROD tokens with expired timeout. */
169 	mtx_lock(&softc->tpc_lock);
170 	TAILQ_FOREACH_SAFE(token, &softc->tpc_tokens, links, ttoken) {
171 		if (token->active ||
172 		    time_uptime < token->last_active + token->timeout + 1)
173 			continue;
174 		TAILQ_REMOVE(&softc->tpc_tokens, token, links);
175 		free(token->params, M_CTL);
176 		free(token, M_CTL);
177 	}
178 	mtx_unlock(&softc->tpc_lock);
179 	callout_schedule(&softc->tpc_timeout, hz);
180 }
181 
182 void
183 ctl_tpc_init(struct ctl_softc *softc)
184 {
185 
186 	mtx_init(&softc->tpc_lock, "CTL TPC mutex", NULL, MTX_DEF);
187 	TAILQ_INIT(&softc->tpc_tokens);
188 	callout_init_mtx(&softc->tpc_timeout, &softc->ctl_lock, 0);
189 	callout_reset(&softc->tpc_timeout, hz, tpc_timeout, softc);
190 }
191 
192 void
193 ctl_tpc_shutdown(struct ctl_softc *softc)
194 {
195 	struct tpc_token *token;
196 
197 	callout_drain(&softc->tpc_timeout);
198 
199 	/* Free ROD tokens. */
200 	mtx_lock(&softc->tpc_lock);
201 	while ((token = TAILQ_FIRST(&softc->tpc_tokens)) != NULL) {
202 		TAILQ_REMOVE(&softc->tpc_tokens, token, links);
203 		free(token->params, M_CTL);
204 		free(token, M_CTL);
205 	}
206 	mtx_unlock(&softc->tpc_lock);
207 	mtx_destroy(&softc->tpc_lock);
208 }
209 
210 void
211 ctl_tpc_lun_init(struct ctl_lun *lun)
212 {
213 
214 	TAILQ_INIT(&lun->tpc_lists);
215 }
216 
217 void
218 ctl_tpc_lun_shutdown(struct ctl_lun *lun)
219 {
220 	struct ctl_softc *softc = lun->ctl_softc;
221 	struct tpc_list *list;
222 	struct tpc_token *token, *ttoken;
223 
224 	/* Free lists for this LUN. */
225 	while ((list = TAILQ_FIRST(&lun->tpc_lists)) != NULL) {
226 		TAILQ_REMOVE(&lun->tpc_lists, list, links);
227 		KASSERT(list->completed,
228 		    ("Not completed TPC (%p) on shutdown", list));
229 		free(list, M_CTL);
230 	}
231 
232 	/* Free ROD tokens for this LUN. */
233 	mtx_lock(&softc->tpc_lock);
234 	TAILQ_FOREACH_SAFE(token, &softc->tpc_tokens, links, ttoken) {
235 		if (token->lun != lun->lun || token->active)
236 			continue;
237 		TAILQ_REMOVE(&softc->tpc_tokens, token, links);
238 		free(token->params, M_CTL);
239 		free(token, M_CTL);
240 	}
241 	mtx_unlock(&softc->tpc_lock);
242 }
243 
244 int
245 ctl_inquiry_evpd_tpc(struct ctl_scsiio *ctsio, int alloc_len)
246 {
247 	struct scsi_vpd_tpc *tpc_ptr;
248 	struct scsi_vpd_tpc_descriptor *d_ptr;
249 	struct scsi_vpd_tpc_descriptor_bdrl *bdrl_ptr;
250 	struct scsi_vpd_tpc_descriptor_sc *sc_ptr;
251 	struct scsi_vpd_tpc_descriptor_sc_descr *scd_ptr;
252 	struct scsi_vpd_tpc_descriptor_pd *pd_ptr;
253 	struct scsi_vpd_tpc_descriptor_sd *sd_ptr;
254 	struct scsi_vpd_tpc_descriptor_sdid *sdid_ptr;
255 	struct scsi_vpd_tpc_descriptor_rtf *rtf_ptr;
256 	struct scsi_vpd_tpc_descriptor_rtf_block *rtfb_ptr;
257 	struct scsi_vpd_tpc_descriptor_srt *srt_ptr;
258 	struct scsi_vpd_tpc_descriptor_srtd *srtd_ptr;
259 	struct scsi_vpd_tpc_descriptor_gco *gco_ptr;
260 	struct ctl_lun *lun;
261 	int data_len;
262 
263 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
264 
265 	data_len = sizeof(struct scsi_vpd_tpc) +
266 	    sizeof(struct scsi_vpd_tpc_descriptor_bdrl) +
267 	    roundup2(sizeof(struct scsi_vpd_tpc_descriptor_sc) +
268 	     2 * sizeof(struct scsi_vpd_tpc_descriptor_sc_descr) + 11, 4) +
269 	    sizeof(struct scsi_vpd_tpc_descriptor_pd) +
270 	    roundup2(sizeof(struct scsi_vpd_tpc_descriptor_sd) + 4, 4) +
271 	    roundup2(sizeof(struct scsi_vpd_tpc_descriptor_sdid) + 2, 4) +
272 	    sizeof(struct scsi_vpd_tpc_descriptor_rtf) +
273 	     sizeof(struct scsi_vpd_tpc_descriptor_rtf_block) +
274 	    sizeof(struct scsi_vpd_tpc_descriptor_srt) +
275 	     2*sizeof(struct scsi_vpd_tpc_descriptor_srtd) +
276 	    sizeof(struct scsi_vpd_tpc_descriptor_gco);
277 
278 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
279 	tpc_ptr = (struct scsi_vpd_tpc *)ctsio->kern_data_ptr;
280 	ctsio->kern_sg_entries = 0;
281 
282 	if (data_len < alloc_len) {
283 		ctsio->residual = alloc_len - data_len;
284 		ctsio->kern_data_len = data_len;
285 		ctsio->kern_total_len = data_len;
286 	} else {
287 		ctsio->residual = 0;
288 		ctsio->kern_data_len = alloc_len;
289 		ctsio->kern_total_len = alloc_len;
290 	}
291 	ctsio->kern_data_resid = 0;
292 	ctsio->kern_rel_offset = 0;
293 	ctsio->kern_sg_entries = 0;
294 
295 	/*
296 	 * The control device is always connected.  The disk device, on the
297 	 * other hand, may not be online all the time.
298 	 */
299 	if (lun != NULL)
300 		tpc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
301 				     lun->be_lun->lun_type;
302 	else
303 		tpc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
304 	tpc_ptr->page_code = SVPD_SCSI_TPC;
305 	scsi_ulto2b(data_len - 4, tpc_ptr->page_length);
306 
307 	/* Block Device ROD Limits */
308 	d_ptr = (struct scsi_vpd_tpc_descriptor *)&tpc_ptr->descr[0];
309 	bdrl_ptr = (struct scsi_vpd_tpc_descriptor_bdrl *)d_ptr;
310 	scsi_ulto2b(SVPD_TPC_BDRL, bdrl_ptr->desc_type);
311 	scsi_ulto2b(sizeof(*bdrl_ptr) - 4, bdrl_ptr->desc_length);
312 	scsi_ulto2b(TPC_MAX_SEGS, bdrl_ptr->maximum_ranges);
313 	scsi_ulto4b(TPC_MAX_TOKEN_TIMEOUT,
314 	    bdrl_ptr->maximum_inactivity_timeout);
315 	scsi_ulto4b(TPC_DFL_TOKEN_TIMEOUT,
316 	    bdrl_ptr->default_inactivity_timeout);
317 	scsi_u64to8b(0, bdrl_ptr->maximum_token_transfer_size);
318 	scsi_u64to8b(0, bdrl_ptr->optimal_transfer_count);
319 
320 	/* Supported commands */
321 	d_ptr = (struct scsi_vpd_tpc_descriptor *)
322 	    (&d_ptr->parameters[0] + scsi_2btoul(d_ptr->desc_length));
323 	sc_ptr = (struct scsi_vpd_tpc_descriptor_sc *)d_ptr;
324 	scsi_ulto2b(SVPD_TPC_SC, sc_ptr->desc_type);
325 	sc_ptr->list_length = 2 * sizeof(*scd_ptr) + 11;
326 	scsi_ulto2b(roundup2(1 + sc_ptr->list_length, 4), sc_ptr->desc_length);
327 	scd_ptr = &sc_ptr->descr[0];
328 	scd_ptr->opcode = EXTENDED_COPY;
329 	scd_ptr->sa_length = 5;
330 	scd_ptr->supported_service_actions[0] = EC_EC_LID1;
331 	scd_ptr->supported_service_actions[1] = EC_EC_LID4;
332 	scd_ptr->supported_service_actions[2] = EC_PT;
333 	scd_ptr->supported_service_actions[3] = EC_WUT;
334 	scd_ptr->supported_service_actions[4] = EC_COA;
335 	scd_ptr = (struct scsi_vpd_tpc_descriptor_sc_descr *)
336 	    &scd_ptr->supported_service_actions[scd_ptr->sa_length];
337 	scd_ptr->opcode = RECEIVE_COPY_STATUS;
338 	scd_ptr->sa_length = 6;
339 	scd_ptr->supported_service_actions[0] = RCS_RCS_LID1;
340 	scd_ptr->supported_service_actions[1] = RCS_RCFD;
341 	scd_ptr->supported_service_actions[2] = RCS_RCS_LID4;
342 	scd_ptr->supported_service_actions[3] = RCS_RCOP;
343 	scd_ptr->supported_service_actions[4] = RCS_RRTI;
344 	scd_ptr->supported_service_actions[5] = RCS_RART;
345 
346 	/* Parameter data. */
347 	d_ptr = (struct scsi_vpd_tpc_descriptor *)
348 	    (&d_ptr->parameters[0] + scsi_2btoul(d_ptr->desc_length));
349 	pd_ptr = (struct scsi_vpd_tpc_descriptor_pd *)d_ptr;
350 	scsi_ulto2b(SVPD_TPC_PD, pd_ptr->desc_type);
351 	scsi_ulto2b(sizeof(*pd_ptr) - 4, pd_ptr->desc_length);
352 	scsi_ulto2b(TPC_MAX_CSCDS, pd_ptr->maximum_cscd_descriptor_count);
353 	scsi_ulto2b(TPC_MAX_SEGS, pd_ptr->maximum_segment_descriptor_count);
354 	scsi_ulto4b(TPC_MAX_LIST, pd_ptr->maximum_descriptor_list_length);
355 	scsi_ulto4b(TPC_MAX_INLINE, pd_ptr->maximum_inline_data_length);
356 
357 	/* Supported Descriptors */
358 	d_ptr = (struct scsi_vpd_tpc_descriptor *)
359 	    (&d_ptr->parameters[0] + scsi_2btoul(d_ptr->desc_length));
360 	sd_ptr = (struct scsi_vpd_tpc_descriptor_sd *)d_ptr;
361 	scsi_ulto2b(SVPD_TPC_SD, sd_ptr->desc_type);
362 	scsi_ulto2b(roundup2(sizeof(*sd_ptr) - 4 + 4, 4), sd_ptr->desc_length);
363 	sd_ptr->list_length = 4;
364 	sd_ptr->supported_descriptor_codes[0] = EC_SEG_B2B;
365 	sd_ptr->supported_descriptor_codes[1] = EC_SEG_VERIFY;
366 	sd_ptr->supported_descriptor_codes[2] = EC_SEG_REGISTER_KEY;
367 	sd_ptr->supported_descriptor_codes[3] = EC_CSCD_ID;
368 
369 	/* Supported CSCD Descriptor IDs */
370 	d_ptr = (struct scsi_vpd_tpc_descriptor *)
371 	    (&d_ptr->parameters[0] + scsi_2btoul(d_ptr->desc_length));
372 	sdid_ptr = (struct scsi_vpd_tpc_descriptor_sdid *)d_ptr;
373 	scsi_ulto2b(SVPD_TPC_SDID, sdid_ptr->desc_type);
374 	scsi_ulto2b(roundup2(sizeof(*sdid_ptr) - 4 + 2, 4), sdid_ptr->desc_length);
375 	scsi_ulto2b(2, sdid_ptr->list_length);
376 	scsi_ulto2b(0xffff, &sdid_ptr->supported_descriptor_ids[0]);
377 
378 	/* ROD Token Features */
379 	d_ptr = (struct scsi_vpd_tpc_descriptor *)
380 	    (&d_ptr->parameters[0] + scsi_2btoul(d_ptr->desc_length));
381 	rtf_ptr = (struct scsi_vpd_tpc_descriptor_rtf *)d_ptr;
382 	scsi_ulto2b(SVPD_TPC_RTF, rtf_ptr->desc_type);
383 	scsi_ulto2b(sizeof(*rtf_ptr) - 4 + sizeof(*rtfb_ptr), rtf_ptr->desc_length);
384 	rtf_ptr->remote_tokens = 0;
385 	scsi_ulto4b(TPC_MIN_TOKEN_TIMEOUT, rtf_ptr->minimum_token_lifetime);
386 	scsi_ulto4b(UINT32_MAX, rtf_ptr->maximum_token_lifetime);
387 	scsi_ulto4b(TPC_MAX_TOKEN_TIMEOUT,
388 	    rtf_ptr->maximum_token_inactivity_timeout);
389 	scsi_ulto2b(sizeof(*rtfb_ptr), rtf_ptr->type_specific_features_length);
390 	rtfb_ptr = (struct scsi_vpd_tpc_descriptor_rtf_block *)
391 	    &rtf_ptr->type_specific_features;
392 	rtfb_ptr->type_format = SVPD_TPC_RTF_BLOCK;
393 	scsi_ulto2b(sizeof(*rtfb_ptr) - 4, rtfb_ptr->desc_length);
394 	scsi_ulto2b(0, rtfb_ptr->optimal_length_granularity);
395 	scsi_u64to8b(0, rtfb_ptr->maximum_bytes);
396 	scsi_u64to8b(0, rtfb_ptr->optimal_bytes);
397 	scsi_u64to8b(TPC_MAX_IOCHUNK_SIZE,
398 	    rtfb_ptr->optimal_bytes_to_token_per_segment);
399 	scsi_u64to8b(TPC_MAX_IOCHUNK_SIZE,
400 	    rtfb_ptr->optimal_bytes_from_token_per_segment);
401 
402 	/* Supported ROD Tokens */
403 	d_ptr = (struct scsi_vpd_tpc_descriptor *)
404 	    (&d_ptr->parameters[0] + scsi_2btoul(d_ptr->desc_length));
405 	srt_ptr = (struct scsi_vpd_tpc_descriptor_srt *)d_ptr;
406 	scsi_ulto2b(SVPD_TPC_SRT, srt_ptr->desc_type);
407 	scsi_ulto2b(sizeof(*srt_ptr) - 4 + 2*sizeof(*srtd_ptr), srt_ptr->desc_length);
408 	scsi_ulto2b(2*sizeof(*srtd_ptr), srt_ptr->rod_type_descriptors_length);
409 	srtd_ptr = (struct scsi_vpd_tpc_descriptor_srtd *)
410 	    &srt_ptr->rod_type_descriptors;
411 	scsi_ulto4b(ROD_TYPE_AUR, srtd_ptr->rod_type);
412 	srtd_ptr->flags = SVPD_TPC_SRTD_TIN | SVPD_TPC_SRTD_TOUT;
413 	scsi_ulto2b(0, srtd_ptr->preference_indicator);
414 	srtd_ptr++;
415 	scsi_ulto4b(ROD_TYPE_BLOCK_ZERO, srtd_ptr->rod_type);
416 	srtd_ptr->flags = SVPD_TPC_SRTD_TIN;
417 	scsi_ulto2b(0, srtd_ptr->preference_indicator);
418 
419 	/* General Copy Operations */
420 	d_ptr = (struct scsi_vpd_tpc_descriptor *)
421 	    (&d_ptr->parameters[0] + scsi_2btoul(d_ptr->desc_length));
422 	gco_ptr = (struct scsi_vpd_tpc_descriptor_gco *)d_ptr;
423 	scsi_ulto2b(SVPD_TPC_GCO, gco_ptr->desc_type);
424 	scsi_ulto2b(sizeof(*gco_ptr) - 4, gco_ptr->desc_length);
425 	scsi_ulto4b(TPC_MAX_LISTS, gco_ptr->total_concurrent_copies);
426 	scsi_ulto4b(TPC_MAX_LISTS, gco_ptr->maximum_identified_concurrent_copies);
427 	scsi_ulto4b(TPC_MAX_SEG, gco_ptr->maximum_segment_length);
428 	gco_ptr->data_segment_granularity = 0;
429 	gco_ptr->inline_data_granularity = 0;
430 
431 	ctl_set_success(ctsio);
432 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
433 	ctsio->be_move_done = ctl_config_move_done;
434 	ctl_datamove((union ctl_io *)ctsio);
435 
436 	return (CTL_RETVAL_COMPLETE);
437 }
438 
439 int
440 ctl_receive_copy_operating_parameters(struct ctl_scsiio *ctsio)
441 {
442 	struct scsi_receive_copy_operating_parameters *cdb;
443 	struct scsi_receive_copy_operating_parameters_data *data;
444 	int retval;
445 	int alloc_len, total_len;
446 
447 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
448 
449 	cdb = (struct scsi_receive_copy_operating_parameters *)ctsio->cdb;
450 
451 	retval = CTL_RETVAL_COMPLETE;
452 
453 	total_len = sizeof(*data) + 4;
454 	alloc_len = scsi_4btoul(cdb->length);
455 
456 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
457 
458 	ctsio->kern_sg_entries = 0;
459 
460 	if (total_len < alloc_len) {
461 		ctsio->residual = alloc_len - total_len;
462 		ctsio->kern_data_len = total_len;
463 		ctsio->kern_total_len = total_len;
464 	} else {
465 		ctsio->residual = 0;
466 		ctsio->kern_data_len = alloc_len;
467 		ctsio->kern_total_len = alloc_len;
468 	}
469 	ctsio->kern_data_resid = 0;
470 	ctsio->kern_rel_offset = 0;
471 
472 	data = (struct scsi_receive_copy_operating_parameters_data *)ctsio->kern_data_ptr;
473 	scsi_ulto4b(sizeof(*data) - 4 + 4, data->length);
474 	data->snlid = RCOP_SNLID;
475 	scsi_ulto2b(TPC_MAX_CSCDS, data->maximum_cscd_descriptor_count);
476 	scsi_ulto2b(TPC_MAX_SEGS, data->maximum_segment_descriptor_count);
477 	scsi_ulto4b(TPC_MAX_LIST, data->maximum_descriptor_list_length);
478 	scsi_ulto4b(TPC_MAX_SEG, data->maximum_segment_length);
479 	scsi_ulto4b(TPC_MAX_INLINE, data->maximum_inline_data_length);
480 	scsi_ulto4b(0, data->held_data_limit);
481 	scsi_ulto4b(0, data->maximum_stream_device_transfer_size);
482 	scsi_ulto2b(TPC_MAX_LISTS, data->total_concurrent_copies);
483 	data->maximum_concurrent_copies = TPC_MAX_LISTS;
484 	data->data_segment_granularity = 0;
485 	data->inline_data_granularity = 0;
486 	data->held_data_granularity = 0;
487 	data->implemented_descriptor_list_length = 4;
488 	data->list_of_implemented_descriptor_type_codes[0] = EC_SEG_B2B;
489 	data->list_of_implemented_descriptor_type_codes[1] = EC_SEG_VERIFY;
490 	data->list_of_implemented_descriptor_type_codes[2] = EC_SEG_REGISTER_KEY;
491 	data->list_of_implemented_descriptor_type_codes[3] = EC_CSCD_ID;
492 
493 	ctl_set_success(ctsio);
494 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
495 	ctsio->be_move_done = ctl_config_move_done;
496 	ctl_datamove((union ctl_io *)ctsio);
497 	return (retval);
498 }
499 
500 static struct tpc_list *
501 tpc_find_list(struct ctl_lun *lun, uint32_t list_id, uint32_t init_idx)
502 {
503 	struct tpc_list *list;
504 
505 	mtx_assert(&lun->lun_lock, MA_OWNED);
506 	TAILQ_FOREACH(list, &lun->tpc_lists, links) {
507 		if ((list->flags & EC_LIST_ID_USAGE_MASK) !=
508 		     EC_LIST_ID_USAGE_NONE && list->list_id == list_id &&
509 		    list->init_idx == init_idx)
510 			break;
511 	}
512 	return (list);
513 }
514 
515 int
516 ctl_receive_copy_status_lid1(struct ctl_scsiio *ctsio)
517 {
518 	struct ctl_lun *lun;
519 	struct scsi_receive_copy_status_lid1 *cdb;
520 	struct scsi_receive_copy_status_lid1_data *data;
521 	struct tpc_list *list;
522 	struct tpc_list list_copy;
523 	int retval;
524 	int alloc_len, total_len;
525 	uint32_t list_id;
526 
527 	CTL_DEBUG_PRINT(("ctl_receive_copy_status_lid1\n"));
528 
529 	cdb = (struct scsi_receive_copy_status_lid1 *)ctsio->cdb;
530 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
531 
532 	retval = CTL_RETVAL_COMPLETE;
533 
534 	list_id = cdb->list_identifier;
535 	mtx_lock(&lun->lun_lock);
536 	list = tpc_find_list(lun, list_id,
537 	    ctl_get_resindex(&ctsio->io_hdr.nexus));
538 	if (list == NULL) {
539 		mtx_unlock(&lun->lun_lock);
540 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
541 		    /*command*/ 1, /*field*/ 2, /*bit_valid*/ 0,
542 		    /*bit*/ 0);
543 		ctl_done((union ctl_io *)ctsio);
544 		return (retval);
545 	}
546 	list_copy = *list;
547 	if (list->completed) {
548 		TAILQ_REMOVE(&lun->tpc_lists, list, links);
549 		free(list, M_CTL);
550 	}
551 	mtx_unlock(&lun->lun_lock);
552 
553 	total_len = sizeof(*data);
554 	alloc_len = scsi_4btoul(cdb->length);
555 
556 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
557 
558 	ctsio->kern_sg_entries = 0;
559 
560 	if (total_len < alloc_len) {
561 		ctsio->residual = alloc_len - total_len;
562 		ctsio->kern_data_len = total_len;
563 		ctsio->kern_total_len = total_len;
564 	} else {
565 		ctsio->residual = 0;
566 		ctsio->kern_data_len = alloc_len;
567 		ctsio->kern_total_len = alloc_len;
568 	}
569 	ctsio->kern_data_resid = 0;
570 	ctsio->kern_rel_offset = 0;
571 
572 	data = (struct scsi_receive_copy_status_lid1_data *)ctsio->kern_data_ptr;
573 	scsi_ulto4b(sizeof(*data) - 4, data->available_data);
574 	if (list_copy.completed) {
575 		if (list_copy.error || list_copy.abort)
576 			data->copy_command_status = RCS_CCS_ERROR;
577 		else
578 			data->copy_command_status = RCS_CCS_COMPLETED;
579 	} else
580 		data->copy_command_status = RCS_CCS_INPROG;
581 	scsi_ulto2b(list_copy.curseg, data->segments_processed);
582 	if (list_copy.curbytes <= UINT32_MAX) {
583 		data->transfer_count_units = RCS_TC_BYTES;
584 		scsi_ulto4b(list_copy.curbytes, data->transfer_count);
585 	} else {
586 		data->transfer_count_units = RCS_TC_MBYTES;
587 		scsi_ulto4b(list_copy.curbytes >> 20, data->transfer_count);
588 	}
589 
590 	ctl_set_success(ctsio);
591 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
592 	ctsio->be_move_done = ctl_config_move_done;
593 	ctl_datamove((union ctl_io *)ctsio);
594 	return (retval);
595 }
596 
597 int
598 ctl_receive_copy_failure_details(struct ctl_scsiio *ctsio)
599 {
600 	struct ctl_lun *lun;
601 	struct scsi_receive_copy_failure_details *cdb;
602 	struct scsi_receive_copy_failure_details_data *data;
603 	struct tpc_list *list;
604 	struct tpc_list list_copy;
605 	int retval;
606 	int alloc_len, total_len;
607 	uint32_t list_id;
608 
609 	CTL_DEBUG_PRINT(("ctl_receive_copy_failure_details\n"));
610 
611 	cdb = (struct scsi_receive_copy_failure_details *)ctsio->cdb;
612 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
613 
614 	retval = CTL_RETVAL_COMPLETE;
615 
616 	list_id = cdb->list_identifier;
617 	mtx_lock(&lun->lun_lock);
618 	list = tpc_find_list(lun, list_id,
619 	    ctl_get_resindex(&ctsio->io_hdr.nexus));
620 	if (list == NULL || !list->completed) {
621 		mtx_unlock(&lun->lun_lock);
622 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
623 		    /*command*/ 1, /*field*/ 2, /*bit_valid*/ 0,
624 		    /*bit*/ 0);
625 		ctl_done((union ctl_io *)ctsio);
626 		return (retval);
627 	}
628 	list_copy = *list;
629 	TAILQ_REMOVE(&lun->tpc_lists, list, links);
630 	free(list, M_CTL);
631 	mtx_unlock(&lun->lun_lock);
632 
633 	total_len = sizeof(*data) + list_copy.sense_len;
634 	alloc_len = scsi_4btoul(cdb->length);
635 
636 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
637 
638 	ctsio->kern_sg_entries = 0;
639 
640 	if (total_len < alloc_len) {
641 		ctsio->residual = alloc_len - total_len;
642 		ctsio->kern_data_len = total_len;
643 		ctsio->kern_total_len = total_len;
644 	} else {
645 		ctsio->residual = 0;
646 		ctsio->kern_data_len = alloc_len;
647 		ctsio->kern_total_len = alloc_len;
648 	}
649 	ctsio->kern_data_resid = 0;
650 	ctsio->kern_rel_offset = 0;
651 
652 	data = (struct scsi_receive_copy_failure_details_data *)ctsio->kern_data_ptr;
653 	if (list_copy.completed && (list_copy.error || list_copy.abort)) {
654 		scsi_ulto4b(sizeof(*data) - 4 + list_copy.sense_len,
655 		    data->available_data);
656 		data->copy_command_status = RCS_CCS_ERROR;
657 	} else
658 		scsi_ulto4b(0, data->available_data);
659 	scsi_ulto2b(list_copy.sense_len, data->sense_data_length);
660 	memcpy(data->sense_data, &list_copy.sense_data, list_copy.sense_len);
661 
662 	ctl_set_success(ctsio);
663 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
664 	ctsio->be_move_done = ctl_config_move_done;
665 	ctl_datamove((union ctl_io *)ctsio);
666 	return (retval);
667 }
668 
669 int
670 ctl_receive_copy_status_lid4(struct ctl_scsiio *ctsio)
671 {
672 	struct ctl_lun *lun;
673 	struct scsi_receive_copy_status_lid4 *cdb;
674 	struct scsi_receive_copy_status_lid4_data *data;
675 	struct tpc_list *list;
676 	struct tpc_list list_copy;
677 	int retval;
678 	int alloc_len, total_len;
679 	uint32_t list_id;
680 
681 	CTL_DEBUG_PRINT(("ctl_receive_copy_status_lid4\n"));
682 
683 	cdb = (struct scsi_receive_copy_status_lid4 *)ctsio->cdb;
684 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
685 
686 	retval = CTL_RETVAL_COMPLETE;
687 
688 	list_id = scsi_4btoul(cdb->list_identifier);
689 	mtx_lock(&lun->lun_lock);
690 	list = tpc_find_list(lun, list_id,
691 	    ctl_get_resindex(&ctsio->io_hdr.nexus));
692 	if (list == NULL) {
693 		mtx_unlock(&lun->lun_lock);
694 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
695 		    /*command*/ 1, /*field*/ 2, /*bit_valid*/ 0,
696 		    /*bit*/ 0);
697 		ctl_done((union ctl_io *)ctsio);
698 		return (retval);
699 	}
700 	list_copy = *list;
701 	if (list->completed) {
702 		TAILQ_REMOVE(&lun->tpc_lists, list, links);
703 		free(list, M_CTL);
704 	}
705 	mtx_unlock(&lun->lun_lock);
706 
707 	total_len = sizeof(*data) + list_copy.sense_len;
708 	alloc_len = scsi_4btoul(cdb->length);
709 
710 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
711 
712 	ctsio->kern_sg_entries = 0;
713 
714 	if (total_len < alloc_len) {
715 		ctsio->residual = alloc_len - total_len;
716 		ctsio->kern_data_len = total_len;
717 		ctsio->kern_total_len = total_len;
718 	} else {
719 		ctsio->residual = 0;
720 		ctsio->kern_data_len = alloc_len;
721 		ctsio->kern_total_len = alloc_len;
722 	}
723 	ctsio->kern_data_resid = 0;
724 	ctsio->kern_rel_offset = 0;
725 
726 	data = (struct scsi_receive_copy_status_lid4_data *)ctsio->kern_data_ptr;
727 	scsi_ulto4b(sizeof(*data) - 4 + list_copy.sense_len,
728 	    data->available_data);
729 	data->response_to_service_action = list_copy.service_action;
730 	if (list_copy.completed) {
731 		if (list_copy.error)
732 			data->copy_command_status = RCS_CCS_ERROR;
733 		else if (list_copy.abort)
734 			data->copy_command_status = RCS_CCS_ABORTED;
735 		else
736 			data->copy_command_status = RCS_CCS_COMPLETED;
737 	} else
738 		data->copy_command_status = RCS_CCS_INPROG_FG;
739 	scsi_ulto2b(list_copy.curops, data->operation_counter);
740 	scsi_ulto4b(UINT32_MAX, data->estimated_status_update_delay);
741 	data->transfer_count_units = RCS_TC_BYTES;
742 	scsi_u64to8b(list_copy.curbytes, data->transfer_count);
743 	scsi_ulto2b(list_copy.curseg, data->segments_processed);
744 	data->length_of_the_sense_data_field = list_copy.sense_len;
745 	data->sense_data_length = list_copy.sense_len;
746 	memcpy(data->sense_data, &list_copy.sense_data, list_copy.sense_len);
747 
748 	ctl_set_success(ctsio);
749 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
750 	ctsio->be_move_done = ctl_config_move_done;
751 	ctl_datamove((union ctl_io *)ctsio);
752 	return (retval);
753 }
754 
755 int
756 ctl_copy_operation_abort(struct ctl_scsiio *ctsio)
757 {
758 	struct ctl_lun *lun;
759 	struct scsi_copy_operation_abort *cdb;
760 	struct tpc_list *list;
761 	int retval;
762 	uint32_t list_id;
763 
764 	CTL_DEBUG_PRINT(("ctl_copy_operation_abort\n"));
765 
766 	cdb = (struct scsi_copy_operation_abort *)ctsio->cdb;
767 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
768 
769 	retval = CTL_RETVAL_COMPLETE;
770 
771 	list_id = scsi_4btoul(cdb->list_identifier);
772 	mtx_lock(&lun->lun_lock);
773 	list = tpc_find_list(lun, list_id,
774 	    ctl_get_resindex(&ctsio->io_hdr.nexus));
775 	if (list == NULL) {
776 		mtx_unlock(&lun->lun_lock);
777 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
778 		    /*command*/ 1, /*field*/ 2, /*bit_valid*/ 0,
779 		    /*bit*/ 0);
780 		ctl_done((union ctl_io *)ctsio);
781 		return (retval);
782 	}
783 	list->abort = 1;
784 	mtx_unlock(&lun->lun_lock);
785 
786 	ctl_set_success(ctsio);
787 	ctl_done((union ctl_io *)ctsio);
788 	return (retval);
789 }
790 
791 static uint64_t
792 tpc_resolve(struct tpc_list *list, uint16_t idx, uint32_t *ss,
793     uint32_t *pb, uint32_t *pbo)
794 {
795 
796 	if (idx == 0xffff) {
797 		if (ss && list->lun->be_lun)
798 			*ss = list->lun->be_lun->blocksize;
799 		if (pb && list->lun->be_lun)
800 			*pb = list->lun->be_lun->blocksize <<
801 			    list->lun->be_lun->pblockexp;
802 		if (pbo && list->lun->be_lun)
803 			*pbo = list->lun->be_lun->blocksize *
804 			    list->lun->be_lun->pblockoff;
805 		return (list->lun->lun);
806 	}
807 	if (idx >= list->ncscd)
808 		return (UINT64_MAX);
809 	return (tpcl_resolve(list->lun->ctl_softc,
810 	    list->init_port, &list->cscd[idx], ss, pb, pbo));
811 }
812 
813 static int
814 tpc_process_b2b(struct tpc_list *list)
815 {
816 	struct scsi_ec_segment_b2b *seg;
817 	struct scsi_ec_cscd_dtsp *sdstp, *ddstp;
818 	struct tpc_io *tior, *tiow;
819 	struct runl run;
820 	uint64_t sl, dl;
821 	off_t srclba, dstlba, numbytes, donebytes, roundbytes;
822 	int numlba;
823 	uint32_t srcblock, dstblock, pb, pbo, adj;
824 
825 	if (list->stage == 1) {
826 		while ((tior = TAILQ_FIRST(&list->allio)) != NULL) {
827 			TAILQ_REMOVE(&list->allio, tior, links);
828 			ctl_free_io(tior->io);
829 			free(tior, M_CTL);
830 		}
831 		free(list->buf, M_CTL);
832 		if (list->abort) {
833 			ctl_set_task_aborted(list->ctsio);
834 			return (CTL_RETVAL_ERROR);
835 		} else if (list->error) {
836 			ctl_set_sense(list->ctsio, /*current_error*/ 1,
837 			    /*sense_key*/ SSD_KEY_COPY_ABORTED,
838 			    /*asc*/ 0x0d, /*ascq*/ 0x01, SSD_ELEM_NONE);
839 			return (CTL_RETVAL_ERROR);
840 		}
841 		list->cursectors += list->segsectors;
842 		list->curbytes += list->segbytes;
843 		return (CTL_RETVAL_COMPLETE);
844 	}
845 
846 	TAILQ_INIT(&list->allio);
847 	seg = (struct scsi_ec_segment_b2b *)list->seg[list->curseg];
848 	sl = tpc_resolve(list, scsi_2btoul(seg->src_cscd), &srcblock, NULL, NULL);
849 	dl = tpc_resolve(list, scsi_2btoul(seg->dst_cscd), &dstblock, &pb, &pbo);
850 	if (sl >= CTL_MAX_LUNS || dl >= CTL_MAX_LUNS) {
851 		ctl_set_sense(list->ctsio, /*current_error*/ 1,
852 		    /*sense_key*/ SSD_KEY_COPY_ABORTED,
853 		    /*asc*/ 0x08, /*ascq*/ 0x04, SSD_ELEM_NONE);
854 		return (CTL_RETVAL_ERROR);
855 	}
856 	if (pbo > 0)
857 		pbo = pb - pbo;
858 	sdstp = &list->cscd[scsi_2btoul(seg->src_cscd)].dtsp;
859 	if (scsi_3btoul(sdstp->block_length) != 0)
860 		srcblock = scsi_3btoul(sdstp->block_length);
861 	ddstp = &list->cscd[scsi_2btoul(seg->dst_cscd)].dtsp;
862 	if (scsi_3btoul(ddstp->block_length) != 0)
863 		dstblock = scsi_3btoul(ddstp->block_length);
864 	numlba = scsi_2btoul(seg->number_of_blocks);
865 	if (seg->flags & EC_SEG_DC)
866 		numbytes = (off_t)numlba * dstblock;
867 	else
868 		numbytes = (off_t)numlba * srcblock;
869 	srclba = scsi_8btou64(seg->src_lba);
870 	dstlba = scsi_8btou64(seg->dst_lba);
871 
872 //	printf("Copy %ju bytes from %ju @ %ju to %ju @ %ju\n",
873 //	    (uintmax_t)numbytes, sl, scsi_8btou64(seg->src_lba),
874 //	    dl, scsi_8btou64(seg->dst_lba));
875 
876 	if (numbytes == 0)
877 		return (CTL_RETVAL_COMPLETE);
878 
879 	if (numbytes % srcblock != 0 || numbytes % dstblock != 0) {
880 		ctl_set_sense(list->ctsio, /*current_error*/ 1,
881 		    /*sense_key*/ SSD_KEY_COPY_ABORTED,
882 		    /*asc*/ 0x26, /*ascq*/ 0x0A, SSD_ELEM_NONE);
883 		return (CTL_RETVAL_ERROR);
884 	}
885 
886 	list->buf = malloc(numbytes, M_CTL, M_WAITOK);
887 	list->segbytes = numbytes;
888 	list->segsectors = numbytes / dstblock;
889 	donebytes = 0;
890 	TAILQ_INIT(&run);
891 	list->tbdio = 0;
892 	while (donebytes < numbytes) {
893 		roundbytes = numbytes - donebytes;
894 		if (roundbytes > TPC_MAX_IO_SIZE) {
895 			roundbytes = TPC_MAX_IO_SIZE;
896 			roundbytes -= roundbytes % dstblock;
897 			if (pb > dstblock) {
898 				adj = (dstlba * dstblock + roundbytes - pbo) % pb;
899 				if (roundbytes > adj)
900 					roundbytes -= adj;
901 			}
902 		}
903 
904 		tior = malloc(sizeof(*tior), M_CTL, M_WAITOK | M_ZERO);
905 		TAILQ_INIT(&tior->run);
906 		tior->list = list;
907 		TAILQ_INSERT_TAIL(&list->allio, tior, links);
908 		tior->io = tpcl_alloc_io();
909 		ctl_scsi_read_write(tior->io,
910 				    /*data_ptr*/ &list->buf[donebytes],
911 				    /*data_len*/ roundbytes,
912 				    /*read_op*/ 1,
913 				    /*byte2*/ 0,
914 				    /*minimum_cdb_size*/ 0,
915 				    /*lba*/ srclba,
916 				    /*num_blocks*/ roundbytes / srcblock,
917 				    /*tag_type*/ CTL_TAG_SIMPLE,
918 				    /*control*/ 0);
919 		tior->io->io_hdr.retries = 3;
920 		tior->lun = sl;
921 		tior->io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = tior;
922 
923 		tiow = malloc(sizeof(*tior), M_CTL, M_WAITOK | M_ZERO);
924 		TAILQ_INIT(&tiow->run);
925 		tiow->list = list;
926 		TAILQ_INSERT_TAIL(&list->allio, tiow, links);
927 		tiow->io = tpcl_alloc_io();
928 		ctl_scsi_read_write(tiow->io,
929 				    /*data_ptr*/ &list->buf[donebytes],
930 				    /*data_len*/ roundbytes,
931 				    /*read_op*/ 0,
932 				    /*byte2*/ 0,
933 				    /*minimum_cdb_size*/ 0,
934 				    /*lba*/ dstlba,
935 				    /*num_blocks*/ roundbytes / dstblock,
936 				    /*tag_type*/ CTL_TAG_SIMPLE,
937 				    /*control*/ 0);
938 		tiow->io->io_hdr.retries = 3;
939 		tiow->lun = dl;
940 		tiow->io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = tiow;
941 
942 		TAILQ_INSERT_TAIL(&tior->run, tiow, rlinks);
943 		TAILQ_INSERT_TAIL(&run, tior, rlinks);
944 		list->tbdio++;
945 		donebytes += roundbytes;
946 		srclba += roundbytes / srcblock;
947 		dstlba += roundbytes / dstblock;
948 	}
949 
950 	while ((tior = TAILQ_FIRST(&run)) != NULL) {
951 		TAILQ_REMOVE(&run, tior, rlinks);
952 		if (tpcl_queue(tior->io, tior->lun) != CTL_RETVAL_COMPLETE)
953 			panic("tpcl_queue() error");
954 	}
955 
956 	list->stage++;
957 	return (CTL_RETVAL_QUEUED);
958 }
959 
960 static int
961 tpc_process_verify(struct tpc_list *list)
962 {
963 	struct scsi_ec_segment_verify *seg;
964 	struct tpc_io *tio;
965 	uint64_t sl;
966 
967 	if (list->stage == 1) {
968 		while ((tio = TAILQ_FIRST(&list->allio)) != NULL) {
969 			TAILQ_REMOVE(&list->allio, tio, links);
970 			ctl_free_io(tio->io);
971 			free(tio, M_CTL);
972 		}
973 		if (list->abort) {
974 			ctl_set_task_aborted(list->ctsio);
975 			return (CTL_RETVAL_ERROR);
976 		} else if (list->error) {
977 			ctl_set_sense(list->ctsio, /*current_error*/ 1,
978 			    /*sense_key*/ SSD_KEY_COPY_ABORTED,
979 			    /*asc*/ 0x0d, /*ascq*/ 0x01, SSD_ELEM_NONE);
980 			return (CTL_RETVAL_ERROR);
981 		} else
982 			return (CTL_RETVAL_COMPLETE);
983 	}
984 
985 	TAILQ_INIT(&list->allio);
986 	seg = (struct scsi_ec_segment_verify *)list->seg[list->curseg];
987 	sl = tpc_resolve(list, scsi_2btoul(seg->src_cscd), NULL, NULL, NULL);
988 	if (sl >= CTL_MAX_LUNS) {
989 		ctl_set_sense(list->ctsio, /*current_error*/ 1,
990 		    /*sense_key*/ SSD_KEY_COPY_ABORTED,
991 		    /*asc*/ 0x08, /*ascq*/ 0x04, SSD_ELEM_NONE);
992 		return (CTL_RETVAL_ERROR);
993 	}
994 
995 //	printf("Verify %ju\n", sl);
996 
997 	if ((seg->tur & 0x01) == 0)
998 		return (CTL_RETVAL_COMPLETE);
999 
1000 	list->tbdio = 1;
1001 	tio = malloc(sizeof(*tio), M_CTL, M_WAITOK | M_ZERO);
1002 	TAILQ_INIT(&tio->run);
1003 	tio->list = list;
1004 	TAILQ_INSERT_TAIL(&list->allio, tio, links);
1005 	tio->io = tpcl_alloc_io();
1006 	ctl_scsi_tur(tio->io, /*tag_type*/ CTL_TAG_SIMPLE, /*control*/ 0);
1007 	tio->io->io_hdr.retries = 3;
1008 	tio->lun = sl;
1009 	tio->io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = tio;
1010 	list->stage++;
1011 	if (tpcl_queue(tio->io, tio->lun) != CTL_RETVAL_COMPLETE)
1012 		panic("tpcl_queue() error");
1013 	return (CTL_RETVAL_QUEUED);
1014 }
1015 
1016 static int
1017 tpc_process_register_key(struct tpc_list *list)
1018 {
1019 	struct scsi_ec_segment_register_key *seg;
1020 	struct tpc_io *tio;
1021 	uint64_t dl;
1022 	int datalen;
1023 
1024 	if (list->stage == 1) {
1025 		while ((tio = TAILQ_FIRST(&list->allio)) != NULL) {
1026 			TAILQ_REMOVE(&list->allio, tio, links);
1027 			ctl_free_io(tio->io);
1028 			free(tio, M_CTL);
1029 		}
1030 		free(list->buf, M_CTL);
1031 		if (list->abort) {
1032 			ctl_set_task_aborted(list->ctsio);
1033 			return (CTL_RETVAL_ERROR);
1034 		} else if (list->error) {
1035 			ctl_set_sense(list->ctsio, /*current_error*/ 1,
1036 			    /*sense_key*/ SSD_KEY_COPY_ABORTED,
1037 			    /*asc*/ 0x0d, /*ascq*/ 0x01, SSD_ELEM_NONE);
1038 			return (CTL_RETVAL_ERROR);
1039 		} else
1040 			return (CTL_RETVAL_COMPLETE);
1041 	}
1042 
1043 	TAILQ_INIT(&list->allio);
1044 	seg = (struct scsi_ec_segment_register_key *)list->seg[list->curseg];
1045 	dl = tpc_resolve(list, scsi_2btoul(seg->dst_cscd), NULL, NULL, NULL);
1046 	if (dl >= CTL_MAX_LUNS) {
1047 		ctl_set_sense(list->ctsio, /*current_error*/ 1,
1048 		    /*sense_key*/ SSD_KEY_COPY_ABORTED,
1049 		    /*asc*/ 0x08, /*ascq*/ 0x04, SSD_ELEM_NONE);
1050 		return (CTL_RETVAL_ERROR);
1051 	}
1052 
1053 //	printf("Register Key %ju\n", dl);
1054 
1055 	list->tbdio = 1;
1056 	tio = malloc(sizeof(*tio), M_CTL, M_WAITOK | M_ZERO);
1057 	TAILQ_INIT(&tio->run);
1058 	tio->list = list;
1059 	TAILQ_INSERT_TAIL(&list->allio, tio, links);
1060 	tio->io = tpcl_alloc_io();
1061 	datalen = sizeof(struct scsi_per_res_out_parms);
1062 	list->buf = malloc(datalen, M_CTL, M_WAITOK);
1063 	ctl_scsi_persistent_res_out(tio->io,
1064 	    list->buf, datalen, SPRO_REGISTER, -1,
1065 	    scsi_8btou64(seg->res_key), scsi_8btou64(seg->sa_res_key),
1066 	    /*tag_type*/ CTL_TAG_SIMPLE, /*control*/ 0);
1067 	tio->io->io_hdr.retries = 3;
1068 	tio->lun = dl;
1069 	tio->io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = tio;
1070 	list->stage++;
1071 	if (tpcl_queue(tio->io, tio->lun) != CTL_RETVAL_COMPLETE)
1072 		panic("tpcl_queue() error");
1073 	return (CTL_RETVAL_QUEUED);
1074 }
1075 
1076 static off_t
1077 tpc_ranges_length(struct scsi_range_desc *range, int nrange)
1078 {
1079 	off_t length = 0;
1080 	int r;
1081 
1082 	for (r = 0; r < nrange; r++)
1083 		length += scsi_4btoul(range[r].length);
1084 	return (length);
1085 }
1086 
1087 static int
1088 tpc_skip_ranges(struct scsi_range_desc *range, int nrange, off_t skip,
1089     int *srange, off_t *soffset)
1090 {
1091 	off_t off;
1092 	int r;
1093 
1094 	r = 0;
1095 	off = 0;
1096 	while (r < nrange) {
1097 		if (skip - off < scsi_4btoul(range[r].length)) {
1098 			*srange = r;
1099 			*soffset = skip - off;
1100 			return (0);
1101 		}
1102 		off += scsi_4btoul(range[r].length);
1103 		r++;
1104 	}
1105 	return (-1);
1106 }
1107 
1108 static int
1109 tpc_process_wut(struct tpc_list *list)
1110 {
1111 	struct tpc_io *tio, *tior, *tiow;
1112 	struct runl run, *prun;
1113 	int drange, srange;
1114 	off_t doffset, soffset;
1115 	off_t srclba, dstlba, numbytes, donebytes, roundbytes;
1116 	uint32_t srcblock, dstblock, pb, pbo, adj;
1117 
1118 	if (list->stage > 0) {
1119 		/* Cleanup after previous rounds. */
1120 		while ((tio = TAILQ_FIRST(&list->allio)) != NULL) {
1121 			TAILQ_REMOVE(&list->allio, tio, links);
1122 			ctl_free_io(tio->io);
1123 			free(tio, M_CTL);
1124 		}
1125 		free(list->buf, M_CTL);
1126 		if (list->abort) {
1127 			ctl_set_task_aborted(list->ctsio);
1128 			return (CTL_RETVAL_ERROR);
1129 		} else if (list->error) {
1130 			ctl_set_sense(list->ctsio, /*current_error*/ 1,
1131 			    /*sense_key*/ SSD_KEY_COPY_ABORTED,
1132 			    /*asc*/ 0x0d, /*ascq*/ 0x01, SSD_ELEM_NONE);
1133 			return (CTL_RETVAL_ERROR);
1134 		}
1135 		list->cursectors += list->segsectors;
1136 		list->curbytes += list->segbytes;
1137 	}
1138 
1139 	/* Check where we are on destination ranges list. */
1140 	if (tpc_skip_ranges(list->range, list->nrange, list->cursectors,
1141 	    &drange, &doffset) != 0)
1142 		return (CTL_RETVAL_COMPLETE);
1143 	dstblock = list->lun->be_lun->blocksize;
1144 	pb = dstblock << list->lun->be_lun->pblockexp;
1145 	if (list->lun->be_lun->pblockoff > 0)
1146 		pbo = pb - dstblock * list->lun->be_lun->pblockoff;
1147 	else
1148 		pbo = 0;
1149 
1150 	/* Check where we are on source ranges list. */
1151 	srcblock = list->token->blocksize;
1152 	if (tpc_skip_ranges(list->token->range, list->token->nrange,
1153 	    list->offset_into_rod + list->cursectors * dstblock / srcblock,
1154 	    &srange, &soffset) != 0) {
1155 		ctl_set_sense(list->ctsio, /*current_error*/ 1,
1156 		    /*sense_key*/ SSD_KEY_COPY_ABORTED,
1157 		    /*asc*/ 0x0d, /*ascq*/ 0x04, SSD_ELEM_NONE);
1158 		return (CTL_RETVAL_ERROR);
1159 	}
1160 
1161 	srclba = scsi_8btou64(list->token->range[srange].lba) + soffset;
1162 	dstlba = scsi_8btou64(list->range[drange].lba) + doffset;
1163 	numbytes = srcblock *
1164 	    (scsi_4btoul(list->token->range[srange].length) - soffset);
1165 	numbytes = omin(numbytes, dstblock *
1166 	    (scsi_4btoul(list->range[drange].length) - doffset));
1167 	if (numbytes > TPC_MAX_IOCHUNK_SIZE) {
1168 		numbytes = TPC_MAX_IOCHUNK_SIZE;
1169 		numbytes -= numbytes % dstblock;
1170 		if (pb > dstblock) {
1171 			adj = (dstlba * dstblock + numbytes - pbo) % pb;
1172 			if (numbytes > adj)
1173 				numbytes -= adj;
1174 		}
1175 	}
1176 
1177 	if (numbytes % srcblock != 0 || numbytes % dstblock != 0) {
1178 		ctl_set_sense(list->ctsio, /*current_error*/ 1,
1179 		    /*sense_key*/ SSD_KEY_COPY_ABORTED,
1180 		    /*asc*/ 0x26, /*ascq*/ 0x0A, SSD_ELEM_NONE);
1181 		return (CTL_RETVAL_ERROR);
1182 	}
1183 
1184 	list->buf = malloc(numbytes, M_CTL, M_WAITOK |
1185 	    (list->token == NULL ? M_ZERO : 0));
1186 	list->segbytes = numbytes;
1187 	list->segsectors = numbytes / dstblock;
1188 //printf("Copy chunk of %ju sectors from %ju to %ju\n", list->segsectors,
1189 //    srclba, dstlba);
1190 	donebytes = 0;
1191 	TAILQ_INIT(&run);
1192 	prun = &run;
1193 	list->tbdio = 1;
1194 	TAILQ_INIT(&list->allio);
1195 	while (donebytes < numbytes) {
1196 		roundbytes = numbytes - donebytes;
1197 		if (roundbytes > TPC_MAX_IO_SIZE) {
1198 			roundbytes = TPC_MAX_IO_SIZE;
1199 			roundbytes -= roundbytes % dstblock;
1200 			if (pb > dstblock) {
1201 				adj = (dstlba * dstblock + roundbytes - pbo) % pb;
1202 				if (roundbytes > adj)
1203 					roundbytes -= adj;
1204 			}
1205 		}
1206 
1207 		tior = malloc(sizeof(*tior), M_CTL, M_WAITOK | M_ZERO);
1208 		TAILQ_INIT(&tior->run);
1209 		tior->list = list;
1210 		TAILQ_INSERT_TAIL(&list->allio, tior, links);
1211 		tior->io = tpcl_alloc_io();
1212 		ctl_scsi_read_write(tior->io,
1213 				    /*data_ptr*/ &list->buf[donebytes],
1214 				    /*data_len*/ roundbytes,
1215 				    /*read_op*/ 1,
1216 				    /*byte2*/ 0,
1217 				    /*minimum_cdb_size*/ 0,
1218 				    /*lba*/ srclba,
1219 				    /*num_blocks*/ roundbytes / srcblock,
1220 				    /*tag_type*/ CTL_TAG_SIMPLE,
1221 				    /*control*/ 0);
1222 		tior->io->io_hdr.retries = 3;
1223 		tior->lun = list->token->lun;
1224 		tior->io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = tior;
1225 
1226 		tiow = malloc(sizeof(*tiow), M_CTL, M_WAITOK | M_ZERO);
1227 		TAILQ_INIT(&tiow->run);
1228 		tiow->list = list;
1229 		TAILQ_INSERT_TAIL(&list->allio, tiow, links);
1230 		tiow->io = tpcl_alloc_io();
1231 		ctl_scsi_read_write(tiow->io,
1232 				    /*data_ptr*/ &list->buf[donebytes],
1233 				    /*data_len*/ roundbytes,
1234 				    /*read_op*/ 0,
1235 				    /*byte2*/ 0,
1236 				    /*minimum_cdb_size*/ 0,
1237 				    /*lba*/ dstlba,
1238 				    /*num_blocks*/ roundbytes / dstblock,
1239 				    /*tag_type*/ CTL_TAG_SIMPLE,
1240 				    /*control*/ 0);
1241 		tiow->io->io_hdr.retries = 3;
1242 		tiow->lun = list->lun->lun;
1243 		tiow->io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = tiow;
1244 
1245 		TAILQ_INSERT_TAIL(&tior->run, tiow, rlinks);
1246 		TAILQ_INSERT_TAIL(prun, tior, rlinks);
1247 		prun = &tior->run;
1248 		donebytes += roundbytes;
1249 		srclba += roundbytes / srcblock;
1250 		dstlba += roundbytes / dstblock;
1251 	}
1252 
1253 	while ((tior = TAILQ_FIRST(&run)) != NULL) {
1254 		TAILQ_REMOVE(&run, tior, rlinks);
1255 		if (tpcl_queue(tior->io, tior->lun) != CTL_RETVAL_COMPLETE)
1256 			panic("tpcl_queue() error");
1257 	}
1258 
1259 	list->stage++;
1260 	return (CTL_RETVAL_QUEUED);
1261 }
1262 
1263 static int
1264 tpc_process_zero_wut(struct tpc_list *list)
1265 {
1266 	struct tpc_io *tio, *tiow;
1267 	struct runl run, *prun;
1268 	int r;
1269 	uint32_t dstblock, len;
1270 
1271 	if (list->stage > 0) {
1272 complete:
1273 		/* Cleanup after previous rounds. */
1274 		while ((tio = TAILQ_FIRST(&list->allio)) != NULL) {
1275 			TAILQ_REMOVE(&list->allio, tio, links);
1276 			ctl_free_io(tio->io);
1277 			free(tio, M_CTL);
1278 		}
1279 		free(list->buf, M_CTL);
1280 		if (list->abort) {
1281 			ctl_set_task_aborted(list->ctsio);
1282 			return (CTL_RETVAL_ERROR);
1283 		} else if (list->error) {
1284 			ctl_set_sense(list->ctsio, /*current_error*/ 1,
1285 			    /*sense_key*/ SSD_KEY_COPY_ABORTED,
1286 			    /*asc*/ 0x0d, /*ascq*/ 0x01, SSD_ELEM_NONE);
1287 			return (CTL_RETVAL_ERROR);
1288 		}
1289 		list->cursectors += list->segsectors;
1290 		list->curbytes += list->segbytes;
1291 		return (CTL_RETVAL_COMPLETE);
1292 	}
1293 
1294 	dstblock = list->lun->be_lun->blocksize;
1295 	list->buf = malloc(dstblock, M_CTL, M_WAITOK | M_ZERO);
1296 	TAILQ_INIT(&run);
1297 	prun = &run;
1298 	list->tbdio = 1;
1299 	TAILQ_INIT(&list->allio);
1300 	list->segsectors = 0;
1301 	for (r = 0; r < list->nrange; r++) {
1302 		len = scsi_4btoul(list->range[r].length);
1303 		if (len == 0)
1304 			continue;
1305 
1306 		tiow = malloc(sizeof(*tiow), M_CTL, M_WAITOK | M_ZERO);
1307 		TAILQ_INIT(&tiow->run);
1308 		tiow->list = list;
1309 		TAILQ_INSERT_TAIL(&list->allio, tiow, links);
1310 		tiow->io = tpcl_alloc_io();
1311 		ctl_scsi_write_same(tiow->io,
1312 				    /*data_ptr*/ list->buf,
1313 				    /*data_len*/ dstblock,
1314 				    /*byte2*/ 0,
1315 				    /*lba*/ scsi_8btou64(list->range[r].lba),
1316 				    /*num_blocks*/ len,
1317 				    /*tag_type*/ CTL_TAG_SIMPLE,
1318 				    /*control*/ 0);
1319 		tiow->io->io_hdr.retries = 3;
1320 		tiow->lun = list->lun->lun;
1321 		tiow->io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = tiow;
1322 
1323 		TAILQ_INSERT_TAIL(prun, tiow, rlinks);
1324 		prun = &tiow->run;
1325 		list->segsectors += len;
1326 	}
1327 	list->segbytes = list->segsectors * dstblock;
1328 
1329 	if (TAILQ_EMPTY(&run))
1330 		goto complete;
1331 
1332 	while ((tiow = TAILQ_FIRST(&run)) != NULL) {
1333 		TAILQ_REMOVE(&run, tiow, rlinks);
1334 		if (tpcl_queue(tiow->io, tiow->lun) != CTL_RETVAL_COMPLETE)
1335 			panic("tpcl_queue() error");
1336 	}
1337 
1338 	list->stage++;
1339 	return (CTL_RETVAL_QUEUED);
1340 }
1341 
1342 static void
1343 tpc_process(struct tpc_list *list)
1344 {
1345 	struct ctl_lun *lun = list->lun;
1346 	struct ctl_softc *softc = lun->ctl_softc;
1347 	struct scsi_ec_segment *seg;
1348 	struct ctl_scsiio *ctsio = list->ctsio;
1349 	int retval = CTL_RETVAL_COMPLETE;
1350 
1351 	if (list->service_action == EC_WUT) {
1352 		if (list->token != NULL)
1353 			retval = tpc_process_wut(list);
1354 		else
1355 			retval = tpc_process_zero_wut(list);
1356 		if (retval == CTL_RETVAL_QUEUED)
1357 			return;
1358 		if (retval == CTL_RETVAL_ERROR) {
1359 			list->error = 1;
1360 			goto done;
1361 		}
1362 	} else {
1363 //printf("ZZZ %d cscd, %d segs\n", list->ncscd, list->nseg);
1364 		while (list->curseg < list->nseg) {
1365 			seg = list->seg[list->curseg];
1366 			switch (seg->type_code) {
1367 			case EC_SEG_B2B:
1368 				retval = tpc_process_b2b(list);
1369 				break;
1370 			case EC_SEG_VERIFY:
1371 				retval = tpc_process_verify(list);
1372 				break;
1373 			case EC_SEG_REGISTER_KEY:
1374 				retval = tpc_process_register_key(list);
1375 				break;
1376 			default:
1377 				ctl_set_sense(ctsio, /*current_error*/ 1,
1378 				    /*sense_key*/ SSD_KEY_COPY_ABORTED,
1379 				    /*asc*/ 0x26, /*ascq*/ 0x09, SSD_ELEM_NONE);
1380 				goto done;
1381 			}
1382 			if (retval == CTL_RETVAL_QUEUED)
1383 				return;
1384 			if (retval == CTL_RETVAL_ERROR) {
1385 				list->error = 1;
1386 				goto done;
1387 			}
1388 			list->curseg++;
1389 			list->stage = 0;
1390 		}
1391 	}
1392 
1393 	ctl_set_success(ctsio);
1394 
1395 done:
1396 //printf("ZZZ done\n");
1397 	free(list->params, M_CTL);
1398 	list->params = NULL;
1399 	if (list->token) {
1400 		mtx_lock(&softc->tpc_lock);
1401 		if (--list->token->active == 0)
1402 			list->token->last_active = time_uptime;
1403 		mtx_unlock(&softc->tpc_lock);
1404 		list->token = NULL;
1405 	}
1406 	mtx_lock(&lun->lun_lock);
1407 	if ((list->flags & EC_LIST_ID_USAGE_MASK) == EC_LIST_ID_USAGE_NONE) {
1408 		TAILQ_REMOVE(&lun->tpc_lists, list, links);
1409 		free(list, M_CTL);
1410 	} else {
1411 		list->completed = 1;
1412 		list->last_active = time_uptime;
1413 		list->sense_data = ctsio->sense_data;
1414 		list->sense_len = ctsio->sense_len;
1415 		list->scsi_status = ctsio->scsi_status;
1416 	}
1417 	mtx_unlock(&lun->lun_lock);
1418 
1419 	ctl_done((union ctl_io *)ctsio);
1420 }
1421 
1422 /*
1423  * For any sort of check condition, busy, etc., we just retry.  We do not
1424  * decrement the retry count for unit attention type errors.  These are
1425  * normal, and we want to save the retry count for "real" errors.  Otherwise,
1426  * we could end up with situations where a command will succeed in some
1427  * situations and fail in others, depending on whether a unit attention is
1428  * pending.  Also, some of our error recovery actions, most notably the
1429  * LUN reset action, will cause a unit attention.
1430  *
1431  * We can add more detail here later if necessary.
1432  */
1433 static tpc_error_action
1434 tpc_checkcond_parse(union ctl_io *io)
1435 {
1436 	tpc_error_action error_action;
1437 	int error_code, sense_key, asc, ascq;
1438 
1439 	/*
1440 	 * Default to retrying the command.
1441 	 */
1442 	error_action = TPC_ERR_RETRY;
1443 
1444 	scsi_extract_sense_len(&io->scsiio.sense_data,
1445 			       io->scsiio.sense_len,
1446 			       &error_code,
1447 			       &sense_key,
1448 			       &asc,
1449 			       &ascq,
1450 			       /*show_errors*/ 1);
1451 
1452 	switch (error_code) {
1453 	case SSD_DEFERRED_ERROR:
1454 	case SSD_DESC_DEFERRED_ERROR:
1455 		error_action |= TPC_ERR_NO_DECREMENT;
1456 		break;
1457 	case SSD_CURRENT_ERROR:
1458 	case SSD_DESC_CURRENT_ERROR:
1459 	default:
1460 		switch (sense_key) {
1461 		case SSD_KEY_UNIT_ATTENTION:
1462 			error_action |= TPC_ERR_NO_DECREMENT;
1463 			break;
1464 		case SSD_KEY_HARDWARE_ERROR:
1465 			/*
1466 			 * This is our generic "something bad happened"
1467 			 * error code.  It often isn't recoverable.
1468 			 */
1469 			if ((asc == 0x44) && (ascq == 0x00))
1470 				error_action = TPC_ERR_FAIL;
1471 			break;
1472 		case SSD_KEY_NOT_READY:
1473 			/*
1474 			 * If the LUN is powered down, there likely isn't
1475 			 * much point in retrying right now.
1476 			 */
1477 			if ((asc == 0x04) && (ascq == 0x02))
1478 				error_action = TPC_ERR_FAIL;
1479 			/*
1480 			 * If the LUN is offline, there probably isn't much
1481 			 * point in retrying, either.
1482 			 */
1483 			if ((asc == 0x04) && (ascq == 0x03))
1484 				error_action = TPC_ERR_FAIL;
1485 			break;
1486 		}
1487 	}
1488 	return (error_action);
1489 }
1490 
1491 static tpc_error_action
1492 tpc_error_parse(union ctl_io *io)
1493 {
1494 	tpc_error_action error_action = TPC_ERR_RETRY;
1495 
1496 	switch (io->io_hdr.io_type) {
1497 	case CTL_IO_SCSI:
1498 		switch (io->io_hdr.status & CTL_STATUS_MASK) {
1499 		case CTL_SCSI_ERROR:
1500 			switch (io->scsiio.scsi_status) {
1501 			case SCSI_STATUS_CHECK_COND:
1502 				error_action = tpc_checkcond_parse(io);
1503 				break;
1504 			default:
1505 				break;
1506 			}
1507 			break;
1508 		default:
1509 			break;
1510 		}
1511 		break;
1512 	case CTL_IO_TASK:
1513 		break;
1514 	default:
1515 		panic("%s: invalid ctl_io type %d\n", __func__,
1516 		      io->io_hdr.io_type);
1517 		break;
1518 	}
1519 	return (error_action);
1520 }
1521 
1522 void
1523 tpc_done(union ctl_io *io)
1524 {
1525 	struct tpc_io *tio, *tior;
1526 
1527 	/*
1528 	 * Very minimal retry logic.  We basically retry if we got an error
1529 	 * back, and the retry count is greater than 0.  If we ever want
1530 	 * more sophisticated initiator type behavior, the CAM error
1531 	 * recovery code in ../common might be helpful.
1532 	 */
1533 	tio = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1534 	if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
1535 	 && (io->io_hdr.retries > 0)) {
1536 		ctl_io_status old_status;
1537 		tpc_error_action error_action;
1538 
1539 		error_action = tpc_error_parse(io);
1540 		switch (error_action & TPC_ERR_MASK) {
1541 		case TPC_ERR_FAIL:
1542 			break;
1543 		case TPC_ERR_RETRY:
1544 		default:
1545 			if ((error_action & TPC_ERR_NO_DECREMENT) == 0)
1546 				io->io_hdr.retries--;
1547 			old_status = io->io_hdr.status;
1548 			io->io_hdr.status = CTL_STATUS_NONE;
1549 			io->io_hdr.flags &= ~CTL_FLAG_ABORT;
1550 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1551 			if (tpcl_queue(io, tio->lun) != CTL_RETVAL_COMPLETE) {
1552 				printf("%s: error returned from ctl_queue()!\n",
1553 				       __func__);
1554 				io->io_hdr.status = old_status;
1555 			} else
1556 				return;
1557 		}
1558 	}
1559 
1560 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
1561 		tio->list->error = 1;
1562 	else
1563 		atomic_add_int(&tio->list->curops, 1);
1564 	if (!tio->list->error && !tio->list->abort) {
1565 		while ((tior = TAILQ_FIRST(&tio->run)) != NULL) {
1566 			TAILQ_REMOVE(&tio->run, tior, rlinks);
1567 			atomic_add_int(&tio->list->tbdio, 1);
1568 			if (tpcl_queue(tior->io, tior->lun) != CTL_RETVAL_COMPLETE)
1569 				panic("tpcl_queue() error");
1570 		}
1571 	}
1572 	if (atomic_fetchadd_int(&tio->list->tbdio, -1) == 1)
1573 		tpc_process(tio->list);
1574 }
1575 
1576 int
1577 ctl_extended_copy_lid1(struct ctl_scsiio *ctsio)
1578 {
1579 	struct scsi_extended_copy *cdb;
1580 	struct scsi_extended_copy_lid1_data *data;
1581 	struct ctl_lun *lun;
1582 	struct tpc_list *list, *tlist;
1583 	uint8_t *ptr;
1584 	char *value;
1585 	int len, off, lencscd, lenseg, leninl, nseg;
1586 
1587 	CTL_DEBUG_PRINT(("ctl_extended_copy_lid1\n"));
1588 
1589 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
1590 	cdb = (struct scsi_extended_copy *)ctsio->cdb;
1591 	len = scsi_4btoul(cdb->length);
1592 
1593 	if (len < sizeof(struct scsi_extended_copy_lid1_data) ||
1594 	    len > sizeof(struct scsi_extended_copy_lid1_data) +
1595 	    TPC_MAX_LIST + TPC_MAX_INLINE) {
1596 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
1597 		    /*field*/ 9, /*bit_valid*/ 0, /*bit*/ 0);
1598 		goto done;
1599 	}
1600 
1601 	/*
1602 	 * If we've got a kernel request that hasn't been malloced yet,
1603 	 * malloc it and tell the caller the data buffer is here.
1604 	 */
1605 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
1606 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
1607 		ctsio->kern_data_len = len;
1608 		ctsio->kern_total_len = len;
1609 		ctsio->kern_data_resid = 0;
1610 		ctsio->kern_rel_offset = 0;
1611 		ctsio->kern_sg_entries = 0;
1612 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
1613 		ctsio->be_move_done = ctl_config_move_done;
1614 		ctl_datamove((union ctl_io *)ctsio);
1615 
1616 		return (CTL_RETVAL_COMPLETE);
1617 	}
1618 
1619 	data = (struct scsi_extended_copy_lid1_data *)ctsio->kern_data_ptr;
1620 	lencscd = scsi_2btoul(data->cscd_list_length);
1621 	lenseg = scsi_4btoul(data->segment_list_length);
1622 	leninl = scsi_4btoul(data->inline_data_length);
1623 	if (len < sizeof(struct scsi_extended_copy_lid1_data) +
1624 	    lencscd + lenseg + leninl ||
1625 	    leninl > TPC_MAX_INLINE) {
1626 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 0,
1627 		    /*field*/ 2, /*bit_valid*/ 0, /*bit*/ 0);
1628 		goto done;
1629 	}
1630 	if (lencscd > TPC_MAX_CSCDS * sizeof(struct scsi_ec_cscd)) {
1631 		ctl_set_sense(ctsio, /*current_error*/ 1,
1632 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1633 		    /*asc*/ 0x26, /*ascq*/ 0x06, SSD_ELEM_NONE);
1634 		goto done;
1635 	}
1636 	if (lencscd + lenseg > TPC_MAX_LIST) {
1637 		ctl_set_param_len_error(ctsio);
1638 		goto done;
1639 	}
1640 
1641 	list = malloc(sizeof(struct tpc_list), M_CTL, M_WAITOK | M_ZERO);
1642 	list->service_action = cdb->service_action;
1643 	value = ctl_get_opt(&lun->be_lun->options, "insecure_tpc");
1644 	if (value != NULL && strcmp(value, "on") == 0)
1645 		list->init_port = -1;
1646 	else
1647 		list->init_port = ctsio->io_hdr.nexus.targ_port;
1648 	list->init_idx = ctl_get_resindex(&ctsio->io_hdr.nexus);
1649 	list->list_id = data->list_identifier;
1650 	list->flags = data->flags;
1651 	list->params = ctsio->kern_data_ptr;
1652 	list->cscd = (struct scsi_ec_cscd *)&data->data[0];
1653 	ptr = &data->data[lencscd];
1654 	for (nseg = 0, off = 0; off < lenseg; nseg++) {
1655 		if (nseg >= TPC_MAX_SEGS) {
1656 			free(list, M_CTL);
1657 			ctl_set_sense(ctsio, /*current_error*/ 1,
1658 			    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1659 			    /*asc*/ 0x26, /*ascq*/ 0x08, SSD_ELEM_NONE);
1660 			goto done;
1661 		}
1662 		list->seg[nseg] = (struct scsi_ec_segment *)(ptr + off);
1663 		off += sizeof(struct scsi_ec_segment) +
1664 		    scsi_2btoul(list->seg[nseg]->descr_length);
1665 	}
1666 	list->inl = &data->data[lencscd + lenseg];
1667 	list->ncscd = lencscd / sizeof(struct scsi_ec_cscd);
1668 	list->nseg = nseg;
1669 	list->leninl = leninl;
1670 	list->ctsio = ctsio;
1671 	list->lun = lun;
1672 	mtx_lock(&lun->lun_lock);
1673 	if ((list->flags & EC_LIST_ID_USAGE_MASK) != EC_LIST_ID_USAGE_NONE) {
1674 		tlist = tpc_find_list(lun, list->list_id, list->init_idx);
1675 		if (tlist != NULL && !tlist->completed) {
1676 			mtx_unlock(&lun->lun_lock);
1677 			free(list, M_CTL);
1678 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
1679 			    /*command*/ 0, /*field*/ 0, /*bit_valid*/ 0,
1680 			    /*bit*/ 0);
1681 			goto done;
1682 		}
1683 		if (tlist != NULL) {
1684 			TAILQ_REMOVE(&lun->tpc_lists, tlist, links);
1685 			free(tlist, M_CTL);
1686 		}
1687 	}
1688 	TAILQ_INSERT_TAIL(&lun->tpc_lists, list, links);
1689 	mtx_unlock(&lun->lun_lock);
1690 
1691 	tpc_process(list);
1692 	return (CTL_RETVAL_COMPLETE);
1693 
1694 done:
1695 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
1696 		free(ctsio->kern_data_ptr, M_CTL);
1697 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
1698 	}
1699 	ctl_done((union ctl_io *)ctsio);
1700 	return (CTL_RETVAL_COMPLETE);
1701 }
1702 
1703 int
1704 ctl_extended_copy_lid4(struct ctl_scsiio *ctsio)
1705 {
1706 	struct scsi_extended_copy *cdb;
1707 	struct scsi_extended_copy_lid4_data *data;
1708 	struct ctl_lun *lun;
1709 	struct tpc_list *list, *tlist;
1710 	uint8_t *ptr;
1711 	char *value;
1712 	int len, off, lencscd, lenseg, leninl, nseg;
1713 
1714 	CTL_DEBUG_PRINT(("ctl_extended_copy_lid4\n"));
1715 
1716 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
1717 	cdb = (struct scsi_extended_copy *)ctsio->cdb;
1718 	len = scsi_4btoul(cdb->length);
1719 
1720 	if (len < sizeof(struct scsi_extended_copy_lid4_data) ||
1721 	    len > sizeof(struct scsi_extended_copy_lid4_data) +
1722 	    TPC_MAX_LIST + TPC_MAX_INLINE) {
1723 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
1724 		    /*field*/ 9, /*bit_valid*/ 0, /*bit*/ 0);
1725 		goto done;
1726 	}
1727 
1728 	/*
1729 	 * If we've got a kernel request that hasn't been malloced yet,
1730 	 * malloc it and tell the caller the data buffer is here.
1731 	 */
1732 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
1733 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
1734 		ctsio->kern_data_len = len;
1735 		ctsio->kern_total_len = len;
1736 		ctsio->kern_data_resid = 0;
1737 		ctsio->kern_rel_offset = 0;
1738 		ctsio->kern_sg_entries = 0;
1739 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
1740 		ctsio->be_move_done = ctl_config_move_done;
1741 		ctl_datamove((union ctl_io *)ctsio);
1742 
1743 		return (CTL_RETVAL_COMPLETE);
1744 	}
1745 
1746 	data = (struct scsi_extended_copy_lid4_data *)ctsio->kern_data_ptr;
1747 	lencscd = scsi_2btoul(data->cscd_list_length);
1748 	lenseg = scsi_2btoul(data->segment_list_length);
1749 	leninl = scsi_2btoul(data->inline_data_length);
1750 	if (len < sizeof(struct scsi_extended_copy_lid4_data) +
1751 	    lencscd + lenseg + leninl ||
1752 	    leninl > TPC_MAX_INLINE) {
1753 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 0,
1754 		    /*field*/ 2, /*bit_valid*/ 0, /*bit*/ 0);
1755 		goto done;
1756 	}
1757 	if (lencscd > TPC_MAX_CSCDS * sizeof(struct scsi_ec_cscd)) {
1758 		ctl_set_sense(ctsio, /*current_error*/ 1,
1759 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1760 		    /*asc*/ 0x26, /*ascq*/ 0x06, SSD_ELEM_NONE);
1761 		goto done;
1762 	}
1763 	if (lencscd + lenseg > TPC_MAX_LIST) {
1764 		ctl_set_param_len_error(ctsio);
1765 		goto done;
1766 	}
1767 
1768 	list = malloc(sizeof(struct tpc_list), M_CTL, M_WAITOK | M_ZERO);
1769 	list->service_action = cdb->service_action;
1770 	value = ctl_get_opt(&lun->be_lun->options, "insecure_tpc");
1771 	if (value != NULL && strcmp(value, "on") == 0)
1772 		list->init_port = -1;
1773 	else
1774 		list->init_port = ctsio->io_hdr.nexus.targ_port;
1775 	list->init_idx = ctl_get_resindex(&ctsio->io_hdr.nexus);
1776 	list->list_id = scsi_4btoul(data->list_identifier);
1777 	list->flags = data->flags;
1778 	list->params = ctsio->kern_data_ptr;
1779 	list->cscd = (struct scsi_ec_cscd *)&data->data[0];
1780 	ptr = &data->data[lencscd];
1781 	for (nseg = 0, off = 0; off < lenseg; nseg++) {
1782 		if (nseg >= TPC_MAX_SEGS) {
1783 			free(list, M_CTL);
1784 			ctl_set_sense(ctsio, /*current_error*/ 1,
1785 			    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1786 			    /*asc*/ 0x26, /*ascq*/ 0x08, SSD_ELEM_NONE);
1787 			goto done;
1788 		}
1789 		list->seg[nseg] = (struct scsi_ec_segment *)(ptr + off);
1790 		off += sizeof(struct scsi_ec_segment) +
1791 		    scsi_2btoul(list->seg[nseg]->descr_length);
1792 	}
1793 	list->inl = &data->data[lencscd + lenseg];
1794 	list->ncscd = lencscd / sizeof(struct scsi_ec_cscd);
1795 	list->nseg = nseg;
1796 	list->leninl = leninl;
1797 	list->ctsio = ctsio;
1798 	list->lun = lun;
1799 	mtx_lock(&lun->lun_lock);
1800 	if ((list->flags & EC_LIST_ID_USAGE_MASK) != EC_LIST_ID_USAGE_NONE) {
1801 		tlist = tpc_find_list(lun, list->list_id, list->init_idx);
1802 		if (tlist != NULL && !tlist->completed) {
1803 			mtx_unlock(&lun->lun_lock);
1804 			free(list, M_CTL);
1805 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
1806 			    /*command*/ 0, /*field*/ 0, /*bit_valid*/ 0,
1807 			    /*bit*/ 0);
1808 			goto done;
1809 		}
1810 		if (tlist != NULL) {
1811 			TAILQ_REMOVE(&lun->tpc_lists, tlist, links);
1812 			free(tlist, M_CTL);
1813 		}
1814 	}
1815 	TAILQ_INSERT_TAIL(&lun->tpc_lists, list, links);
1816 	mtx_unlock(&lun->lun_lock);
1817 
1818 	tpc_process(list);
1819 	return (CTL_RETVAL_COMPLETE);
1820 
1821 done:
1822 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
1823 		free(ctsio->kern_data_ptr, M_CTL);
1824 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
1825 	}
1826 	ctl_done((union ctl_io *)ctsio);
1827 	return (CTL_RETVAL_COMPLETE);
1828 }
1829 
1830 static void
1831 tpc_create_token(struct ctl_lun *lun, struct ctl_port *port, off_t len,
1832     struct scsi_token *token)
1833 {
1834 	static int id = 0;
1835 	struct scsi_vpd_id_descriptor *idd = NULL;
1836 	struct scsi_ec_cscd_id *cscd;
1837 	struct scsi_read_capacity_data_long *dtsd;
1838 	int targid_len;
1839 
1840 	scsi_ulto4b(ROD_TYPE_AUR, token->type);
1841 	scsi_ulto2b(0x01f8, token->length);
1842 	scsi_u64to8b(atomic_fetchadd_int(&id, 1), &token->body[0]);
1843 	if (lun->lun_devid)
1844 		idd = scsi_get_devid_desc((struct scsi_vpd_id_descriptor *)
1845 		    lun->lun_devid->data, lun->lun_devid->len,
1846 		    scsi_devid_is_lun_naa);
1847 	if (idd == NULL && lun->lun_devid)
1848 		idd = scsi_get_devid_desc((struct scsi_vpd_id_descriptor *)
1849 		    lun->lun_devid->data, lun->lun_devid->len,
1850 		    scsi_devid_is_lun_eui64);
1851 	if (idd != NULL) {
1852 		cscd = (struct scsi_ec_cscd_id *)&token->body[8];
1853 		cscd->type_code = EC_CSCD_ID;
1854 		cscd->luidt_pdt = T_DIRECT;
1855 		memcpy(&cscd->codeset, idd, 4 + idd->length);
1856 		scsi_ulto3b(lun->be_lun->blocksize, cscd->dtsp.block_length);
1857 	}
1858 	scsi_u64to8b(0, &token->body[40]); /* XXX: Should be 128bit value. */
1859 	scsi_u64to8b(len, &token->body[48]);
1860 
1861 	/* ROD token device type specific data (RC16 without first field) */
1862 	dtsd = (struct scsi_read_capacity_data_long *)&token->body[88 - 8];
1863 	scsi_ulto4b(lun->be_lun->blocksize, dtsd->length);
1864 	dtsd->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
1865 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, dtsd->lalba_lbp);
1866 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
1867 		dtsd->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
1868 
1869 	if (port->target_devid) {
1870 		targid_len = port->target_devid->len;
1871 		memcpy(&token->body[120], port->target_devid->data, targid_len);
1872 	} else
1873 		targid_len = 32;
1874 	arc4rand(&token->body[120 + targid_len], 384 - targid_len, 0);
1875 };
1876 
1877 int
1878 ctl_populate_token(struct ctl_scsiio *ctsio)
1879 {
1880 	struct scsi_populate_token *cdb;
1881 	struct scsi_populate_token_data *data;
1882 	struct ctl_softc *softc;
1883 	struct ctl_lun *lun;
1884 	struct ctl_port *port;
1885 	struct tpc_list *list, *tlist;
1886 	struct tpc_token *token;
1887 	int len, lendesc;
1888 
1889 	CTL_DEBUG_PRINT(("ctl_populate_token\n"));
1890 
1891 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
1892 	softc = lun->ctl_softc;
1893 	port = softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
1894 	cdb = (struct scsi_populate_token *)ctsio->cdb;
1895 	len = scsi_4btoul(cdb->length);
1896 
1897 	if (len < sizeof(struct scsi_populate_token_data) ||
1898 	    len > sizeof(struct scsi_populate_token_data) +
1899 	     TPC_MAX_SEGS * sizeof(struct scsi_range_desc)) {
1900 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
1901 		    /*field*/ 9, /*bit_valid*/ 0, /*bit*/ 0);
1902 		goto done;
1903 	}
1904 
1905 	/*
1906 	 * If we've got a kernel request that hasn't been malloced yet,
1907 	 * malloc it and tell the caller the data buffer is here.
1908 	 */
1909 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
1910 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
1911 		ctsio->kern_data_len = len;
1912 		ctsio->kern_total_len = len;
1913 		ctsio->kern_data_resid = 0;
1914 		ctsio->kern_rel_offset = 0;
1915 		ctsio->kern_sg_entries = 0;
1916 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
1917 		ctsio->be_move_done = ctl_config_move_done;
1918 		ctl_datamove((union ctl_io *)ctsio);
1919 
1920 		return (CTL_RETVAL_COMPLETE);
1921 	}
1922 
1923 	data = (struct scsi_populate_token_data *)ctsio->kern_data_ptr;
1924 	lendesc = scsi_2btoul(data->range_descriptor_length);
1925 	if (len < sizeof(struct scsi_populate_token_data) + lendesc) {
1926 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 0,
1927 		    /*field*/ 2, /*bit_valid*/ 0, /*bit*/ 0);
1928 		goto done;
1929 	}
1930 /*
1931 	printf("PT(list=%u) flags=%x to=%d rt=%x len=%x\n",
1932 	    scsi_4btoul(cdb->list_identifier),
1933 	    data->flags, scsi_4btoul(data->inactivity_timeout),
1934 	    scsi_4btoul(data->rod_type),
1935 	    scsi_2btoul(data->range_descriptor_length));
1936 */
1937 	if ((data->flags & EC_PT_RTV) &&
1938 	    scsi_4btoul(data->rod_type) != ROD_TYPE_AUR) {
1939 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 0,
1940 		    /*field*/ 8, /*bit_valid*/ 0, /*bit*/ 0);
1941 		goto done;
1942 	}
1943 
1944 	list = malloc(sizeof(struct tpc_list), M_CTL, M_WAITOK | M_ZERO);
1945 	list->service_action = cdb->service_action;
1946 	list->init_port = ctsio->io_hdr.nexus.targ_port;
1947 	list->init_idx = ctl_get_resindex(&ctsio->io_hdr.nexus);
1948 	list->list_id = scsi_4btoul(cdb->list_identifier);
1949 	list->flags = data->flags;
1950 	list->ctsio = ctsio;
1951 	list->lun = lun;
1952 	mtx_lock(&lun->lun_lock);
1953 	tlist = tpc_find_list(lun, list->list_id, list->init_idx);
1954 	if (tlist != NULL && !tlist->completed) {
1955 		mtx_unlock(&lun->lun_lock);
1956 		free(list, M_CTL);
1957 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
1958 		    /*command*/ 0, /*field*/ 0, /*bit_valid*/ 0,
1959 		    /*bit*/ 0);
1960 		goto done;
1961 	}
1962 	if (tlist != NULL) {
1963 		TAILQ_REMOVE(&lun->tpc_lists, tlist, links);
1964 		free(tlist, M_CTL);
1965 	}
1966 	TAILQ_INSERT_TAIL(&lun->tpc_lists, list, links);
1967 	mtx_unlock(&lun->lun_lock);
1968 
1969 	token = malloc(sizeof(*token), M_CTL, M_WAITOK | M_ZERO);
1970 	token->lun = lun->lun;
1971 	token->blocksize = lun->be_lun->blocksize;
1972 	token->params = ctsio->kern_data_ptr;
1973 	token->range = &data->desc[0];
1974 	token->nrange = scsi_2btoul(data->range_descriptor_length) /
1975 	    sizeof(struct scsi_range_desc);
1976 	list->cursectors = tpc_ranges_length(token->range, token->nrange);
1977 	list->curbytes = (off_t)list->cursectors * lun->be_lun->blocksize;
1978 	tpc_create_token(lun, port, list->curbytes,
1979 	    (struct scsi_token *)token->token);
1980 	token->active = 0;
1981 	token->last_active = time_uptime;
1982 	token->timeout = scsi_4btoul(data->inactivity_timeout);
1983 	if (token->timeout == 0)
1984 		token->timeout = TPC_DFL_TOKEN_TIMEOUT;
1985 	else if (token->timeout < TPC_MIN_TOKEN_TIMEOUT)
1986 		token->timeout = TPC_MIN_TOKEN_TIMEOUT;
1987 	else if (token->timeout > TPC_MAX_TOKEN_TIMEOUT) {
1988 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
1989 		    /*command*/ 0, /*field*/ 4, /*bit_valid*/ 0,
1990 		    /*bit*/ 0);
1991 	}
1992 	memcpy(list->res_token, token->token, sizeof(list->res_token));
1993 	list->res_token_valid = 1;
1994 	list->curseg = 0;
1995 	list->completed = 1;
1996 	list->last_active = time_uptime;
1997 	mtx_lock(&softc->tpc_lock);
1998 	TAILQ_INSERT_TAIL(&softc->tpc_tokens, token, links);
1999 	mtx_unlock(&softc->tpc_lock);
2000 	ctl_set_success(ctsio);
2001 	ctl_done((union ctl_io *)ctsio);
2002 	return (CTL_RETVAL_COMPLETE);
2003 
2004 done:
2005 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
2006 		free(ctsio->kern_data_ptr, M_CTL);
2007 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
2008 	}
2009 	ctl_done((union ctl_io *)ctsio);
2010 	return (CTL_RETVAL_COMPLETE);
2011 }
2012 
2013 int
2014 ctl_write_using_token(struct ctl_scsiio *ctsio)
2015 {
2016 	struct scsi_write_using_token *cdb;
2017 	struct scsi_write_using_token_data *data;
2018 	struct ctl_softc *softc;
2019 	struct ctl_lun *lun;
2020 	struct tpc_list *list, *tlist;
2021 	struct tpc_token *token;
2022 	int len, lendesc;
2023 
2024 	CTL_DEBUG_PRINT(("ctl_write_using_token\n"));
2025 
2026 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
2027 	softc = lun->ctl_softc;
2028 	cdb = (struct scsi_write_using_token *)ctsio->cdb;
2029 	len = scsi_4btoul(cdb->length);
2030 
2031 	if (len < sizeof(struct scsi_populate_token_data) ||
2032 	    len > sizeof(struct scsi_populate_token_data) +
2033 	     TPC_MAX_SEGS * sizeof(struct scsi_range_desc)) {
2034 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
2035 		    /*field*/ 9, /*bit_valid*/ 0, /*bit*/ 0);
2036 		goto done;
2037 	}
2038 
2039 	/*
2040 	 * If we've got a kernel request that hasn't been malloced yet,
2041 	 * malloc it and tell the caller the data buffer is here.
2042 	 */
2043 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
2044 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
2045 		ctsio->kern_data_len = len;
2046 		ctsio->kern_total_len = len;
2047 		ctsio->kern_data_resid = 0;
2048 		ctsio->kern_rel_offset = 0;
2049 		ctsio->kern_sg_entries = 0;
2050 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
2051 		ctsio->be_move_done = ctl_config_move_done;
2052 		ctl_datamove((union ctl_io *)ctsio);
2053 
2054 		return (CTL_RETVAL_COMPLETE);
2055 	}
2056 
2057 	data = (struct scsi_write_using_token_data *)ctsio->kern_data_ptr;
2058 	lendesc = scsi_2btoul(data->range_descriptor_length);
2059 	if (len < sizeof(struct scsi_populate_token_data) + lendesc) {
2060 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 0,
2061 		    /*field*/ 2, /*bit_valid*/ 0, /*bit*/ 0);
2062 		goto done;
2063 	}
2064 /*
2065 	printf("WUT(list=%u) flags=%x off=%ju len=%x\n",
2066 	    scsi_4btoul(cdb->list_identifier),
2067 	    data->flags, scsi_8btou64(data->offset_into_rod),
2068 	    scsi_2btoul(data->range_descriptor_length));
2069 */
2070 	list = malloc(sizeof(struct tpc_list), M_CTL, M_WAITOK | M_ZERO);
2071 	list->service_action = cdb->service_action;
2072 	list->init_port = ctsio->io_hdr.nexus.targ_port;
2073 	list->init_idx = ctl_get_resindex(&ctsio->io_hdr.nexus);
2074 	list->list_id = scsi_4btoul(cdb->list_identifier);
2075 	list->flags = data->flags;
2076 	list->params = ctsio->kern_data_ptr;
2077 	list->range = &data->desc[0];
2078 	list->nrange = scsi_2btoul(data->range_descriptor_length) /
2079 	    sizeof(struct scsi_range_desc);
2080 	list->offset_into_rod = scsi_8btou64(data->offset_into_rod);
2081 	list->ctsio = ctsio;
2082 	list->lun = lun;
2083 	mtx_lock(&lun->lun_lock);
2084 	tlist = tpc_find_list(lun, list->list_id, list->init_idx);
2085 	if (tlist != NULL && !tlist->completed) {
2086 		mtx_unlock(&lun->lun_lock);
2087 		free(list, M_CTL);
2088 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
2089 		    /*command*/ 0, /*field*/ 0, /*bit_valid*/ 0,
2090 		    /*bit*/ 0);
2091 		goto done;
2092 	}
2093 	if (tlist != NULL) {
2094 		TAILQ_REMOVE(&lun->tpc_lists, tlist, links);
2095 		free(tlist, M_CTL);
2096 	}
2097 	TAILQ_INSERT_TAIL(&lun->tpc_lists, list, links);
2098 	mtx_unlock(&lun->lun_lock);
2099 
2100 	/* Block device zero ROD token -> no token. */
2101 	if (scsi_4btoul(data->rod_token) == ROD_TYPE_BLOCK_ZERO) {
2102 		tpc_process(list);
2103 		return (CTL_RETVAL_COMPLETE);
2104 	}
2105 
2106 	mtx_lock(&softc->tpc_lock);
2107 	TAILQ_FOREACH(token, &softc->tpc_tokens, links) {
2108 		if (memcmp(token->token, data->rod_token,
2109 		    sizeof(data->rod_token)) == 0)
2110 			break;
2111 	}
2112 	if (token != NULL) {
2113 		token->active++;
2114 		list->token = token;
2115 		if (data->flags & EC_WUT_DEL_TKN)
2116 			token->timeout = 0;
2117 	}
2118 	mtx_unlock(&softc->tpc_lock);
2119 	if (token == NULL) {
2120 		mtx_lock(&lun->lun_lock);
2121 		TAILQ_REMOVE(&lun->tpc_lists, list, links);
2122 		mtx_unlock(&lun->lun_lock);
2123 		free(list, M_CTL);
2124 		ctl_set_sense(ctsio, /*current_error*/ 1,
2125 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
2126 		    /*asc*/ 0x23, /*ascq*/ 0x04, SSD_ELEM_NONE);
2127 		goto done;
2128 	}
2129 
2130 	tpc_process(list);
2131 	return (CTL_RETVAL_COMPLETE);
2132 
2133 done:
2134 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
2135 		free(ctsio->kern_data_ptr, M_CTL);
2136 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
2137 	}
2138 	ctl_done((union ctl_io *)ctsio);
2139 	return (CTL_RETVAL_COMPLETE);
2140 }
2141 
2142 int
2143 ctl_receive_rod_token_information(struct ctl_scsiio *ctsio)
2144 {
2145 	struct ctl_lun *lun;
2146 	struct scsi_receive_rod_token_information *cdb;
2147 	struct scsi_receive_copy_status_lid4_data *data;
2148 	struct tpc_list *list;
2149 	struct tpc_list list_copy;
2150 	uint8_t *ptr;
2151 	int retval;
2152 	int alloc_len, total_len, token_len;
2153 	uint32_t list_id;
2154 
2155 	CTL_DEBUG_PRINT(("ctl_receive_rod_token_information\n"));
2156 
2157 	cdb = (struct scsi_receive_rod_token_information *)ctsio->cdb;
2158 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
2159 
2160 	retval = CTL_RETVAL_COMPLETE;
2161 
2162 	list_id = scsi_4btoul(cdb->list_identifier);
2163 	mtx_lock(&lun->lun_lock);
2164 	list = tpc_find_list(lun, list_id,
2165 	    ctl_get_resindex(&ctsio->io_hdr.nexus));
2166 	if (list == NULL) {
2167 		mtx_unlock(&lun->lun_lock);
2168 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
2169 		    /*command*/ 1, /*field*/ 2, /*bit_valid*/ 0,
2170 		    /*bit*/ 0);
2171 		ctl_done((union ctl_io *)ctsio);
2172 		return (retval);
2173 	}
2174 	list_copy = *list;
2175 	if (list->completed) {
2176 		TAILQ_REMOVE(&lun->tpc_lists, list, links);
2177 		free(list, M_CTL);
2178 	}
2179 	mtx_unlock(&lun->lun_lock);
2180 
2181 	token_len = list_copy.res_token_valid ? 2 + sizeof(list_copy.res_token) : 0;
2182 	total_len = sizeof(*data) + list_copy.sense_len + 4 + token_len;
2183 	alloc_len = scsi_4btoul(cdb->length);
2184 
2185 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
2186 
2187 	ctsio->kern_sg_entries = 0;
2188 
2189 	if (total_len < alloc_len) {
2190 		ctsio->residual = alloc_len - total_len;
2191 		ctsio->kern_data_len = total_len;
2192 		ctsio->kern_total_len = total_len;
2193 	} else {
2194 		ctsio->residual = 0;
2195 		ctsio->kern_data_len = alloc_len;
2196 		ctsio->kern_total_len = alloc_len;
2197 	}
2198 	ctsio->kern_data_resid = 0;
2199 	ctsio->kern_rel_offset = 0;
2200 
2201 	data = (struct scsi_receive_copy_status_lid4_data *)ctsio->kern_data_ptr;
2202 	scsi_ulto4b(sizeof(*data) - 4 + list_copy.sense_len +
2203 	    4 + token_len, data->available_data);
2204 	data->response_to_service_action = list_copy.service_action;
2205 	if (list_copy.completed) {
2206 		if (list_copy.error)
2207 			data->copy_command_status = RCS_CCS_ERROR;
2208 		else if (list_copy.abort)
2209 			data->copy_command_status = RCS_CCS_ABORTED;
2210 		else
2211 			data->copy_command_status = RCS_CCS_COMPLETED;
2212 	} else
2213 		data->copy_command_status = RCS_CCS_INPROG_FG;
2214 	scsi_ulto2b(list_copy.curops, data->operation_counter);
2215 	scsi_ulto4b(UINT32_MAX, data->estimated_status_update_delay);
2216 	data->transfer_count_units = RCS_TC_LBAS;
2217 	scsi_u64to8b(list_copy.cursectors, data->transfer_count);
2218 	scsi_ulto2b(list_copy.curseg, data->segments_processed);
2219 	data->length_of_the_sense_data_field = list_copy.sense_len;
2220 	data->sense_data_length = list_copy.sense_len;
2221 	memcpy(data->sense_data, &list_copy.sense_data, list_copy.sense_len);
2222 
2223 	ptr = &data->sense_data[data->length_of_the_sense_data_field];
2224 	scsi_ulto4b(token_len, &ptr[0]);
2225 	if (list_copy.res_token_valid) {
2226 		scsi_ulto2b(0, &ptr[4]);
2227 		memcpy(&ptr[6], list_copy.res_token, sizeof(list_copy.res_token));
2228 	}
2229 /*
2230 	printf("RRTI(list=%u) valid=%d\n",
2231 	    scsi_4btoul(cdb->list_identifier), list_copy.res_token_valid);
2232 */
2233 	ctl_set_success(ctsio);
2234 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
2235 	ctsio->be_move_done = ctl_config_move_done;
2236 	ctl_datamove((union ctl_io *)ctsio);
2237 	return (retval);
2238 }
2239 
2240 int
2241 ctl_report_all_rod_tokens(struct ctl_scsiio *ctsio)
2242 {
2243 	struct ctl_softc *softc;
2244 	struct ctl_lun *lun;
2245 	struct scsi_report_all_rod_tokens *cdb;
2246 	struct scsi_report_all_rod_tokens_data *data;
2247 	struct tpc_token *token;
2248 	int retval;
2249 	int alloc_len, total_len, tokens, i;
2250 
2251 	CTL_DEBUG_PRINT(("ctl_receive_rod_token_information\n"));
2252 
2253 	cdb = (struct scsi_report_all_rod_tokens *)ctsio->cdb;
2254 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
2255 	softc = lun->ctl_softc;
2256 
2257 	retval = CTL_RETVAL_COMPLETE;
2258 
2259 	tokens = 0;
2260 	mtx_lock(&softc->tpc_lock);
2261 	TAILQ_FOREACH(token, &softc->tpc_tokens, links)
2262 		tokens++;
2263 	mtx_unlock(&softc->tpc_lock);
2264 	if (tokens > 512)
2265 		tokens = 512;
2266 
2267 	total_len = sizeof(*data) + tokens * 96;
2268 	alloc_len = scsi_4btoul(cdb->length);
2269 
2270 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
2271 
2272 	ctsio->kern_sg_entries = 0;
2273 
2274 	if (total_len < alloc_len) {
2275 		ctsio->residual = alloc_len - total_len;
2276 		ctsio->kern_data_len = total_len;
2277 		ctsio->kern_total_len = total_len;
2278 	} else {
2279 		ctsio->residual = 0;
2280 		ctsio->kern_data_len = alloc_len;
2281 		ctsio->kern_total_len = alloc_len;
2282 	}
2283 	ctsio->kern_data_resid = 0;
2284 	ctsio->kern_rel_offset = 0;
2285 
2286 	data = (struct scsi_report_all_rod_tokens_data *)ctsio->kern_data_ptr;
2287 	i = 0;
2288 	mtx_lock(&softc->tpc_lock);
2289 	TAILQ_FOREACH(token, &softc->tpc_tokens, links) {
2290 		if (i >= tokens)
2291 			break;
2292 		memcpy(&data->rod_management_token_list[i * 96],
2293 		    token->token, 96);
2294 		i++;
2295 	}
2296 	mtx_unlock(&softc->tpc_lock);
2297 	scsi_ulto4b(sizeof(*data) - 4 + i * 96, data->available_data);
2298 /*
2299 	printf("RART tokens=%d\n", i);
2300 */
2301 	ctl_set_success(ctsio);
2302 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
2303 	ctsio->be_move_done = ctl_config_move_done;
2304 	ctl_datamove((union ctl_io *)ctsio);
2305 	return (retval);
2306 }
2307 
2308