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