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