xref: /titanic_52/usr/src/uts/common/io/sata/impl/sata.c (revision 55553f719b521a0bb4deab6efc944cd30c1a56aa)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * SATA Framework
31  * Generic SATA Host Adapter Implementation
32  */
33 
34 #include <sys/conf.h>
35 #include <sys/file.h>
36 #include <sys/ddi.h>
37 #include <sys/sunddi.h>
38 #include <sys/modctl.h>
39 #include <sys/cmn_err.h>
40 #include <sys/errno.h>
41 #include <sys/thread.h>
42 #include <sys/kstat.h>
43 #include <sys/note.h>
44 #include <sys/sysevent.h>
45 #include <sys/sysevent/eventdefs.h>
46 #include <sys/sysevent/dr.h>
47 #include <sys/taskq.h>
48 
49 #include <sys/sata/impl/sata.h>
50 #include <sys/sata/sata_hba.h>
51 #include <sys/sata/sata_defs.h>
52 #include <sys/sata/sata_cfgadm.h>
53 
54 /* Debug flags - defined in sata.h */
55 int	sata_debug_flags = 0;
56 int	sata_msg = 0;
57 
58 /*
59  * Flags enabling selected SATA HBA framework functionality
60  */
61 #define	SATA_ENABLE_QUEUING		1
62 #define	SATA_ENABLE_NCQ			2
63 #define	SATA_ENABLE_PROCESS_EVENTS	4
64 int sata_func_enable =
65 	SATA_ENABLE_PROCESS_EVENTS | SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ;
66 
67 /*
68  * Global variable setting default maximum queue depth (NCQ or TCQ)
69  * Note:minimum queue depth is 1
70  */
71 int sata_max_queue_depth = SATA_MAX_QUEUE_DEPTH; /* max NCQ/TCQ queue depth */
72 
73 /*
74  * Currently used default NCQ/TCQ queue depth. It is set-up during the driver
75  * initialization, using value from sata_max_queue_depth
76  * It is adjusted to minimum supported by the controller and by the device,
77  * if queueing is enabled.
78  */
79 static	int sata_current_max_qdepth;
80 
81 /*
82  * Global variable determining the default behavior after device hotpluggin.
83  * If non-zero, the hotplugged device is onlined (if possible) without explicit
84  * IOCTL request (AP_CONFIGURE).
85  * If zero, hotplugged device is identified, but not onlined.
86  * Enabling (AP_CONNECT) device port with an attached device does not result
87  * in device onlining regardless of the flag setting
88  */
89 int sata_auto_online = 0;
90 
91 #ifdef SATA_DEBUG
92 
93 #define	SATA_LOG_D(args)	sata_log args
94 uint64_t mbuf_count = 0;
95 uint64_t mbuffail_count = 0;
96 
97 sata_atapi_cmd_t sata_atapi_trace[64];
98 uint32_t sata_atapi_trace_index = 0;
99 int sata_atapi_trace_save = 1;
100 static	void sata_save_atapi_trace(sata_pkt_txlate_t *, int);
101 #define	SATAATAPITRACE(spx, count)	if (sata_atapi_trace_save) \
102     sata_save_atapi_trace(spx, count);
103 
104 #else
105 #define	SATA_LOG_D(arg)
106 #define	SATAATAPITRACE(spx, count)
107 #endif
108 
109 #if 0
110 static void
111 sata_test_atapi_packet_command(sata_hba_inst_t *, int);
112 #endif
113 #define	LEGACY_HWID_LEN	64	/* Model (40) + Serial (20) + pad */
114 
115 
116 /*
117  * SATA cb_ops functions
118  */
119 static 	int sata_hba_open(dev_t *, int, int, cred_t *);
120 static 	int sata_hba_close(dev_t, int, int, cred_t *);
121 static 	int sata_hba_ioctl(dev_t, int, intptr_t, int, cred_t *,	int *);
122 
123 /*
124  * SCSA required entry points
125  */
126 static	int sata_scsi_tgt_init(dev_info_t *, dev_info_t *,
127     scsi_hba_tran_t *, struct scsi_device *);
128 static	int sata_scsi_tgt_probe(struct scsi_device *,
129     int (*callback)(void));
130 static void sata_scsi_tgt_free(dev_info_t *, dev_info_t *,
131     scsi_hba_tran_t *, struct scsi_device *);
132 static 	int sata_scsi_start(struct scsi_address *, struct scsi_pkt *);
133 static 	int sata_scsi_abort(struct scsi_address *, struct scsi_pkt *);
134 static 	int sata_scsi_reset(struct scsi_address *, int);
135 static 	int sata_scsi_getcap(struct scsi_address *, char *, int);
136 static 	int sata_scsi_setcap(struct scsi_address *, char *, int, int);
137 static 	struct scsi_pkt *sata_scsi_init_pkt(struct scsi_address *,
138     struct scsi_pkt *, struct buf *, int, int, int, int, int (*)(caddr_t),
139     caddr_t);
140 static 	void sata_scsi_destroy_pkt(struct scsi_address *, struct scsi_pkt *);
141 static 	void sata_scsi_dmafree(struct scsi_address *, struct scsi_pkt *);
142 static 	void sata_scsi_sync_pkt(struct scsi_address *, struct scsi_pkt *);
143 
144 /*
145  * SATA HBA interface functions are defined in sata_hba.h header file
146  */
147 
148 /* Event processing functions */
149 static	void sata_event_daemon(void *);
150 static	void sata_event_thread_control(int);
151 static	void sata_process_controller_events(sata_hba_inst_t *sata_hba_inst);
152 static	void sata_process_device_reset(sata_hba_inst_t *, sata_address_t *);
153 static	void sata_process_port_failed_event(sata_hba_inst_t *,
154     sata_address_t *);
155 static	void sata_process_port_link_events(sata_hba_inst_t *,
156     sata_address_t *);
157 static	void sata_process_device_detached(sata_hba_inst_t *, sata_address_t *);
158 static	void sata_process_device_attached(sata_hba_inst_t *, sata_address_t *);
159 static	void sata_process_port_pwr_change(sata_hba_inst_t *, sata_address_t *);
160 static	void sata_process_cntrl_pwr_level_change(sata_hba_inst_t *);
161 static	void sata_process_target_node_cleanup(sata_hba_inst_t *,
162     sata_address_t *);
163 static	void sata_process_device_autoonline(sata_hba_inst_t *,
164     sata_address_t *saddr);
165 
166 /*
167  * Local translation functions
168  */
169 static	int sata_txlt_inquiry(sata_pkt_txlate_t *);
170 static	int sata_txlt_test_unit_ready(sata_pkt_txlate_t *);
171 static	int sata_txlt_start_stop_unit(sata_pkt_txlate_t *);
172 static	int sata_txlt_read_capacity(sata_pkt_txlate_t *);
173 static	int sata_txlt_request_sense(sata_pkt_txlate_t *);
174 static 	int sata_txlt_read(sata_pkt_txlate_t *);
175 static 	int sata_txlt_write(sata_pkt_txlate_t *);
176 static 	int sata_txlt_log_sense(sata_pkt_txlate_t *);
177 static 	int sata_txlt_log_select(sata_pkt_txlate_t *);
178 static 	int sata_txlt_mode_sense(sata_pkt_txlate_t *);
179 static 	int sata_txlt_mode_select(sata_pkt_txlate_t *);
180 static 	int sata_txlt_synchronize_cache(sata_pkt_txlate_t *);
181 static 	int sata_txlt_write_buffer(sata_pkt_txlate_t *);
182 static 	int sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *);
183 
184 static 	int sata_hba_start(sata_pkt_txlate_t *, int *);
185 static	int sata_txlt_invalid_command(sata_pkt_txlate_t *);
186 static	int sata_txlt_lba_out_of_range(sata_pkt_txlate_t *);
187 static 	void sata_txlt_rw_completion(sata_pkt_t *);
188 static 	void sata_txlt_nodata_cmd_completion(sata_pkt_t *);
189 static 	void sata_txlt_download_mcode_cmd_completion(sata_pkt_t *);
190 static 	int sata_emul_rw_completion(sata_pkt_txlate_t *);
191 static 	struct scsi_extended_sense *sata_immediate_error_response(
192     sata_pkt_txlate_t *, int);
193 static	struct scsi_extended_sense *sata_arq_sense(sata_pkt_txlate_t *);
194 
195 static 	int sata_txlt_atapi(sata_pkt_txlate_t *);
196 static 	void sata_txlt_atapi_completion(sata_pkt_t *);
197 
198 /*
199  * Local functions for ioctl
200  */
201 static	int32_t sata_get_port_num(sata_hba_inst_t *,  struct devctl_iocdata *);
202 static	void sata_cfgadm_state(sata_hba_inst_t *, int32_t,
203     devctl_ap_state_t *);
204 static	dev_info_t *sata_get_target_dip(dev_info_t *, int32_t);
205 static	dev_info_t *sata_get_scsi_target_dip(dev_info_t *, sata_address_t *);
206 static	dev_info_t *sata_devt_to_devinfo(dev_t);
207 static	int sata_ioctl_connect(sata_hba_inst_t *, sata_device_t *);
208 static	int sata_ioctl_disconnect(sata_hba_inst_t *, sata_device_t *);
209 static	int sata_ioctl_configure(sata_hba_inst_t *, sata_device_t *);
210 static	int sata_ioctl_unconfigure(sata_hba_inst_t *, sata_device_t *);
211 static	int sata_ioctl_activate(sata_hba_inst_t *, sata_device_t *);
212 static	int sata_ioctl_deactivate(sata_hba_inst_t *, sata_device_t *);
213 static	int sata_ioctl_reset_port(sata_hba_inst_t *, sata_device_t *);
214 static	int sata_ioctl_reset_device(sata_hba_inst_t *, sata_device_t *);
215 static	int sata_ioctl_reset_all(sata_hba_inst_t *);
216 static	int sata_ioctl_port_self_test(sata_hba_inst_t *, sata_device_t *);
217 static	int sata_ioctl_get_device_path(sata_hba_inst_t *, sata_device_t *,
218     sata_ioctl_data_t *, int mode);
219 static	int sata_ioctl_get_ap_type(sata_hba_inst_t *, sata_device_t *,
220     sata_ioctl_data_t *, int mode);
221 static	int sata_ioctl_get_model_info(sata_hba_inst_t *, sata_device_t *,
222     sata_ioctl_data_t *, int mode);
223 static	int sata_ioctl_get_revfirmware_info(sata_hba_inst_t *, sata_device_t *,
224     sata_ioctl_data_t *, int mode);
225 static	int sata_ioctl_get_serialnumber_info(sata_hba_inst_t *,
226     sata_device_t *, sata_ioctl_data_t *, int mode);
227 
228 /*
229  * Local functions
230  */
231 static 	void sata_remove_hba_instance(dev_info_t *);
232 static 	int sata_validate_sata_hba_tran(dev_info_t *, sata_hba_tran_t *);
233 static 	void sata_probe_ports(sata_hba_inst_t *);
234 static 	int sata_reprobe_port(sata_hba_inst_t *, sata_device_t *, int);
235 static 	int sata_add_device(dev_info_t *, sata_hba_inst_t *, int cport,
236     int pmport);
237 static 	dev_info_t *sata_create_target_node(dev_info_t *, sata_hba_inst_t *,
238     sata_address_t *);
239 static 	int sata_validate_scsi_address(sata_hba_inst_t *,
240     struct scsi_address *, sata_device_t *);
241 static 	int sata_validate_sata_address(sata_hba_inst_t *, int, int, int);
242 static	sata_pkt_t *sata_pkt_alloc(sata_pkt_txlate_t *, int (*)(caddr_t));
243 static	void sata_pkt_free(sata_pkt_txlate_t *);
244 static	int sata_dma_buf_setup(sata_pkt_txlate_t *, int, int (*)(caddr_t),
245     caddr_t, ddi_dma_attr_t *);
246 static	int sata_probe_device(sata_hba_inst_t *, sata_device_t *);
247 static	sata_drive_info_t *sata_get_device_info(sata_hba_inst_t *,
248     sata_device_t *);
249 static 	int sata_identify_device(sata_hba_inst_t *, sata_drive_info_t *);
250 static	void sata_reidentify_device(sata_pkt_txlate_t *);
251 static	struct buf *sata_alloc_local_buffer(sata_pkt_txlate_t *, int);
252 static 	void sata_free_local_buffer(sata_pkt_txlate_t *);
253 static 	uint64_t sata_check_capacity(sata_drive_info_t *);
254 void 	sata_adjust_dma_attr(sata_drive_info_t *, ddi_dma_attr_t *,
255     ddi_dma_attr_t *);
256 static 	int sata_fetch_device_identify_data(sata_hba_inst_t *,
257     sata_drive_info_t *);
258 static	void sata_update_port_info(sata_hba_inst_t *, sata_device_t *);
259 static	void sata_update_port_scr(sata_port_scr_t *, sata_device_t *);
260 static	int sata_set_dma_mode(sata_hba_inst_t *, sata_drive_info_t *);
261 static	int sata_set_cache_mode(sata_hba_inst_t *, sata_drive_info_t *, int);
262 static	int sata_set_rmsn(sata_hba_inst_t *, sata_drive_info_t *, int);
263 static	int sata_set_drive_features(sata_hba_inst_t *,
264     sata_drive_info_t *, int flag);
265 static	void sata_init_write_cache_mode(sata_drive_info_t *sdinfo);
266 static	int sata_initialize_device(sata_hba_inst_t *, sata_drive_info_t *);
267 static	void sata_identdev_to_inquiry(sata_hba_inst_t *, sata_drive_info_t *,
268     uint8_t *);
269 static	int sata_get_atapi_inquiry_data(sata_hba_inst_t *, sata_address_t *,
270     struct scsi_inquiry *);
271 static	int sata_build_msense_page_1(sata_drive_info_t *, int, uint8_t *);
272 static	int sata_build_msense_page_8(sata_drive_info_t *, int, uint8_t *);
273 static	int sata_build_msense_page_1a(sata_drive_info_t *, int, uint8_t *);
274 static	int sata_build_msense_page_1c(sata_drive_info_t *, int, uint8_t *);
275 static	int sata_mode_select_page_8(sata_pkt_txlate_t *,
276     struct mode_cache_scsi3 *, int, int *, int *, int *);
277 static	int sata_mode_select_page_1c(sata_pkt_txlate_t *,
278     struct mode_info_excpt_page *, int, int *, int *, int *);
279 static	int sata_build_msense_page_30(sata_drive_info_t *, int, uint8_t *);
280 static	int sata_mode_select_page_30(sata_pkt_txlate_t *,
281     struct mode_acoustic_management *, int, int *, int *, int *);
282 
283 static	int sata_build_lsense_page_0(sata_drive_info_t *, uint8_t *);
284 static	int sata_build_lsense_page_10(sata_drive_info_t *, uint8_t *,
285     sata_hba_inst_t *);
286 static	int sata_build_lsense_page_2f(sata_drive_info_t *, uint8_t *,
287     sata_hba_inst_t *);
288 static	int sata_build_lsense_page_30(sata_drive_info_t *, uint8_t *,
289     sata_hba_inst_t *);
290 static	void sata_save_drive_settings(sata_drive_info_t *);
291 static	void sata_show_drive_info(sata_hba_inst_t *, sata_drive_info_t *);
292 static	void sata_log(sata_hba_inst_t *, uint_t, char *fmt, ...);
293 static	int sata_fetch_smart_return_status(sata_hba_inst_t *,
294     sata_drive_info_t *);
295 static	int sata_fetch_smart_data(sata_hba_inst_t *, sata_drive_info_t *,
296     struct smart_data *);
297 static	int sata_smart_selftest_log(sata_hba_inst_t *,
298     sata_drive_info_t *,
299     struct smart_selftest_log *);
300 static	int sata_ext_smart_selftest_read_log(sata_hba_inst_t *,
301     sata_drive_info_t *, struct smart_ext_selftest_log *, uint16_t);
302 static	int sata_smart_read_log(sata_hba_inst_t *, sata_drive_info_t *,
303     uint8_t *, uint8_t, uint8_t);
304 static	int sata_read_log_ext_directory(sata_hba_inst_t *, sata_drive_info_t *,
305     struct read_log_ext_directory *);
306 static	void sata_gen_sysevent(sata_hba_inst_t *, sata_address_t *, int);
307 static	void sata_xlate_errors(sata_pkt_txlate_t *);
308 static	void sata_decode_device_error(sata_pkt_txlate_t *,
309     struct scsi_extended_sense *);
310 static	void sata_set_device_removed(dev_info_t *);
311 static	boolean_t sata_check_device_removed(dev_info_t *);
312 static	void sata_set_target_node_cleanup(sata_hba_inst_t *, sata_address_t *);
313 static	int sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *,
314     sata_drive_info_t *);
315 static	int sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *,
316     sata_drive_info_t *);
317 static	void sata_atapi_packet_cmd_setup(sata_cmd_t *, sata_drive_info_t *);
318 static	void sata_fixed_sense_data_preset(struct scsi_extended_sense *);
319 static  void sata_target_devid_register(dev_info_t *, sata_drive_info_t *);
320 static  int sata_check_modser(char *, int);
321 
322 
323 
324 /*
325  * SATA Framework will ignore SATA HBA driver cb_ops structure and
326  * register following one with SCSA framework.
327  * Open & close are provided, so scsi framework will not use its own
328  */
329 static struct cb_ops sata_cb_ops = {
330 	sata_hba_open,			/* open */
331 	sata_hba_close,			/* close */
332 	nodev,				/* strategy */
333 	nodev,				/* print */
334 	nodev,				/* dump */
335 	nodev,				/* read */
336 	nodev,				/* write */
337 	sata_hba_ioctl,			/* ioctl */
338 	nodev,				/* devmap */
339 	nodev,				/* mmap */
340 	nodev,				/* segmap */
341 	nochpoll,			/* chpoll */
342 	ddi_prop_op,			/* cb_prop_op */
343 	0,				/* streamtab */
344 	D_NEW | D_MP,			/* cb_flag */
345 	CB_REV,				/* rev */
346 	nodev,				/* aread */
347 	nodev				/* awrite */
348 };
349 
350 
351 extern struct mod_ops mod_miscops;
352 extern uchar_t	scsi_cdb_size[];
353 
354 static struct modlmisc modlmisc = {
355 	&mod_miscops,			/* Type of module */
356 	"SATA Module v%I%"		/* module name */
357 };
358 
359 
360 static struct modlinkage modlinkage = {
361 	MODREV_1,
362 	(void *)&modlmisc,
363 	NULL
364 };
365 
366 /*
367  * Default sata pkt timeout. Used when a target driver scsi_pkt time is zero,
368  * i.e. when scsi_pkt has not timeout specified.
369  */
370 static int sata_default_pkt_time = 60;	/* 60 seconds */
371 
372 /*
373  * Intermediate buffer device access attributes - they are required,
374  * but not necessarily used.
375  */
376 static ddi_device_acc_attr_t sata_acc_attr = {
377 	DDI_DEVICE_ATTR_V0,
378 	DDI_STRUCTURE_LE_ACC,
379 	DDI_STRICTORDER_ACC
380 };
381 
382 
383 /*
384  * Mutexes protecting structures in multithreaded operations.
385  * Because events are relatively rare, a single global mutex protecting
386  * data structures should be sufficient. To increase performance, add
387  * separate mutex per each sata port and use global mutex only to protect
388  * common data structures.
389  */
390 static	kmutex_t sata_mutex;		/* protects sata_hba_list */
391 static	kmutex_t sata_log_mutex;	/* protects log */
392 
393 static 	char sata_log_buf[256];
394 
395 /* Default write cache setting for SATA hard disks */
396 int	sata_write_cache = 1;		/* enabled */
397 
398 /* Default write cache setting for SATA ATAPI CD/DVD */
399 int 	sata_atapicdvd_write_cache = 1; /* enabled */
400 
401 /*
402  * Linked list of HBA instances
403  */
404 static 	sata_hba_inst_t *sata_hba_list = NULL;
405 static 	sata_hba_inst_t *sata_hba_list_tail = NULL;
406 /*
407  * Pointer to per-instance SATA HBA soft structure is stored in sata_hba_tran
408  * structure and in sata soft state.
409  */
410 
411 /*
412  * Event daemon related variables
413  */
414 static 	kmutex_t sata_event_mutex;
415 static 	kcondvar_t sata_event_cv;
416 static 	kthread_t *sata_event_thread = NULL;
417 static 	int sata_event_thread_terminate = 0;
418 static 	int sata_event_pending = 0;
419 static 	int sata_event_thread_active = 0;
420 extern 	pri_t minclsyspri;
421 
422 /*
423  * NCQ error recovery command
424  */
425 static const sata_cmd_t sata_rle_cmd = {
426 	SATA_CMD_REV,
427 	NULL,
428 	{
429 		SATA_DIR_READ
430 	},
431 	ATA_ADDR_LBA48,
432 	0,
433 	0,
434 	0,
435 	0,
436 	0,
437 	1,
438 	READ_LOG_EXT_NCQ_ERROR_RECOVERY,
439 	0,
440 	0,
441 	0,
442 	SATAC_READ_LOG_EXT,
443 	0,
444 	0,
445 	0,
446 };
447 
448 /*
449  * ATAPI error recovery CDB
450  */
451 static const uint8_t sata_rqsense_cdb[SATA_ATAPI_RQSENSE_CDB_LEN] = {
452 	SCMD_REQUEST_SENSE,
453 	0,			/* Only fixed RQ format is supported */
454 	0,
455 	0,
456 	SATA_ATAPI_MIN_RQSENSE_LEN, /* Less data may be returned */
457 	0
458 };
459 
460 
461 /* Warlock directives */
462 
463 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran))
464 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_device))
465 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_ops))
466 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_extended_sense))
467 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_arq_status))
468 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_attr))
469 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_cookie_t))
470 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", devctl_ap_state))
471 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_info::devi_state))
472 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_list))
473 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_list))
474 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_next))
475 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_prev))
476 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", \
477     sata_hba_inst::satahba_scsi_tran))
478 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_tran))
479 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_dip))
480 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_hba_inst::satahba_attached))
481 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_inst::satahba_dev_port))
482 _NOTE(MUTEX_PROTECTS_DATA(sata_hba_inst::satahba_mutex,
483     sata_hba_inst::satahba_event_flags))
484 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
485     sata_cport_info::cport_devp))
486 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_devp))
487 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_cport_info::cport_addr))
488 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
489     sata_cport_info::cport_dev_type))
490 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_dev_type))
491 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
492     sata_cport_info::cport_state))
493 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_state))
494 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
495     sata_pmport_info::pmport_state))
496 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_state))
497 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_dev_type))
498 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_sata_drive))
499 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_dev_port))
500 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_num_dev_ports))
501 #ifdef SATA_DEBUG
502 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuf_count))
503 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuffail_count))
504 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace))
505 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace_index))
506 #endif
507 
508 /* End of warlock directives */
509 
510 /* ************** loadable module configuration functions ************** */
511 
512 int
513 _init()
514 {
515 	int rval;
516 
517 	mutex_init(&sata_mutex, NULL, MUTEX_DRIVER, NULL);
518 	mutex_init(&sata_event_mutex, NULL, MUTEX_DRIVER, NULL);
519 	mutex_init(&sata_log_mutex, NULL, MUTEX_DRIVER, NULL);
520 	cv_init(&sata_event_cv, NULL, CV_DRIVER, NULL);
521 	if ((rval = mod_install(&modlinkage)) != 0) {
522 #ifdef SATA_DEBUG
523 		cmn_err(CE_WARN, "sata: _init: mod_install failed\n");
524 #endif
525 		mutex_destroy(&sata_log_mutex);
526 		cv_destroy(&sata_event_cv);
527 		mutex_destroy(&sata_event_mutex);
528 		mutex_destroy(&sata_mutex);
529 	}
530 	return (rval);
531 }
532 
533 int
534 _fini()
535 {
536 	int rval;
537 
538 	if ((rval = mod_remove(&modlinkage)) != 0)
539 		return (rval);
540 
541 	mutex_destroy(&sata_log_mutex);
542 	cv_destroy(&sata_event_cv);
543 	mutex_destroy(&sata_event_mutex);
544 	mutex_destroy(&sata_mutex);
545 	return (rval);
546 }
547 
548 int
549 _info(struct modinfo *modinfop)
550 {
551 	return (mod_info(&modlinkage, modinfop));
552 }
553 
554 
555 
556 /* ********************* SATA HBA entry points ********************* */
557 
558 
559 /*
560  * Called by SATA HBA from _init().
561  * Registers HBA driver instance/sata framework pair with scsi framework, by
562  * calling scsi_hba_init().
563  *
564  * SATA HBA driver cb_ops are ignored - SATA HBA framework cb_ops are used
565  * instead. SATA HBA framework cb_ops pointer overwrites SATA HBA driver
566  * cb_ops pointer in SATA HBA driver dev_ops structure.
567  * SATA HBA framework cb_ops supplies cb_open cb_close and cb_ioctl vectors.
568  *
569  * Return status of the scsi_hba_init() is returned to a calling SATA HBA
570  * driver.
571  */
572 int
573 sata_hba_init(struct modlinkage *modlp)
574 {
575 	int rval;
576 	struct dev_ops *hba_ops;
577 
578 	SATADBG1(SATA_DBG_HBA_IF, NULL,
579 	    "sata_hba_init: name %s \n",
580 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
581 	/*
582 	 * Fill-up cb_ops and dev_ops when necessary
583 	 */
584 	hba_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
585 	/*
586 	 * Provide pointer to SATA dev_ops
587 	 */
588 	hba_ops->devo_cb_ops = &sata_cb_ops;
589 
590 	/*
591 	 * Register SATA HBA with SCSI framework
592 	 */
593 	if ((rval = scsi_hba_init(modlp)) != 0) {
594 		SATADBG1(SATA_DBG_HBA_IF, NULL,
595 		    "sata_hba_init: scsi hba init failed\n", NULL);
596 		return (rval);
597 	}
598 
599 	return (0);
600 }
601 
602 
603 /* HBA attach stages */
604 #define	HBA_ATTACH_STAGE_SATA_HBA_INST	1
605 #define	HBA_ATTACH_STAGE_SCSI_ATTACHED	2
606 #define	HBA_ATTACH_STAGE_SETUP		4
607 #define	HBA_ATTACH_STAGE_LINKED		8
608 
609 
610 /*
611  *
612  * Called from SATA HBA driver's attach routine to attach an instance of
613  * the HBA.
614  *
615  * For DDI_ATTACH command:
616  * sata_hba_inst structure is allocated here and initialized with pointers to
617  * SATA framework implementation of required scsi tran functions.
618  * The scsi_tran's tran_hba_private field is used by SATA Framework to point
619  * to the soft structure (sata_hba_inst) allocated by SATA framework for
620  * SATA HBA instance related data.
621  * The scsi_tran's tran_hba_private field is used by SATA framework to
622  * store a pointer to per-HBA-instance of sata_hba_inst structure.
623  * The sata_hba_inst structure is cross-linked to scsi tran structure.
624  * Among other info, a pointer to sata_hba_tran structure is stored in
625  * sata_hba_inst. The sata_hba_inst structures for different HBA instances are
626  * linked together into the list, pointed to by sata_hba_list.
627  * On the first HBA instance attach the sata event thread is initialized.
628  * Attachment points are created for all SATA ports of the HBA being attached.
629  * All HBA instance's SATA ports are probed and type of plugged devices is
630  * determined. For each device of a supported type, a target node is created.
631  *
632  * DDI_SUCCESS is returned when attachment process is successful,
633  * DDI_FAILURE is returned otherwise.
634  *
635  * For DDI_RESUME command:
636  * Not implemented at this time (postponed until phase 2 of the development).
637  */
638 int
639 sata_hba_attach(dev_info_t *dip, sata_hba_tran_t *sata_tran,
640     ddi_attach_cmd_t cmd)
641 {
642 	sata_hba_inst_t	*sata_hba_inst;
643 	scsi_hba_tran_t *scsi_tran = NULL;
644 	int hba_attach_state = 0;
645 	char taskq_name[MAXPATHLEN];
646 
647 	SATADBG3(SATA_DBG_HBA_IF, NULL,
648 	    "sata_hba_attach: node %s (%s%d)\n",
649 	    ddi_node_name(dip), ddi_driver_name(dip),
650 	    ddi_get_instance(dip));
651 
652 	if (cmd == DDI_RESUME) {
653 		/*
654 		 * Postponed until phase 2 of the development
655 		 */
656 		return (DDI_FAILURE);
657 	}
658 
659 	if (cmd != DDI_ATTACH) {
660 		return (DDI_FAILURE);
661 	}
662 
663 	/* cmd == DDI_ATTACH */
664 
665 	if (sata_validate_sata_hba_tran(dip, sata_tran) != SATA_SUCCESS) {
666 		SATA_LOG_D((NULL, CE_WARN,
667 		    "sata_hba_attach: invalid sata_hba_tran"));
668 		return (DDI_FAILURE);
669 	}
670 	/*
671 	 * Allocate and initialize SCSI tran structure.
672 	 * SATA copy of tran_bus_config is provided to create port nodes.
673 	 */
674 	scsi_tran = scsi_hba_tran_alloc(dip, SCSI_HBA_CANSLEEP);
675 	if (scsi_tran == NULL)
676 		return (DDI_FAILURE);
677 	/*
678 	 * Allocate soft structure for SATA HBA instance.
679 	 * There is a separate softstate for each HBA instance.
680 	 */
681 	sata_hba_inst = kmem_zalloc(sizeof (struct sata_hba_inst), KM_SLEEP);
682 	ASSERT(sata_hba_inst != NULL); /* this should not fail */
683 	mutex_init(&sata_hba_inst->satahba_mutex, NULL, MUTEX_DRIVER, NULL);
684 	hba_attach_state |= HBA_ATTACH_STAGE_SATA_HBA_INST;
685 
686 	/*
687 	 * scsi_trans's tran_hba_private is used by SATA Framework to point to
688 	 * soft structure allocated by SATA framework for
689 	 * SATA HBA instance related data.
690 	 */
691 	scsi_tran->tran_hba_private	= sata_hba_inst;
692 	scsi_tran->tran_tgt_private	= NULL;
693 
694 	scsi_tran->tran_tgt_init	= sata_scsi_tgt_init;
695 	scsi_tran->tran_tgt_probe	= sata_scsi_tgt_probe;
696 	scsi_tran->tran_tgt_free	= sata_scsi_tgt_free;
697 
698 	scsi_tran->tran_start		= sata_scsi_start;
699 	scsi_tran->tran_reset		= sata_scsi_reset;
700 	scsi_tran->tran_abort		= sata_scsi_abort;
701 	scsi_tran->tran_getcap		= sata_scsi_getcap;
702 	scsi_tran->tran_setcap		= sata_scsi_setcap;
703 	scsi_tran->tran_init_pkt	= sata_scsi_init_pkt;
704 	scsi_tran->tran_destroy_pkt	= sata_scsi_destroy_pkt;
705 
706 	scsi_tran->tran_dmafree		= sata_scsi_dmafree;
707 	scsi_tran->tran_sync_pkt	= sata_scsi_sync_pkt;
708 
709 	scsi_tran->tran_reset_notify	= NULL;
710 	scsi_tran->tran_get_bus_addr	= NULL;
711 	scsi_tran->tran_quiesce		= NULL;
712 	scsi_tran->tran_unquiesce	= NULL;
713 	scsi_tran->tran_bus_reset	= NULL;
714 
715 	if (scsi_hba_attach_setup(dip, sata_tran->sata_tran_hba_dma_attr,
716 	    scsi_tran, 0) != DDI_SUCCESS) {
717 #ifdef SATA_DEBUG
718 		cmn_err(CE_WARN, "?SATA: %s%d hba scsi attach failed",
719 		    ddi_driver_name(dip), ddi_get_instance(dip));
720 #endif
721 		goto fail;
722 	}
723 	hba_attach_state |= HBA_ATTACH_STAGE_SCSI_ATTACHED;
724 
725 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "sata")) {
726 		if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
727 		    "sata", 1) != DDI_PROP_SUCCESS) {
728 			SATA_LOG_D((NULL, CE_WARN, "sata_hba_attach: "
729 			    "failed to create hba sata prop"));
730 			goto fail;
731 		}
732 	}
733 
734 	/*
735 	 * Save pointers in hba instance soft state.
736 	 */
737 	sata_hba_inst->satahba_scsi_tran = scsi_tran;
738 	sata_hba_inst->satahba_tran = sata_tran;
739 	sata_hba_inst->satahba_dip = dip;
740 
741 	/*
742 	 * Create a task queue to handle emulated commands completion
743 	 * Use node name, dash, instance number as the queue name.
744 	 */
745 	taskq_name[0] = '\0';
746 	(void) strlcat(taskq_name, DEVI(dip)->devi_node_name,
747 	    sizeof (taskq_name));
748 	(void) snprintf(taskq_name + strlen(taskq_name),
749 	    sizeof (taskq_name) - strlen(taskq_name),
750 	    "-%d", DEVI(dip)->devi_instance);
751 	sata_hba_inst->satahba_taskq = taskq_create(taskq_name, 1,
752 	    minclsyspri, 1, sata_tran->sata_tran_hba_num_cports,
753 	    TASKQ_DYNAMIC);
754 
755 	hba_attach_state |= HBA_ATTACH_STAGE_SETUP;
756 
757 	/*
758 	 * Create events thread if not created yet.
759 	 */
760 	sata_event_thread_control(1);
761 
762 	/*
763 	 * Link this hba instance into the list.
764 	 */
765 	mutex_enter(&sata_mutex);
766 
767 	if (sata_hba_list == NULL) {
768 		/*
769 		 * The first instance of HBA is attached.
770 		 * Set current/active default maximum NCQ/TCQ queue depth for
771 		 * all SATA devices. It is done here and now, to eliminate the
772 		 * possibility of the dynamic, programatic modification of the
773 		 * queue depth via global (and public) sata_max_queue_depth
774 		 * variable (this would require special handling in HBA drivers)
775 		 */
776 		sata_current_max_qdepth = sata_max_queue_depth;
777 		if (sata_current_max_qdepth > 32)
778 			sata_current_max_qdepth = 32;
779 		else if (sata_current_max_qdepth < 1)
780 			sata_current_max_qdepth = 1;
781 	}
782 
783 	sata_hba_inst->satahba_next = NULL;
784 	sata_hba_inst->satahba_prev = sata_hba_list_tail;
785 	if (sata_hba_list == NULL) {
786 		sata_hba_list = sata_hba_inst;
787 	}
788 	if (sata_hba_list_tail != NULL) {
789 		sata_hba_list_tail->satahba_next = sata_hba_inst;
790 	}
791 	sata_hba_list_tail = sata_hba_inst;
792 	mutex_exit(&sata_mutex);
793 	hba_attach_state |= HBA_ATTACH_STAGE_LINKED;
794 
795 	/*
796 	 * Create SATA HBA devctl minor node for sata_hba_open, close, ioctl
797 	 * SATA HBA driver should not use its own open/close entry points.
798 	 *
799 	 * Make sure that instance number doesn't overflow
800 	 * when forming minor numbers.
801 	 */
802 	ASSERT(ddi_get_instance(dip) <= (L_MAXMIN >> INST_MINOR_SHIFT));
803 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
804 	    INST2DEVCTL(ddi_get_instance(dip)),
805 	    DDI_NT_SATA_NEXUS, 0) != DDI_SUCCESS) {
806 #ifdef SATA_DEBUG
807 		cmn_err(CE_WARN, "sata_hba_attach: "
808 		    "cannot create devctl minor node");
809 #endif
810 		goto fail;
811 	}
812 
813 
814 	/*
815 	 * Set-up kstats here, if necessary.
816 	 * (postponed until phase 2 of the development).
817 	 */
818 
819 
820 	/*
821 	 * Probe controller ports. This operation will describe a current
822 	 * controller/port/multipliers/device configuration and will create
823 	 * attachment points.
824 	 * We may end-up with just a controller with no devices attached.
825 	 * For the ports with a supported device attached, device target nodes
826 	 * are created and devices are initialized.
827 	 */
828 	sata_probe_ports(sata_hba_inst);
829 
830 	sata_hba_inst->satahba_attached = 1;
831 	return (DDI_SUCCESS);
832 
833 fail:
834 	if (hba_attach_state & HBA_ATTACH_STAGE_LINKED) {
835 		(void) sata_remove_hba_instance(dip);
836 		if (sata_hba_list == NULL)
837 			sata_event_thread_control(0);
838 	}
839 
840 	if (hba_attach_state & HBA_ATTACH_STAGE_SETUP) {
841 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
842 		taskq_destroy(sata_hba_inst->satahba_taskq);
843 	}
844 
845 	if (hba_attach_state & HBA_ATTACH_STAGE_SCSI_ATTACHED)
846 		(void) scsi_hba_detach(dip);
847 
848 	if (hba_attach_state & HBA_ATTACH_STAGE_SATA_HBA_INST) {
849 		mutex_destroy(&sata_hba_inst->satahba_mutex);
850 		kmem_free((void *)sata_hba_inst,
851 		    sizeof (struct sata_hba_inst));
852 		scsi_hba_tran_free(scsi_tran);
853 	}
854 
855 	sata_log(NULL, CE_WARN, "?SATA: %s%d hba attach failed",
856 	    ddi_driver_name(dip), ddi_get_instance(dip));
857 
858 	return (DDI_FAILURE);
859 }
860 
861 
862 /*
863  * Called by SATA HBA from to detach an instance of the driver.
864  *
865  * For DDI_DETACH command:
866  * Free local structures allocated for SATA HBA instance during
867  * sata_hba_attach processing.
868  *
869  * Returns DDI_SUCCESS when HBA was detached, DDI_FAILURE otherwise.
870  *
871  * For DDI_SUSPEND command:
872  * Not implemented at this time (postponed until phase 2 of the development)
873  * Returnd DDI_SUCCESS.
874  *
875  * When the last HBA instance is detached, the event daemon is terminated.
876  *
877  * NOTE: cport support only, no port multiplier support.
878  */
879 int
880 sata_hba_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
881 {
882 	dev_info_t	*tdip;
883 	sata_hba_inst_t	*sata_hba_inst;
884 	scsi_hba_tran_t *scsi_hba_tran;
885 	sata_cport_info_t *cportinfo;
886 	sata_drive_info_t *sdinfo;
887 	int ncport;
888 
889 	SATADBG3(SATA_DBG_HBA_IF, NULL, "sata_hba_detach: node %s (%s%d)\n",
890 	    ddi_node_name(dip), ddi_driver_name(dip), ddi_get_instance(dip));
891 
892 	switch (cmd) {
893 	case DDI_DETACH:
894 
895 		if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
896 			return (DDI_FAILURE);
897 
898 		sata_hba_inst = scsi_hba_tran->tran_hba_private;
899 		if (sata_hba_inst == NULL)
900 			return (DDI_FAILURE);
901 
902 		if (scsi_hba_detach(dip) == DDI_FAILURE) {
903 			sata_hba_inst->satahba_attached = 1;
904 			return (DDI_FAILURE);
905 		}
906 
907 		/*
908 		 * Free all target nodes - at this point
909 		 * devices should be at least offlined
910 		 * otherwise scsi_hba_detach() should not be called.
911 		 */
912 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
913 		    ncport++) {
914 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
915 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
916 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
917 				if (sdinfo != NULL) {
918 					tdip = sata_get_target_dip(dip,
919 					    ncport);
920 					if (tdip != NULL) {
921 						if (ndi_devi_offline(tdip,
922 						    NDI_DEVI_REMOVE) !=
923 						    NDI_SUCCESS) {
924 							SATA_LOG_D((
925 							    sata_hba_inst,
926 							    CE_WARN,
927 							    "sata_hba_detach: "
928 							    "Target node not "
929 							    "removed !"));
930 							return (DDI_FAILURE);
931 						}
932 					}
933 				}
934 			}
935 		}
936 		/*
937 		 * Disable sata event daemon processing for this HBA
938 		 */
939 		sata_hba_inst->satahba_attached = 0;
940 
941 		/*
942 		 * Remove event daemon thread, if it is last HBA instance.
943 		 */
944 
945 		mutex_enter(&sata_mutex);
946 		if (sata_hba_list->satahba_next == NULL) {
947 			mutex_exit(&sata_mutex);
948 			sata_event_thread_control(0);
949 			mutex_enter(&sata_mutex);
950 		}
951 		mutex_exit(&sata_mutex);
952 
953 		/* Remove this HBA instance from the HBA list */
954 		sata_remove_hba_instance(dip);
955 
956 		/*
957 		 * At this point there should be no target nodes attached.
958 		 * Detach and destroy device and port info structures.
959 		 */
960 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
961 		    ncport++) {
962 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
963 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
964 				sdinfo =
965 				    cportinfo->cport_devp.cport_sata_drive;
966 				if (sdinfo != NULL) {
967 					/* Release device structure */
968 					kmem_free(sdinfo,
969 					    sizeof (sata_drive_info_t));
970 				}
971 				/* Release cport info */
972 				mutex_destroy(&cportinfo->cport_mutex);
973 				kmem_free(cportinfo,
974 				    sizeof (sata_cport_info_t));
975 			}
976 		}
977 
978 		scsi_hba_tran_free(sata_hba_inst->satahba_scsi_tran);
979 
980 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
981 
982 		taskq_destroy(sata_hba_inst->satahba_taskq);
983 
984 		mutex_destroy(&sata_hba_inst->satahba_mutex);
985 		kmem_free((void *)sata_hba_inst,
986 		    sizeof (struct sata_hba_inst));
987 
988 		return (DDI_SUCCESS);
989 
990 	case DDI_SUSPEND:
991 		/*
992 		 * Postponed until phase 2
993 		 */
994 		return (DDI_FAILURE);
995 
996 	default:
997 		return (DDI_FAILURE);
998 	}
999 }
1000 
1001 
1002 /*
1003  * Called by an HBA drive from _fini() routine.
1004  * Unregisters SATA HBA instance/SATA framework pair from the scsi framework.
1005  */
1006 void
1007 sata_hba_fini(struct modlinkage *modlp)
1008 {
1009 	SATADBG1(SATA_DBG_HBA_IF, NULL,
1010 	    "sata_hba_fini: name %s\n",
1011 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
1012 
1013 	scsi_hba_fini(modlp);
1014 }
1015 
1016 
1017 /*
1018  * Default open and close routine for sata_hba framework.
1019  *
1020  */
1021 /*
1022  * Open devctl node.
1023  *
1024  * Returns:
1025  * 0 if node was open successfully, error code otherwise.
1026  *
1027  *
1028  */
1029 
1030 static int
1031 sata_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
1032 {
1033 #ifndef __lock_lint
1034 	_NOTE(ARGUNUSED(credp))
1035 #endif
1036 	int rv = 0;
1037 	dev_info_t *dip;
1038 	scsi_hba_tran_t *scsi_hba_tran;
1039 	sata_hba_inst_t	*sata_hba_inst;
1040 
1041 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_open: entered", NULL);
1042 
1043 	if (otyp != OTYP_CHR)
1044 		return (EINVAL);
1045 
1046 	dip = sata_devt_to_devinfo(*devp);
1047 	if (dip == NULL)
1048 		return (ENXIO);
1049 
1050 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1051 		return (ENXIO);
1052 
1053 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1054 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1055 		return (ENXIO);
1056 
1057 	mutex_enter(&sata_mutex);
1058 	if (flags & FEXCL) {
1059 		if (sata_hba_inst->satahba_open_flag != 0) {
1060 			rv = EBUSY;
1061 		} else {
1062 			sata_hba_inst->satahba_open_flag =
1063 			    SATA_DEVCTL_EXOPENED;
1064 		}
1065 	} else {
1066 		if (sata_hba_inst->satahba_open_flag == SATA_DEVCTL_EXOPENED) {
1067 			rv = EBUSY;
1068 		} else {
1069 			sata_hba_inst->satahba_open_flag =
1070 			    SATA_DEVCTL_SOPENED;
1071 		}
1072 	}
1073 	mutex_exit(&sata_mutex);
1074 
1075 	return (rv);
1076 }
1077 
1078 
1079 /*
1080  * Close devctl node.
1081  * Returns:
1082  * 0 if node was closed successfully, error code otherwise.
1083  *
1084  */
1085 
1086 static int
1087 sata_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
1088 {
1089 #ifndef __lock_lint
1090 	_NOTE(ARGUNUSED(credp))
1091 	_NOTE(ARGUNUSED(flag))
1092 #endif
1093 	dev_info_t *dip;
1094 	scsi_hba_tran_t *scsi_hba_tran;
1095 	sata_hba_inst_t	*sata_hba_inst;
1096 
1097 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_close: entered", NULL);
1098 
1099 	if (otyp != OTYP_CHR)
1100 		return (EINVAL);
1101 
1102 	dip = sata_devt_to_devinfo(dev);
1103 	if (dip == NULL)
1104 		return (ENXIO);
1105 
1106 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1107 		return (ENXIO);
1108 
1109 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1110 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1111 		return (ENXIO);
1112 
1113 	mutex_enter(&sata_mutex);
1114 	sata_hba_inst->satahba_open_flag = 0;
1115 	mutex_exit(&sata_mutex);
1116 	return (0);
1117 }
1118 
1119 
1120 
1121 /*
1122  * Standard IOCTL commands for SATA hotplugging.
1123  * Implemented DEVCTL_AP commands:
1124  * DEVCTL_AP_CONNECT
1125  * DEVCTL_AP_DISCONNECT
1126  * DEVCTL_AP_CONFIGURE
1127  * DEVCTL_UNCONFIGURE
1128  * DEVCTL_AP_CONTROL
1129  *
1130  * Commands passed to default ndi ioctl handler:
1131  * DEVCTL_DEVICE_GETSTATE
1132  * DEVCTL_DEVICE_ONLINE
1133  * DEVCTL_DEVICE_OFFLINE
1134  * DEVCTL_DEVICE_REMOVE
1135  * DEVCTL_DEVICE_INSERT
1136  * DEVCTL_BUS_GETSTATE
1137  *
1138  * All other cmds are passed to HBA if it provide ioctl handler, or failed
1139  * if not.
1140  *
1141  * Returns:
1142  * 0 if successful,
1143  * error code if operation failed.
1144  *
1145  * NOTE: Port Multiplier is not supported.
1146  *
1147  */
1148 
1149 static int
1150 sata_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
1151     int *rvalp)
1152 {
1153 #ifndef __lock_lint
1154 	_NOTE(ARGUNUSED(credp))
1155 	_NOTE(ARGUNUSED(rvalp))
1156 #endif
1157 	int rv = 0;
1158 	int32_t	comp_port = -1;
1159 	dev_info_t *dip;
1160 	devctl_ap_state_t ap_state;
1161 	struct devctl_iocdata *dcp = NULL;
1162 	scsi_hba_tran_t *scsi_hba_tran;
1163 	sata_hba_inst_t *sata_hba_inst;
1164 	sata_device_t sata_device;
1165 	sata_cport_info_t *cportinfo;
1166 	int cport, pmport, qual;
1167 	int rval = SATA_SUCCESS;
1168 
1169 	dip = sata_devt_to_devinfo(dev);
1170 	if (dip == NULL)
1171 		return (ENXIO);
1172 
1173 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1174 		return (ENXIO);
1175 
1176 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1177 	if (sata_hba_inst == NULL)
1178 		return (ENXIO);
1179 
1180 	if (sata_hba_inst->satahba_tran == NULL)
1181 		return (ENXIO);
1182 
1183 	switch (cmd) {
1184 
1185 	case DEVCTL_DEVICE_GETSTATE:
1186 	case DEVCTL_DEVICE_ONLINE:
1187 	case DEVCTL_DEVICE_OFFLINE:
1188 	case DEVCTL_DEVICE_REMOVE:
1189 	case DEVCTL_BUS_GETSTATE:
1190 		/*
1191 		 * There may be more cases that we want to pass to default
1192 		 * handler rather than fail them.
1193 		 */
1194 		return (ndi_devctl_ioctl(dip, cmd, arg, mode, 0));
1195 	}
1196 
1197 	/* read devctl ioctl data */
1198 	if (cmd != DEVCTL_AP_CONTROL) {
1199 		if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS)
1200 			return (EFAULT);
1201 
1202 		if ((comp_port = sata_get_port_num(sata_hba_inst, dcp)) ==
1203 		    -1) {
1204 			if (dcp)
1205 				ndi_dc_freehdl(dcp);
1206 			return (EINVAL);
1207 		}
1208 
1209 		cport = SCSI_TO_SATA_CPORT(comp_port);
1210 		pmport = SCSI_TO_SATA_PMPORT(comp_port);
1211 		/* Only cport is considered now, i.e. SATA_ADDR_CPORT */
1212 		qual = SATA_ADDR_CPORT;
1213 		if (sata_validate_sata_address(sata_hba_inst, cport, pmport,
1214 		    qual) != 0) {
1215 			ndi_dc_freehdl(dcp);
1216 			return (EINVAL);
1217 		}
1218 
1219 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1220 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1221 		    cport_mutex);
1222 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1223 			/*
1224 			 * Cannot process ioctl request now. Come back later.
1225 			 */
1226 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1227 			    cport_mutex);
1228 			ndi_dc_freehdl(dcp);
1229 			return (EBUSY);
1230 		}
1231 		/* Block event processing for this port */
1232 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1233 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1234 
1235 		sata_device.satadev_addr.cport = cport;
1236 		sata_device.satadev_addr.pmport = pmport;
1237 		sata_device.satadev_addr.qual = qual;
1238 		sata_device.satadev_rev = SATA_DEVICE_REV;
1239 	}
1240 
1241 	switch (cmd) {
1242 
1243 	case DEVCTL_AP_DISCONNECT:
1244 
1245 		/*
1246 		 * Normally, cfgadm sata plugin will try to offline
1247 		 * (unconfigure) device before this request. Nevertheless,
1248 		 * if a device is still configured, we need to
1249 		 * attempt to offline and unconfigure device first, and we will
1250 		 * deactivate the port regardless of the unconfigure
1251 		 * operation results.
1252 		 *
1253 		 */
1254 		rv = sata_ioctl_disconnect(sata_hba_inst, &sata_device);
1255 
1256 		break;
1257 
1258 	case DEVCTL_AP_UNCONFIGURE:
1259 
1260 		/*
1261 		 * The unconfigure operation uses generic nexus operation to
1262 		 * offline a device. It leaves a target device node attached.
1263 		 * and obviously sata_drive_info attached as well, because
1264 		 * from the hardware point of view nothing has changed.
1265 		 */
1266 		rv = sata_ioctl_unconfigure(sata_hba_inst, &sata_device);
1267 		break;
1268 
1269 	case DEVCTL_AP_CONNECT:
1270 	{
1271 		/*
1272 		 * The sata cfgadm pluging will invoke this operation only if
1273 		 * port was found in the disconnect state (failed state
1274 		 * is also treated as the disconnected state).
1275 		 * If port activation is successful and a device is found
1276 		 * attached to the port, the initialization sequence is
1277 		 * executed to probe the port and attach
1278 		 * a device structure to a port structure. The device is not
1279 		 * set in configured state (system-wise) by this operation.
1280 		 */
1281 
1282 		rv = sata_ioctl_connect(sata_hba_inst, &sata_device);
1283 
1284 		break;
1285 	}
1286 
1287 	case DEVCTL_AP_CONFIGURE:
1288 	{
1289 		/*
1290 		 * A port may be in an active or shutdown state.
1291 		 * If port is in a failed state, operation is aborted.
1292 		 * If a port is in a shutdown state, sata_tran_port_activate()
1293 		 * is invoked prior to any other operation.
1294 		 *
1295 		 * Onlining the device involves creating a new target node.
1296 		 * If there is an old target node present (belonging to
1297 		 * previously removed device), the operation is aborted - the
1298 		 * old node has to be released and removed before configure
1299 		 * operation is attempted.
1300 		 */
1301 
1302 		rv = sata_ioctl_configure(sata_hba_inst, &sata_device);
1303 
1304 		break;
1305 	}
1306 
1307 	case DEVCTL_AP_GETSTATE:
1308 
1309 		sata_cfgadm_state(sata_hba_inst, comp_port, &ap_state);
1310 
1311 		ap_state.ap_last_change = (time_t)-1;
1312 		ap_state.ap_error_code = 0;
1313 		ap_state.ap_in_transition = 0;
1314 
1315 		/* Copy the return AP-state information to the user space */
1316 		if (ndi_dc_return_ap_state(&ap_state, dcp) != NDI_SUCCESS) {
1317 			rv = EFAULT;
1318 		}
1319 		break;
1320 
1321 	case DEVCTL_AP_CONTROL:
1322 	{
1323 		/*
1324 		 * Generic devctl for hardware specific functionality
1325 		 */
1326 		sata_ioctl_data_t	ioc;
1327 
1328 		ASSERT(dcp == NULL);
1329 
1330 		/* Copy in user ioctl data first */
1331 #ifdef _MULTI_DATAMODEL
1332 		if (ddi_model_convert_from(mode & FMODELS) ==
1333 		    DDI_MODEL_ILP32) {
1334 
1335 			sata_ioctl_data_32_t	ioc32;
1336 
1337 			if (ddi_copyin((void *)arg, (void *)&ioc32,
1338 			    sizeof (ioc32), mode) != 0) {
1339 				rv = EFAULT;
1340 				break;
1341 			}
1342 			ioc.cmd 	= (uint_t)ioc32.cmd;
1343 			ioc.port	= (uint_t)ioc32.port;
1344 			ioc.get_size	= (uint_t)ioc32.get_size;
1345 			ioc.buf		= (caddr_t)(uintptr_t)ioc32.buf;
1346 			ioc.bufsiz	= (uint_t)ioc32.bufsiz;
1347 			ioc.misc_arg	= (uint_t)ioc32.misc_arg;
1348 		} else
1349 #endif /* _MULTI_DATAMODEL */
1350 		if (ddi_copyin((void *)arg, (void *)&ioc, sizeof (ioc),
1351 		    mode) != 0) {
1352 			return (EFAULT);
1353 		}
1354 
1355 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
1356 		    "sata_hba_ioctl: DEVCTL_AP_CONTROL "
1357 		    "cmd 0x%x, port 0x%x", ioc.cmd, ioc.port);
1358 
1359 		/*
1360 		 * To avoid BE/LE and 32/64 issues, a get_size always returns
1361 		 * a 32-bit number.
1362 		 */
1363 		if (ioc.get_size != 0 && ioc.bufsiz != (sizeof (uint32_t))) {
1364 			return (EINVAL);
1365 		}
1366 		/* validate address */
1367 		cport = SCSI_TO_SATA_CPORT(ioc.port);
1368 		pmport = SCSI_TO_SATA_PMPORT(ioc.port);
1369 		qual = SCSI_TO_SATA_ADDR_QUAL(ioc.port);
1370 
1371 		/* Override address qualifier - handle cport only for now */
1372 		qual = SATA_ADDR_CPORT;
1373 
1374 		if (sata_validate_sata_address(sata_hba_inst, cport,
1375 		    pmport, qual) != 0)
1376 			return (EINVAL);
1377 
1378 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1379 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1380 		    cport_mutex);
1381 		/* Is the port locked by event processing daemon ? */
1382 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1383 			/*
1384 			 * Cannot process ioctl request now. Come back later
1385 			 */
1386 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1387 			    cport_mutex);
1388 			return (EBUSY);
1389 		}
1390 		/* Block event processing for this port */
1391 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1392 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1393 
1394 
1395 		sata_device.satadev_addr.cport = cport;
1396 		sata_device.satadev_addr.pmport = pmport;
1397 		sata_device.satadev_addr.qual = qual;
1398 		sata_device.satadev_rev = SATA_DEVICE_REV;
1399 
1400 		switch (ioc.cmd) {
1401 
1402 		case SATA_CFGA_RESET_PORT:
1403 			/*
1404 			 * There is no protection for configured device.
1405 			 */
1406 			rv = sata_ioctl_reset_port(sata_hba_inst, &sata_device);
1407 			break;
1408 
1409 		case SATA_CFGA_RESET_DEVICE:
1410 			/*
1411 			 * There is no protection for configured device.
1412 			 */
1413 			rv = sata_ioctl_reset_device(sata_hba_inst,
1414 			    &sata_device);
1415 			break;
1416 
1417 		case SATA_CFGA_RESET_ALL:
1418 			/*
1419 			 * There is no protection for configured devices.
1420 			 */
1421 			rv = sata_ioctl_reset_all(sata_hba_inst);
1422 			/*
1423 			 * We return here, because common return is for
1424 			 * a single port operation - we have already unlocked
1425 			 * all ports and no dc handle was allocated.
1426 			 */
1427 			return (rv);
1428 
1429 		case SATA_CFGA_PORT_DEACTIVATE:
1430 			/*
1431 			 * Arbitrarily unconfigure attached device, if any.
1432 			 * Even if the unconfigure fails, proceed with the
1433 			 * port deactivation.
1434 			 */
1435 			rv = sata_ioctl_deactivate(sata_hba_inst, &sata_device);
1436 
1437 			break;
1438 
1439 		case SATA_CFGA_PORT_ACTIVATE:
1440 
1441 			rv = sata_ioctl_activate(sata_hba_inst, &sata_device);
1442 			break;
1443 
1444 		case SATA_CFGA_PORT_SELF_TEST:
1445 
1446 			rv = sata_ioctl_port_self_test(sata_hba_inst,
1447 			    &sata_device);
1448 			break;
1449 
1450 		case SATA_CFGA_GET_DEVICE_PATH:
1451 			if (qual == SATA_ADDR_CPORT)
1452 				sata_device.satadev_addr.qual =
1453 				    SATA_ADDR_DCPORT;
1454 			else
1455 				sata_device.satadev_addr.qual =
1456 				    SATA_ADDR_DPMPORT;
1457 			rv = sata_ioctl_get_device_path(sata_hba_inst,
1458 			    &sata_device, &ioc, mode);
1459 			break;
1460 
1461 		case SATA_CFGA_GET_AP_TYPE:
1462 
1463 			rv = sata_ioctl_get_ap_type(sata_hba_inst,
1464 			    &sata_device, &ioc, mode);
1465 			break;
1466 
1467 		case SATA_CFGA_GET_MODEL_INFO:
1468 
1469 			rv = sata_ioctl_get_model_info(sata_hba_inst,
1470 			    &sata_device, &ioc, mode);
1471 			break;
1472 
1473 		case SATA_CFGA_GET_REVFIRMWARE_INFO:
1474 
1475 			rv = sata_ioctl_get_revfirmware_info(sata_hba_inst,
1476 			    &sata_device, &ioc, mode);
1477 			break;
1478 
1479 		case SATA_CFGA_GET_SERIALNUMBER_INFO:
1480 
1481 			rv = sata_ioctl_get_serialnumber_info(sata_hba_inst,
1482 			    &sata_device, &ioc, mode);
1483 			break;
1484 
1485 		default:
1486 			rv = EINVAL;
1487 			break;
1488 
1489 		} /* End of DEVCTL_AP_CONTROL cmd switch */
1490 
1491 		break;
1492 	}
1493 
1494 	default:
1495 	{
1496 		/*
1497 		 * If we got here, we got an IOCTL that SATA HBA Framework
1498 		 * does not recognize. Pass ioctl to HBA driver, in case
1499 		 * it could process it.
1500 		 */
1501 		sata_hba_tran_t *sata_tran = sata_hba_inst->satahba_tran;
1502 		dev_info_t	*mydip = SATA_DIP(sata_hba_inst);
1503 
1504 		SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1505 		    "IOCTL 0x%2x not supported in SATA framework, "
1506 		    "passthrough to HBA", cmd);
1507 
1508 		if (sata_tran->sata_tran_ioctl == NULL) {
1509 			rv = EINVAL;
1510 			break;
1511 		}
1512 		rval = (*sata_tran->sata_tran_ioctl)(mydip, cmd, arg);
1513 		if (rval != 0) {
1514 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1515 			    "IOCTL 0x%2x failed in HBA", cmd);
1516 			rv = rval;
1517 		}
1518 		break;
1519 	}
1520 
1521 	} /* End of main IOCTL switch */
1522 
1523 	if (dcp) {
1524 		ndi_dc_freehdl(dcp);
1525 	}
1526 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1527 	cportinfo->cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
1528 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1529 
1530 	return (rv);
1531 }
1532 
1533 
1534 /*
1535  * Create error retrieval sata packet
1536  *
1537  * A sata packet is allocated and set-up to contain specified error retrieval
1538  * command and appropriate dma-able data buffer.
1539  * No association with any scsi packet is made and no callback routine is
1540  * specified.
1541  *
1542  * Returns a pointer to sata packet upon successfull packet creation.
1543  * Returns NULL, if packet cannot be created.
1544  */
1545 sata_pkt_t *
1546 sata_get_error_retrieval_pkt(dev_info_t *dip, sata_device_t *sata_device,
1547     int pkt_type)
1548 {
1549 	sata_hba_inst_t	*sata_hba_inst;
1550 	sata_pkt_txlate_t *spx;
1551 	sata_pkt_t *spkt;
1552 	sata_drive_info_t *sdinfo;
1553 
1554 	mutex_enter(&sata_mutex);
1555 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1556 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1557 		if (SATA_DIP(sata_hba_inst) == dip)
1558 			break;
1559 	}
1560 	mutex_exit(&sata_mutex);
1561 	ASSERT(sata_hba_inst != NULL);
1562 
1563 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
1564 	if (sdinfo == NULL) {
1565 		sata_log(sata_hba_inst, CE_WARN,
1566 		    "sata: error recovery request for non-attached device at "
1567 		    "cport %d", sata_device->satadev_addr.cport);
1568 		return (NULL);
1569 	}
1570 
1571 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1572 	spx->txlt_sata_hba_inst = sata_hba_inst;
1573 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
1574 	spkt = sata_pkt_alloc(spx, NULL);
1575 	if (spkt == NULL) {
1576 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1577 		return (NULL);
1578 	}
1579 	/* address is needed now */
1580 	spkt->satapkt_device.satadev_addr = sata_device->satadev_addr;
1581 
1582 	switch (pkt_type) {
1583 	case SATA_ERR_RETR_PKT_TYPE_NCQ:
1584 		if (sata_ncq_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1585 			return (spkt);
1586 		break;
1587 
1588 	case SATA_ERR_RETR_PKT_TYPE_ATAPI:
1589 		if (sata_atapi_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1590 			return (spkt);
1591 		break;
1592 
1593 	default:
1594 		break;
1595 	}
1596 
1597 	sata_pkt_free(spx);
1598 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1599 	return (NULL);
1600 
1601 }
1602 
1603 
1604 /*
1605  * Free error retrieval sata packet
1606  *
1607  * Free sata packet and any associated resources allocated previously by
1608  * sata_get_error_retrieval_pkt().
1609  *
1610  * Void return.
1611  */
1612 void
1613 sata_free_error_retrieval_pkt(sata_pkt_t *sata_pkt)
1614 {
1615 	sata_pkt_txlate_t *spx =
1616 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1617 
1618 	ASSERT(sata_pkt != NULL);
1619 
1620 	sata_free_local_buffer(spx);
1621 	sata_pkt_free(spx);
1622 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1623 
1624 }
1625 
1626 
1627 /* ****************** SCSA required entry points *********************** */
1628 
1629 /*
1630  * Implementation of scsi tran_tgt_init.
1631  * sata_scsi_tgt_init() initializes scsi_device structure
1632  *
1633  * If successful, DDI_SUCCESS is returned.
1634  * DDI_FAILURE is returned if addressed device does not exist
1635  */
1636 
1637 static int
1638 sata_scsi_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
1639     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
1640 {
1641 #ifndef __lock_lint
1642 	_NOTE(ARGUNUSED(hba_dip))
1643 	_NOTE(ARGUNUSED(tgt_dip))
1644 #endif
1645 	sata_device_t		sata_device;
1646 	sata_drive_info_t	*sdinfo;
1647 	struct sata_id		*sid;
1648 	sata_hba_inst_t		*sata_hba_inst;
1649 	char			model[SATA_ID_MODEL_LEN + 1];
1650 	char			fw[SATA_ID_FW_LEN + 1];
1651 	char			*vid, *pid;
1652 	int			i;
1653 
1654 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
1655 
1656 	/* Validate scsi device address */
1657 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
1658 	    &sata_device) != 0)
1659 		return (DDI_FAILURE);
1660 
1661 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1662 	    sata_device.satadev_addr.cport)));
1663 
1664 	/* sata_device now contains a valid sata address */
1665 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
1666 	if (sdinfo == NULL) {
1667 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1668 		    sata_device.satadev_addr.cport)));
1669 		return (DDI_FAILURE);
1670 	}
1671 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1672 	    sata_device.satadev_addr.cport)));
1673 
1674 	/*
1675 	 * Check if we need to create a legacy devid (i.e cmdk style) for
1676 	 * the target disks.
1677 	 *
1678 	 * HBA devinfo node will have the property "use-cmdk-devid-format"
1679 	 * if we need to create cmdk-style devid for all the disk devices
1680 	 * attached to this controller. This property may have been set
1681 	 * from HBA driver's .conf file or by the HBA driver in its
1682 	 * attach(9F) function.
1683 	 */
1684 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
1685 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
1686 	    "use-cmdk-devid-format", 0) == 1)) {
1687 		/* register a legacy devid for this target node */
1688 		sata_target_devid_register(tgt_dip, sdinfo);
1689 	}
1690 
1691 
1692 	/*
1693 	 * 'Identify Device Data' does not always fit in standard SCSI
1694 	 * INQUIRY data, so establish INQUIRY_* properties with full-form
1695 	 * of information.
1696 	 */
1697 	sid = &sdinfo->satadrv_id;
1698 #ifdef	_LITTLE_ENDIAN
1699 	swab(sid->ai_model, model, SATA_ID_MODEL_LEN);
1700 	swab(sid->ai_fw, fw, SATA_ID_FW_LEN);
1701 #else	/* _LITTLE_ENDIAN */
1702 	bcopy(sid->ai_model, model, SATA_ID_MODEL_LEN);
1703 	bcopy(sid->ai_fw, fw, SATA_ID_FW_LEN);
1704 #endif	/* _LITTLE_ENDIAN */
1705 	model[SATA_ID_MODEL_LEN] = 0;
1706 	fw[SATA_ID_FW_LEN] = 0;
1707 
1708 	/* split model into into vid/pid */
1709 	for (i = 0, pid = model; i < SATA_ID_MODEL_LEN; i++, pid++)
1710 		if ((*pid == ' ') || (*pid == '\t'))
1711 			break;
1712 	if (i < SATA_ID_MODEL_LEN) {
1713 		vid = model;
1714 		*pid++ = 0;		/* terminate vid, establish pid */
1715 	} else {
1716 		vid = NULL;		/* vid will stay "ATA     " */
1717 		pid = model;		/* model is all pid */
1718 	}
1719 
1720 	if (vid)
1721 		(void) scsi_hba_prop_update_inqstring(sd, INQUIRY_VENDOR_ID,
1722 		    vid, strlen(vid));
1723 	if (pid)
1724 		(void) scsi_hba_prop_update_inqstring(sd, INQUIRY_PRODUCT_ID,
1725 		    pid, strlen(pid));
1726 	(void) scsi_hba_prop_update_inqstring(sd, INQUIRY_REVISION_ID,
1727 	    fw, strlen(fw));
1728 
1729 	return (DDI_SUCCESS);
1730 }
1731 
1732 /*
1733  * Implementation of scsi tran_tgt_probe.
1734  * Probe target, by calling default scsi routine scsi_hba_probe()
1735  */
1736 static int
1737 sata_scsi_tgt_probe(struct scsi_device *sd, int (*callback)(void))
1738 {
1739 	sata_hba_inst_t *sata_hba_inst =
1740 	    (sata_hba_inst_t *)(sd->sd_address.a_hba_tran->tran_hba_private);
1741 	int rval;
1742 
1743 	rval = scsi_hba_probe(sd, callback);
1744 
1745 	if (rval == SCSIPROBE_EXISTS) {
1746 		/*
1747 		 * Set property "pm-capable" on the target device node, so that
1748 		 * the target driver will not try to fetch scsi cycle counters
1749 		 * before enabling device power-management.
1750 		 */
1751 		if ((ddi_prop_update_int(DDI_DEV_T_NONE, sd->sd_dev,
1752 		    "pm-capable", 1)) != DDI_PROP_SUCCESS) {
1753 			sata_log(sata_hba_inst, CE_WARN,
1754 			    "SATA device at port %d: "
1755 			    "will not be power-managed ",
1756 			    SCSI_TO_SATA_CPORT(sd->sd_address.a_target));
1757 			SATA_LOG_D((sata_hba_inst, CE_WARN,
1758 			    "failure updating pm-capable property"));
1759 		}
1760 	}
1761 	return (rval);
1762 }
1763 
1764 /*
1765  * Implementation of scsi tran_tgt_free.
1766  * Release all resources allocated for scsi_device
1767  */
1768 static void
1769 sata_scsi_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
1770     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
1771 {
1772 #ifndef __lock_lint
1773 	_NOTE(ARGUNUSED(hba_dip))
1774 #endif
1775 	sata_device_t		sata_device;
1776 	sata_drive_info_t	*sdinfo;
1777 	sata_hba_inst_t		*sata_hba_inst;
1778 	ddi_devid_t		devid;
1779 
1780 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
1781 
1782 	/* Validate scsi device address */
1783 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
1784 	    &sata_device) != 0)
1785 		return;
1786 
1787 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1788 	    sata_device.satadev_addr.cport)));
1789 
1790 	/* sata_device now should contain a valid sata address */
1791 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
1792 	if (sdinfo == NULL) {
1793 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1794 		    sata_device.satadev_addr.cport)));
1795 		return;
1796 	}
1797 	/*
1798 	 * We did not allocate any resources in sata_scsi_tgt_init()
1799 	 * other than few properties.
1800 	 * Free them.
1801 	 */
1802 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1803 	    sata_device.satadev_addr.cport)));
1804 	(void) ndi_prop_remove(DDI_DEV_T_NONE, tgt_dip, "pm-capable");
1805 
1806 	/*
1807 	 * If devid was previously created but not freed up from
1808 	 * sd(7D) driver (i.e during detach(9F)) then do it here.
1809 	 */
1810 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
1811 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
1812 	    "use-cmdk-devid-format", 0) == 1) &&
1813 	    (ddi_devid_get(tgt_dip, &devid) == DDI_SUCCESS)) {
1814 		ddi_devid_unregister(tgt_dip);
1815 		ddi_devid_free(devid);
1816 	}
1817 }
1818 
1819 /*
1820  * Implementation of scsi tran_init_pkt
1821  * Upon successful return, scsi pkt buffer has DMA resources allocated.
1822  *
1823  * It seems that we should always allocate pkt, even if the address is
1824  * for non-existing device - just use some default for dma_attr.
1825  * The reason is that there is no way to communicate this to a caller here.
1826  * Subsequent call to sata_scsi_start may fail appropriately.
1827  * Simply returning NULL does not seem to discourage a target driver...
1828  *
1829  * Returns a pointer to initialized scsi_pkt, or NULL otherwise.
1830  */
1831 static struct scsi_pkt *
1832 sata_scsi_init_pkt(struct scsi_address *ap, struct scsi_pkt *pkt,
1833     struct buf *bp, int cmdlen, int statuslen, int tgtlen, int flags,
1834     int (*callback)(caddr_t), caddr_t arg)
1835 {
1836 	sata_hba_inst_t *sata_hba_inst =
1837 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
1838 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
1839 	sata_device_t sata_device;
1840 	sata_drive_info_t *sdinfo;
1841 	sata_pkt_txlate_t *spx;
1842 	ddi_dma_attr_t cur_dma_attr;
1843 	int rval;
1844 	boolean_t new_pkt = TRUE;
1845 
1846 	ASSERT(ap->a_hba_tran->tran_hba_dip == dip);
1847 
1848 	/*
1849 	 * We need to translate the address, even if it could be
1850 	 * a bogus one, for a non-existing device
1851 	 */
1852 	sata_device.satadev_addr.qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
1853 	sata_device.satadev_addr.cport = SCSI_TO_SATA_CPORT(ap->a_target);
1854 	sata_device.satadev_addr.pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
1855 	sata_device.satadev_rev = SATA_DEVICE_REV;
1856 
1857 	if (pkt == NULL) {
1858 		/*
1859 		 * Have to allocate a brand new scsi packet.
1860 		 * We need to operate with auto request sense enabled.
1861 		 */
1862 		pkt = scsi_hba_pkt_alloc(dip, ap, cmdlen,
1863 		    MAX(statuslen, sizeof (struct scsi_arq_status)),
1864 		    tgtlen, sizeof (sata_pkt_txlate_t), callback, arg);
1865 
1866 		if (pkt == NULL)
1867 			return (NULL);
1868 
1869 		/* Fill scsi packet structure */
1870 		pkt->pkt_comp		= (void (*)())NULL;
1871 		pkt->pkt_time		= 0;
1872 		pkt->pkt_resid		= 0;
1873 		pkt->pkt_statistics	= 0;
1874 		pkt->pkt_reason		= 0;
1875 
1876 		/*
1877 		 * pkt_hba_private will point to sata pkt txlate structure
1878 		 */
1879 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
1880 		bzero(spx, sizeof (sata_pkt_txlate_t));
1881 
1882 		spx->txlt_scsi_pkt = pkt;
1883 		spx->txlt_sata_hba_inst = sata_hba_inst;
1884 
1885 		/* Allocate sata_pkt */
1886 		spx->txlt_sata_pkt = sata_pkt_alloc(spx, callback);
1887 		if (spx->txlt_sata_pkt == NULL) {
1888 			/* Could not allocate sata pkt */
1889 			scsi_hba_pkt_free(ap, pkt);
1890 			return (NULL);
1891 		}
1892 		/* Set sata address */
1893 		spx->txlt_sata_pkt->satapkt_device.satadev_addr =
1894 		    sata_device.satadev_addr;
1895 		spx->txlt_sata_pkt->satapkt_device.satadev_rev =
1896 		    sata_device.satadev_rev;
1897 
1898 		if ((bp == NULL) || (bp->b_bcount == 0))
1899 			return (pkt);
1900 
1901 		spx->txlt_total_residue = bp->b_bcount;
1902 	} else {
1903 		new_pkt = FALSE;
1904 		/*
1905 		 * Packet was preallocated/initialized by previous call
1906 		 */
1907 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
1908 
1909 		if ((bp == NULL) || (bp->b_bcount == 0)) {
1910 			return (pkt);
1911 		}
1912 		ASSERT(spx->txlt_buf_dma_handle != NULL);
1913 
1914 		/* Pkt is available already: spx->txlt_scsi_pkt == pkt; */
1915 	}
1916 
1917 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
1918 
1919 	/*
1920 	 * We use an adjusted version of the dma_attr, to account
1921 	 * for device addressing limitations.
1922 	 * sata_adjust_dma_attr() will handle sdinfo == NULL which may
1923 	 * happen when a device is not yet configured.
1924 	 */
1925 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1926 	    sata_device.satadev_addr.cport)));
1927 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
1928 	    &spx->txlt_sata_pkt->satapkt_device);
1929 	/* NULL sdinfo may be passsed to sata_adjust_dma_attr() */
1930 	sata_adjust_dma_attr(sdinfo,
1931 	    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
1932 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1933 	    sata_device.satadev_addr.cport)));
1934 	/*
1935 	 * Allocate necessary DMA resources for the packet's data buffer
1936 	 * NOTE:
1937 	 * In case of read/write commands, DMA resource allocation here is
1938 	 * based on the premise that the transfer length specified in
1939 	 * the read/write scsi cdb will match exactly DMA resources -
1940 	 * returning correct packet residue is crucial.
1941 	 */
1942 	if ((rval = sata_dma_buf_setup(spx, flags, callback, arg,
1943 	    &cur_dma_attr)) != DDI_SUCCESS) {
1944 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
1945 		sata_pkt_free(spx);
1946 		/*
1947 		 * If a DMA allocation request fails with
1948 		 * DDI_DMA_NOMAPPING, indicate the error by calling
1949 		 * bioerror(9F) with bp and an error code of EFAULT.
1950 		 * If a DMA allocation request fails with
1951 		 * DDI_DMA_TOOBIG, indicate the error by calling
1952 		 * bioerror(9F) with bp and an error code of EINVAL.
1953 		 */
1954 		switch (rval) {
1955 		case DDI_DMA_NORESOURCES:
1956 			bioerror(bp, 0);
1957 			break;
1958 		case DDI_DMA_NOMAPPING:
1959 		case DDI_DMA_BADATTR:
1960 			bioerror(bp, EFAULT);
1961 			break;
1962 		case DDI_DMA_TOOBIG:
1963 		default:
1964 			bioerror(bp, EINVAL);
1965 			break;
1966 		}
1967 		if (new_pkt == TRUE)
1968 			scsi_hba_pkt_free(ap, pkt);
1969 		return (NULL);
1970 	}
1971 	/* Set number of bytes that are not yet accounted for */
1972 	pkt->pkt_resid = spx->txlt_total_residue;
1973 	ASSERT(pkt->pkt_resid >= 0);
1974 
1975 	return (pkt);
1976 }
1977 
1978 /*
1979  * Implementation of scsi tran_start.
1980  * Translate scsi cmd into sata operation and return status.
1981  * ATAPI CDBs are passed to ATAPI devices - the device determines what commands
1982  * are supported.
1983  * For SATA hard disks, supported scsi commands:
1984  * SCMD_INQUIRY
1985  * SCMD_TEST_UNIT_READY
1986  * SCMD_START_STOP
1987  * SCMD_READ_CAPACITY
1988  * SCMD_REQUEST_SENSE
1989  * SCMD_LOG_SENSE_G1
1990  * SCMD_LOG_SELECT_G1
1991  * SCMD_MODE_SENSE	(specific pages)
1992  * SCMD_MODE_SENSE_G1	(specific pages)
1993  * SCMD_MODE_SELECT	(specific pages)
1994  * SCMD_MODE_SELECT_G1	(specific pages)
1995  * SCMD_SYNCHRONIZE_CACHE
1996  * SCMD_SYNCHRONIZE_CACHE_G1
1997  * SCMD_READ
1998  * SCMD_READ_G1
1999  * SCMD_READ_G4
2000  * SCMD_READ_G5
2001  * SCMD_WRITE
2002  * SCMD_WRITE_BUFFER
2003  * SCMD_WRITE_G1
2004  * SCMD_WRITE_G4
2005  * SCMD_WRITE_G5
2006  * SCMD_SEEK		(noop)
2007  * SCMD_SDIAG
2008  *
2009  * All other commands are rejected as unsupported.
2010  *
2011  * Returns:
2012  * TRAN_ACCEPT if command was executed successfully or accepted by HBA driver
2013  * for execution. TRAN_ACCEPT may be returned also if device was removed but
2014  * a callback could be scheduled.
2015  * TRAN_BADPKT if cmd was directed to invalid address.
2016  * TRAN_FATAL_ERROR is command was rejected due to hardware error, including
2017  * some unspecified error. TRAN_FATAL_ERROR may be also returned if a device
2018  * was removed and there was no callback specified in scsi pkt.
2019  * TRAN_BUSY if command could not be executed becasue HBA driver or SATA
2020  * framework was busy performing some other operation(s).
2021  *
2022  */
2023 static int
2024 sata_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
2025 {
2026 	sata_hba_inst_t *sata_hba_inst =
2027 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2028 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2029 	sata_drive_info_t *sdinfo;
2030 	struct buf *bp;
2031 	int cport;
2032 	int rval;
2033 
2034 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2035 	    "sata_scsi_start: cmd 0x%02x\n", pkt->pkt_cdbp[0]);
2036 
2037 	ASSERT(spx != NULL &&
2038 	    spx->txlt_scsi_pkt == pkt && spx->txlt_sata_pkt != NULL);
2039 
2040 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
2041 
2042 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2043 	sdinfo = sata_get_device_info(sata_hba_inst,
2044 	    &spx->txlt_sata_pkt->satapkt_device);
2045 	if (sdinfo == NULL ||
2046 	    SATA_CPORT_INFO(sata_hba_inst, cport)->cport_tgtnode_clean ==
2047 	    B_FALSE) {
2048 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2049 		pkt->pkt_reason = CMD_DEV_GONE;
2050 		/*
2051 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
2052 		 * only in callback function (for normal requests) and
2053 		 * in the dump code path.
2054 		 * So, if the callback is available, we need to do
2055 		 * the callback rather than returning TRAN_FATAL_ERROR here.
2056 		 */
2057 		if (pkt->pkt_comp != NULL) {
2058 			/* scsi callback required */
2059 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2060 			    (task_func_t *)pkt->pkt_comp,
2061 			    (void *)pkt, TQ_SLEEP) == NULL)
2062 				/* Scheduling the callback failed */
2063 				return (TRAN_BUSY);
2064 			return (TRAN_ACCEPT);
2065 		}
2066 		/* No callback available */
2067 		return (TRAN_FATAL_ERROR);
2068 	}
2069 
2070 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
2071 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2072 		rval = sata_txlt_atapi(spx);
2073 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2074 		    "sata_scsi_start atapi: rval %d\n", rval);
2075 		return (rval);
2076 	}
2077 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2078 
2079 	/* ATA Disk commands processing starts here */
2080 
2081 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2082 
2083 	switch (pkt->pkt_cdbp[0]) {
2084 
2085 	case SCMD_INQUIRY:
2086 		/* Mapped to identify device */
2087 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2088 			bp_mapin(bp);
2089 		rval = sata_txlt_inquiry(spx);
2090 		break;
2091 
2092 	case SCMD_TEST_UNIT_READY:
2093 		/*
2094 		 * SAT "SATA to ATA Translation" doc specifies translation
2095 		 * to ATA CHECK POWER MODE.
2096 		 */
2097 		rval = sata_txlt_test_unit_ready(spx);
2098 		break;
2099 
2100 	case SCMD_START_STOP:
2101 		/* Mapping depends on the command */
2102 		rval = sata_txlt_start_stop_unit(spx);
2103 		break;
2104 
2105 	case SCMD_READ_CAPACITY:
2106 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2107 			bp_mapin(bp);
2108 		rval = sata_txlt_read_capacity(spx);
2109 		break;
2110 
2111 	case SCMD_REQUEST_SENSE:
2112 		/*
2113 		 * Always No Sense, since we force ARQ
2114 		 */
2115 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2116 			bp_mapin(bp);
2117 		rval = sata_txlt_request_sense(spx);
2118 		break;
2119 
2120 	case SCMD_LOG_SENSE_G1:
2121 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2122 			bp_mapin(bp);
2123 		rval = sata_txlt_log_sense(spx);
2124 		break;
2125 
2126 	case SCMD_LOG_SELECT_G1:
2127 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2128 			bp_mapin(bp);
2129 		rval = sata_txlt_log_select(spx);
2130 		break;
2131 
2132 	case SCMD_MODE_SENSE:
2133 	case SCMD_MODE_SENSE_G1:
2134 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2135 			bp_mapin(bp);
2136 		rval = sata_txlt_mode_sense(spx);
2137 		break;
2138 
2139 
2140 	case SCMD_MODE_SELECT:
2141 	case SCMD_MODE_SELECT_G1:
2142 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2143 			bp_mapin(bp);
2144 		rval = sata_txlt_mode_select(spx);
2145 		break;
2146 
2147 	case SCMD_SYNCHRONIZE_CACHE:
2148 	case SCMD_SYNCHRONIZE_CACHE_G1:
2149 		rval = sata_txlt_synchronize_cache(spx);
2150 		break;
2151 
2152 	case SCMD_READ:
2153 	case SCMD_READ_G1:
2154 	case SCMD_READ_G4:
2155 	case SCMD_READ_G5:
2156 		rval = sata_txlt_read(spx);
2157 		break;
2158 	case SCMD_WRITE_BUFFER:
2159 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2160 			bp_mapin(bp);
2161 		rval = sata_txlt_write_buffer(spx);
2162 		break;
2163 
2164 	case SCMD_WRITE:
2165 	case SCMD_WRITE_G1:
2166 	case SCMD_WRITE_G4:
2167 	case SCMD_WRITE_G5:
2168 		rval = sata_txlt_write(spx);
2169 		break;
2170 
2171 	case SCMD_SEEK:
2172 		rval = sata_txlt_nodata_cmd_immediate(spx);
2173 		break;
2174 
2175 		/* Other cases will be filed later */
2176 		/* postponed until phase 2 of the development */
2177 	default:
2178 		rval = sata_txlt_invalid_command(spx);
2179 		break;
2180 	}
2181 
2182 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2183 	    "sata_scsi_start: rval %d\n", rval);
2184 
2185 	return (rval);
2186 }
2187 
2188 /*
2189  * Implementation of scsi tran_abort.
2190  * Abort specific pkt or all packets.
2191  *
2192  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2193  *
2194  * May be called from an interrupt level.
2195  */
2196 static int
2197 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2198 {
2199 	sata_hba_inst_t *sata_hba_inst =
2200 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2201 	sata_device_t	sata_device;
2202 	sata_pkt_t	*sata_pkt;
2203 
2204 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2205 	    "sata_scsi_abort: %s at target: 0x%x\n",
2206 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2207 
2208 	/* Validate address */
2209 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2210 		/* Invalid address */
2211 		return (0);
2212 
2213 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2214 	    sata_device.satadev_addr.cport)));
2215 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2216 		/* invalid address */
2217 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2218 		    sata_device.satadev_addr.cport)));
2219 		return (0);
2220 	}
2221 	if (scsi_pkt == NULL) {
2222 		/*
2223 		 * Abort all packets.
2224 		 * Although we do not have specific packet, we still need
2225 		 * dummy packet structure to pass device address to HBA.
2226 		 * Allocate one, without sleeping. Fail if pkt cannot be
2227 		 * allocated.
2228 		 */
2229 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2230 		if (sata_pkt == NULL) {
2231 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2232 			    sata_device.satadev_addr.cport)));
2233 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2234 			    "could not allocate sata_pkt"));
2235 			return (0);
2236 		}
2237 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2238 		sata_pkt->satapkt_device = sata_device;
2239 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2240 	} else {
2241 		if (scsi_pkt->pkt_ha_private == NULL) {
2242 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2243 			    sata_device.satadev_addr.cport)));
2244 			return (0); /* Bad scsi pkt */
2245 		}
2246 		/* extract pointer to sata pkt */
2247 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2248 		    txlt_sata_pkt;
2249 	}
2250 
2251 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2252 	    sata_device.satadev_addr.cport)));
2253 	/* Send abort request to HBA */
2254 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2255 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2256 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2257 	    SATA_SUCCESS) {
2258 		if (scsi_pkt == NULL)
2259 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2260 		/* Success */
2261 		return (1);
2262 	}
2263 	/* Else, something did not go right */
2264 	if (scsi_pkt == NULL)
2265 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
2266 	/* Failure */
2267 	return (0);
2268 }
2269 
2270 
2271 /*
2272  * Implementation of scsi tran_reset.
2273  * RESET_ALL request is translated into port reset.
2274  * RESET_TARGET requests is translated into a device reset,
2275  * RESET_LUN request is accepted only for LUN 0 and translated into
2276  * device reset.
2277  * The target reset should cause all HBA active and queued packets to
2278  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
2279  * the return. HBA should report reset event for the device.
2280  *
2281  * Returns 1 upon success, 0 upon failure.
2282  */
2283 static int
2284 sata_scsi_reset(struct scsi_address *ap, int level)
2285 {
2286 	sata_hba_inst_t	*sata_hba_inst =
2287 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2288 	sata_device_t	sata_device;
2289 	int		val;
2290 
2291 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2292 	    "sata_scsi_reset: level %d target: 0x%x\n",
2293 	    level, ap->a_target);
2294 
2295 	/* Validate address */
2296 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
2297 	if (val == -1)
2298 		/* Invalid address */
2299 		return (0);
2300 
2301 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2302 	    sata_device.satadev_addr.cport)));
2303 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2304 		/* invalid address */
2305 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2306 		    sata_device.satadev_addr.cport)));
2307 		return (0);
2308 	}
2309 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2310 	    sata_device.satadev_addr.cport)));
2311 	if (level == RESET_ALL) {
2312 		/* port reset - cport only */
2313 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2314 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2315 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2316 			return (1);
2317 		else
2318 			return (0);
2319 
2320 	} else if (val == 0 &&
2321 	    (level == RESET_TARGET || level == RESET_LUN)) {
2322 		/* reset device (device attached) */
2323 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2324 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2325 			return (1);
2326 		else
2327 			return (0);
2328 	}
2329 	return (0);
2330 }
2331 
2332 
2333 /*
2334  * Implementation of scsi tran_getcap (get transport/device capabilities).
2335  * Supported capabilities for SATA hard disks:
2336  * auto-rqsense		(always supported)
2337  * tagged-qing		(supported if HBA supports it)
2338  * untagged-qing	(could be supported if disk supports it, but because
2339  *			 caching behavior allowing untagged queuing actually
2340  *			 results in reduced performance.  sd tries to throttle
2341  *			 back to only 3 outstanding commands, which may
2342  *			 work for real SCSI disks, but with read ahead
2343  *			 caching, having more than 1 outstanding command
2344  *			 results in cache thrashing.)
2345  * sector_size
2346  * dma_max
2347  * interconnect-type	(INTERCONNECT_SATA)
2348  *
2349  * Supported capabilities for ATAPI devices (CD/DVD):
2350  * auto-rqsense		(always supported)
2351  * sector_size
2352  * dma_max
2353  * interconnect-type	(INTERCONNECT_SATA)
2354  *
2355  * Request for other capabilities is rejected as unsupported.
2356  *
2357  * Returns supported capability value, or -1 if capability is unsuppported or
2358  * the address is invalid - no device.
2359  */
2360 
2361 static int
2362 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
2363 {
2364 
2365 	sata_hba_inst_t 	*sata_hba_inst =
2366 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2367 	sata_device_t		sata_device;
2368 	sata_drive_info_t	*sdinfo;
2369 	ddi_dma_attr_t		adj_dma_attr;
2370 	int 			rval;
2371 
2372 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2373 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
2374 	    ap->a_target, cap);
2375 
2376 	/*
2377 	 * We want to process the capabilities on per port granularity.
2378 	 * So, we are specifically restricting ourselves to whom != 0
2379 	 * to exclude the controller wide handling.
2380 	 */
2381 	if (cap == NULL || whom == 0)
2382 		return (-1);
2383 
2384 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2385 		/* Invalid address */
2386 		return (-1);
2387 	}
2388 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2389 	    sata_device.satadev_addr.cport)));
2390 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
2391 	    NULL) {
2392 		/* invalid address */
2393 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2394 		    sata_device.satadev_addr.cport)));
2395 		return (-1);
2396 	}
2397 
2398 	switch (scsi_hba_lookup_capstr(cap)) {
2399 	case SCSI_CAP_ARQ:
2400 		rval = 1;		/* ARQ supported, turned on */
2401 		break;
2402 
2403 	case SCSI_CAP_SECTOR_SIZE:
2404 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
2405 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
2406 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
2407 			rval = SATA_ATAPI_SECTOR_SIZE;
2408 		else rval = -1;
2409 		break;
2410 
2411 	/*
2412 	 * untagged queuing cause a performance inversion because of
2413 	 * the way sd operates.  Because of this reason we do not
2414 	 * use it when available.
2415 	 */
2416 	case SCSI_CAP_UNTAGGED_QING:
2417 		if (sdinfo->satadrv_features_enabled &
2418 		    SATA_DEV_F_E_UNTAGGED_QING)
2419 			rval = 1;	/* Untagged queuing available */
2420 		else
2421 			rval = -1;	/* Untagged queuing not available */
2422 		break;
2423 
2424 	case SCSI_CAP_TAGGED_QING:
2425 		if ((sdinfo->satadrv_features_enabled &
2426 		    SATA_DEV_F_E_TAGGED_QING) &&
2427 		    (sdinfo->satadrv_max_queue_depth > 1))
2428 			rval = 1;	/* Tagged queuing available */
2429 		else
2430 			rval = -1;	/* Tagged queuing not available */
2431 		break;
2432 
2433 	case SCSI_CAP_DMA_MAX:
2434 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
2435 		    &adj_dma_attr);
2436 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
2437 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
2438 		break;
2439 
2440 	case SCSI_CAP_INTERCONNECT_TYPE:
2441 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
2442 		break;
2443 
2444 	default:
2445 		rval = -1;
2446 		break;
2447 	}
2448 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2449 	    sata_device.satadev_addr.cport)));
2450 	return (rval);
2451 }
2452 
2453 /*
2454  * Implementation of scsi tran_setcap
2455  *
2456  * Only SCSI_CAP_UNTAGGED_QING and  SCSI_CAP_TAGGED_QING are changeable.
2457  *
2458  */
2459 static int
2460 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
2461 {
2462 	sata_hba_inst_t	*sata_hba_inst =
2463 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2464 	sata_device_t	sata_device;
2465 	sata_drive_info_t	*sdinfo;
2466 	int		rval;
2467 
2468 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2469 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
2470 
2471 	/*
2472 	 * We want to process the capabilities on per port granularity.
2473 	 * So, we are specifically restricting ourselves to whom != 0
2474 	 * to exclude the controller wide handling.
2475 	 */
2476 	if (cap == NULL || whom == 0) {
2477 		return (-1);
2478 	}
2479 
2480 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2481 		/* Invalid address */
2482 		return (-1);
2483 	}
2484 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2485 	    sata_device.satadev_addr.cport)));
2486 	if ((sdinfo = sata_get_device_info(sata_hba_inst,
2487 	    &sata_device)) == NULL) {
2488 		/* invalid address */
2489 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2490 		    sata_device.satadev_addr.cport)));
2491 		return (-1);
2492 	}
2493 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2494 	    sata_device.satadev_addr.cport)));
2495 
2496 	switch (scsi_hba_lookup_capstr(cap)) {
2497 	case SCSI_CAP_ARQ:
2498 	case SCSI_CAP_SECTOR_SIZE:
2499 	case SCSI_CAP_DMA_MAX:
2500 	case SCSI_CAP_INTERCONNECT_TYPE:
2501 		rval = 0;
2502 		break;
2503 	case SCSI_CAP_UNTAGGED_QING:
2504 		if (SATA_QDEPTH(sata_hba_inst) > 1) {
2505 			rval = 1;
2506 			if (value == 1) {
2507 				sdinfo->satadrv_features_enabled |=
2508 				    SATA_DEV_F_E_UNTAGGED_QING;
2509 			} else if (value == 0) {
2510 				sdinfo->satadrv_features_enabled &=
2511 				    ~SATA_DEV_F_E_UNTAGGED_QING;
2512 			} else {
2513 				rval = -1;
2514 			}
2515 		} else {
2516 			rval = 0;
2517 		}
2518 		break;
2519 	case SCSI_CAP_TAGGED_QING:
2520 		/* This can TCQ or NCQ */
2521 		if (sata_func_enable & SATA_ENABLE_QUEUING &&
2522 		    ((sdinfo->satadrv_features_support & SATA_DEV_F_TCQ &&
2523 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_QCMD) ||
2524 		    (sata_func_enable & SATA_ENABLE_NCQ &&
2525 		    sdinfo->satadrv_features_support & SATA_DEV_F_NCQ &&
2526 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_NCQ)) &&
2527 		    (sdinfo->satadrv_max_queue_depth > 1)) {
2528 			rval = 1;
2529 			if (value == 1) {
2530 				sdinfo->satadrv_features_enabled |=
2531 				    SATA_DEV_F_E_TAGGED_QING;
2532 			} else if (value == 0) {
2533 				sdinfo->satadrv_features_enabled &=
2534 				    ~SATA_DEV_F_E_TAGGED_QING;
2535 			} else {
2536 				rval = -1;
2537 			}
2538 		} else {
2539 			rval = 0;
2540 		}
2541 		break;
2542 	default:
2543 		rval = -1;
2544 		break;
2545 	}
2546 	return (rval);
2547 }
2548 
2549 /*
2550  * Implementations of scsi tran_destroy_pkt.
2551  * Free resources allocated by sata_scsi_init_pkt()
2552  */
2553 static void
2554 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2555 {
2556 	sata_pkt_txlate_t *spx;
2557 
2558 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2559 
2560 	if (spx->txlt_buf_dma_handle != NULL) {
2561 		if (spx->txlt_tmp_buf != NULL)  {
2562 			ASSERT(spx->txlt_tmp_buf_handle != 0);
2563 			/*
2564 			 * Intermediate DMA buffer was allocated.
2565 			 * Free allocated buffer and associated access handle.
2566 			 */
2567 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
2568 			spx->txlt_tmp_buf = NULL;
2569 		}
2570 		/*
2571 		 * Free DMA resources - cookies and handles
2572 		 */
2573 		if (spx->txlt_dma_cookie_list != NULL) {
2574 			if (spx->txlt_dma_cookie_list !=
2575 			    &spx->txlt_dma_cookie) {
2576 				(void) kmem_free(spx->txlt_dma_cookie_list,
2577 				    spx->txlt_dma_cookie_list_len *
2578 				    sizeof (ddi_dma_cookie_t));
2579 				spx->txlt_dma_cookie_list = NULL;
2580 			}
2581 		}
2582 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
2583 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
2584 	}
2585 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2586 	sata_pkt_free(spx);
2587 
2588 	scsi_hba_pkt_free(ap, pkt);
2589 }
2590 
2591 /*
2592  * Implementation of scsi tran_dmafree.
2593  * Free DMA resources allocated by sata_scsi_init_pkt()
2594  */
2595 
2596 static void
2597 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
2598 {
2599 #ifndef __lock_lint
2600 	_NOTE(ARGUNUSED(ap))
2601 #endif
2602 	sata_pkt_txlate_t *spx;
2603 
2604 	ASSERT(pkt != NULL);
2605 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2606 
2607 	if (spx->txlt_buf_dma_handle != NULL) {
2608 		if (spx->txlt_tmp_buf != NULL)  {
2609 			/*
2610 			 * Intermediate DMA buffer was allocated.
2611 			 * Free allocated buffer and associated access handle.
2612 			 */
2613 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
2614 			spx->txlt_tmp_buf = NULL;
2615 		}
2616 		/*
2617 		 * Free DMA resources - cookies and handles
2618 		 */
2619 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
2620 		if (spx->txlt_dma_cookie_list != NULL) {
2621 			if (spx->txlt_dma_cookie_list !=
2622 			    &spx->txlt_dma_cookie) {
2623 				(void) kmem_free(spx->txlt_dma_cookie_list,
2624 				    spx->txlt_dma_cookie_list_len *
2625 				    sizeof (ddi_dma_cookie_t));
2626 				spx->txlt_dma_cookie_list = NULL;
2627 			}
2628 		}
2629 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
2630 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
2631 		spx->txlt_buf_dma_handle = NULL;
2632 	}
2633 }
2634 
2635 /*
2636  * Implementation of scsi tran_sync_pkt.
2637  *
2638  * The assumption below is that pkt is unique - there is no need to check ap
2639  *
2640  * Synchronize DMA buffer and, if the intermediate buffer is used, copy data
2641  * into/from the real buffer.
2642  */
2643 static void
2644 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2645 {
2646 #ifndef __lock_lint
2647 	_NOTE(ARGUNUSED(ap))
2648 #endif
2649 	int rval;
2650 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2651 	struct buf *bp;
2652 	int direction;
2653 
2654 	ASSERT(spx != NULL);
2655 	if (spx->txlt_buf_dma_handle != NULL) {
2656 		direction = spx->txlt_sata_pkt->
2657 		    satapkt_cmd.satacmd_flags.sata_data_direction;
2658 		if (spx->txlt_sata_pkt != NULL &&
2659 		    direction != SATA_DIR_NODATA_XFER) {
2660 			if (spx->txlt_tmp_buf != NULL) {
2661 				/* Intermediate DMA buffer used */
2662 				bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2663 
2664 				if (direction & SATA_DIR_WRITE) {
2665 					bcopy(bp->b_un.b_addr,
2666 					    spx->txlt_tmp_buf, bp->b_bcount);
2667 				}
2668 			}
2669 			/* Sync the buffer for device or for CPU */
2670 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle,   0, 0,
2671 			    (direction & SATA_DIR_WRITE) ?
2672 			    DDI_DMA_SYNC_FORDEV :  DDI_DMA_SYNC_FORCPU);
2673 			ASSERT(rval == DDI_SUCCESS);
2674 			if (spx->txlt_tmp_buf != NULL &&
2675 			    !(direction & SATA_DIR_WRITE)) {
2676 				/* Intermediate DMA buffer used for read */
2677 				bcopy(spx->txlt_tmp_buf,
2678 				    bp->b_un.b_addr, bp->b_bcount);
2679 			}
2680 
2681 		}
2682 	}
2683 }
2684 
2685 
2686 
2687 /* *******************  SATA - SCSI Translation functions **************** */
2688 /*
2689  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
2690  * translation.
2691  */
2692 
2693 /*
2694  * Checks if a device exists and can be access and translates common
2695  * scsi_pkt data to sata_pkt data.
2696  *
2697  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_CMPLT if device exists and
2698  * sata_pkt was set-up.
2699  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_DEV_GONE if device does not
2700  * exist and pkt_comp callback was scheduled.
2701  * Returns other TRAN_XXXXX values when error occured and command should be
2702  * rejected with the returned TRAN_XXXXX value.
2703  *
2704  * This function should be called with port mutex held.
2705  */
2706 static int
2707 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx)
2708 {
2709 	sata_drive_info_t *sdinfo;
2710 	sata_device_t sata_device;
2711 	const struct sata_cmd_flags sata_initial_cmd_flags = {
2712 		SATA_DIR_NODATA_XFER,
2713 		/* all other values to 0/FALSE */
2714 	};
2715 	/*
2716 	 * Pkt_reason has to be set if the pkt_comp callback is invoked,
2717 	 * and that implies TRAN_ACCEPT return value. Any other returned value
2718 	 * indicates that the scsi packet was not accepted (the reason will not
2719 	 * be checked by the scsi traget driver).
2720 	 * To make debugging easier, we set pkt_reason to know value here.
2721 	 * It may be changed later when different completion reason is
2722 	 * determined.
2723 	 */
2724 	spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
2725 
2726 	/* Validate address */
2727 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
2728 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
2729 
2730 	case -1:
2731 		/* Invalid address or invalid device type */
2732 		return (TRAN_BADPKT);
2733 	case 1:
2734 		/* valid address but no device - it has disappeared ? */
2735 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
2736 		/*
2737 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
2738 		 * only in callback function (for normal requests) and
2739 		 * in the dump code path.
2740 		 * So, if the callback is available, we need to do
2741 		 * the callback rather than returning TRAN_FATAL_ERROR here.
2742 		 */
2743 		if (spx->txlt_scsi_pkt->pkt_comp != NULL) {
2744 			/* scsi callback required */
2745 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2746 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2747 			    (void *)spx->txlt_scsi_pkt,
2748 			    TQ_SLEEP) == NULL)
2749 				/* Scheduling the callback failed */
2750 				return (TRAN_BUSY);
2751 
2752 			return (TRAN_ACCEPT);
2753 		}
2754 		return (TRAN_FATAL_ERROR);
2755 	default:
2756 		/* all OK */
2757 		break;
2758 	}
2759 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
2760 	    &spx->txlt_sata_pkt->satapkt_device);
2761 
2762 	/*
2763 	 * If device is in reset condition, reject the packet with
2764 	 * TRAN_BUSY, unless:
2765 	 * 1. system is panicking (dumping)
2766 	 * In such case only one thread is running and there is no way to
2767 	 * process reset.
2768 	 * 2. cfgadm operation is is progress (internal APCTL lock is set)
2769 	 * Some cfgadm operations involve drive commands, so reset condition
2770 	 * needs to be ignored for IOCTL operations.
2771 	 */
2772 	if ((sdinfo->satadrv_event_flags &
2773 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
2774 
2775 		if (!ddi_in_panic() &&
2776 		    ((SATA_CPORT_EVENT_FLAGS(spx->txlt_sata_hba_inst,
2777 		    sata_device.satadev_addr.cport) &
2778 		    SATA_APCTL_LOCK_PORT_BUSY) == 0)) {
2779 			spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
2780 			SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
2781 			    "sata_scsi_start: rejecting command because "
2782 			    "of device reset state\n", NULL);
2783 			return (TRAN_BUSY);
2784 		}
2785 	}
2786 
2787 	/*
2788 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
2789 	 * sata_scsi_pkt_init() because pkt init had to work also with
2790 	 * non-existing devices.
2791 	 * Now we know that the packet was set-up for a real device, so its
2792 	 * type is known.
2793 	 */
2794 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
2795 
2796 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
2797 	if ((SATA_CPORT_INFO(spx->txlt_sata_hba_inst,
2798 	    sata_device.satadev_addr.cport)->cport_event_flags &
2799 	    SATA_APCTL_LOCK_PORT_BUSY) != 0) {
2800 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
2801 		    sata_ignore_dev_reset = B_TRUE;
2802 	}
2803 	/*
2804 	 * At this point the generic translation routine determined that the
2805 	 * scsi packet should be accepted. Packet completion reason may be
2806 	 * changed later when a different completion reason is determined.
2807 	 */
2808 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
2809 
2810 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
2811 		/* Synchronous execution */
2812 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
2813 		    SATA_OPMODE_POLLING;
2814 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
2815 		    sata_ignore_dev_reset = ddi_in_panic();
2816 	} else {
2817 		/* Asynchronous execution */
2818 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
2819 		    SATA_OPMODE_INTERRUPTS;
2820 	}
2821 	/* Convert queuing information */
2822 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
2823 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
2824 		    B_TRUE;
2825 	else if (spx->txlt_scsi_pkt->pkt_flags &
2826 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
2827 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
2828 		    B_TRUE;
2829 
2830 	/* Always limit pkt time */
2831 	if (spx->txlt_scsi_pkt->pkt_time == 0)
2832 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
2833 	else
2834 		/* Pass on scsi_pkt time */
2835 		spx->txlt_sata_pkt->satapkt_time =
2836 		    spx->txlt_scsi_pkt->pkt_time;
2837 
2838 	return (TRAN_ACCEPT);
2839 }
2840 
2841 
2842 /*
2843  * Translate ATA Identify Device data to SCSI Inquiry data.
2844  * This function may be called only for ATA devices.
2845  * This function should not be called for ATAPI devices - they
2846  * respond directly to SCSI Inquiry command.
2847  *
2848  * SATA Identify Device data has to be valid in sata_rive_info.
2849  * Buffer has to accomodate the inquiry length (36 bytes).
2850  *
2851  * This function should be called with a port mutex held.
2852  */
2853 static	void
2854 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
2855     sata_drive_info_t *sdinfo, uint8_t *buf)
2856 {
2857 
2858 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
2859 	struct sata_id *sid = &sdinfo->satadrv_id;
2860 
2861 	/* Start with a nice clean slate */
2862 	bzero((void *)inq, sizeof (struct scsi_inquiry));
2863 
2864 	/*
2865 	 * Rely on the dev_type for setting paripheral qualifier.
2866 	 * Assume that  DTYPE_RODIRECT applies to CD/DVD R/W devices.
2867 	 * It could be that DTYPE_OPTICAL could also qualify in the future.
2868 	 * ATAPI Inquiry may provide more data to the target driver.
2869 	 */
2870 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
2871 	    DTYPE_DIRECT : DTYPE_RODIRECT; /* DTYPE_UNKNOWN; */
2872 
2873 	inq->inq_rmb = sid->ai_config & SATA_REM_MEDIA ? 1 : 0;
2874 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
2875 	inq->inq_iso = 0;	/* ISO version */
2876 	inq->inq_ecma = 0;	/* ECMA version */
2877 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
2878 	inq->inq_aenc = 0;	/* Async event notification cap. */
2879 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg - NO */
2880 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
2881 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
2882 	inq->inq_len = 31;	/* Additional length */
2883 	inq->inq_dualp = 0;	/* dual port device - NO */
2884 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
2885 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
2886 	inq->inq_linked = 0;	/* Supports linked commands - NO */
2887 				/*
2888 				 * Queuing support - controller has to
2889 				 * support some sort of command queuing.
2890 				 */
2891 	if (SATA_QDEPTH(sata_hba_inst) > 1)
2892 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
2893 	else
2894 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
2895 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
2896 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
2897 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
2898 
2899 #ifdef	_LITTLE_ENDIAN
2900 	/* Swap text fields to match SCSI format */
2901 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
2902 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
2903 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
2904 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
2905 	else
2906 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
2907 #else	/* _LITTLE_ENDIAN */
2908 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
2909 	bcopy(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
2910 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
2911 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
2912 	else
2913 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
2914 #endif	/* _LITTLE_ENDIAN */
2915 }
2916 
2917 
2918 /*
2919  * Scsi response set up for invalid command (command not supported)
2920  *
2921  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
2922  */
2923 static int
2924 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
2925 {
2926 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
2927 	struct scsi_extended_sense *sense;
2928 
2929 	scsipkt->pkt_reason = CMD_CMPLT;
2930 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
2931 	    STATE_SENT_CMD | STATE_GOT_STATUS;
2932 
2933 	*scsipkt->pkt_scbp = STATUS_CHECK;
2934 
2935 	sense = sata_arq_sense(spx);
2936 	sense->es_key = KEY_ILLEGAL_REQUEST;
2937 	sense->es_add_code = SD_SCSI_ASC_INVALID_COMMAND_CODE;
2938 
2939 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
2940 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
2941 
2942 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
2943 	    scsipkt->pkt_comp != NULL)
2944 		/* scsi callback required */
2945 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2946 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2947 		    (void *)spx->txlt_scsi_pkt,
2948 		    TQ_SLEEP) == NULL)
2949 			/* Scheduling the callback failed */
2950 			return (TRAN_BUSY);
2951 	return (TRAN_ACCEPT);
2952 }
2953 
2954 /*
2955  * Scsi response setup for
2956  * emulated non-data command that requires no action/return data
2957  *
2958  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
2959  */
2960 static 	int
2961 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
2962 {
2963 	int rval;
2964 
2965 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
2966 
2967 	if (((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) ||
2968 	    (spx->txlt_scsi_pkt->pkt_reason == CMD_DEV_GONE)) {
2969 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
2970 		return (rval);
2971 	}
2972 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
2973 
2974 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
2975 	    STATE_SENT_CMD | STATE_GOT_STATUS;
2976 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
2977 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
2978 
2979 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
2980 	    "Scsi_pkt completion reason %x\n",
2981 	    spx->txlt_scsi_pkt->pkt_reason);
2982 
2983 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
2984 	    spx->txlt_scsi_pkt->pkt_comp != NULL)
2985 		/* scsi callback required */
2986 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2987 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2988 		    (void *)spx->txlt_scsi_pkt,
2989 		    TQ_SLEEP) == NULL)
2990 			/* Scheduling the callback failed */
2991 			return (TRAN_BUSY);
2992 	return (TRAN_ACCEPT);
2993 }
2994 
2995 
2996 /*
2997  * SATA translate command: Inquiry / Identify Device
2998  * Use cached Identify Device data for now, rather than issuing actual
2999  * Device Identify cmd request. If device is detached and re-attached,
3000  * asynchromous event processing should fetch and refresh Identify Device
3001  * data.
3002  * Two VPD pages are supported now:
3003  * Vital Product Data page
3004  * Unit Serial Number page
3005  *
3006  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3007  */
3008 
3009 #define	EVPD			1	/* Extended Vital Product Data flag */
3010 #define	CMDDT			2	/* Command Support Data - Obsolete */
3011 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VDP Pages Page COde */
3012 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3013 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3014 
3015 static int
3016 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3017 {
3018 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3019 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3020 	sata_drive_info_t *sdinfo;
3021 	struct scsi_extended_sense *sense;
3022 	int count;
3023 	uint8_t *p;
3024 	int i, j;
3025 	uint8_t page_buf[0xff]; /* Max length */
3026 	int rval;
3027 
3028 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3029 
3030 	if (((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) ||
3031 	    (spx->txlt_scsi_pkt->pkt_reason == CMD_DEV_GONE)) {
3032 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3033 		return (rval);
3034 	}
3035 
3036 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3037 	    &spx->txlt_sata_pkt->satapkt_device);
3038 
3039 	ASSERT(sdinfo != NULL);
3040 
3041 	scsipkt->pkt_reason = CMD_CMPLT;
3042 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3043 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3044 
3045 	/* Reject not supported request */
3046 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3047 		*scsipkt->pkt_scbp = STATUS_CHECK;
3048 		sense = sata_arq_sense(spx);
3049 		sense->es_key = KEY_ILLEGAL_REQUEST;
3050 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3051 		goto done;
3052 	}
3053 
3054 	/* Valid Inquiry request */
3055 	*scsipkt->pkt_scbp = STATUS_GOOD;
3056 
3057 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3058 
3059 		/*
3060 		 * Because it is fully emulated command storing data
3061 		 * programatically in the specified buffer, release
3062 		 * preallocated DMA resources before storing data in the buffer,
3063 		 * so no unwanted DMA sync would take place.
3064 		 */
3065 		sata_scsi_dmafree(NULL, scsipkt);
3066 
3067 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3068 			/* Standard Inquiry Data request */
3069 			struct scsi_inquiry inq;
3070 			unsigned int bufsize;
3071 
3072 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3073 			    sdinfo, (uint8_t *)&inq);
3074 			/* Copy no more than requested */
3075 			count = MIN(bp->b_bcount,
3076 			    sizeof (struct scsi_inquiry));
3077 			bufsize = scsipkt->pkt_cdbp[4];
3078 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3079 			count = MIN(count, bufsize);
3080 			bcopy(&inq, bp->b_un.b_addr, count);
3081 
3082 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3083 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3084 			    bufsize - count : 0;
3085 		} else {
3086 			/*
3087 			 * peripheral_qualifier = 0;
3088 			 *
3089 			 * We are dealing only with HD and will be
3090 			 * dealing with CD/DVD devices soon
3091 			 */
3092 			uint8_t peripheral_device_type =
3093 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3094 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3095 
3096 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3097 			case INQUIRY_SUP_VPD_PAGE:
3098 				/*
3099 				 * Request for suported Vital Product Data
3100 				 * pages - assuming only 2 page codes
3101 				 * supported
3102 				 */
3103 				page_buf[0] = peripheral_device_type;
3104 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3105 				page_buf[2] = 0;
3106 				page_buf[3] = 2; /* page length */
3107 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3108 				page_buf[5] = INQUIRY_USN_PAGE;
3109 				/* Copy no more than requested */
3110 				count = MIN(bp->b_bcount, 6);
3111 				bcopy(page_buf, bp->b_un.b_addr, count);
3112 				break;
3113 			case INQUIRY_USN_PAGE:
3114 				/*
3115 				 * Request for Unit Serial Number page
3116 				 */
3117 				page_buf[0] = peripheral_device_type;
3118 				page_buf[1] = INQUIRY_USN_PAGE;
3119 				page_buf[2] = 0;
3120 				page_buf[3] = 20; /* remaining page length */
3121 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3122 #ifdef	_LITTLE_ENDIAN
3123 				swab(p, &page_buf[4], 20);
3124 #else
3125 				bcopy(p, &page_buf[4], 20);
3126 #endif
3127 				for (i = 0; i < 20; i++) {
3128 					if (page_buf[4 + i] == '\0' ||
3129 					    page_buf[4 + i] == '\040') {
3130 						break;
3131 					}
3132 				}
3133 				/*
3134 				 * 'i' contains string length.
3135 				 *
3136 				 * Least significant character of the serial
3137 				 * number shall appear as the last byte,
3138 				 * according to SBC-3 spec.
3139 				 */
3140 				p = &page_buf[20 + 4 - 1];
3141 				for (j = i; j > 0; j--, p--) {
3142 					*p = *(p - 20 + i);
3143 				}
3144 				p = &page_buf[4];
3145 				for (j = 20 - i; j > 0; j--) {
3146 					*p++ = '\040';
3147 				}
3148 				count = MIN(bp->b_bcount, 24);
3149 				bcopy(page_buf, bp->b_un.b_addr, count);
3150 				break;
3151 
3152 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3153 				/*
3154 				 * We may want to implement this page, when
3155 				 * identifiers are common for SATA devices
3156 				 * But not now.
3157 				 */
3158 				/*FALLTHROUGH*/
3159 
3160 			default:
3161 				/* Request for unsupported VPD page */
3162 				*scsipkt->pkt_scbp = STATUS_CHECK;
3163 				sense = sata_arq_sense(spx);
3164 				sense->es_key = KEY_ILLEGAL_REQUEST;
3165 				sense->es_add_code =
3166 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3167 				goto done;
3168 			}
3169 		}
3170 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3171 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3172 		    scsipkt->pkt_cdbp[4] - count : 0;
3173 	}
3174 done:
3175 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3176 
3177 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3178 	    "Scsi_pkt completion reason %x\n",
3179 	    scsipkt->pkt_reason);
3180 
3181 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3182 	    scsipkt->pkt_comp != NULL) {
3183 		/* scsi callback required */
3184 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3185 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3186 		    TQ_SLEEP) == NULL)
3187 			/* Scheduling the callback failed */
3188 			return (TRAN_BUSY);
3189 	}
3190 	return (TRAN_ACCEPT);
3191 }
3192 
3193 /*
3194  * SATA translate command: Request Sense.
3195  * Emulated command (ATA version for SATA hard disks)
3196  * Always NO SENSE, because any sense data should be reported by ARQ sense.
3197  *
3198  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3199  */
3200 static int
3201 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3202 {
3203 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3204 	struct scsi_extended_sense sense;
3205 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3206 	int rval;
3207 
3208 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3209 
3210 	if (((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) ||
3211 	    (spx->txlt_scsi_pkt->pkt_reason == CMD_DEV_GONE)) {
3212 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3213 		return (rval);
3214 	}
3215 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3216 
3217 
3218 	scsipkt->pkt_reason = CMD_CMPLT;
3219 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3220 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3221 	*scsipkt->pkt_scbp = STATUS_GOOD;
3222 
3223 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3224 		/*
3225 		 * Because it is fully emulated command storing data
3226 		 * programatically in the specified buffer, release
3227 		 * preallocated DMA resources before storing data in the buffer,
3228 		 * so no unwanted DMA sync would take place.
3229 		 */
3230 		int count = MIN(bp->b_bcount,
3231 		    sizeof (struct scsi_extended_sense));
3232 		sata_scsi_dmafree(NULL, scsipkt);
3233 		bzero(&sense, sizeof (struct scsi_extended_sense));
3234 		sense.es_valid = 0;	/* Valid LBA */
3235 		sense.es_class = 7;	/* Response code 0x70 - current err */
3236 		sense.es_key = KEY_NO_SENSE;
3237 		sense.es_add_len = 6;	/* Additional length */
3238 		/* Copy no more than requested */
3239 		bcopy(&sense, bp->b_un.b_addr, count);
3240 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3241 		scsipkt->pkt_resid = 0;
3242 	}
3243 
3244 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3245 	    "Scsi_pkt completion reason %x\n",
3246 	    scsipkt->pkt_reason);
3247 
3248 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3249 	    scsipkt->pkt_comp != NULL)
3250 		/* scsi callback required */
3251 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3252 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3253 		    TQ_SLEEP) == NULL)
3254 			/* Scheduling the callback failed */
3255 			return (TRAN_BUSY);
3256 	return (TRAN_ACCEPT);
3257 }
3258 
3259 /*
3260  * SATA translate command: Test Unit Ready
3261  * At the moment this is an emulated command (ATA version for SATA hard disks).
3262  * May be translated into Check Power Mode command in the future
3263  *
3264  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3265  */
3266 static int
3267 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3268 {
3269 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3270 	struct scsi_extended_sense *sense;
3271 	int power_state;
3272 	int rval;
3273 
3274 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3275 
3276 	if (((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) ||
3277 	    (spx->txlt_scsi_pkt->pkt_reason == CMD_DEV_GONE)) {
3278 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3279 		return (rval);
3280 	}
3281 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3282 
3283 	/* At this moment, emulate it rather than execute anything */
3284 	power_state = SATA_PWRMODE_ACTIVE;
3285 
3286 	scsipkt->pkt_reason = CMD_CMPLT;
3287 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3288 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3289 
3290 	switch (power_state) {
3291 	case SATA_PWRMODE_ACTIVE:
3292 	case SATA_PWRMODE_IDLE:
3293 		*scsipkt->pkt_scbp = STATUS_GOOD;
3294 		break;
3295 	default:
3296 		/* PWR mode standby */
3297 		*scsipkt->pkt_scbp = STATUS_CHECK;
3298 		sense = sata_arq_sense(spx);
3299 		sense->es_key = KEY_NOT_READY;
3300 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
3301 		break;
3302 	}
3303 
3304 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3305 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3306 
3307 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3308 	    scsipkt->pkt_comp != NULL)
3309 		/* scsi callback required */
3310 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3311 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3312 		    TQ_SLEEP) == NULL)
3313 			/* Scheduling the callback failed */
3314 			return (TRAN_BUSY);
3315 
3316 	return (TRAN_ACCEPT);
3317 }
3318 
3319 
3320 /*
3321  * SATA translate command: Start Stop Unit
3322  * Translation depends on a command:
3323  *	Start Unit translated into Idle Immediate
3324  *	Stop Unit translated into Standby Immediate
3325  *	Unload Media / NOT SUPPORTED YET
3326  *	Load Media / NOT SUPPROTED YET
3327  * Power condition bits are ignored, so is Immediate bit
3328  * Requesting synchronous execution.
3329  *
3330  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
3331  * appropriate values in scsi_pkt fields.
3332  */
3333 static int
3334 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
3335 {
3336 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3337 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3338 	struct scsi_extended_sense *sense;
3339 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3340 	int cport = SATA_TXLT_CPORT(spx);
3341 	int rval;
3342 	int synch;
3343 
3344 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3345 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
3346 
3347 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3348 
3349 	if (((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) ||
3350 	    (spx->txlt_scsi_pkt->pkt_reason == CMD_DEV_GONE)) {
3351 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3352 		return (rval);
3353 	}
3354 
3355 	if (scsipkt->pkt_cdbp[4] & 2) {
3356 		/* Load/Unload Media - invalid request */
3357 		*scsipkt->pkt_scbp = STATUS_CHECK;
3358 		sense = sata_arq_sense(spx);
3359 		sense->es_key = KEY_ILLEGAL_REQUEST;
3360 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3361 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3362 
3363 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3364 		    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3365 
3366 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3367 		    scsipkt->pkt_comp != NULL)
3368 			/* scsi callback required */
3369 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3370 			    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3371 			    TQ_SLEEP) == NULL)
3372 				/* Scheduling the callback failed */
3373 				return (TRAN_BUSY);
3374 
3375 		return (TRAN_ACCEPT);
3376 	}
3377 	scmd->satacmd_addr_type = 0;
3378 	scmd->satacmd_sec_count_lsb = 0;
3379 	scmd->satacmd_lba_low_lsb = 0;
3380 	scmd->satacmd_lba_mid_lsb = 0;
3381 	scmd->satacmd_lba_high_lsb = 0;
3382 	scmd->satacmd_features_reg = 0;
3383 	scmd->satacmd_device_reg = 0;
3384 	scmd->satacmd_status_reg = 0;
3385 	if (scsipkt->pkt_cdbp[4] & 1) {
3386 		/* Start Unit */
3387 		scmd->satacmd_cmd_reg = SATAC_IDLE_IM;
3388 	} else {
3389 		/* Stop Unit */
3390 		scmd->satacmd_cmd_reg = SATAC_STANDBY_IM;
3391 	}
3392 
3393 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
3394 		/* Need to set-up a callback function */
3395 		spx->txlt_sata_pkt->satapkt_comp =
3396 		    sata_txlt_nodata_cmd_completion;
3397 		synch = FALSE;
3398 	} else {
3399 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
3400 		synch = TRUE;
3401 	}
3402 
3403 	/* Transfer command to HBA */
3404 	if (sata_hba_start(spx, &rval) != 0) {
3405 		/* Pkt not accepted for execution */
3406 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3407 		return (rval);
3408 	}
3409 
3410 	/*
3411 	 * If execution is non-synchronous,
3412 	 * a callback function will handle potential errors, translate
3413 	 * the response and will do a callback to a target driver.
3414 	 * If it was synchronous, check execution status using the same
3415 	 * framework callback.
3416 	 */
3417 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3418 	if (synch) {
3419 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3420 		    "synchronous execution status %x\n",
3421 		    spx->txlt_sata_pkt->satapkt_reason);
3422 
3423 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
3424 	}
3425 	return (TRAN_ACCEPT);
3426 
3427 }
3428 
3429 
3430 /*
3431  * SATA translate command:  Read Capacity.
3432  * Emulated command for SATA disks.
3433  * Capacity is retrieved from cached Idenifty Device data.
3434  * Identify Device data shows effective disk capacity, not the native
3435  * capacity, which may be limitted by Set Max Address command.
3436  * This is ATA version for SATA hard disks.
3437  *
3438  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3439  */
3440 static int
3441 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
3442 {
3443 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3444 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3445 	sata_drive_info_t *sdinfo;
3446 	uint64_t val;
3447 	uchar_t *rbuf;
3448 	int rval;
3449 
3450 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3451 	    "sata_txlt_read_capacity: ", NULL);
3452 
3453 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3454 
3455 	if (((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) ||
3456 	    (spx->txlt_scsi_pkt->pkt_reason == CMD_DEV_GONE)) {
3457 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3458 		return (rval);
3459 	}
3460 
3461 	scsipkt->pkt_reason = CMD_CMPLT;
3462 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3463 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3464 	*scsipkt->pkt_scbp = STATUS_GOOD;
3465 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3466 		/*
3467 		 * Because it is fully emulated command storing data
3468 		 * programatically in the specified buffer, release
3469 		 * preallocated DMA resources before storing data in the buffer,
3470 		 * so no unwanted DMA sync would take place.
3471 		 */
3472 		sata_scsi_dmafree(NULL, scsipkt);
3473 
3474 		sdinfo = sata_get_device_info(
3475 		    spx->txlt_sata_hba_inst,
3476 		    &spx->txlt_sata_pkt->satapkt_device);
3477 		/* Last logical block address */
3478 		val = sdinfo->satadrv_capacity - 1;
3479 		rbuf = (uchar_t *)bp->b_un.b_addr;
3480 		/* Need to swap endians to match scsi format */
3481 		rbuf[0] = (val >> 24) & 0xff;
3482 		rbuf[1] = (val >> 16) & 0xff;
3483 		rbuf[2] = (val >> 8) & 0xff;
3484 		rbuf[3] = val & 0xff;
3485 		/* block size - always 512 bytes, for now */
3486 		rbuf[4] = 0;
3487 		rbuf[5] = 0;
3488 		rbuf[6] = 0x02;
3489 		rbuf[7] = 0;
3490 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3491 		scsipkt->pkt_resid = 0;
3492 
3493 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
3494 		    sdinfo->satadrv_capacity -1);
3495 	}
3496 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3497 	/*
3498 	 * If a callback was requested, do it now.
3499 	 */
3500 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3501 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3502 
3503 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3504 	    scsipkt->pkt_comp != NULL)
3505 		/* scsi callback required */
3506 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3507 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3508 		    TQ_SLEEP) == NULL)
3509 			/* Scheduling the callback failed */
3510 			return (TRAN_BUSY);
3511 
3512 	return (TRAN_ACCEPT);
3513 }
3514 
3515 /*
3516  * SATA translate command: Mode Sense.
3517  * Translated into appropriate SATA command or emulated.
3518  * Saved Values Page Control (03) are not supported.
3519  *
3520  * NOTE: only caching mode sense page is currently implemented.
3521  *
3522  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3523  */
3524 
3525 static int
3526 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
3527 {
3528 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
3529 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3530 	sata_drive_info_t *sdinfo;
3531 	sata_id_t *sata_id;
3532 	struct scsi_extended_sense *sense;
3533 	int 		len, bdlen, count, alc_len;
3534 	int		pc;	/* Page Control code */
3535 	uint8_t		*buf;	/* mode sense buffer */
3536 	int		rval;
3537 
3538 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3539 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
3540 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
3541 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
3542 
3543 	buf = kmem_zalloc(1024, KM_SLEEP);
3544 
3545 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3546 
3547 	if (((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) ||
3548 	    (spx->txlt_scsi_pkt->pkt_reason == CMD_DEV_GONE)) {
3549 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3550 		kmem_free(buf, 1024);
3551 		return (rval);
3552 	}
3553 
3554 	scsipkt->pkt_reason = CMD_CMPLT;
3555 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3556 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3557 
3558 	pc = scsipkt->pkt_cdbp[2] >> 6;
3559 
3560 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3561 		/*
3562 		 * Because it is fully emulated command storing data
3563 		 * programatically in the specified buffer, release
3564 		 * preallocated DMA resources before storing data in the buffer,
3565 		 * so no unwanted DMA sync would take place.
3566 		 */
3567 		sata_scsi_dmafree(NULL, scsipkt);
3568 
3569 		len = 0;
3570 		bdlen = 0;
3571 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
3572 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
3573 			    (scsipkt->pkt_cdbp[0] & 0x10))
3574 				bdlen = 16;
3575 			else
3576 				bdlen = 8;
3577 		}
3578 		/* Build mode parameter header */
3579 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
3580 			/* 4-byte mode parameter header */
3581 			buf[len++] = 0;   	/* mode data length */
3582 			buf[len++] = 0;		/* medium type */
3583 			buf[len++] = 0;		/* dev-specific param */
3584 			buf[len++] = bdlen;	/* Block Descriptor length */
3585 		} else {
3586 			/* 8-byte mode parameter header */
3587 			buf[len++] = 0;		/* mode data length */
3588 			buf[len++] = 0;
3589 			buf[len++] = 0;		/* medium type */
3590 			buf[len++] = 0;		/* dev-specific param */
3591 			if (bdlen == 16)
3592 				buf[len++] = 1;	/* long lba descriptor */
3593 			else
3594 				buf[len++] = 0;
3595 			buf[len++] = 0;
3596 			buf[len++] = 0;		/* Block Descriptor length */
3597 			buf[len++] = bdlen;
3598 		}
3599 
3600 		sdinfo = sata_get_device_info(
3601 		    spx->txlt_sata_hba_inst,
3602 		    &spx->txlt_sata_pkt->satapkt_device);
3603 
3604 		/* Build block descriptor only if not disabled (DBD) */
3605 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
3606 			/* Block descriptor - direct-access device format */
3607 			if (bdlen == 8) {
3608 				/* build regular block descriptor */
3609 				buf[len++] =
3610 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
3611 				buf[len++] =
3612 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
3613 				buf[len++] =
3614 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
3615 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
3616 				buf[len++] = 0; /* density code */
3617 				buf[len++] = 0;
3618 				if (sdinfo->satadrv_type ==
3619 				    SATA_DTYPE_ATADISK)
3620 					buf[len++] = 2;
3621 				else
3622 					/* ATAPI */
3623 					buf[len++] = 8;
3624 				buf[len++] = 0;
3625 			} else if (bdlen == 16) {
3626 				/* Long LBA Accepted */
3627 				/* build long lba block descriptor */
3628 #ifndef __lock_lint
3629 				buf[len++] =
3630 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
3631 				buf[len++] =
3632 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
3633 				buf[len++] =
3634 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
3635 				buf[len++] =
3636 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
3637 #endif
3638 				buf[len++] =
3639 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
3640 				buf[len++] =
3641 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
3642 				buf[len++] =
3643 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
3644 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
3645 				buf[len++] = 0;
3646 				buf[len++] = 0; /* density code */
3647 				buf[len++] = 0;
3648 				buf[len++] = 0;
3649 				if (sdinfo->satadrv_type ==
3650 				    SATA_DTYPE_ATADISK)
3651 					buf[len++] = 2;
3652 				else
3653 					/* ATAPI */
3654 					buf[len++] = 8;
3655 				buf[len++] = 0;
3656 			}
3657 		}
3658 
3659 		sata_id = &sdinfo->satadrv_id;
3660 
3661 		/*
3662 		 * Add requested pages.
3663 		 * Page 3 and 4 are obsolete and we are not supporting them.
3664 		 * We deal now with:
3665 		 * caching (read/write cache control).
3666 		 * We should eventually deal with following mode pages:
3667 		 * error recovery  (0x01),
3668 		 * power condition (0x1a),
3669 		 * exception control page (enables SMART) (0x1c),
3670 		 * enclosure management (ses),
3671 		 * protocol-specific port mode (port control).
3672 		 */
3673 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
3674 		case MODEPAGE_RW_ERRRECOV:
3675 			/* DAD_MODE_ERR_RECOV */
3676 			/* R/W recovery */
3677 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
3678 			break;
3679 		case MODEPAGE_CACHING:
3680 			/* DAD_MODE_CACHE */
3681 			/* Reject not supported request for saved parameters */
3682 			if (pc == 3) {
3683 				*scsipkt->pkt_scbp = STATUS_CHECK;
3684 				sense = sata_arq_sense(spx);
3685 				sense->es_key = KEY_ILLEGAL_REQUEST;
3686 				sense->es_add_code =
3687 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
3688 				goto done;
3689 			}
3690 
3691 			/* caching */
3692 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
3693 			break;
3694 		case MODEPAGE_INFO_EXCPT:
3695 			/* exception cntrl */
3696 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
3697 				len += sata_build_msense_page_1c(sdinfo, pc,
3698 				    buf+len);
3699 			}
3700 			else
3701 				goto err;
3702 			break;
3703 		case MODEPAGE_POWER_COND:
3704 			/* DAD_MODE_POWER_COND */
3705 			/* power condition */
3706 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
3707 			break;
3708 
3709 		case MODEPAGE_ACOUSTIC_MANAG:
3710 			/* acoustic management */
3711 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
3712 			break;
3713 		case MODEPAGE_ALLPAGES:
3714 			/* all pages */
3715 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
3716 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
3717 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
3718 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
3719 				len += sata_build_msense_page_1c(sdinfo, pc,
3720 				    buf+len);
3721 			}
3722 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
3723 			break;
3724 		default:
3725 		err:
3726 			/* Invalid request */
3727 			*scsipkt->pkt_scbp = STATUS_CHECK;
3728 			sense = sata_arq_sense(spx);
3729 			sense->es_key = KEY_ILLEGAL_REQUEST;
3730 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3731 			goto done;
3732 		}
3733 
3734 		/* fix total mode data length */
3735 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
3736 			/* 4-byte mode parameter header */
3737 			buf[0] = len - 1;   	/* mode data length */
3738 		} else {
3739 			buf[0] = (len -2) >> 8;
3740 			buf[1] = (len -2) & 0xff;
3741 		}
3742 
3743 
3744 		/* Check allocation length */
3745 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
3746 			alc_len = scsipkt->pkt_cdbp[4];
3747 		} else {
3748 			alc_len = scsipkt->pkt_cdbp[7];
3749 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
3750 		}
3751 		/*
3752 		 * We do not check for possible parameters truncation
3753 		 * (alc_len < len) assuming that the target driver works
3754 		 * correctly. Just avoiding overrun.
3755 		 * Copy no more than requested and possible, buffer-wise.
3756 		 */
3757 		count = MIN(alc_len, len);
3758 		count = MIN(bp->b_bcount, count);
3759 		bcopy(buf, bp->b_un.b_addr, count);
3760 
3761 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3762 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
3763 	}
3764 	*scsipkt->pkt_scbp = STATUS_GOOD;
3765 done:
3766 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3767 	(void) kmem_free(buf, 1024);
3768 
3769 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3770 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3771 
3772 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3773 	    scsipkt->pkt_comp != NULL)
3774 		/* scsi callback required */
3775 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3776 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3777 		    TQ_SLEEP) == NULL)
3778 			/* Scheduling the callback failed */
3779 			return (TRAN_BUSY);
3780 
3781 	return (TRAN_ACCEPT);
3782 }
3783 
3784 
3785 /*
3786  * SATA translate command: Mode Select.
3787  * Translated into appropriate SATA command or emulated.
3788  * Saving parameters is not supported.
3789  * Changing device capacity is not supported (although theoretically
3790  * possible by executing SET FEATURES/SET MAX ADDRESS)
3791  *
3792  * Assumption is that the target driver is working correctly.
3793  *
3794  * More than one SATA command may be executed to perform operations specified
3795  * by mode select pages. The first error terminates further execution.
3796  * Operations performed successully are not backed-up in such case.
3797  *
3798  * NOTE: only caching mode select page is implemented.
3799  * Caching setup is remembered so it could be re-stored in case of
3800  * an unexpected device reset.
3801  *
3802  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3803  */
3804 
3805 static int
3806 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
3807 {
3808 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3809 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3810 	struct scsi_extended_sense *sense;
3811 	int len, pagelen, count, pllen;
3812 	uint8_t *buf;	/* mode select buffer */
3813 	int rval, stat;
3814 	uint_t nointr_flag;
3815 	int dmod = 0;
3816 
3817 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3818 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
3819 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
3820 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
3821 
3822 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3823 
3824 	if (((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) ||
3825 	    (spx->txlt_scsi_pkt->pkt_reason == CMD_DEV_GONE)) {
3826 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3827 		return (rval);
3828 	}
3829 
3830 	rval = TRAN_ACCEPT;
3831 
3832 	scsipkt->pkt_reason = CMD_CMPLT;
3833 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3834 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3835 
3836 	/* Reject not supported request */
3837 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
3838 		*scsipkt->pkt_scbp = STATUS_CHECK;
3839 		sense = sata_arq_sense(spx);
3840 		sense->es_key = KEY_ILLEGAL_REQUEST;
3841 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3842 		goto done;
3843 	}
3844 
3845 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
3846 		pllen = scsipkt->pkt_cdbp[4];
3847 	} else {
3848 		pllen = scsipkt->pkt_cdbp[7];
3849 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
3850 	}
3851 
3852 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
3853 
3854 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
3855 		buf = (uint8_t *)bp->b_un.b_addr;
3856 		count = MIN(bp->b_bcount, pllen);
3857 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3858 		scsipkt->pkt_resid = 0;
3859 		pllen = count;
3860 
3861 		/*
3862 		 * Check the header to skip the block descriptor(s) - we
3863 		 * do not support setting device capacity.
3864 		 * Existing macros do not recognize long LBA dscriptor,
3865 		 * hence manual calculation.
3866 		 */
3867 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
3868 			/* 6-bytes CMD, 4 bytes header */
3869 			if (count <= 4)
3870 				goto done;		/* header only */
3871 			len = buf[3] + 4;
3872 		} else {
3873 			/* 10-bytes CMD, 8 bytes header */
3874 			if (count <= 8)
3875 				goto done;		/* header only */
3876 			len = buf[6];
3877 			len = (len << 8) + buf[7] + 8;
3878 		}
3879 		if (len >= count)
3880 			goto done;	/* header + descriptor(s) only */
3881 
3882 		pllen -= len;		/* remaining data length */
3883 
3884 		/*
3885 		 * We may be executing SATA command and want to execute it
3886 		 * in SYNCH mode, regardless of scsi_pkt setting.
3887 		 * Save scsi_pkt setting and indicate SYNCH mode
3888 		 */
3889 		nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
3890 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3891 		    scsipkt->pkt_comp != NULL) {
3892 			scsipkt->pkt_flags |= FLAG_NOINTR;
3893 		}
3894 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
3895 
3896 		/*
3897 		 * len is now the offset to a first mode select page
3898 		 * Process all pages
3899 		 */
3900 		while (pllen > 0) {
3901 			switch ((int)buf[len]) {
3902 			case MODEPAGE_CACHING:
3903 				/* No support for SP (saving) */
3904 				if (scsipkt->pkt_cdbp[1] & 0x01) {
3905 					*scsipkt->pkt_scbp = STATUS_CHECK;
3906 					sense = sata_arq_sense(spx);
3907 					sense->es_key = KEY_ILLEGAL_REQUEST;
3908 					sense->es_add_code =
3909 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3910 					goto done;
3911 				}
3912 				stat = sata_mode_select_page_8(spx,
3913 				    (struct mode_cache_scsi3 *)&buf[len],
3914 				    pllen, &pagelen, &rval, &dmod);
3915 				/*
3916 				 * The pagelen value indicates the number of
3917 				 * parameter bytes already processed.
3918 				 * The rval is the return value from
3919 				 * sata_tran_start().
3920 				 * The stat indicates the overall status of
3921 				 * the operation(s).
3922 				 */
3923 				if (stat != SATA_SUCCESS)
3924 					/*
3925 					 * Page processing did not succeed -
3926 					 * all error info is already set-up,
3927 					 * just return
3928 					 */
3929 					pllen = 0; /* this breaks the loop */
3930 				else {
3931 					len += pagelen;
3932 					pllen -= pagelen;
3933 				}
3934 				break;
3935 
3936 			case MODEPAGE_INFO_EXCPT:
3937 				stat = sata_mode_select_page_1c(spx,
3938 				    (struct mode_info_excpt_page *)&buf[len],
3939 				    pllen, &pagelen, &rval, &dmod);
3940 				/*
3941 				 * The pagelen value indicates the number of
3942 				 * parameter bytes already processed.
3943 				 * The rval is the return value from
3944 				 * sata_tran_start().
3945 				 * The stat indicates the overall status of
3946 				 * the operation(s).
3947 				 */
3948 				if (stat != SATA_SUCCESS)
3949 					/*
3950 					 * Page processing did not succeed -
3951 					 * all error info is already set-up,
3952 					 * just return
3953 					 */
3954 					pllen = 0; /* this breaks the loop */
3955 				else {
3956 					len += pagelen;
3957 					pllen -= pagelen;
3958 				}
3959 				break;
3960 
3961 			case MODEPAGE_ACOUSTIC_MANAG:
3962 				stat = sata_mode_select_page_30(spx,
3963 				    (struct mode_acoustic_management *)
3964 				    &buf[len], pllen, &pagelen, &rval, &dmod);
3965 				/*
3966 				 * The pagelen value indicates the number of
3967 				 * parameter bytes already processed.
3968 				 * The rval is the return value from
3969 				 * sata_tran_start().
3970 				 * The stat indicates the overall status of
3971 				 * the operation(s).
3972 				 */
3973 				if (stat != SATA_SUCCESS)
3974 					/*
3975 					 * Page processing did not succeed -
3976 					 * all error info is already set-up,
3977 					 * just return
3978 					 */
3979 					pllen = 0; /* this breaks the loop */
3980 				else {
3981 					len += pagelen;
3982 					pllen -= pagelen;
3983 				}
3984 
3985 				break;
3986 			default:
3987 				*scsipkt->pkt_scbp = STATUS_CHECK;
3988 				sense = sata_arq_sense(spx);
3989 				sense->es_key = KEY_ILLEGAL_REQUEST;
3990 				sense->es_add_code =
3991 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
3992 				goto done;
3993 			}
3994 		}
3995 	}
3996 done:
3997 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3998 	/*
3999 	 * If device parameters were modified, fetch and store the new
4000 	 * Identify Device data. Since port mutex could have been released
4001 	 * for accessing HBA driver, we need to re-check device existence.
4002 	 */
4003 	if (dmod != 0) {
4004 		sata_drive_info_t new_sdinfo, *sdinfo;
4005 		int rv = 0;
4006 
4007 		/*
4008 		 * Following statement has to be changed if this function is
4009 		 * used for devices other than SATA hard disks.
4010 		 */
4011 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
4012 
4013 		new_sdinfo.satadrv_addr =
4014 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
4015 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
4016 		    &new_sdinfo);
4017 
4018 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4019 		/*
4020 		 * Since port mutex could have been released when
4021 		 * accessing HBA driver, we need to re-check that the
4022 		 * framework still holds the device info structure.
4023 		 */
4024 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4025 		    &spx->txlt_sata_pkt->satapkt_device);
4026 		if (sdinfo != NULL) {
4027 			/*
4028 			 * Device still has info structure in the
4029 			 * sata framework. Copy newly fetched info
4030 			 */
4031 			if (rv == 0) {
4032 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
4033 				sata_save_drive_settings(sdinfo);
4034 			} else {
4035 				/*
4036 				 * Could not fetch new data - invalidate
4037 				 * sata_drive_info. That makes device
4038 				 * unusable.
4039 				 */
4040 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
4041 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
4042 			}
4043 		}
4044 		if (rv != 0 || sdinfo == NULL) {
4045 			/*
4046 			 * This changes the overall mode select completion
4047 			 * reason to a failed one !!!!!
4048 			 */
4049 			*scsipkt->pkt_scbp = STATUS_CHECK;
4050 			sense = sata_arq_sense(spx);
4051 			scsipkt->pkt_reason = CMD_INCOMPLETE;
4052 			rval = TRAN_ACCEPT;
4053 		}
4054 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4055 	}
4056 	/* Restore the scsi pkt flags */
4057 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
4058 	scsipkt->pkt_flags |= nointr_flag;
4059 
4060 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4061 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4062 
4063 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4064 	    scsipkt->pkt_comp != NULL)
4065 		/* scsi callback required */
4066 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4067 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4068 		    TQ_SLEEP) == NULL)
4069 			/* Scheduling the callback failed */
4070 			return (TRAN_BUSY);
4071 
4072 	return (rval);
4073 }
4074 
4075 
4076 
4077 /*
4078  * Translate command: Log Sense
4079  */
4080 static 	int
4081 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
4082 {
4083 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4084 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4085 	sata_drive_info_t *sdinfo;
4086 	struct scsi_extended_sense *sense;
4087 	int 		len, count, alc_len;
4088 	int		pc;	/* Page Control code */
4089 	int		page_code;	/* Page code */
4090 	uint8_t		*buf;	/* log sense buffer */
4091 	int		rval;
4092 #define	MAX_LOG_SENSE_PAGE_SIZE	512
4093 
4094 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4095 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
4096 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4097 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4098 
4099 	buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
4100 
4101 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4102 
4103 	if (((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) ||
4104 	    (spx->txlt_scsi_pkt->pkt_reason == CMD_DEV_GONE)) {
4105 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4106 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4107 		return (rval);
4108 	}
4109 
4110 	scsipkt->pkt_reason = CMD_CMPLT;
4111 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4112 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4113 
4114 	pc = scsipkt->pkt_cdbp[2] >> 6;
4115 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
4116 
4117 	/* Reject not supported request for all but cumulative values */
4118 	switch (pc) {
4119 	case PC_CUMULATIVE_VALUES:
4120 		break;
4121 	default:
4122 		*scsipkt->pkt_scbp = STATUS_CHECK;
4123 		sense = sata_arq_sense(spx);
4124 		sense->es_key = KEY_ILLEGAL_REQUEST;
4125 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4126 		goto done;
4127 	}
4128 
4129 	switch (page_code) {
4130 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
4131 	case PAGE_CODE_SELF_TEST_RESULTS:
4132 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
4133 	case PAGE_CODE_SMART_READ_DATA:
4134 		break;
4135 	default:
4136 		*scsipkt->pkt_scbp = STATUS_CHECK;
4137 		sense = sata_arq_sense(spx);
4138 		sense->es_key = KEY_ILLEGAL_REQUEST;
4139 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4140 		goto done;
4141 	}
4142 
4143 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4144 		/*
4145 		 * Because log sense uses local buffers for data retrieval from
4146 		 * the devices and sets the data programatically in the
4147 		 * original specified buffer, release preallocated DMA
4148 		 * resources before storing data in the original buffer,
4149 		 * so no unwanted DMA sync would take place.
4150 		 */
4151 		sata_id_t *sata_id;
4152 
4153 		sata_scsi_dmafree(NULL, scsipkt);
4154 
4155 		len = 0;
4156 
4157 		/* Build log parameter header */
4158 		buf[len++] = page_code;	/* page code as in the CDB */
4159 		buf[len++] = 0;		/* reserved */
4160 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
4161 		buf[len++] = 0;		/* (LSB) */
4162 
4163 		sdinfo = sata_get_device_info(
4164 		    spx->txlt_sata_hba_inst,
4165 		    &spx->txlt_sata_pkt->satapkt_device);
4166 
4167 
4168 		/*
4169 		 * Add requested pages.
4170 		 */
4171 		switch (page_code) {
4172 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
4173 			len = sata_build_lsense_page_0(sdinfo, buf + len);
4174 			break;
4175 		case PAGE_CODE_SELF_TEST_RESULTS:
4176 			sata_id = &sdinfo->satadrv_id;
4177 			if ((! (sata_id->ai_cmdset84 &
4178 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
4179 			    (! (sata_id->ai_features87 &
4180 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
4181 				*scsipkt->pkt_scbp = STATUS_CHECK;
4182 				sense = sata_arq_sense(spx);
4183 				sense->es_key = KEY_ILLEGAL_REQUEST;
4184 				sense->es_add_code =
4185 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4186 
4187 				goto done;
4188 			}
4189 			len = sata_build_lsense_page_10(sdinfo, buf + len,
4190 			    spx->txlt_sata_hba_inst);
4191 			break;
4192 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
4193 			sata_id = &sdinfo->satadrv_id;
4194 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
4195 				*scsipkt->pkt_scbp = STATUS_CHECK;
4196 				sense = sata_arq_sense(spx);
4197 				sense->es_key = KEY_ILLEGAL_REQUEST;
4198 				sense->es_add_code =
4199 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4200 
4201 				goto done;
4202 			}
4203 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
4204 				*scsipkt->pkt_scbp = STATUS_CHECK;
4205 				sense = sata_arq_sense(spx);
4206 				sense->es_key = KEY_ABORTED_COMMAND;
4207 				sense->es_add_code =
4208 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
4209 				sense->es_qual_code =
4210 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
4211 
4212 				goto done;
4213 			}
4214 
4215 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
4216 			    spx->txlt_sata_hba_inst);
4217 			break;
4218 		case PAGE_CODE_SMART_READ_DATA:
4219 			sata_id = &sdinfo->satadrv_id;
4220 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
4221 				*scsipkt->pkt_scbp = STATUS_CHECK;
4222 				sense = sata_arq_sense(spx);
4223 				sense->es_key = KEY_ILLEGAL_REQUEST;
4224 				sense->es_add_code =
4225 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4226 
4227 				goto done;
4228 			}
4229 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
4230 				*scsipkt->pkt_scbp = STATUS_CHECK;
4231 				sense = sata_arq_sense(spx);
4232 				sense->es_key = KEY_ABORTED_COMMAND;
4233 				sense->es_add_code =
4234 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
4235 				sense->es_qual_code =
4236 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
4237 
4238 				goto done;
4239 			}
4240 
4241 			/* This page doesn't include a page header */
4242 			len = sata_build_lsense_page_30(sdinfo, buf,
4243 			    spx->txlt_sata_hba_inst);
4244 			goto no_header;
4245 		default:
4246 			/* Invalid request */
4247 			*scsipkt->pkt_scbp = STATUS_CHECK;
4248 			sense = sata_arq_sense(spx);
4249 			sense->es_key = KEY_ILLEGAL_REQUEST;
4250 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4251 			goto done;
4252 		}
4253 
4254 		/* set parameter log sense data length */
4255 		buf[2] = len >> 8;	/* log sense length (MSB) */
4256 		buf[3] = len & 0xff;	/* log sense length (LSB) */
4257 
4258 		len += SCSI_LOG_PAGE_HDR_LEN;
4259 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
4260 
4261 no_header:
4262 		/* Check allocation length */
4263 		alc_len = scsipkt->pkt_cdbp[7];
4264 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4265 
4266 		/*
4267 		 * We do not check for possible parameters truncation
4268 		 * (alc_len < len) assuming that the target driver works
4269 		 * correctly. Just avoiding overrun.
4270 		 * Copy no more than requested and possible, buffer-wise.
4271 		 */
4272 		count = MIN(alc_len, len);
4273 		count = MIN(bp->b_bcount, count);
4274 		bcopy(buf, bp->b_un.b_addr, count);
4275 
4276 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4277 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4278 	}
4279 	*scsipkt->pkt_scbp = STATUS_GOOD;
4280 done:
4281 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4282 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4283 
4284 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4285 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4286 
4287 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4288 	    scsipkt->pkt_comp != NULL)
4289 		/* scsi callback required */
4290 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4291 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4292 		    TQ_SLEEP) == NULL)
4293 			/* Scheduling the callback failed */
4294 			return (TRAN_BUSY);
4295 
4296 	return (TRAN_ACCEPT);
4297 }
4298 
4299 /*
4300  * Translate command: Log Select
4301  * Not implemented at this time - returns invalid command response.
4302  */
4303 static 	int
4304 sata_txlt_log_select(sata_pkt_txlate_t *spx)
4305 {
4306 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4307 	    "sata_txlt_log_select\n", NULL);
4308 
4309 	return (sata_txlt_invalid_command(spx));
4310 }
4311 
4312 
4313 /*
4314  * Translate command: Read (various types).
4315  * Translated into appropriate type of ATA READ command
4316  * for SATA hard disks.
4317  * Both the device capabilities and requested operation mode are
4318  * considered.
4319  *
4320  * Following scsi cdb fields are ignored:
4321  * rdprotect, dpo, fua, fua_nv, group_number.
4322  *
4323  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
4324  * enable variable sata_func_enable), the capability of the controller and
4325  * capability of a device are checked and if both support queueing, read
4326  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
4327  * command rather than plain READ_XXX command.
4328  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
4329  * both the controller and device suport such functionality, the read
4330  * request will be translated to READ_FPDMA_QUEUED command.
4331  * In both cases the maximum queue depth is derived as minimum of:
4332  * HBA capability,device capability and sata_max_queue_depth variable setting.
4333  * The value passed to HBA driver is decremented by 1, because only 5 bits are
4334  * used to pass max queue depth value, and the maximum possible queue depth
4335  * is 32.
4336  *
4337  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4338  * appropriate values in scsi_pkt fields.
4339  */
4340 static int
4341 sata_txlt_read(sata_pkt_txlate_t *spx)
4342 {
4343 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4344 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4345 	sata_drive_info_t *sdinfo;
4346 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
4347 	int cport = SATA_TXLT_CPORT(spx);
4348 	uint16_t sec_count;
4349 	uint64_t lba;
4350 	int rval;
4351 	int synch;
4352 
4353 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4354 
4355 	if (((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) ||
4356 	    (spx->txlt_scsi_pkt->pkt_reason == CMD_DEV_GONE)) {
4357 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4358 		return (rval);
4359 	}
4360 
4361 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4362 	    &spx->txlt_sata_pkt->satapkt_device);
4363 
4364 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
4365 	/*
4366 	 * Extract LBA and sector count from scsi CDB.
4367 	 */
4368 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
4369 	case SCMD_READ:
4370 		/* 6-byte scsi read cmd : 0x08 */
4371 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
4372 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
4373 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4374 		sec_count = scsipkt->pkt_cdbp[4];
4375 		/* sec_count 0 will be interpreted as 256 by a device */
4376 		break;
4377 	case SCMD_READ_G1:
4378 		/* 10-bytes scsi read command : 0x28 */
4379 		lba = scsipkt->pkt_cdbp[2];
4380 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4381 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4382 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4383 		sec_count = scsipkt->pkt_cdbp[7];
4384 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4385 		break;
4386 	case SCMD_READ_G5:
4387 		/* 12-bytes scsi read command : 0xA8 */
4388 		lba = scsipkt->pkt_cdbp[2];
4389 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4390 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4391 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4392 		sec_count = scsipkt->pkt_cdbp[6];
4393 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
4394 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4395 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
4396 		break;
4397 	case SCMD_READ_G4:
4398 		/* 16-bytes scsi read command : 0x88 */
4399 		lba = scsipkt->pkt_cdbp[2];
4400 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4401 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4402 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4403 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
4404 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
4405 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
4406 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
4407 		sec_count = scsipkt->pkt_cdbp[10];
4408 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
4409 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
4410 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
4411 		break;
4412 	default:
4413 		/* Unsupported command */
4414 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4415 		return (sata_txlt_invalid_command(spx));
4416 	}
4417 
4418 	/*
4419 	 * Check if specified address exceeds device capacity
4420 	 */
4421 	if ((lba >= sdinfo->satadrv_capacity) ||
4422 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
4423 		/* LBA out of range */
4424 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4425 		return (sata_txlt_lba_out_of_range(spx));
4426 	}
4427 
4428 	/*
4429 	 * For zero-length transfer, emulate good completion of the command
4430 	 * (reasons for rejecting the command were already checked).
4431 	 * No DMA resources were allocated.
4432 	 */
4433 	if (spx->txlt_dma_cookie_list == NULL) {
4434 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4435 		return (sata_emul_rw_completion(spx));
4436 	}
4437 
4438 	/*
4439 	 * Build cmd block depending on the device capability and
4440 	 * requested operation mode.
4441 	 * Do not bother with non-dma mode - we are working only with
4442 	 * devices supporting DMA.
4443 	 */
4444 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
4445 	scmd->satacmd_device_reg = SATA_ADH_LBA;
4446 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
4447 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
4448 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
4449 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
4450 		scmd->satacmd_sec_count_msb = sec_count >> 8;
4451 #ifndef __lock_lint
4452 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
4453 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
4454 		scmd->satacmd_lba_high_msb = lba >> 40;
4455 #endif
4456 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
4457 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
4458 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
4459 	}
4460 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
4461 	scmd->satacmd_lba_low_lsb = lba & 0xff;
4462 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
4463 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
4464 	scmd->satacmd_features_reg = 0;
4465 	scmd->satacmd_status_reg = 0;
4466 	scmd->satacmd_error_reg = 0;
4467 
4468 	/*
4469 	 * Check if queueing commands should be used and switch
4470 	 * to appropriate command if possible
4471 	 */
4472 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
4473 		boolean_t using_queuing;
4474 
4475 		/* Queuing supported by controller and device? */
4476 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
4477 		    (sdinfo->satadrv_features_support &
4478 		    SATA_DEV_F_NCQ) &&
4479 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4480 		    SATA_CTLF_NCQ)) {
4481 			using_queuing = B_TRUE;
4482 
4483 			/* NCQ supported - use FPDMA READ */
4484 			scmd->satacmd_cmd_reg =
4485 			    SATAC_READ_FPDMA_QUEUED;
4486 			scmd->satacmd_features_reg_ext =
4487 			    scmd->satacmd_sec_count_msb;
4488 			scmd->satacmd_sec_count_msb = 0;
4489 		} else if ((sdinfo->satadrv_features_support &
4490 		    SATA_DEV_F_TCQ) &&
4491 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4492 		    SATA_CTLF_QCMD)) {
4493 			using_queuing = B_TRUE;
4494 
4495 			/* Legacy queueing */
4496 			if (sdinfo->satadrv_features_support &
4497 			    SATA_DEV_F_LBA48) {
4498 				scmd->satacmd_cmd_reg =
4499 				    SATAC_READ_DMA_QUEUED_EXT;
4500 				scmd->satacmd_features_reg_ext =
4501 				    scmd->satacmd_sec_count_msb;
4502 				scmd->satacmd_sec_count_msb = 0;
4503 			} else {
4504 				scmd->satacmd_cmd_reg =
4505 				    SATAC_READ_DMA_QUEUED;
4506 			}
4507 		} else	/* NCQ nor legacy queuing not supported */
4508 			using_queuing = B_FALSE;
4509 
4510 		/*
4511 		 * If queuing, the sector count goes in the features register
4512 		 * and the secount count will contain the tag.
4513 		 */
4514 		if (using_queuing) {
4515 			scmd->satacmd_features_reg =
4516 			    scmd->satacmd_sec_count_lsb;
4517 			scmd->satacmd_sec_count_lsb = 0;
4518 			scmd->satacmd_flags.sata_queued = B_TRUE;
4519 
4520 			/* Set-up maximum queue depth */
4521 			scmd->satacmd_flags.sata_max_queue_depth =
4522 			    sdinfo->satadrv_max_queue_depth - 1;
4523 		} else if (sdinfo->satadrv_features_enabled &
4524 		    SATA_DEV_F_E_UNTAGGED_QING) {
4525 			/*
4526 			 * Although NCQ/TCQ is not enabled, untagged queuing
4527 			 * may be still used.
4528 			 * Set-up the maximum untagged queue depth.
4529 			 * Use controller's queue depth from sata_hba_tran.
4530 			 * SATA HBA drivers may ignore this value and rely on
4531 			 * the internal limits.For drivers that do not
4532 			 * ignore untaged queue depth, limit the value to
4533 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
4534 			 * largest value that can be passed via
4535 			 * satacmd_flags.sata_max_queue_depth.
4536 			 */
4537 			scmd->satacmd_flags.sata_max_queue_depth =
4538 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
4539 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
4540 
4541 		} else {
4542 			scmd->satacmd_flags.sata_max_queue_depth = 0;
4543 		}
4544 	} else
4545 		scmd->satacmd_flags.sata_max_queue_depth = 0;
4546 
4547 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
4548 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
4549 	    scmd->satacmd_cmd_reg, lba, sec_count);
4550 
4551 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
4552 		/* Need callback function */
4553 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
4554 		synch = FALSE;
4555 	} else
4556 		synch = TRUE;
4557 
4558 	/* Transfer command to HBA */
4559 	if (sata_hba_start(spx, &rval) != 0) {
4560 		/* Pkt not accepted for execution */
4561 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4562 		return (rval);
4563 	}
4564 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4565 	/*
4566 	 * If execution is non-synchronous,
4567 	 * a callback function will handle potential errors, translate
4568 	 * the response and will do a callback to a target driver.
4569 	 * If it was synchronous, check execution status using the same
4570 	 * framework callback.
4571 	 */
4572 	if (synch) {
4573 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4574 		    "synchronous execution status %x\n",
4575 		    spx->txlt_sata_pkt->satapkt_reason);
4576 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
4577 	}
4578 	return (TRAN_ACCEPT);
4579 }
4580 
4581 
4582 /*
4583  * SATA translate command: Write (various types)
4584  * Translated into appropriate type of ATA WRITE command
4585  * for SATA hard disks.
4586  * Both the device capabilities and requested operation mode are
4587  * considered.
4588  *
4589  * Following scsi cdb fields are ignored:
4590  * rwprotect, dpo, fua, fua_nv, group_number.
4591  *
4592  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
4593  * enable variable sata_func_enable), the capability of the controller and
4594  * capability of a device are checked and if both support queueing, write
4595  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
4596  * command rather than plain WRITE_XXX command.
4597  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
4598  * both the controller and device suport such functionality, the write
4599  * request will be translated to WRITE_FPDMA_QUEUED command.
4600  * In both cases the maximum queue depth is derived as minimum of:
4601  * HBA capability,device capability and sata_max_queue_depth variable setting.
4602  * The value passed to HBA driver is decremented by 1, because only 5 bits are
4603  * used to pass max queue depth value, and the maximum possible queue depth
4604  * is 32.
4605  *
4606  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4607  * appropriate values in scsi_pkt fields.
4608  */
4609 static int
4610 sata_txlt_write(sata_pkt_txlate_t *spx)
4611 {
4612 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4613 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4614 	sata_drive_info_t *sdinfo;
4615 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
4616 	int cport = SATA_TXLT_CPORT(spx);
4617 	uint16_t sec_count;
4618 	uint64_t lba;
4619 	int rval;
4620 	int synch;
4621 
4622 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4623 
4624 	if (((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) ||
4625 	    (spx->txlt_scsi_pkt->pkt_reason == CMD_DEV_GONE)) {
4626 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4627 		return (rval);
4628 	}
4629 
4630 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4631 	    &spx->txlt_sata_pkt->satapkt_device);
4632 
4633 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
4634 	/*
4635 	 * Extract LBA and sector count from scsi CDB
4636 	 */
4637 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
4638 	case SCMD_WRITE:
4639 		/* 6-byte scsi read cmd : 0x0A */
4640 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
4641 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
4642 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4643 		sec_count = scsipkt->pkt_cdbp[4];
4644 		/* sec_count 0 will be interpreted as 256 by a device */
4645 		break;
4646 	case SCMD_WRITE_G1:
4647 		/* 10-bytes scsi write command : 0x2A */
4648 		lba = scsipkt->pkt_cdbp[2];
4649 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4650 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4651 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4652 		sec_count = scsipkt->pkt_cdbp[7];
4653 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4654 		break;
4655 	case SCMD_WRITE_G5:
4656 		/* 12-bytes scsi read command : 0xAA */
4657 		lba = scsipkt->pkt_cdbp[2];
4658 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4659 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4660 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4661 		sec_count = scsipkt->pkt_cdbp[6];
4662 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
4663 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4664 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
4665 		break;
4666 	case SCMD_WRITE_G4:
4667 		/* 16-bytes scsi write command : 0x8A */
4668 		lba = scsipkt->pkt_cdbp[2];
4669 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4670 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4671 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4672 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
4673 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
4674 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
4675 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
4676 		sec_count = scsipkt->pkt_cdbp[10];
4677 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
4678 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
4679 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
4680 		break;
4681 	default:
4682 		/* Unsupported command */
4683 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4684 		return (sata_txlt_invalid_command(spx));
4685 	}
4686 
4687 	/*
4688 	 * Check if specified address and length exceeds device capacity
4689 	 */
4690 	if ((lba >= sdinfo->satadrv_capacity) ||
4691 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
4692 		/* LBA out of range */
4693 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4694 		return (sata_txlt_lba_out_of_range(spx));
4695 	}
4696 
4697 	/*
4698 	 * For zero-length transfer, emulate good completion of the command
4699 	 * (reasons for rejecting the command were already checked).
4700 	 * No DMA resources were allocated.
4701 	 */
4702 	if (spx->txlt_dma_cookie_list == NULL) {
4703 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4704 		return (sata_emul_rw_completion(spx));
4705 	}
4706 
4707 	/*
4708 	 * Build cmd block depending on the device capability and
4709 	 * requested operation mode.
4710 	 * Do not bother with non-dma mode- we are working only with
4711 	 * devices supporting DMA.
4712 	 */
4713 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
4714 	scmd->satacmd_device_reg = SATA_ADH_LBA;
4715 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
4716 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
4717 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
4718 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
4719 		scmd->satacmd_sec_count_msb = sec_count >> 8;
4720 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
4721 #ifndef __lock_lint
4722 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
4723 		scmd->satacmd_lba_high_msb = lba >> 40;
4724 #endif
4725 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
4726 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
4727 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
4728 	}
4729 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
4730 	scmd->satacmd_lba_low_lsb = lba & 0xff;
4731 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
4732 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
4733 	scmd->satacmd_features_reg = 0;
4734 	scmd->satacmd_status_reg = 0;
4735 	scmd->satacmd_error_reg = 0;
4736 
4737 	/*
4738 	 * Check if queueing commands should be used and switch
4739 	 * to appropriate command if possible
4740 	 */
4741 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
4742 		boolean_t using_queuing;
4743 
4744 		/* Queuing supported by controller and device? */
4745 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
4746 		    (sdinfo->satadrv_features_support &
4747 		    SATA_DEV_F_NCQ) &&
4748 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4749 		    SATA_CTLF_NCQ)) {
4750 			using_queuing = B_TRUE;
4751 
4752 			/* NCQ supported - use FPDMA WRITE */
4753 			scmd->satacmd_cmd_reg =
4754 			    SATAC_WRITE_FPDMA_QUEUED;
4755 			scmd->satacmd_features_reg_ext =
4756 			    scmd->satacmd_sec_count_msb;
4757 			scmd->satacmd_sec_count_msb = 0;
4758 		} else if ((sdinfo->satadrv_features_support &
4759 		    SATA_DEV_F_TCQ) &&
4760 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4761 		    SATA_CTLF_QCMD)) {
4762 			using_queuing = B_TRUE;
4763 
4764 			/* Legacy queueing */
4765 			if (sdinfo->satadrv_features_support &
4766 			    SATA_DEV_F_LBA48) {
4767 				scmd->satacmd_cmd_reg =
4768 				    SATAC_WRITE_DMA_QUEUED_EXT;
4769 				scmd->satacmd_features_reg_ext =
4770 				    scmd->satacmd_sec_count_msb;
4771 				scmd->satacmd_sec_count_msb = 0;
4772 			} else {
4773 				scmd->satacmd_cmd_reg =
4774 				    SATAC_WRITE_DMA_QUEUED;
4775 			}
4776 		} else	/*  NCQ nor legacy queuing not supported */
4777 			using_queuing = B_FALSE;
4778 
4779 		if (using_queuing) {
4780 			scmd->satacmd_features_reg =
4781 			    scmd->satacmd_sec_count_lsb;
4782 			scmd->satacmd_sec_count_lsb = 0;
4783 			scmd->satacmd_flags.sata_queued = B_TRUE;
4784 			/* Set-up maximum queue depth */
4785 			scmd->satacmd_flags.sata_max_queue_depth =
4786 			    sdinfo->satadrv_max_queue_depth - 1;
4787 		} else if (sdinfo->satadrv_features_enabled &
4788 		    SATA_DEV_F_E_UNTAGGED_QING) {
4789 			/*
4790 			 * Although NCQ/TCQ is not enabled, untagged queuing
4791 			 * may be still used.
4792 			 * Set-up the maximum untagged queue depth.
4793 			 * Use controller's queue depth from sata_hba_tran.
4794 			 * SATA HBA drivers may ignore this value and rely on
4795 			 * the internal limits. For drivera that do not
4796 			 * ignore untaged queue depth, limit the value to
4797 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
4798 			 * largest value that can be passed via
4799 			 * satacmd_flags.sata_max_queue_depth.
4800 			 */
4801 			scmd->satacmd_flags.sata_max_queue_depth =
4802 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
4803 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
4804 
4805 		} else {
4806 			scmd->satacmd_flags.sata_max_queue_depth = 0;
4807 		}
4808 	} else
4809 		scmd->satacmd_flags.sata_max_queue_depth = 0;
4810 
4811 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4812 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
4813 	    scmd->satacmd_cmd_reg, lba, sec_count);
4814 
4815 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
4816 		/* Need callback function */
4817 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
4818 		synch = FALSE;
4819 	} else
4820 		synch = TRUE;
4821 
4822 	/* Transfer command to HBA */
4823 	if (sata_hba_start(spx, &rval) != 0) {
4824 		/* Pkt not accepted for execution */
4825 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4826 		return (rval);
4827 	}
4828 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4829 
4830 	/*
4831 	 * If execution is non-synchronous,
4832 	 * a callback function will handle potential errors, translate
4833 	 * the response and will do a callback to a target driver.
4834 	 * If it was synchronous, check execution status using the same
4835 	 * framework callback.
4836 	 */
4837 	if (synch) {
4838 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4839 		    "synchronous execution status %x\n",
4840 		    spx->txlt_sata_pkt->satapkt_reason);
4841 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
4842 	}
4843 	return (TRAN_ACCEPT);
4844 }
4845 
4846 
4847 /*
4848  * Implements SCSI SBC WRITE BUFFER command download microcode option
4849  */
4850 static int
4851 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
4852 {
4853 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
4854 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
4855 
4856 	sata_hba_inst_t *sata_hba_inst = SATA_TXLT_HBA_INST(spx);
4857 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4858 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
4859 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4860 
4861 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4862 	struct scsi_extended_sense *sense;
4863 	int rval, mode, sector_count;
4864 	int cport = SATA_TXLT_CPORT(spx);
4865 
4866 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
4867 
4868 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4869 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
4870 
4871 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4872 
4873 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
4874 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4875 		return (rval);
4876 	}
4877 
4878 	/* Use synchronous mode */
4879 	spx->txlt_sata_pkt->satapkt_op_mode
4880 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
4881 
4882 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
4883 
4884 	scsipkt->pkt_reason = CMD_CMPLT;
4885 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4886 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4887 
4888 	/*
4889 	 * The SCSI to ATA translation specification only calls
4890 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
4891 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
4892 	 * ATA 8 (draft) got rid of download microcode for temp
4893 	 * and it is even optional for ATA 7, so it may be aborted.
4894 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
4895 	 * it is not specified and the buffer offset for SCSI is a 16-bit
4896 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
4897 	 * sectors.  Thus the offset really doesn't buy us anything.
4898 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
4899 	 * is revised, this can be revisisted.
4900 	 */
4901 	/* Reject not supported request */
4902 	switch (mode) {
4903 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
4904 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
4905 		break;
4906 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
4907 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
4908 		break;
4909 	default:
4910 		goto bad_param;
4911 	}
4912 
4913 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
4914 
4915 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
4916 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
4917 		goto bad_param;
4918 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
4919 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
4920 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
4921 	scmd->satacmd_lba_mid_lsb = 0;
4922 	scmd->satacmd_lba_high_lsb = 0;
4923 	scmd->satacmd_device_reg = 0;
4924 	spx->txlt_sata_pkt->satapkt_comp = NULL;
4925 	scmd->satacmd_addr_type = 0;
4926 
4927 	/* Transfer command to HBA */
4928 	if (sata_hba_start(spx, &rval) != 0) {
4929 		/* Pkt not accepted for execution */
4930 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
4931 		return (rval);
4932 	}
4933 
4934 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
4935 
4936 	/* Then we need synchronous check the status of the disk */
4937 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4938 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
4939 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
4940 		scsipkt->pkt_reason = CMD_CMPLT;
4941 
4942 		/* Download commmand succeed, so probe and identify device */
4943 		sata_reidentify_device(spx);
4944 	} else {
4945 		/* Something went wrong, microcode download command failed */
4946 		scsipkt->pkt_reason = CMD_INCOMPLETE;
4947 		*scsipkt->pkt_scbp = STATUS_CHECK;
4948 		sense = sata_arq_sense(spx);
4949 		switch (sata_pkt->satapkt_reason) {
4950 		case SATA_PKT_PORT_ERROR:
4951 			/*
4952 			 * We have no device data. Assume no data transfered.
4953 			 */
4954 			sense->es_key = KEY_HARDWARE_ERROR;
4955 			break;
4956 
4957 		case SATA_PKT_DEV_ERROR:
4958 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
4959 			    SATA_STATUS_ERR) {
4960 				/*
4961 				 * determine dev error reason from error
4962 				 * reg content
4963 				 */
4964 				sata_decode_device_error(spx, sense);
4965 				break;
4966 			}
4967 			/* No extended sense key - no info available */
4968 			break;
4969 
4970 		case SATA_PKT_TIMEOUT:
4971 			scsipkt->pkt_reason = CMD_TIMEOUT;
4972 			scsipkt->pkt_statistics |=
4973 			    STAT_TIMEOUT | STAT_DEV_RESET;
4974 			/* No extended sense key ? */
4975 			break;
4976 
4977 		case SATA_PKT_ABORTED:
4978 			scsipkt->pkt_reason = CMD_ABORTED;
4979 			scsipkt->pkt_statistics |= STAT_ABORTED;
4980 			/* No extended sense key ? */
4981 			break;
4982 
4983 		case SATA_PKT_RESET:
4984 			/* pkt aborted by an explicit reset from a host */
4985 			scsipkt->pkt_reason = CMD_RESET;
4986 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
4987 			break;
4988 
4989 		default:
4990 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
4991 			    "sata_txlt_nodata_cmd_completion: "
4992 			    "invalid packet completion reason %d",
4993 			    sata_pkt->satapkt_reason));
4994 			scsipkt->pkt_reason = CMD_TRAN_ERR;
4995 			break;
4996 		}
4997 
4998 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4999 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5000 
5001 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5002 		    scsipkt->pkt_comp != NULL)
5003 			/* scsi callback required */
5004 			(*scsipkt->pkt_comp)(scsipkt);
5005 	}
5006 	return (TRAN_ACCEPT);
5007 
5008 bad_param:
5009 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5010 	*scsipkt->pkt_scbp = STATUS_CHECK;
5011 	sense = sata_arq_sense(spx);
5012 	sense->es_key = KEY_ILLEGAL_REQUEST;
5013 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5014 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5015 	    scsipkt->pkt_comp != NULL) {
5016 		/* scsi callback required */
5017 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5018 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5019 		    TQ_SLEEP) == 0) {
5020 			/* Scheduling the callback failed */
5021 			rval = TRAN_BUSY;
5022 		}
5023 	}
5024 	return (rval);
5025 }
5026 
5027 /*
5028  * Re-identify device after doing a firmware download.
5029  */
5030 static void
5031 sata_reidentify_device(sata_pkt_txlate_t *spx)
5032 {
5033 #define	DOWNLOAD_WAIT_TIME_SECS	60
5034 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
5035 	int rval;
5036 	int retry_cnt;
5037 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5038 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
5039 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
5040 	sata_drive_info_t *sdinfo;
5041 
5042 	/*
5043 	 * Before returning good status, probe device.
5044 	 * Device probing will get IDENTIFY DEVICE data, if possible.
5045 	 * The assumption is that the new microcode is applied by the
5046 	 * device. It is a caller responsibility to verify this.
5047 	 */
5048 	for (retry_cnt = 0;
5049 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
5050 	    retry_cnt++) {
5051 		rval = sata_probe_device(sata_hba_inst, &sata_device);
5052 
5053 		if (rval == SATA_SUCCESS) { /* Set default features */
5054 			sdinfo = sata_get_device_info(sata_hba_inst,
5055 			    &sata_device);
5056 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
5057 			    SATA_SUCCESS) {
5058 				/* retry */
5059 				(void) sata_initialize_device(sata_hba_inst,
5060 				    sdinfo);
5061 			}
5062 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5063 			    scsipkt->pkt_comp != NULL)
5064 				(*scsipkt->pkt_comp)(scsipkt);
5065 			return;
5066 		} else if (rval == SATA_RETRY) {
5067 			delay(drv_usectohz(1000000 *
5068 			    DOWNLOAD_WAIT_INTERVAL_SECS));
5069 			continue;
5070 		} else	/* failed - no reason to retry */
5071 			break;
5072 	}
5073 
5074 	/*
5075 	 * Something went wrong, device probing failed.
5076 	 */
5077 	SATA_LOG_D((sata_hba_inst, CE_WARN,
5078 	    "Cannot probe device after downloading microcode\n"));
5079 
5080 	/* Reset device to force retrying the probe. */
5081 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
5082 	    (SATA_DIP(sata_hba_inst), &sata_device);
5083 
5084 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5085 	    scsipkt->pkt_comp != NULL)
5086 		(*scsipkt->pkt_comp)(scsipkt);
5087 }
5088 
5089 
5090 /*
5091  * Translate command: Synchronize Cache.
5092  * Translates into Flush Cache command for SATA hard disks.
5093  *
5094  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5095  * appropriate values in scsi_pkt fields.
5096  */
5097 static 	int
5098 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
5099 {
5100 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5101 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5102 	int cport = SATA_TXLT_CPORT(spx);
5103 	int rval;
5104 	int synch;
5105 
5106 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5107 
5108 	if (((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) ||
5109 	    (spx->txlt_scsi_pkt->pkt_reason == CMD_DEV_GONE)) {
5110 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5111 		return (rval);
5112 	}
5113 
5114 	scmd->satacmd_addr_type = 0;
5115 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
5116 	scmd->satacmd_device_reg = 0;
5117 	scmd->satacmd_sec_count_lsb = 0;
5118 	scmd->satacmd_lba_low_lsb = 0;
5119 	scmd->satacmd_lba_mid_lsb = 0;
5120 	scmd->satacmd_lba_high_lsb = 0;
5121 	scmd->satacmd_features_reg = 0;
5122 	scmd->satacmd_status_reg = 0;
5123 	scmd->satacmd_error_reg = 0;
5124 
5125 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5126 	    "sata_txlt_synchronize_cache\n", NULL);
5127 
5128 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5129 		/* Need to set-up a callback function */
5130 		spx->txlt_sata_pkt->satapkt_comp =
5131 		    sata_txlt_nodata_cmd_completion;
5132 		synch = FALSE;
5133 	} else
5134 		synch = TRUE;
5135 
5136 	/* Transfer command to HBA */
5137 	if (sata_hba_start(spx, &rval) != 0) {
5138 		/* Pkt not accepted for execution */
5139 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5140 		return (rval);
5141 	}
5142 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5143 
5144 	/*
5145 	 * If execution non-synchronous, it had to be completed
5146 	 * a callback function will handle potential errors, translate
5147 	 * the response and will do a callback to a target driver.
5148 	 * If it was synchronous, check status, using the same
5149 	 * framework callback.
5150 	 */
5151 	if (synch) {
5152 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5153 		    "synchronous execution status %x\n",
5154 		    spx->txlt_sata_pkt->satapkt_reason);
5155 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
5156 	}
5157 	return (TRAN_ACCEPT);
5158 }
5159 
5160 
5161 /*
5162  * Send pkt to SATA HBA driver
5163  *
5164  * This function may be called only if the operation is requested by scsi_pkt,
5165  * i.e. scsi_pkt is not NULL.
5166  *
5167  * This function has to be called with cport mutex held. It does release
5168  * the mutex when it calls HBA driver sata_tran_start function and
5169  * re-acquires it afterwards.
5170  *
5171  * If return value is 0, pkt was accepted, -1 otherwise
5172  * rval is set to appropriate sata_scsi_start return value.
5173  *
5174  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
5175  * have called the sata_pkt callback function for this packet.
5176  *
5177  * The scsi callback has to be performed by the caller of this routine.
5178  *
5179  * Note 2: No port multiplier support for now.
5180  */
5181 static int
5182 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
5183 {
5184 	int stat, cport;
5185 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
5186 	sata_drive_info_t *sdinfo;
5187 	sata_device_t *sata_device;
5188 	uint8_t cmd;
5189 	struct sata_cmd_flags cmd_flags;
5190 
5191 	ASSERT(spx->txlt_sata_pkt != NULL);
5192 
5193 	cport = SATA_TXLT_CPORT(spx);
5194 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5195 
5196 	sdinfo = sata_get_device_info(sata_hba_inst,
5197 	    &spx->txlt_sata_pkt->satapkt_device);
5198 	ASSERT(sdinfo != NULL);
5199 
5200 	/* Clear device reset state? */
5201 	if (sdinfo->satadrv_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
5202 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
5203 		    sata_clear_dev_reset = B_TRUE;
5204 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_CLEAR_DEVICE_RESET;
5205 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5206 		    "sata_hba_start: clearing device reset state\n", NULL);
5207 	}
5208 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
5209 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
5210 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
5211 
5212 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5213 
5214 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5215 	    "Sata cmd 0x%2x\n", cmd);
5216 
5217 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
5218 	    spx->txlt_sata_pkt);
5219 
5220 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5221 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
5222 	/*
5223 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
5224 	 * with the sata callback, the sata_pkt could be already destroyed
5225 	 * by the time we check ther return status from the hba_start()
5226 	 * function, because sata_scsi_destroy_pkt() could have been already
5227 	 * called (perhaps in the interrupt context). So, in such case, there
5228 	 * should be no references to it. In other cases, sata_pkt still
5229 	 * exists.
5230 	 */
5231 	switch (stat) {
5232 	case SATA_TRAN_ACCEPTED:
5233 		/*
5234 		 * pkt accepted for execution.
5235 		 * If it was executed synchronously, it is already completed
5236 		 * and pkt completion_reason indicates completion status.
5237 		 */
5238 		*rval = TRAN_ACCEPT;
5239 		return (0);
5240 
5241 	case SATA_TRAN_QUEUE_FULL:
5242 		/*
5243 		 * Controller detected queue full condition.
5244 		 */
5245 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
5246 		    "sata_hba_start: queue full\n", NULL);
5247 
5248 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
5249 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
5250 
5251 		*rval = TRAN_BUSY;
5252 		break;
5253 
5254 	case SATA_TRAN_PORT_ERROR:
5255 		/*
5256 		 * Communication/link with device or general port error
5257 		 * detected before pkt execution begun.
5258 		 */
5259 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
5260 		    SATA_ADDR_CPORT ||
5261 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
5262 		    SATA_ADDR_DCPORT)
5263 			sata_log(sata_hba_inst, CE_CONT,
5264 			    "SATA port %d error",
5265 			    sata_device->satadev_addr.cport);
5266 		else
5267 			sata_log(sata_hba_inst, CE_CONT,
5268 			    "SATA port %d pmport %d error\n",
5269 			    sata_device->satadev_addr.cport,
5270 			    sata_device->satadev_addr.pmport);
5271 
5272 		/*
5273 		 * Update the port/device structure.
5274 		 * sata_pkt should be still valid. Since port error is
5275 		 * returned, sata_device content should reflect port
5276 		 * state - it means, that sata address have been changed,
5277 		 * because original packet's sata address refered to a device
5278 		 * attached to some port.
5279 		 */
5280 		sata_update_port_info(sata_hba_inst, sata_device);
5281 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
5282 		*rval = TRAN_FATAL_ERROR;
5283 		break;
5284 
5285 	case SATA_TRAN_CMD_UNSUPPORTED:
5286 		/*
5287 		 * Command rejected by HBA as unsupported. It was HBA driver
5288 		 * that rejected the command, command was not sent to
5289 		 * an attached device.
5290 		 */
5291 		if ((sdinfo != NULL) &&
5292 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
5293 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5294 			    "sat_hba_start: cmd 0x%2x rejected "
5295 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
5296 
5297 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5298 		(void) sata_txlt_invalid_command(spx);
5299 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5300 
5301 		*rval = TRAN_ACCEPT;
5302 		break;
5303 
5304 	case SATA_TRAN_BUSY:
5305 		/*
5306 		 * Command rejected by HBA because other operation prevents
5307 		 * accepting the packet, or device is in RESET condition.
5308 		 */
5309 		if (sdinfo != NULL) {
5310 			sdinfo->satadrv_state =
5311 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
5312 
5313 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
5314 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5315 				    "sata_hba_start: cmd 0x%2x rejected "
5316 				    "because of device reset condition\n",
5317 				    cmd);
5318 			} else {
5319 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5320 				    "sata_hba_start: cmd 0x%2x rejected "
5321 				    "with SATA_TRAN_BUSY status\n",
5322 				    cmd);
5323 			}
5324 		}
5325 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
5326 		*rval = TRAN_BUSY;
5327 		break;
5328 
5329 	default:
5330 		/* Unrecognized HBA response */
5331 		SATA_LOG_D((sata_hba_inst, CE_WARN,
5332 		    "sata_hba_start: unrecognized HBA response "
5333 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
5334 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
5335 		*rval = TRAN_FATAL_ERROR;
5336 		break;
5337 	}
5338 
5339 	/*
5340 	 * If we got here, the packet was rejected.
5341 	 * Check if we need to remember reset state clearing request
5342 	 */
5343 	if (cmd_flags.sata_clear_dev_reset) {
5344 		/*
5345 		 * Check if device is still configured - it may have
5346 		 * disapeared from the configuration
5347 		 */
5348 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
5349 		if (sdinfo != NULL) {
5350 			/*
5351 			 * Restore the flag that requests clearing of
5352 			 * the device reset state,
5353 			 * so the next sata packet may carry it to HBA.
5354 			 */
5355 			sdinfo->satadrv_event_flags |=
5356 			    SATA_EVNT_CLEAR_DEVICE_RESET;
5357 		}
5358 	}
5359 	return (-1);
5360 }
5361 
5362 /*
5363  * Scsi response setup for invalid LBA
5364  *
5365  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
5366  */
5367 static int
5368 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
5369 {
5370 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5371 	struct scsi_extended_sense *sense;
5372 
5373 	scsipkt->pkt_reason = CMD_CMPLT;
5374 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5375 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5376 	*scsipkt->pkt_scbp = STATUS_CHECK;
5377 
5378 	*scsipkt->pkt_scbp = STATUS_CHECK;
5379 	sense = sata_arq_sense(spx);
5380 	sense->es_key = KEY_ILLEGAL_REQUEST;
5381 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
5382 
5383 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5384 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5385 
5386 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5387 	    scsipkt->pkt_comp != NULL)
5388 		/* scsi callback required */
5389 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5390 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5391 		    TQ_SLEEP) == NULL)
5392 			/* Scheduling the callback failed */
5393 			return (TRAN_BUSY);
5394 	return (TRAN_ACCEPT);
5395 }
5396 
5397 
5398 /*
5399  * Analyze device status and error registers and translate them into
5400  * appropriate scsi sense codes.
5401  * NOTE: non-packet commands only for now
5402  */
5403 static void
5404 sata_decode_device_error(sata_pkt_txlate_t *spx,
5405     struct scsi_extended_sense *sense)
5406 {
5407 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
5408 
5409 	ASSERT(sense != NULL);
5410 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
5411 	    SATA_STATUS_ERR);
5412 
5413 
5414 	if (err_reg & SATA_ERROR_ICRC) {
5415 		sense->es_key = KEY_ABORTED_COMMAND;
5416 		sense->es_add_code = 0x08; /* Communication failure */
5417 		return;
5418 	}
5419 
5420 	if (err_reg & SATA_ERROR_UNC) {
5421 		sense->es_key = KEY_MEDIUM_ERROR;
5422 		/* Information bytes (LBA) need to be set by a caller */
5423 		return;
5424 	}
5425 
5426 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
5427 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
5428 		sense->es_key = KEY_UNIT_ATTENTION;
5429 		sense->es_add_code = 0x3a; /* No media present */
5430 		return;
5431 	}
5432 
5433 	if (err_reg & SATA_ERROR_IDNF) {
5434 		if (err_reg & SATA_ERROR_ABORT) {
5435 			sense->es_key = KEY_ABORTED_COMMAND;
5436 		} else {
5437 			sense->es_key = KEY_ILLEGAL_REQUEST;
5438 			sense->es_add_code = 0x21; /* LBA out of range */
5439 		}
5440 		return;
5441 	}
5442 
5443 	if (err_reg & SATA_ERROR_ABORT) {
5444 		ASSERT(spx->txlt_sata_pkt != NULL);
5445 		sense->es_key = KEY_ABORTED_COMMAND;
5446 		return;
5447 	}
5448 }
5449 
5450 /*
5451  * Extract error LBA from sata_pkt.satapkt_cmd register fields
5452  */
5453 static void
5454 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
5455 {
5456 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
5457 
5458 	*lba = 0;
5459 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
5460 		*lba = sata_cmd->satacmd_lba_high_msb;
5461 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
5462 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
5463 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
5464 		*lba = sata_cmd->satacmd_device_reg & 0xf;
5465 	}
5466 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
5467 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
5468 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
5469 }
5470 
5471 /*
5472  * This is fixed sense format - if LBA exceeds the info field size,
5473  * no valid info will be returned (valid bit in extended sense will
5474  * be set to 0).
5475  */
5476 static struct scsi_extended_sense *
5477 sata_arq_sense(sata_pkt_txlate_t *spx)
5478 {
5479 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5480 	struct scsi_arq_status *arqs;
5481 	struct scsi_extended_sense *sense;
5482 
5483 	/* Fill ARQ sense data */
5484 	scsipkt->pkt_state |= STATE_ARQ_DONE;
5485 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
5486 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
5487 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
5488 	arqs->sts_rqpkt_reason = CMD_CMPLT;
5489 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5490 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
5491 	arqs->sts_rqpkt_resid = 0;
5492 	sense = &arqs->sts_sensedata;
5493 	bzero(sense, sizeof (struct scsi_extended_sense));
5494 	sata_fixed_sense_data_preset(sense);
5495 	return (sense);
5496 }
5497 
5498 
5499 /*
5500  * Emulated SATA Read/Write command completion for zero-length requests.
5501  * This request always succedes, so in synchronous mode it always returns
5502  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
5503  * callback cannot be scheduled.
5504  */
5505 static int
5506 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
5507 {
5508 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5509 
5510 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5511 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5512 	scsipkt->pkt_reason = CMD_CMPLT;
5513 	*scsipkt->pkt_scbp = STATUS_GOOD;
5514 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5515 		/* scsi callback required - have to schedule it */
5516 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5517 		    (task_func_t *)scsipkt->pkt_comp,
5518 		    (void *)scsipkt, TQ_SLEEP) == NULL)
5519 			/* Scheduling the callback failed */
5520 			return (TRAN_BUSY);
5521 	}
5522 	return (TRAN_ACCEPT);
5523 }
5524 
5525 
5526 /*
5527  * Translate completion status of SATA read/write commands into scsi response.
5528  * pkt completion_reason is checked to determine the completion status.
5529  * Do scsi callback if necessary.
5530  *
5531  * Note: this function may be called also for synchronously executed
5532  * commands.
5533  * This function may be used only if scsi_pkt is non-NULL.
5534  */
5535 static void
5536 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
5537 {
5538 	sata_pkt_txlate_t *spx =
5539 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
5540 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
5541 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5542 	struct scsi_extended_sense *sense;
5543 	uint64_t lba;
5544 	struct buf *bp;
5545 	int rval;
5546 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5547 		/* Normal completion */
5548 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5549 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
5550 		scsipkt->pkt_reason = CMD_CMPLT;
5551 		*scsipkt->pkt_scbp = STATUS_GOOD;
5552 		if (spx->txlt_tmp_buf != NULL) {
5553 			/* Temporary buffer was used */
5554 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5555 			if (bp->b_flags & B_READ) {
5556 				rval = ddi_dma_sync(
5557 				    spx->txlt_buf_dma_handle, 0, 0,
5558 				    DDI_DMA_SYNC_FORCPU);
5559 				ASSERT(rval == DDI_SUCCESS);
5560 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
5561 				    bp->b_bcount);
5562 			}
5563 		}
5564 	} else {
5565 		/*
5566 		 * Something went wrong - analyze return
5567 		 */
5568 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5569 		    STATE_SENT_CMD | STATE_GOT_STATUS;
5570 		scsipkt->pkt_reason = CMD_INCOMPLETE;
5571 		*scsipkt->pkt_scbp = STATUS_CHECK;
5572 		sense = sata_arq_sense(spx);
5573 		ASSERT(sense != NULL);
5574 
5575 		/*
5576 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
5577 		 * extract from device registers the failing LBA.
5578 		 */
5579 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
5580 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
5581 			    (scmd->satacmd_lba_mid_msb != 0 ||
5582 			    scmd->satacmd_lba_high_msb != 0)) {
5583 				/*
5584 				 * We have problem reporting this cmd LBA
5585 				 * in fixed sense data format, because of
5586 				 * the size of the scsi LBA fields.
5587 				 */
5588 				sense->es_valid = 0;
5589 			} else {
5590 				sata_extract_error_lba(spx, &lba);
5591 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
5592 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
5593 				sense->es_info_3 = (lba & 0xFF00) >> 8;
5594 				sense->es_info_4 = lba & 0xFF;
5595 			}
5596 		} else {
5597 			/* Invalid extended sense info */
5598 			sense->es_valid = 0;
5599 		}
5600 
5601 		switch (sata_pkt->satapkt_reason) {
5602 		case SATA_PKT_PORT_ERROR:
5603 			/* We may want to handle DEV GONE state as well */
5604 			/*
5605 			 * We have no device data. Assume no data transfered.
5606 			 */
5607 			sense->es_key = KEY_HARDWARE_ERROR;
5608 			break;
5609 
5610 		case SATA_PKT_DEV_ERROR:
5611 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
5612 			    SATA_STATUS_ERR) {
5613 				/*
5614 				 * determine dev error reason from error
5615 				 * reg content
5616 				 */
5617 				sata_decode_device_error(spx, sense);
5618 				if (sense->es_key == KEY_MEDIUM_ERROR) {
5619 					switch (scmd->satacmd_cmd_reg) {
5620 					case SATAC_READ_DMA:
5621 					case SATAC_READ_DMA_EXT:
5622 					case SATAC_READ_DMA_QUEUED:
5623 					case SATAC_READ_DMA_QUEUED_EXT:
5624 					case SATAC_READ_FPDMA_QUEUED:
5625 						/* Unrecovered read error */
5626 						sense->es_add_code =
5627 						    SD_SCSI_ASC_UNREC_READ_ERR;
5628 						break;
5629 					case SATAC_WRITE_DMA:
5630 					case SATAC_WRITE_DMA_EXT:
5631 					case SATAC_WRITE_DMA_QUEUED:
5632 					case SATAC_WRITE_DMA_QUEUED_EXT:
5633 					case SATAC_WRITE_FPDMA_QUEUED:
5634 						/* Write error */
5635 						sense->es_add_code =
5636 						    SD_SCSI_ASC_WRITE_ERR;
5637 						break;
5638 					default:
5639 						/* Internal error */
5640 						SATA_LOG_D((
5641 						    spx->txlt_sata_hba_inst,
5642 						    CE_WARN,
5643 						    "sata_txlt_rw_completion :"
5644 						    "internal error - invalid "
5645 						    "command 0x%2x",
5646 						    scmd->satacmd_cmd_reg));
5647 						break;
5648 					}
5649 				}
5650 				break;
5651 			}
5652 			/* No extended sense key - no info available */
5653 			scsipkt->pkt_reason = CMD_INCOMPLETE;
5654 			break;
5655 
5656 		case SATA_PKT_TIMEOUT:
5657 			scsipkt->pkt_reason = CMD_TIMEOUT;
5658 			scsipkt->pkt_statistics |=
5659 			    STAT_TIMEOUT | STAT_DEV_RESET;
5660 			sense->es_key = KEY_ABORTED_COMMAND;
5661 			break;
5662 
5663 		case SATA_PKT_ABORTED:
5664 			scsipkt->pkt_reason = CMD_ABORTED;
5665 			scsipkt->pkt_statistics |= STAT_ABORTED;
5666 			sense->es_key = KEY_ABORTED_COMMAND;
5667 			break;
5668 
5669 		case SATA_PKT_RESET:
5670 			scsipkt->pkt_reason = CMD_RESET;
5671 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
5672 			sense->es_key = KEY_ABORTED_COMMAND;
5673 			break;
5674 
5675 		default:
5676 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
5677 			    "sata_txlt_rw_completion: "
5678 			    "invalid packet completion reason"));
5679 			scsipkt->pkt_reason = CMD_TRAN_ERR;
5680 			break;
5681 		}
5682 	}
5683 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5684 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5685 
5686 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5687 	    scsipkt->pkt_comp != NULL)
5688 		/* scsi callback required */
5689 		(*scsipkt->pkt_comp)(scsipkt);
5690 }
5691 
5692 
5693 /*
5694  * Translate completion status of non-data commands (i.e. commands returning
5695  * no data).
5696  * pkt completion_reason is checked to determine the completion status.
5697  * Do scsi callback if necessary (FLAG_NOINTR == 0)
5698  *
5699  * Note: this function may be called also for synchronously executed
5700  * commands.
5701  * This function may be used only if scsi_pkt is non-NULL.
5702  */
5703 
5704 static 	void
5705 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
5706 {
5707 	sata_pkt_txlate_t *spx =
5708 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
5709 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5710 	struct scsi_extended_sense *sense;
5711 
5712 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5713 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5714 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5715 		/* Normal completion */
5716 		scsipkt->pkt_reason = CMD_CMPLT;
5717 		*scsipkt->pkt_scbp = STATUS_GOOD;
5718 	} else {
5719 		/* Something went wrong */
5720 		scsipkt->pkt_reason = CMD_INCOMPLETE;
5721 		*scsipkt->pkt_scbp = STATUS_CHECK;
5722 		sense = sata_arq_sense(spx);
5723 		switch (sata_pkt->satapkt_reason) {
5724 		case SATA_PKT_PORT_ERROR:
5725 			/*
5726 			 * We have no device data. Assume no data transfered.
5727 			 */
5728 			sense->es_key = KEY_HARDWARE_ERROR;
5729 			break;
5730 
5731 		case SATA_PKT_DEV_ERROR:
5732 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
5733 			    SATA_STATUS_ERR) {
5734 				/*
5735 				 * determine dev error reason from error
5736 				 * reg content
5737 				 */
5738 				sata_decode_device_error(spx, sense);
5739 				break;
5740 			}
5741 			/* No extended sense key - no info available */
5742 			break;
5743 
5744 		case SATA_PKT_TIMEOUT:
5745 			scsipkt->pkt_reason = CMD_TIMEOUT;
5746 			scsipkt->pkt_statistics |=
5747 			    STAT_TIMEOUT | STAT_DEV_RESET;
5748 			/* No extended sense key ? */
5749 			break;
5750 
5751 		case SATA_PKT_ABORTED:
5752 			scsipkt->pkt_reason = CMD_ABORTED;
5753 			scsipkt->pkt_statistics |= STAT_ABORTED;
5754 			/* No extended sense key ? */
5755 			break;
5756 
5757 		case SATA_PKT_RESET:
5758 			/* pkt aborted by an explicit reset from a host */
5759 			scsipkt->pkt_reason = CMD_RESET;
5760 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
5761 			break;
5762 
5763 		default:
5764 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
5765 			    "sata_txlt_nodata_cmd_completion: "
5766 			    "invalid packet completion reason %d",
5767 			    sata_pkt->satapkt_reason));
5768 			scsipkt->pkt_reason = CMD_TRAN_ERR;
5769 			break;
5770 		}
5771 
5772 	}
5773 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5774 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5775 
5776 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5777 	    scsipkt->pkt_comp != NULL)
5778 		/* scsi callback required */
5779 		(*scsipkt->pkt_comp)(scsipkt);
5780 }
5781 
5782 
5783 /*
5784  * Build Mode sense R/W recovery page
5785  * NOT IMPLEMENTED
5786  */
5787 
5788 static int
5789 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
5790 {
5791 #ifndef __lock_lint
5792 	_NOTE(ARGUNUSED(sdinfo))
5793 	_NOTE(ARGUNUSED(pcntrl))
5794 	_NOTE(ARGUNUSED(buf))
5795 #endif
5796 	return (0);
5797 }
5798 
5799 /*
5800  * Build Mode sense caching page  -  scsi-3 implementation.
5801  * Page length distinguishes previous format from scsi-3 format.
5802  * buf must have space for 0x12 bytes.
5803  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
5804  *
5805  */
5806 static int
5807 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
5808 {
5809 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
5810 	sata_id_t *sata_id = &sdinfo->satadrv_id;
5811 
5812 	/*
5813 	 * Most of the fields are set to 0, being not supported and/or disabled
5814 	 */
5815 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
5816 
5817 	/* Saved paramters not supported */
5818 	if (pcntrl == 3)
5819 		return (0);
5820 	if (pcntrl == 0 || pcntrl == 2) {
5821 		/*
5822 		 * For now treat current and default parameters as same
5823 		 * That may have to change, if target driver will complain
5824 		 */
5825 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
5826 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
5827 
5828 		if ((sata_id->ai_cmdset82 & SATA_LOOK_AHEAD) &&
5829 		    !(sata_id->ai_features85 & SATA_LOOK_AHEAD)) {
5830 			page->dra = 1;		/* Read Ahead disabled */
5831 			page->rcd = 1;		/* Read Cache disabled */
5832 		}
5833 		if ((sata_id->ai_cmdset82 & SATA_WRITE_CACHE) &&
5834 		    (sata_id->ai_features85 & SATA_WRITE_CACHE))
5835 			page->wce = 1;		/* Write Cache enabled */
5836 	} else {
5837 		/* Changeable parameters */
5838 		page->mode_page.code = MODEPAGE_CACHING;
5839 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
5840 		if (sata_id->ai_cmdset82 & SATA_LOOK_AHEAD) {
5841 			page->dra = 1;
5842 			page->rcd = 1;
5843 		}
5844 		if (sata_id->ai_cmdset82 & SATA_WRITE_CACHE)
5845 			page->wce = 1;
5846 	}
5847 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
5848 	    sizeof (struct mode_page));
5849 }
5850 
5851 /*
5852  * Build Mode sense exception cntrl page
5853  */
5854 static int
5855 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
5856 {
5857 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
5858 	sata_id_t *sata_id = &sdinfo->satadrv_id;
5859 
5860 	/*
5861 	 * Most of the fields are set to 0, being not supported and/or disabled
5862 	 */
5863 	bzero(buf, PAGELENGTH_INFO_EXCPT);
5864 
5865 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
5866 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
5867 
5868 	/* Indicate that this is page is saveable */
5869 	page->mode_page.ps = 1;
5870 
5871 	/*
5872 	 * We will return the same data for default, current and saved page.
5873 	 * The only changeable bit is dexcpt and that bit is required
5874 	 * by the ATA specification to be preserved across power cycles.
5875 	 */
5876 	if (pcntrl != 1) {
5877 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
5878 		page->mrie = MRIE_ONLY_ON_REQUEST;
5879 	}
5880 	else
5881 		page->dexcpt = 1;	/* Only changeable parameter */
5882 
5883 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_info_excpt_page));
5884 }
5885 
5886 
5887 static int
5888 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
5889 {
5890 	struct mode_acoustic_management *page =
5891 	    (struct mode_acoustic_management *)buf;
5892 	sata_id_t *sata_id = &sdinfo->satadrv_id;
5893 
5894 	/*
5895 	 * Most of the fields are set to 0, being not supported and/or disabled
5896 	 */
5897 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
5898 
5899 	switch (pcntrl) {
5900 	case P_CNTRL_DEFAULT:
5901 		/*  default paramters not supported */
5902 		return (0);
5903 
5904 	case P_CNTRL_CURRENT:
5905 	case P_CNTRL_SAVED:
5906 		/* Saved and current are supported and are identical */
5907 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
5908 		page->mode_page.length =
5909 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
5910 		page->mode_page.ps = 1;
5911 
5912 		/* Word 83 indicates if feature is supported */
5913 		/* If feature is not supported */
5914 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
5915 			page->acoustic_manag_enable =
5916 			    ACOUSTIC_DISABLED;
5917 		} else {
5918 			page->acoustic_manag_enable =
5919 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
5920 			    != 0);
5921 			/* Word 94 inidicates the value */
5922 #ifdef	_LITTLE_ENDIAN
5923 			page->acoustic_manag_level =
5924 			    (uchar_t)sata_id->ai_acoustic;
5925 			page->vendor_recommended_value =
5926 			    sata_id->ai_acoustic >> 8;
5927 #else
5928 			page->acoustic_manag_level =
5929 			    sata_id->ai_acoustic >> 8;
5930 			page->vendor_recommended_value =
5931 			    (uchar_t)sata_id->ai_acoustic;
5932 #endif
5933 		}
5934 		break;
5935 
5936 	case P_CNTRL_CHANGEABLE:
5937 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
5938 		page->mode_page.length =
5939 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
5940 		page->mode_page.ps = 1;
5941 
5942 		/* Word 83 indicates if the feature is supported */
5943 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
5944 			page->acoustic_manag_enable =
5945 			    ACOUSTIC_ENABLED;
5946 			page->acoustic_manag_level = 0xff;
5947 		}
5948 		break;
5949 	}
5950 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
5951 	    sizeof (struct mode_page));
5952 }
5953 
5954 
5955 /*
5956  * Build Mode sense power condition page
5957  * NOT IMPLEMENTED.
5958  */
5959 static int
5960 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
5961 {
5962 #ifndef __lock_lint
5963 	_NOTE(ARGUNUSED(sdinfo))
5964 	_NOTE(ARGUNUSED(pcntrl))
5965 	_NOTE(ARGUNUSED(buf))
5966 #endif
5967 	return (0);
5968 }
5969 
5970 
5971 /*
5972  * Process mode select caching page 8 (scsi3 format only).
5973  * Read Ahead (same as read cache) and Write Cache may be turned on and off
5974  * if these features are supported by the device. If these features are not
5975  * supported, quietly ignore them.
5976  * This function fails only if the SET FEATURE command sent to
5977  * the device fails. The page format is not varified, assuming that the
5978  * target driver operates correctly - if parameters length is too short,
5979  * we just drop the page.
5980  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
5981  * setting have to be changed.
5982  * SET FEATURE command is executed synchronously, i.e. we wait here until
5983  * it is completed, regardless of the scsi pkt directives.
5984  *
5985  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
5986  * changing DRA will change RCD.
5987  *
5988  * More than one SATA command may be executed to perform operations specified
5989  * by mode select pages. The first error terminates further execution.
5990  * Operations performed successully are not backed-up in such case.
5991  *
5992  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
5993  * If operation resulted in changing device setup, dmod flag should be set to
5994  * one (1). If parameters were not changed, dmod flag should be set to 0.
5995  * Upon return, if operation required sending command to the device, the rval
5996  * should be set to the value returned by sata_hba_start. If operation
5997  * did not require device access, rval should be set to TRAN_ACCEPT.
5998  * The pagelen should be set to the length of the page.
5999  *
6000  * This function has to be called with a port mutex held.
6001  *
6002  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
6003  */
6004 int
6005 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
6006     int parmlen, int *pagelen, int *rval, int *dmod)
6007 {
6008 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6009 	sata_drive_info_t *sdinfo;
6010 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6011 	sata_id_t *sata_id;
6012 	struct scsi_extended_sense *sense;
6013 	int wce, dra;	/* Current settings */
6014 
6015 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6016 	    &spx->txlt_sata_pkt->satapkt_device);
6017 	sata_id = &sdinfo->satadrv_id;
6018 	*dmod = 0;
6019 
6020 	/* Verify parameters length. If too short, drop it */
6021 	if (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
6022 	    sizeof (struct mode_page) < parmlen) {
6023 		*scsipkt->pkt_scbp = STATUS_CHECK;
6024 		sense = sata_arq_sense(spx);
6025 		sense->es_key = KEY_ILLEGAL_REQUEST;
6026 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
6027 		*pagelen = parmlen;
6028 		*rval = TRAN_ACCEPT;
6029 		return (SATA_FAILURE);
6030 	}
6031 
6032 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
6033 
6034 	/*
6035 	 * We can manipulate only write cache and read ahead
6036 	 * (read cache) setting.
6037 	 */
6038 	if (!(sata_id->ai_cmdset82 & SATA_LOOK_AHEAD) &&
6039 	    !(sata_id->ai_cmdset82 & SATA_WRITE_CACHE)) {
6040 		/*
6041 		 * None of the features is supported - ignore
6042 		 */
6043 		*rval = TRAN_ACCEPT;
6044 		return (SATA_SUCCESS);
6045 	}
6046 
6047 	/* Current setting of Read Ahead (and Read Cache) */
6048 	if (sata_id->ai_features85 & SATA_LOOK_AHEAD)
6049 		dra = 0;	/* 0 == not disabled */
6050 	else
6051 		dra = 1;
6052 	/* Current setting of Write Cache */
6053 	if (sata_id->ai_features85 & SATA_WRITE_CACHE)
6054 		wce = 1;
6055 	else
6056 		wce = 0;
6057 
6058 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
6059 		/* nothing to do */
6060 		*rval = TRAN_ACCEPT;
6061 		return (SATA_SUCCESS);
6062 	}
6063 	/*
6064 	 * Need to flip some setting
6065 	 * Set-up Internal SET FEATURES command(s)
6066 	 */
6067 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6068 	scmd->satacmd_addr_type = 0;
6069 	scmd->satacmd_device_reg = 0;
6070 	scmd->satacmd_status_reg = 0;
6071 	scmd->satacmd_error_reg = 0;
6072 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
6073 	if (page->dra != dra || page->rcd != dra) {
6074 		/* Need to flip read ahead setting */
6075 		if (dra == 0)
6076 			/* Disable read ahead / read cache */
6077 			scmd->satacmd_features_reg =
6078 			    SATAC_SF_DISABLE_READ_AHEAD;
6079 		else
6080 			/* Enable read ahead  / read cache */
6081 			scmd->satacmd_features_reg =
6082 			    SATAC_SF_ENABLE_READ_AHEAD;
6083 
6084 		/* Transfer command to HBA */
6085 		if (sata_hba_start(spx, rval) != 0)
6086 			/*
6087 			 * Pkt not accepted for execution.
6088 			 */
6089 			return (SATA_FAILURE);
6090 
6091 		*dmod = 1;
6092 
6093 		/* Now process return */
6094 		if (spx->txlt_sata_pkt->satapkt_reason !=
6095 		    SATA_PKT_COMPLETED) {
6096 			goto failure;	/* Terminate */
6097 		}
6098 	}
6099 
6100 	/* Note that the packet is not removed, so it could be re-used */
6101 	if (page->wce != wce) {
6102 		/* Need to flip Write Cache setting */
6103 		if (page->wce == 1)
6104 			/* Enable write cache */
6105 			scmd->satacmd_features_reg =
6106 			    SATAC_SF_ENABLE_WRITE_CACHE;
6107 		else
6108 			/* Disable write cache */
6109 			scmd->satacmd_features_reg =
6110 			    SATAC_SF_DISABLE_WRITE_CACHE;
6111 
6112 		/* Transfer command to HBA */
6113 		if (sata_hba_start(spx, rval) != 0)
6114 			/*
6115 			 * Pkt not accepted for execution.
6116 			 */
6117 			return (SATA_FAILURE);
6118 
6119 		*dmod = 1;
6120 
6121 		/* Now process return */
6122 		if (spx->txlt_sata_pkt->satapkt_reason !=
6123 		    SATA_PKT_COMPLETED) {
6124 			goto failure;
6125 		}
6126 	}
6127 	return (SATA_SUCCESS);
6128 
6129 failure:
6130 	sata_xlate_errors(spx);
6131 
6132 	return (SATA_FAILURE);
6133 }
6134 
6135 /*
6136  * Process mode select informational exceptions control page 0x1c
6137  *
6138  * The only changeable bit is dexcpt (disable exceptions).
6139  * MRIE (method of reporting informational exceptions) must be
6140  * "only on request".
6141  *
6142  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
6143  * If operation resulted in changing device setup, dmod flag should be set to
6144  * one (1). If parameters were not changed, dmod flag should be set to 0.
6145  * Upon return, if operation required sending command to the device, the rval
6146  * should be set to the value returned by sata_hba_start. If operation
6147  * did not require device access, rval should be set to TRAN_ACCEPT.
6148  * The pagelen should be set to the length of the page.
6149  *
6150  * This function has to be called with a port mutex held.
6151  *
6152  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
6153  */
6154 static	int
6155 sata_mode_select_page_1c(
6156 	sata_pkt_txlate_t *spx,
6157 	struct mode_info_excpt_page *page,
6158 	int parmlen,
6159 	int *pagelen,
6160 	int *rval,
6161 	int *dmod)
6162 {
6163 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6164 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6165 	sata_drive_info_t *sdinfo;
6166 	sata_id_t *sata_id;
6167 	struct scsi_extended_sense *sense;
6168 
6169 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6170 	    &spx->txlt_sata_pkt->satapkt_device);
6171 	sata_id = &sdinfo->satadrv_id;
6172 
6173 	*dmod = 0;
6174 
6175 	/* Verify parameters length. If too short, drop it */
6176 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) < parmlen) ||
6177 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
6178 		*scsipkt->pkt_scbp = STATUS_CHECK;
6179 		sense = sata_arq_sense(spx);
6180 		sense->es_key = KEY_ILLEGAL_REQUEST;
6181 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
6182 		*pagelen = parmlen;
6183 		*rval = TRAN_ACCEPT;
6184 		return (SATA_FAILURE);
6185 	}
6186 
6187 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
6188 
6189 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
6190 		*scsipkt->pkt_scbp = STATUS_CHECK;
6191 		sense = sata_arq_sense(spx);
6192 		sense->es_key = KEY_ILLEGAL_REQUEST;
6193 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6194 		*pagelen = parmlen;
6195 		*rval = TRAN_ACCEPT;
6196 		return (SATA_FAILURE);
6197 	}
6198 
6199 	/* If already in the state requested, we are done */
6200 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
6201 		/* nothing to do */
6202 		*rval = TRAN_ACCEPT;
6203 		return (SATA_SUCCESS);
6204 	}
6205 
6206 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6207 
6208 	/* Build SMART_ENABLE or SMART_DISABLE command */
6209 	scmd->satacmd_addr_type = 0;		/* N/A */
6210 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
6211 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
6212 	scmd->satacmd_features_reg = page->dexcpt ?
6213 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
6214 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
6215 	scmd->satacmd_cmd_reg = SATAC_SMART;
6216 
6217 	/* Transfer command to HBA */
6218 	if (sata_hba_start(spx, rval) != 0)
6219 		/*
6220 		 * Pkt not accepted for execution.
6221 		 */
6222 		return (SATA_FAILURE);
6223 
6224 	*dmod = 1;	/* At least may have been modified */
6225 
6226 	/* Now process return */
6227 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
6228 		return (SATA_SUCCESS);
6229 
6230 	/* Packet did not complete successfully */
6231 	sata_xlate_errors(spx);
6232 
6233 	return (SATA_FAILURE);
6234 }
6235 
6236 int
6237 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
6238     mode_acoustic_management *page, int parmlen, int *pagelen,
6239     int *rval, int *dmod)
6240 {
6241 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6242 	sata_drive_info_t *sdinfo;
6243 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6244 	sata_id_t *sata_id;
6245 	struct scsi_extended_sense *sense;
6246 
6247 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6248 	    &spx->txlt_sata_pkt->satapkt_device);
6249 	sata_id = &sdinfo->satadrv_id;
6250 	*dmod = 0;
6251 
6252 	/* If parmlen is too short or the feature is not supported, drop it */
6253 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
6254 	    sizeof (struct mode_page)) < parmlen) ||
6255 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
6256 		*scsipkt->pkt_scbp = STATUS_CHECK;
6257 		sense = sata_arq_sense(spx);
6258 		sense->es_key = KEY_ILLEGAL_REQUEST;
6259 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
6260 		*pagelen = parmlen;
6261 		*rval = TRAN_ACCEPT;
6262 		return (SATA_FAILURE);
6263 	}
6264 
6265 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
6266 	    sizeof (struct mode_page);
6267 
6268 	/*
6269 	 * We can enable and disable acoustice management and
6270 	 * set the acoustic management level.
6271 	 */
6272 
6273 	/*
6274 	 * Set-up Internal SET FEATURES command(s)
6275 	 */
6276 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6277 	scmd->satacmd_addr_type = 0;
6278 	scmd->satacmd_device_reg = 0;
6279 	scmd->satacmd_status_reg = 0;
6280 	scmd->satacmd_error_reg = 0;
6281 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
6282 	if (page->acoustic_manag_enable) {
6283 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
6284 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
6285 	} else {	/* disabling acoustic management */
6286 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
6287 	}
6288 
6289 	/* Transfer command to HBA */
6290 	if (sata_hba_start(spx, rval) != 0)
6291 		/*
6292 		 * Pkt not accepted for execution.
6293 		 */
6294 		return (SATA_FAILURE);
6295 
6296 	/* Now process return */
6297 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
6298 		sata_xlate_errors(spx);
6299 		return (SATA_FAILURE);
6300 	}
6301 
6302 	*dmod = 1;
6303 
6304 	return (SATA_SUCCESS);
6305 }
6306 
6307 
6308 
6309 
6310 /*
6311  * sata_build_lsense_page0() is used to create the
6312  * SCSI LOG SENSE page 0 (supported log pages)
6313  *
6314  * Currently supported pages are 0, 0x10, 0x2f and 0x30
6315  * (supported log pages, self-test results, informational exceptions
6316  *  and Sun vendor specific ATA SMART data).
6317  *
6318  * Takes a sata_drive_info t * and the address of a buffer
6319  * in which to create the page information.
6320  *
6321  * Returns the number of bytes valid in the buffer.
6322  */
6323 static	int
6324 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
6325 {
6326 	struct log_parameter *lpp = (struct log_parameter *)buf;
6327 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
6328 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
6329 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6330 
6331 	lpp->param_code[0] = 0;
6332 	lpp->param_code[1] = 0;
6333 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
6334 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
6335 
6336 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
6337 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
6338 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
6339 			++num_pages_supported;
6340 		}
6341 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
6342 		++num_pages_supported;
6343 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
6344 		++num_pages_supported;
6345 	}
6346 
6347 	lpp->param_len = num_pages_supported;
6348 
6349 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
6350 	    num_pages_supported);
6351 }
6352 
6353 /*
6354  * sata_build_lsense_page_10() is used to create the
6355  * SCSI LOG SENSE page 0x10 (self-test results)
6356  *
6357  * Takes a sata_drive_info t * and the address of a buffer
6358  * in which to create the page information as well as a sata_hba_inst_t *.
6359  *
6360  * Returns the number of bytes valid in the buffer.
6361  */
6362 static	int
6363 sata_build_lsense_page_10(
6364 	sata_drive_info_t *sdinfo,
6365 	uint8_t *buf,
6366 	sata_hba_inst_t *sata_hba_inst)
6367 {
6368 	struct log_parameter *lpp = (struct log_parameter *)buf;
6369 	int rval;
6370 
6371 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
6372 		struct smart_ext_selftest_log *ext_selftest_log;
6373 
6374 		ext_selftest_log = kmem_zalloc(
6375 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
6376 
6377 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
6378 		    ext_selftest_log, 0);
6379 		if (rval == 0) {
6380 			int index, start_index;
6381 			struct smart_ext_selftest_log_entry *entry;
6382 			static const struct smart_ext_selftest_log_entry empty =
6383 			    {0};
6384 			uint16_t block_num;
6385 			int count;
6386 			boolean_t only_one_block = B_FALSE;
6387 
6388 			index = ext_selftest_log->
6389 			    smart_ext_selftest_log_index[0];
6390 			index |= ext_selftest_log->
6391 			    smart_ext_selftest_log_index[1] << 8;
6392 			if (index == 0)
6393 				goto out;
6394 
6395 			--index;	/* Correct for 0 origin */
6396 			start_index = index;	/* remember where we started */
6397 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6398 			if (block_num != 0) {
6399 				rval = sata_ext_smart_selftest_read_log(
6400 				    sata_hba_inst, sdinfo, ext_selftest_log,
6401 				    block_num);
6402 				if (rval != 0)
6403 					goto out;
6404 			}
6405 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6406 			entry =
6407 			    &ext_selftest_log->
6408 			    smart_ext_selftest_log_entries[index];
6409 
6410 			for (count = 1;
6411 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
6412 			    ++count) {
6413 				uint8_t status;
6414 				uint8_t code;
6415 				uint8_t sense_key;
6416 				uint8_t add_sense_code;
6417 				uint8_t add_sense_code_qual;
6418 
6419 				/* If this is an unused entry, we are done */
6420 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
6421 					/* Broken firmware on some disks */
6422 					if (index + 1 ==
6423 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
6424 						--entry;
6425 						--index;
6426 						if (bcmp(entry, &empty,
6427 						    sizeof (empty)) == 0)
6428 							goto out;
6429 					} else
6430 						goto out;
6431 				}
6432 
6433 				if (only_one_block &&
6434 				    start_index == index)
6435 					goto out;
6436 
6437 				lpp->param_code[0] = 0;
6438 				lpp->param_code[1] = count;
6439 				lpp->param_ctrl_flags =
6440 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
6441 				lpp->param_len =
6442 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
6443 
6444 				status = entry->smart_ext_selftest_log_status;
6445 				status >>= 4;
6446 				switch (status) {
6447 				case 0:
6448 				default:
6449 					sense_key = KEY_NO_SENSE;
6450 					add_sense_code =
6451 					    SD_SCSI_ASC_NO_ADD_SENSE;
6452 					add_sense_code_qual = 0;
6453 					break;
6454 				case 1:
6455 					sense_key = KEY_ABORTED_COMMAND;
6456 					add_sense_code =
6457 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6458 					add_sense_code_qual = SCSI_COMPONENT_81;
6459 					break;
6460 				case 2:
6461 					sense_key = KEY_ABORTED_COMMAND;
6462 					add_sense_code =
6463 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6464 					add_sense_code_qual = SCSI_COMPONENT_82;
6465 					break;
6466 				case 3:
6467 					sense_key = KEY_ABORTED_COMMAND;
6468 					add_sense_code =
6469 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6470 					add_sense_code_qual = SCSI_COMPONENT_83;
6471 					break;
6472 				case 4:
6473 					sense_key = KEY_HARDWARE_ERROR;
6474 					add_sense_code =
6475 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6476 					add_sense_code_qual = SCSI_COMPONENT_84;
6477 					break;
6478 				case 5:
6479 					sense_key = KEY_HARDWARE_ERROR;
6480 					add_sense_code =
6481 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6482 					add_sense_code_qual = SCSI_COMPONENT_85;
6483 					break;
6484 				case 6:
6485 					sense_key = KEY_HARDWARE_ERROR;
6486 					add_sense_code =
6487 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6488 					add_sense_code_qual = SCSI_COMPONENT_86;
6489 					break;
6490 				case 7:
6491 					sense_key = KEY_MEDIUM_ERROR;
6492 					add_sense_code =
6493 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6494 					add_sense_code_qual = SCSI_COMPONENT_87;
6495 					break;
6496 				case 8:
6497 					sense_key = KEY_HARDWARE_ERROR;
6498 					add_sense_code =
6499 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6500 					add_sense_code_qual = SCSI_COMPONENT_88;
6501 					break;
6502 				}
6503 				code = 0;	/* unspecified */
6504 				status |= (code << 4);
6505 				lpp->param_values[0] = status;
6506 				lpp->param_values[1] = 0; /* unspecified */
6507 				lpp->param_values[2] = entry->
6508 				    smart_ext_selftest_log_timestamp[1];
6509 				lpp->param_values[3] = entry->
6510 				    smart_ext_selftest_log_timestamp[0];
6511 				if (status != 0) {
6512 					lpp->param_values[4] = 0;
6513 					lpp->param_values[5] = 0;
6514 					lpp->param_values[6] = entry->
6515 					    smart_ext_selftest_log_failing_lba
6516 					    [5];
6517 					lpp->param_values[7] = entry->
6518 					    smart_ext_selftest_log_failing_lba
6519 					    [4];
6520 					lpp->param_values[8] = entry->
6521 					    smart_ext_selftest_log_failing_lba
6522 					    [3];
6523 					lpp->param_values[9] = entry->
6524 					    smart_ext_selftest_log_failing_lba
6525 					    [2];
6526 					lpp->param_values[10] = entry->
6527 					    smart_ext_selftest_log_failing_lba
6528 					    [1];
6529 					lpp->param_values[11] = entry->
6530 					    smart_ext_selftest_log_failing_lba
6531 					    [0];
6532 				} else {	/* No bad block address */
6533 					lpp->param_values[4] = 0xff;
6534 					lpp->param_values[5] = 0xff;
6535 					lpp->param_values[6] = 0xff;
6536 					lpp->param_values[7] = 0xff;
6537 					lpp->param_values[8] = 0xff;
6538 					lpp->param_values[9] = 0xff;
6539 					lpp->param_values[10] = 0xff;
6540 					lpp->param_values[11] = 0xff;
6541 				}
6542 
6543 				lpp->param_values[12] = sense_key;
6544 				lpp->param_values[13] = add_sense_code;
6545 				lpp->param_values[14] = add_sense_code_qual;
6546 				lpp->param_values[15] = 0; /* undefined */
6547 
6548 				lpp = (struct log_parameter *)
6549 				    (((uint8_t *)lpp) +
6550 				    SCSI_LOG_PARAM_HDR_LEN +
6551 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
6552 
6553 				--index;	/* Back up to previous entry */
6554 				if (index < 0) {
6555 					if (block_num > 0) {
6556 						--block_num;
6557 					} else {
6558 						struct read_log_ext_directory
6559 						    logdir;
6560 
6561 						rval =
6562 						    sata_read_log_ext_directory(
6563 						    sata_hba_inst, sdinfo,
6564 						    &logdir);
6565 						if (rval == -1)
6566 							goto out;
6567 						if ((logdir.read_log_ext_vers
6568 						    [0] == 0) &&
6569 						    (logdir.read_log_ext_vers
6570 						    [1] == 0))
6571 							goto out;
6572 						block_num =
6573 						    logdir.read_log_ext_nblks
6574 						    [EXT_SMART_SELFTEST_LOG_PAGE
6575 						    - 1][0];
6576 						block_num |= logdir.
6577 						    read_log_ext_nblks
6578 						    [EXT_SMART_SELFTEST_LOG_PAGE
6579 						    - 1][1] << 8;
6580 						--block_num;
6581 						only_one_block =
6582 						    (block_num == 0);
6583 					}
6584 					rval = sata_ext_smart_selftest_read_log(
6585 					    sata_hba_inst, sdinfo,
6586 					    ext_selftest_log, block_num);
6587 					if (rval != 0)
6588 						goto out;
6589 
6590 					index =
6591 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
6592 					    1;
6593 				}
6594 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6595 				entry = &ext_selftest_log->
6596 				    smart_ext_selftest_log_entries[index];
6597 			}
6598 		}
6599 out:
6600 		kmem_free(ext_selftest_log,
6601 		    sizeof (struct smart_ext_selftest_log));
6602 	} else {
6603 		struct smart_selftest_log *selftest_log;
6604 
6605 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
6606 		    KM_SLEEP);
6607 
6608 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
6609 		    selftest_log);
6610 
6611 		if (rval == 0) {
6612 			int index;
6613 			int count;
6614 			struct smart_selftest_log_entry *entry;
6615 			static const struct smart_selftest_log_entry empty =
6616 			    { 0 };
6617 
6618 			index = selftest_log->smart_selftest_log_index;
6619 			if (index == 0)
6620 				goto done;
6621 			--index;	/* Correct for 0 origin */
6622 			entry = &selftest_log->
6623 			    smart_selftest_log_entries[index];
6624 			for (count = 1;
6625 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
6626 			    ++count) {
6627 				uint8_t status;
6628 				uint8_t code;
6629 				uint8_t sense_key;
6630 				uint8_t add_sense_code;
6631 				uint8_t add_sense_code_qual;
6632 
6633 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
6634 					goto done;
6635 
6636 				lpp->param_code[0] = 0;
6637 				lpp->param_code[1] = count;
6638 				lpp->param_ctrl_flags =
6639 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
6640 				lpp->param_len =
6641 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
6642 
6643 				status = entry->smart_selftest_log_status;
6644 				status >>= 4;
6645 				switch (status) {
6646 				case 0:
6647 				default:
6648 					sense_key = KEY_NO_SENSE;
6649 					add_sense_code =
6650 					    SD_SCSI_ASC_NO_ADD_SENSE;
6651 					break;
6652 				case 1:
6653 					sense_key = KEY_ABORTED_COMMAND;
6654 					add_sense_code =
6655 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6656 					add_sense_code_qual = SCSI_COMPONENT_81;
6657 					break;
6658 				case 2:
6659 					sense_key = KEY_ABORTED_COMMAND;
6660 					add_sense_code =
6661 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6662 					add_sense_code_qual = SCSI_COMPONENT_82;
6663 					break;
6664 				case 3:
6665 					sense_key = KEY_ABORTED_COMMAND;
6666 					add_sense_code =
6667 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6668 					add_sense_code_qual = SCSI_COMPONENT_83;
6669 					break;
6670 				case 4:
6671 					sense_key = KEY_HARDWARE_ERROR;
6672 					add_sense_code =
6673 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6674 					add_sense_code_qual = SCSI_COMPONENT_84;
6675 					break;
6676 				case 5:
6677 					sense_key = KEY_HARDWARE_ERROR;
6678 					add_sense_code =
6679 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6680 					add_sense_code_qual = SCSI_COMPONENT_85;
6681 					break;
6682 				case 6:
6683 					sense_key = KEY_HARDWARE_ERROR;
6684 					add_sense_code =
6685 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6686 					add_sense_code_qual = SCSI_COMPONENT_86;
6687 					break;
6688 				case 7:
6689 					sense_key = KEY_MEDIUM_ERROR;
6690 					add_sense_code =
6691 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6692 					add_sense_code_qual = SCSI_COMPONENT_87;
6693 					break;
6694 				case 8:
6695 					sense_key = KEY_HARDWARE_ERROR;
6696 					add_sense_code =
6697 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6698 					add_sense_code_qual = SCSI_COMPONENT_88;
6699 					break;
6700 				}
6701 				code = 0;	/* unspecified */
6702 				status |= (code << 4);
6703 				lpp->param_values[0] = status;
6704 				lpp->param_values[1] = 0; /* unspecified */
6705 				lpp->param_values[2] = entry->
6706 				    smart_selftest_log_timestamp[1];
6707 				lpp->param_values[3] = entry->
6708 				    smart_selftest_log_timestamp[0];
6709 				if (status != 0) {
6710 					lpp->param_values[4] = 0;
6711 					lpp->param_values[5] = 0;
6712 					lpp->param_values[6] = 0;
6713 					lpp->param_values[7] = 0;
6714 					lpp->param_values[8] = entry->
6715 					    smart_selftest_log_failing_lba[3];
6716 					lpp->param_values[9] = entry->
6717 					    smart_selftest_log_failing_lba[2];
6718 					lpp->param_values[10] = entry->
6719 					    smart_selftest_log_failing_lba[1];
6720 					lpp->param_values[11] = entry->
6721 					    smart_selftest_log_failing_lba[0];
6722 				} else {	/* No block address */
6723 					lpp->param_values[4] = 0xff;
6724 					lpp->param_values[5] = 0xff;
6725 					lpp->param_values[6] = 0xff;
6726 					lpp->param_values[7] = 0xff;
6727 					lpp->param_values[8] = 0xff;
6728 					lpp->param_values[9] = 0xff;
6729 					lpp->param_values[10] = 0xff;
6730 					lpp->param_values[11] = 0xff;
6731 				}
6732 				lpp->param_values[12] = sense_key;
6733 				lpp->param_values[13] = add_sense_code;
6734 				lpp->param_values[14] = add_sense_code_qual;
6735 				lpp->param_values[15] = 0; /* undefined */
6736 
6737 				lpp = (struct log_parameter *)
6738 				    (((uint8_t *)lpp) +
6739 				    SCSI_LOG_PARAM_HDR_LEN +
6740 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
6741 				--index;	/* back up to previous entry */
6742 				if (index < 0) {
6743 					index =
6744 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
6745 				}
6746 				entry = &selftest_log->
6747 				    smart_selftest_log_entries[index];
6748 			}
6749 		}
6750 done:
6751 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
6752 	}
6753 
6754 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
6755 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
6756 }
6757 
6758 /*
6759  * sata_build_lsense_page_2f() is used to create the
6760  * SCSI LOG SENSE page 0x10 (informational exceptions)
6761  *
6762  * Takes a sata_drive_info t * and the address of a buffer
6763  * in which to create the page information as well as a sata_hba_inst_t *.
6764  *
6765  * Returns the number of bytes valid in the buffer.
6766  */
6767 static	int
6768 sata_build_lsense_page_2f(
6769 	sata_drive_info_t *sdinfo,
6770 	uint8_t *buf,
6771 	sata_hba_inst_t *sata_hba_inst)
6772 {
6773 	struct log_parameter *lpp = (struct log_parameter *)buf;
6774 	int rval;
6775 	uint8_t *smart_data;
6776 	uint8_t temp;
6777 	sata_id_t *sata_id;
6778 #define	SMART_NO_TEMP	0xff
6779 
6780 	lpp->param_code[0] = 0;
6781 	lpp->param_code[1] = 0;
6782 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
6783 
6784 	/* Now get the SMART status w.r.t. threshold exceeded */
6785 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
6786 	switch (rval) {
6787 	case 1:
6788 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
6789 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
6790 		break;
6791 	case 0:
6792 	case -1:	/* failed to get data */
6793 		lpp->param_values[0] = 0;	/* No failure predicted */
6794 		lpp->param_values[1] = 0;
6795 		break;
6796 #if defined(SATA_DEBUG)
6797 	default:
6798 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
6799 		/* NOTREACHED */
6800 #endif
6801 	}
6802 
6803 	sata_id = &sdinfo->satadrv_id;
6804 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
6805 		temp = SMART_NO_TEMP;
6806 	else {
6807 		/* Now get the temperature */
6808 		smart_data = kmem_zalloc(512, KM_SLEEP);
6809 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
6810 		    SCT_STATUS_LOG_PAGE, 1);
6811 		if (rval == -1)
6812 			temp = SMART_NO_TEMP;
6813 		else {
6814 			temp = smart_data[200];
6815 			if (temp & 0x80) {
6816 				if (temp & 0x7f)
6817 					temp = 0;
6818 				else
6819 					temp = SMART_NO_TEMP;
6820 			}
6821 		}
6822 		kmem_free(smart_data, 512);
6823 	}
6824 
6825 	lpp->param_values[2] = temp;	/* most recent temperature */
6826 	lpp->param_values[3] = 0;	/* required vendor specific byte */
6827 
6828 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
6829 
6830 
6831 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
6832 }
6833 
6834 /*
6835  * sata_build_lsense_page_30() is used to create the
6836  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
6837  *
6838  * Takes a sata_drive_info t * and the address of a buffer
6839  * in which to create the page information as well as a sata_hba_inst_t *.
6840  *
6841  * Returns the number of bytes valid in the buffer.
6842  */
6843 static int
6844 sata_build_lsense_page_30(
6845 	sata_drive_info_t *sdinfo,
6846 	uint8_t *buf,
6847 	sata_hba_inst_t *sata_hba_inst)
6848 {
6849 	struct smart_data *smart_data = (struct smart_data *)buf;
6850 	int rval;
6851 
6852 	/* Now do the SMART READ DATA */
6853 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
6854 	if (rval == -1)
6855 		return (0);
6856 
6857 	return (sizeof (struct smart_data));
6858 }
6859 
6860 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
6861 
6862 /*
6863  * Start command for ATAPI device.
6864  * This function processes scsi_pkt requests.
6865  * Only CD/DVD devices are supported.
6866  * Most commands are packet without any translation into Packet Command.
6867  * Some may be trapped and executed as SATA commands (not clear which one).
6868  *
6869  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
6870  * execution).
6871  * Returns other TRAN_XXXX codes if command is not accepted or completed
6872  * (see return values for sata_hba_start()).
6873  *
6874  * Note:
6875  * Inquiry cdb format differs between transport version 2 and 3.
6876  * However, the transport version 3 devices that were checked did not adhere
6877  * to the specification (ignored MSB of the allocation length). Therefore,
6878  * the transport version is not checked, but Inquiry allocation length is
6879  * truncated to 255 bytes if the original allocation length set-up by the
6880  * target driver is greater than 255 bytes.
6881  */
6882 static int
6883 sata_txlt_atapi(sata_pkt_txlate_t *spx)
6884 {
6885 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6886 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6887 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6888 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
6889 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
6890 	    &spx->txlt_sata_pkt->satapkt_device);
6891 	int cport = SATA_TXLT_CPORT(spx);
6892 	int cdblen;
6893 	int rval;
6894 	int synch;
6895 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
6896 
6897 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6898 
6899 	if (((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) ||
6900 	    (spx->txlt_scsi_pkt->pkt_reason == CMD_DEV_GONE)) {
6901 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6902 		return (rval);
6903 	}
6904 
6905 	/*
6906 	 * ATAPI device executes some ATA commands in addition to MMC command
6907 	 * set. These ATA commands may be executed by the regular SATA
6908 	 * translation functions. None needs to be captured now.
6909 	 * Other commands belong to MMC command set and are delivered
6910 	 * to ATAPI device via Packet Command.
6911 	 */
6912 
6913 	/* Check the size of cdb */
6914 	cdblen = scsi_cdb_size[GETGROUP(cdbp)];
6915 	if (cdblen > sdinfo->satadrv_atapi_cdb_len) {
6916 		sata_log(NULL, CE_WARN,
6917 		    "sata: invalid ATAPI cdb length %d",
6918 		    scsipkt->pkt_cdblen);
6919 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6920 		return (TRAN_BADPKT);
6921 	}
6922 
6923 	SATAATAPITRACE(spx, cdblen);
6924 
6925 	/*
6926 	 * For non-read/write commands we need to
6927 	 * map buffer
6928 	 */
6929 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
6930 	case SCMD_READ:
6931 	case SCMD_READ_G1:
6932 	case SCMD_READ_G5:
6933 	case SCMD_READ_G4:
6934 	case SCMD_WRITE:
6935 	case SCMD_WRITE_G1:
6936 	case SCMD_WRITE_G5:
6937 	case SCMD_WRITE_G4:
6938 		break;
6939 	default:
6940 		if (bp != NULL) {
6941 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
6942 				bp_mapin(bp);
6943 		}
6944 		break;
6945 	}
6946 	/*
6947 	 * scmd->satacmd_flags.sata_data_direction default -
6948 	 * SATA_DIR_NODATA_XFER - is set by
6949 	 * sata_txlt_generic_pkt_info().
6950 	 */
6951 	if (scmd->satacmd_bp) {
6952 		if (scmd->satacmd_bp->b_flags & B_READ) {
6953 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
6954 		} else {
6955 			scmd->satacmd_flags.sata_data_direction =
6956 			    SATA_DIR_WRITE;
6957 		}
6958 	}
6959 
6960 	/*
6961 	 * Set up ATAPI packet command.
6962 	 */
6963 
6964 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
6965 
6966 	/* Copy cdb into sata_cmd */
6967 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
6968 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
6969 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
6970 
6971 	/* See note in the command header */
6972 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
6973 		if (scmd->satacmd_acdb[3] != 0)
6974 			scmd->satacmd_acdb[4] = 255;
6975 	}
6976 
6977 #ifdef SATA_DEBUG
6978 	if (sata_debug_flags & SATA_DBG_ATAPI) {
6979 		uint8_t *p = scmd->satacmd_acdb;
6980 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
6981 
6982 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
6983 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
6984 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
6985 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
6986 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
6987 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
6988 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
6989 	}
6990 #endif
6991 
6992 	/*
6993 	 * Preset request sense data to NO SENSE.
6994 	 * If there is no way to get error information via Request Sense,
6995 	 * the packet request sense data would not have to be modified by HBA,
6996 	 * but it could be returned as is.
6997 	 */
6998 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
6999 	sata_fixed_sense_data_preset(
7000 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
7001 
7002 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
7003 		/* Need callback function */
7004 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
7005 		synch = FALSE;
7006 	} else
7007 		synch = TRUE;
7008 
7009 	/* Transfer command to HBA */
7010 	if (sata_hba_start(spx, &rval) != 0) {
7011 		/* Pkt not accepted for execution */
7012 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
7013 		return (rval);
7014 	}
7015 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
7016 	/*
7017 	 * If execution is non-synchronous,
7018 	 * a callback function will handle potential errors, translate
7019 	 * the response and will do a callback to a target driver.
7020 	 * If it was synchronous, use the same framework callback to check
7021 	 * an execution status.
7022 	 */
7023 	if (synch) {
7024 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7025 		    "synchronous execution status %x\n",
7026 		    spx->txlt_sata_pkt->satapkt_reason);
7027 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
7028 	}
7029 	return (TRAN_ACCEPT);
7030 }
7031 
7032 
7033 /*
7034  * ATAPI Packet command completion.
7035  *
7036  * Failure of the command passed via Packet command are considered device
7037  * error. SATA HBA driver would have to retrieve error data (via Request
7038  * Sense command delivered via error retrieval sata packet) and copy it
7039  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
7040  */
7041 static void
7042 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
7043 {
7044 	sata_pkt_txlate_t *spx =
7045 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7046 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7047 	struct scsi_extended_sense *sense;
7048 	struct buf *bp;
7049 	int rval;
7050 
7051 #ifdef SATA_DEBUG
7052 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
7053 #endif
7054 
7055 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7056 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7057 
7058 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7059 		/* Normal completion */
7060 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
7061 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
7062 		scsipkt->pkt_reason = CMD_CMPLT;
7063 		*scsipkt->pkt_scbp = STATUS_GOOD;
7064 		if (spx->txlt_tmp_buf != NULL) {
7065 			/* Temporary buffer was used */
7066 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7067 			if (bp->b_flags & B_READ) {
7068 				rval = ddi_dma_sync(
7069 				    spx->txlt_buf_dma_handle, 0, 0,
7070 				    DDI_DMA_SYNC_FORCPU);
7071 				ASSERT(rval == DDI_SUCCESS);
7072 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7073 				    bp->b_bcount);
7074 			}
7075 		}
7076 	} else {
7077 		/*
7078 		 * Something went wrong - analyze return
7079 		 */
7080 		*scsipkt->pkt_scbp = STATUS_CHECK;
7081 		sense = sata_arq_sense(spx);
7082 
7083 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
7084 			scsipkt->pkt_reason = CMD_INCOMPLETE;
7085 			/*
7086 			 * We may not have ARQ data if there was a double
7087 			 * error. But sense data in sata packet was pre-set
7088 			 * with NO SENSE so it is valid even if HBA could
7089 			 * not retrieve a real sense data.
7090 			 * Just copy this sense data into scsi pkt sense area.
7091 			 */
7092 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
7093 			    SATA_ATAPI_MIN_RQSENSE_LEN);
7094 #ifdef SATA_DEBUG
7095 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
7096 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
7097 				    "sata_txlt_atapi_completion: %02x\n"
7098 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
7099 				    "          %02x %02x %02x %02x %02x %02x "
7100 				    "          %02x %02x %02x %02x %02x %02x\n",
7101 				    scsipkt->pkt_reason,
7102 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
7103 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
7104 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
7105 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
7106 				    rqsp[16], rqsp[17]);
7107 			}
7108 #endif
7109 		} else {
7110 			switch (sata_pkt->satapkt_reason) {
7111 			case SATA_PKT_PORT_ERROR:
7112 				/*
7113 				 * We have no device data.
7114 				 */
7115 				scsipkt->pkt_reason = CMD_INCOMPLETE;
7116 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
7117 				    STATE_GOT_TARGET | STATE_SENT_CMD |
7118 				    STATE_GOT_STATUS);
7119 				sense->es_key = KEY_HARDWARE_ERROR;
7120 				break;
7121 
7122 			case SATA_PKT_TIMEOUT:
7123 				scsipkt->pkt_reason = CMD_TIMEOUT;
7124 				scsipkt->pkt_statistics |=
7125 				    STAT_TIMEOUT | STAT_DEV_RESET;
7126 				/*
7127 				 * Need to check if HARDWARE_ERROR/
7128 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
7129 				 * appropriate.
7130 				 */
7131 				break;
7132 
7133 			case SATA_PKT_ABORTED:
7134 				scsipkt->pkt_reason = CMD_ABORTED;
7135 				scsipkt->pkt_statistics |= STAT_ABORTED;
7136 				/* Should we set key COMMAND_ABPRTED? */
7137 				break;
7138 
7139 			case SATA_PKT_RESET:
7140 				scsipkt->pkt_reason = CMD_RESET;
7141 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
7142 				/*
7143 				 * May be we should set Unit Attention /
7144 				 * Reset. Perhaps the same should be
7145 				 * returned for disks....
7146 				 */
7147 				sense->es_key = KEY_UNIT_ATTENTION;
7148 				sense->es_add_code = SD_SCSI_ASC_RESET;
7149 				break;
7150 
7151 			default:
7152 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7153 				    "sata_txlt_atapi_completion: "
7154 				    "invalid packet completion reason"));
7155 				scsipkt->pkt_reason = CMD_TRAN_ERR;
7156 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
7157 				    STATE_GOT_TARGET | STATE_SENT_CMD |
7158 				    STATE_GOT_STATUS);
7159 				break;
7160 			}
7161 		}
7162 	}
7163 
7164 	SATAATAPITRACE(spx, 0);
7165 
7166 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
7167 	    scsipkt->pkt_comp != NULL) {
7168 		/* scsi callback required */
7169 		(*scsipkt->pkt_comp)(scsipkt);
7170 	}
7171 }
7172 
7173 /*
7174  * Set up error retrieval sata command for ATAPI Packet Command error data
7175  * recovery.
7176  *
7177  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
7178  * returns SATA_FAILURE otherwise.
7179  */
7180 
7181 static int
7182 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
7183 {
7184 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
7185 	sata_cmd_t *scmd;
7186 	struct buf *bp;
7187 
7188 	/*
7189 	 * Allocate dma-able buffer error data.
7190 	 * Buffer allocation will take care of buffer alignment and other DMA
7191 	 * attributes.
7192 	 */
7193 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
7194 	if (bp == NULL) {
7195 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
7196 		    "sata_get_err_retrieval_pkt: "
7197 		    "cannot allocate buffer for error data", NULL);
7198 		return (SATA_FAILURE);
7199 	}
7200 	bp_mapin(bp); /* make data buffer accessible */
7201 
7202 	/* Operation modes are up to the caller */
7203 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
7204 
7205 	/* Synchronous mode, no callback - may be changed by the caller */
7206 	spkt->satapkt_comp = NULL;
7207 	spkt->satapkt_time = sata_default_pkt_time;
7208 
7209 	scmd = &spkt->satapkt_cmd;
7210 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
7211 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
7212 
7213 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
7214 
7215 	/*
7216 	 * Set-up acdb. Request Sense CDB (packet command content) is
7217 	 * not in DMA-able buffer. Its handling is HBA-specific (how
7218 	 * it is transfered into packet FIS).
7219 	 */
7220 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
7221 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
7222 	/* Following zeroing of pad bytes may not be necessary */
7223 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
7224 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
7225 
7226 	/*
7227 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
7228 	 * before accessing it. Handle is in usual place in translate struct.
7229 	 */
7230 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
7231 
7232 	/*
7233 	 * Preset request sense data to NO SENSE.
7234 	 * Here it is redundant, only for a symetry with scsi-originated
7235 	 * packets. It should not be used for anything but debugging.
7236 	 */
7237 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
7238 	sata_fixed_sense_data_preset(
7239 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
7240 
7241 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
7242 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
7243 
7244 	return (SATA_SUCCESS);
7245 }
7246 
7247 /*
7248  * Set-up ATAPI packet command.
7249  * Data transfer direction has to be set-up in sata_cmd structure prior to
7250  * calling this function.
7251  *
7252  * Returns void
7253  */
7254 
7255 static void
7256 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
7257 {
7258 	scmd->satacmd_addr_type = 0;		/* N/A */
7259 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
7260 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
7261 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
7262 	scmd->satacmd_lba_high_lsb =
7263 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
7264 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
7265 
7266 	/*
7267 	 * We want all data to be transfered via DMA.
7268 	 * But specify it only if drive supports DMA and DMA mode is
7269 	 * selected - some drives are sensitive about it.
7270 	 * Hopefully it wil work for all drives....
7271 	 */
7272 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
7273 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
7274 
7275 	/*
7276 	 * Features register requires special care for devices that use
7277 	 * Serial ATA bridge - they need an explicit specification of
7278 	 * the data transfer direction for Packet DMA commands.
7279 	 * Setting this bit is harmless if DMA is not used.
7280 	 *
7281 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
7282 	 * spec they follow.
7283 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
7284 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
7285 	 * ATA/ATAPI-7 support is explicitly indicated.
7286 	 */
7287 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
7288 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
7289 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
7290 		/*
7291 		 * Specification of major version is valid and version 7
7292 		 * is supported. It does automatically imply that all
7293 		 * spec features are supported. For now, we assume that
7294 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
7295 		 */
7296 		if ((sdinfo->satadrv_id.ai_dirdma &
7297 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
7298 			if (scmd->satacmd_flags.sata_data_direction ==
7299 			    SATA_DIR_READ)
7300 			scmd->satacmd_features_reg |=
7301 			    SATA_ATAPI_F_DATA_DIR_READ;
7302 		}
7303 	}
7304 }
7305 
7306 
7307 #ifdef SATA_DEBUG
7308 
7309 /* Display 18 bytes of Inquiry data */
7310 static void
7311 sata_show_inqry_data(uint8_t *buf)
7312 {
7313 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
7314 	uint8_t *p;
7315 
7316 	cmn_err(CE_NOTE, "Inquiry data:");
7317 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
7318 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
7319 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
7320 	cmn_err(CE_NOTE, "ATAPI transport version %d",
7321 	    SATA_ATAPI_TRANS_VERSION(inq));
7322 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
7323 	    inq->inq_rdf, inq->inq_aenc);
7324 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
7325 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
7326 	p = (uint8_t *)inq->inq_vid;
7327 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
7328 	    "%02x %02x %02x %02x",
7329 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
7330 	p = (uint8_t *)inq->inq_vid;
7331 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
7332 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
7333 
7334 	p = (uint8_t *)inq->inq_pid;
7335 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
7336 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
7337 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
7338 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
7339 	p = (uint8_t *)inq->inq_pid;
7340 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
7341 	    "%c %c %c %c %c %c %c %c",
7342 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
7343 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
7344 
7345 	p = (uint8_t *)inq->inq_revision;
7346 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
7347 	    p[0], p[1], p[2], p[3]);
7348 	p = (uint8_t *)inq->inq_revision;
7349 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
7350 	    p[0], p[1], p[2], p[3]);
7351 
7352 }
7353 
7354 
7355 static void
7356 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
7357 {
7358 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
7359 
7360 	if (scsi_pkt == NULL)
7361 		return;
7362 	if (count != 0) {
7363 		/* saving cdb */
7364 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
7365 		    SATA_ATAPI_MAX_CDB_LEN);
7366 		bcopy(scsi_pkt->pkt_cdbp,
7367 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
7368 	} else {
7369 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
7370 		    sts_sensedata,
7371 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
7372 		    SATA_ATAPI_MIN_RQSENSE_LEN);
7373 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
7374 		    scsi_pkt->pkt_reason;
7375 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
7376 		    spx->txlt_sata_pkt->satapkt_reason;
7377 
7378 		if (++sata_atapi_trace_index >= 64)
7379 			sata_atapi_trace_index = 0;
7380 	}
7381 }
7382 
7383 #endif
7384 
7385 /*
7386  * Fetch inquiry data from ATAPI device
7387  * Returns SATA_SUCCESS if operation was successfull, SATA_FAILURE otherwise.
7388  *
7389  * Note:
7390  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
7391  * where the caller expects to see the inquiry data.
7392  *
7393  */
7394 
7395 static int
7396 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
7397     sata_address_t *saddr, struct scsi_inquiry *inq)
7398 {
7399 	sata_pkt_txlate_t *spx;
7400 	sata_pkt_t *spkt;
7401 	struct buf *bp;
7402 	sata_drive_info_t *sdinfo;
7403 	sata_cmd_t *scmd;
7404 	int rval;
7405 	uint8_t *rqsp;
7406 #ifdef SATA_DEBUG
7407 	char msg_buf[MAXPATHLEN];
7408 #endif
7409 
7410 	ASSERT(sata_hba != NULL);
7411 
7412 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
7413 	spx->txlt_sata_hba_inst = sata_hba;
7414 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
7415 	spkt = sata_pkt_alloc(spx, NULL);
7416 	if (spkt == NULL) {
7417 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
7418 		return (SATA_FAILURE);
7419 	}
7420 	/* address is needed now */
7421 	spkt->satapkt_device.satadev_addr = *saddr;
7422 
7423 	/* scsi_inquiry size buffer */
7424 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
7425 	if (bp == NULL) {
7426 		sata_pkt_free(spx);
7427 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
7428 		SATA_LOG_D((sata_hba, CE_WARN,
7429 		    "sata_get_atapi_inquiry_data: "
7430 		    "cannot allocate data buffer"));
7431 		return (SATA_FAILURE);
7432 	}
7433 	bp_mapin(bp); /* make data buffer accessible */
7434 
7435 	scmd = &spkt->satapkt_cmd;
7436 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
7437 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
7438 
7439 	/* Use synchronous mode */
7440 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
7441 	spkt->satapkt_comp = NULL;
7442 	spkt->satapkt_time = sata_default_pkt_time;
7443 
7444 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
7445 
7446 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
7447 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
7448 
7449 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
7450 	sdinfo = sata_get_device_info(sata_hba,
7451 	    &spx->txlt_sata_pkt->satapkt_device);
7452 	if (sdinfo == NULL) {
7453 		/* we have to be carefull about the disapearing device */
7454 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
7455 		rval = SATA_FAILURE;
7456 		goto cleanup;
7457 	}
7458 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
7459 
7460 	/*
7461 	 * Set-up acdb. This works for atapi transport version 2 and later.
7462 	 */
7463 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
7464 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
7465 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
7466 	scmd->satacmd_acdb[1] = 0x00;
7467 	scmd->satacmd_acdb[2] = 0x00;
7468 	scmd->satacmd_acdb[3] = 0x00;
7469 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
7470 	scmd->satacmd_acdb[5] = 0x00;
7471 
7472 	sata_fixed_sense_data_preset(
7473 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
7474 
7475 	/* Transfer command to HBA */
7476 	if (sata_hba_start(spx, &rval) != 0) {
7477 		/* Pkt not accepted for execution */
7478 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
7479 		    "sata_get_atapi_inquiry_data: "
7480 		    "Packet not accepted for execution - ret: %02x", rval);
7481 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
7482 		rval = SATA_FAILURE;
7483 		goto cleanup;
7484 	}
7485 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
7486 
7487 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
7488 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
7489 		    "sata_get_atapi_inquiry_data: "
7490 		    "Packet completed successfully - ret: %02x", rval);
7491 		/*
7492 		 * Sync buffer. Handle is in usual place in translate struct.
7493 		 * Normal completion - copy data into caller's buffer
7494 		 */
7495 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
7496 		    DDI_DMA_SYNC_FORCPU);
7497 		ASSERT(rval == DDI_SUCCESS);
7498 		bcopy(bp->b_un.b_addr, (uint8_t *)inq,
7499 		    sizeof (struct scsi_inquiry));
7500 #ifdef SATA_DEBUG
7501 		if (sata_debug_flags & SATA_DBG_ATAPI) {
7502 			sata_show_inqry_data((uint8_t *)inq);
7503 		}
7504 #endif
7505 		rval = SATA_SUCCESS;
7506 	} else {
7507 		/*
7508 		 * Something went wrong - analyze return - check rqsense data
7509 		 */
7510 		rval = SATA_FAILURE;
7511 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
7512 			/*
7513 			 * ARQ data hopefull show something other than NO SENSE
7514 			 */
7515 			rqsp = scmd->satacmd_rqsense;
7516 #ifdef SATA_DEBUG
7517 			if (sata_debug_flags & SATA_DBG_ATAPI) {
7518 				msg_buf[0] = '\0';
7519 				(void) snprintf(msg_buf, MAXPATHLEN,
7520 				    "ATAPI packet completion reason: %02x\n"
7521 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
7522 				    "          %02x %02x %02x %02x %02x %02x\n"
7523 				    "          %02x %02x %02x %02x %02x %02x",
7524 				    spkt->satapkt_reason,
7525 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
7526 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
7527 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
7528 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
7529 				    rqsp[16], rqsp[17]);
7530 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
7531 				    "%s", msg_buf);
7532 			}
7533 #endif
7534 		} else {
7535 			switch (spkt->satapkt_reason) {
7536 			case SATA_PKT_PORT_ERROR:
7537 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7538 				    "sata_get_atapi_inquiry_data: "
7539 				    "packet reason: port error", NULL);
7540 				break;
7541 
7542 			case SATA_PKT_TIMEOUT:
7543 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7544 				    "sata_get_atapi_inquiry_data: "
7545 				    "packet reason: timeout", NULL);
7546 				break;
7547 
7548 			case SATA_PKT_ABORTED:
7549 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7550 				    "sata_get_atapi_inquiry_data: "
7551 				    "packet reason: aborted", NULL);
7552 				break;
7553 
7554 			case SATA_PKT_RESET:
7555 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7556 				    "sata_get_atapi_inquiry_data: "
7557 				    "packet reason: reset\n", NULL);
7558 				break;
7559 			default:
7560 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7561 				    "sata_get_atapi_inquiry_data: "
7562 				    "invalid packet reason: %02x\n",
7563 				    spkt->satapkt_reason);
7564 				break;
7565 			}
7566 		}
7567 	}
7568 cleanup:
7569 	sata_free_local_buffer(spx);
7570 	sata_pkt_free(spx);
7571 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
7572 	return (rval);
7573 }
7574 
7575 
7576 
7577 
7578 
7579 #if 0
7580 #ifdef SATA_DEBUG
7581 
7582 /*
7583  * Test ATAPI packet command.
7584  * Single threaded test: send packet command in synch mode, process completion
7585  *
7586  */
7587 static void
7588 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
7589 {
7590 	sata_pkt_txlate_t *spx;
7591 	sata_pkt_t *spkt;
7592 	struct buf *bp;
7593 	sata_device_t sata_device;
7594 	sata_drive_info_t *sdinfo;
7595 	sata_cmd_t *scmd;
7596 	int rval;
7597 	uint8_t *rqsp;
7598 
7599 	ASSERT(sata_hba_inst != NULL);
7600 	sata_device.satadev_addr.cport = cport;
7601 	sata_device.satadev_addr.pmport = 0;
7602 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
7603 	sata_device.satadev_rev = SATA_DEVICE_REV;
7604 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7605 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
7606 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7607 	if (sdinfo == NULL) {
7608 		sata_log(sata_hba_inst, CE_WARN,
7609 		    "sata_test_atapi_packet_command: "
7610 		    "no device info for cport %d",
7611 		    sata_device.satadev_addr.cport);
7612 		return;
7613 	}
7614 
7615 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
7616 	spx->txlt_sata_hba_inst = sata_hba_inst;
7617 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
7618 	spkt = sata_pkt_alloc(spx, NULL);
7619 	if (spkt == NULL) {
7620 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
7621 		return;
7622 	}
7623 	/* address is needed now */
7624 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
7625 
7626 	/* 1024k buffer */
7627 	bp = sata_alloc_local_buffer(spx, 1024);
7628 	if (bp == NULL) {
7629 		sata_pkt_free(spx);
7630 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
7631 		sata_log(sata_hba_inst, CE_WARN,
7632 		    "sata_test_atapi_packet_command: "
7633 		    "cannot allocate data buffer");
7634 		return;
7635 	}
7636 	bp_mapin(bp); /* make data buffer accessible */
7637 
7638 	scmd = &spkt->satapkt_cmd;
7639 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
7640 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
7641 
7642 	/* Use synchronous mode */
7643 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
7644 
7645 	/* Synchronous mode, no callback - may be changed by the caller */
7646 	spkt->satapkt_comp = NULL;
7647 	spkt->satapkt_time = sata_default_pkt_time;
7648 
7649 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
7650 
7651 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
7652 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
7653 
7654 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
7655 
7656 	/* Set-up acdb. */
7657 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
7658 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
7659 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
7660 	scmd->satacmd_acdb[1] = 0x00;
7661 	scmd->satacmd_acdb[2] = 0x00;
7662 	scmd->satacmd_acdb[3] = 0x00;
7663 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
7664 	scmd->satacmd_acdb[5] = 0x00;
7665 
7666 	sata_fixed_sense_data_preset(
7667 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
7668 
7669 	/* Transfer command to HBA */
7670 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7671 	if (sata_hba_start(spx, &rval) != 0) {
7672 		/* Pkt not accepted for execution */
7673 		sata_log(sata_hba_inst, CE_WARN,
7674 		    "sata_test_atapi_packet_command: "
7675 		    "Packet not accepted for execution - ret: %02x", rval);
7676 		mutex_exit(
7677 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7678 		goto cleanup;
7679 	}
7680 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7681 
7682 	/*
7683 	 * Sync buffer. Handle is in usual place in translate struct.
7684 	 */
7685 	rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
7686 	    DDI_DMA_SYNC_FORCPU);
7687 	ASSERT(rval == DDI_SUCCESS);
7688 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
7689 		sata_log(sata_hba_inst, CE_WARN,
7690 		    "sata_test_atapi_packet_command: "
7691 		    "Packet completed successfully");
7692 		/*
7693 		 * Normal completion - show inquiry data
7694 		 */
7695 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
7696 	} else {
7697 		/*
7698 		 * Something went wrong - analyze return - check rqsense data
7699 		 */
7700 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
7701 			/*
7702 			 * ARQ data hopefull show something other than NO SENSE
7703 			 */
7704 			rqsp = scmd->satacmd_rqsense;
7705 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
7706 			    "ATAPI packet completion reason: %02x\n"
7707 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
7708 			    "          %02x %02x %02x %02x %02x %02x "
7709 			    "          %02x %02x %02x %02x %02x %02x\n",
7710 			    spkt->satapkt_reason,
7711 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
7712 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
7713 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
7714 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
7715 			    rqsp[16], rqsp[17]);
7716 		} else {
7717 			switch (spkt->satapkt_reason) {
7718 			case SATA_PKT_PORT_ERROR:
7719 				sata_log(sata_hba_inst, CE_WARN,
7720 				    "sata_test_atapi_packet_command: "
7721 				    "packet reason: port error\n");
7722 				break;
7723 
7724 			case SATA_PKT_TIMEOUT:
7725 				sata_log(sata_hba_inst, CE_WARN,
7726 				    "sata_test_atapi_packet_command: "
7727 				    "packet reason: timeout\n");
7728 				break;
7729 
7730 			case SATA_PKT_ABORTED:
7731 				sata_log(sata_hba_inst, CE_WARN,
7732 				    "sata_test_atapi_packet_command: "
7733 				    "packet reason: aborted\n");
7734 				break;
7735 
7736 			case SATA_PKT_RESET:
7737 				sata_log(sata_hba_inst, CE_WARN,
7738 				    "sata_test_atapi_packet_command: "
7739 				    "packet reason: reset\n");
7740 				break;
7741 			default:
7742 				sata_log(sata_hba_inst, CE_WARN,
7743 				    "sata_test_atapi_packet_command: "
7744 				    "invalid packet reason: %02x\n",
7745 				    spkt->satapkt_reason);
7746 				break;
7747 			}
7748 		}
7749 	}
7750 cleanup:
7751 	sata_free_local_buffer(spx);
7752 	sata_pkt_free(spx);
7753 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
7754 }
7755 
7756 #endif /* SATA_DEBUG */
7757 #endif /* 1 */
7758 
7759 
7760 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
7761 
7762 /*
7763  * Validate sata_tran info
7764  * SATA_FAILURE returns if structure is inconsistent or structure revision
7765  * does not match one used by the framework.
7766  *
7767  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
7768  * required function pointers.
7769  * Returns SATA_FAILURE otherwise.
7770  */
7771 static int
7772 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
7773 {
7774 	/*
7775 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
7776 	 * of the SATA interface.
7777 	 */
7778 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
7779 		sata_log(NULL, CE_WARN,
7780 		    "sata: invalid sata_hba_tran version %d for driver %s",
7781 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
7782 		return (SATA_FAILURE);
7783 	}
7784 
7785 	if (dip != sata_tran->sata_tran_hba_dip) {
7786 		SATA_LOG_D((NULL, CE_WARN,
7787 		    "sata: inconsistent sata_tran_hba_dip "
7788 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
7789 		return (SATA_FAILURE);
7790 	}
7791 
7792 	if (sata_tran->sata_tran_probe_port == NULL ||
7793 	    sata_tran->sata_tran_start == NULL ||
7794 	    sata_tran->sata_tran_abort == NULL ||
7795 	    sata_tran->sata_tran_reset_dport == NULL ||
7796 	    sata_tran->sata_tran_hotplug_ops == NULL ||
7797 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
7798 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
7799 	    NULL) {
7800 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
7801 		    "required functions"));
7802 	}
7803 	return (SATA_SUCCESS);
7804 }
7805 
7806 /*
7807  * Remove HBA instance from sata_hba_list.
7808  */
7809 static void
7810 sata_remove_hba_instance(dev_info_t *dip)
7811 {
7812 	sata_hba_inst_t	*sata_hba_inst;
7813 
7814 	mutex_enter(&sata_mutex);
7815 	for (sata_hba_inst = sata_hba_list;
7816 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
7817 	    sata_hba_inst = sata_hba_inst->satahba_next) {
7818 		if (sata_hba_inst->satahba_dip == dip)
7819 			break;
7820 	}
7821 
7822 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
7823 #ifdef SATA_DEBUG
7824 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
7825 		    "unknown HBA instance\n");
7826 #endif
7827 		ASSERT(FALSE);
7828 	}
7829 	if (sata_hba_inst == sata_hba_list) {
7830 		sata_hba_list = sata_hba_inst->satahba_next;
7831 		if (sata_hba_list) {
7832 			sata_hba_list->satahba_prev =
7833 			    (struct sata_hba_inst *)NULL;
7834 		}
7835 		if (sata_hba_inst == sata_hba_list_tail) {
7836 			sata_hba_list_tail = NULL;
7837 		}
7838 	} else if (sata_hba_inst == sata_hba_list_tail) {
7839 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
7840 		if (sata_hba_list_tail) {
7841 			sata_hba_list_tail->satahba_next =
7842 			    (struct sata_hba_inst *)NULL;
7843 		}
7844 	} else {
7845 		sata_hba_inst->satahba_prev->satahba_next =
7846 		    sata_hba_inst->satahba_next;
7847 		sata_hba_inst->satahba_next->satahba_prev =
7848 		    sata_hba_inst->satahba_prev;
7849 	}
7850 	mutex_exit(&sata_mutex);
7851 }
7852 
7853 
7854 
7855 
7856 
7857 /*
7858  * Probe all SATA ports of the specified HBA instance.
7859  * The assumption is that there are no target and attachment point minor nodes
7860  * created by the boot subsystems, so we do not need to prune device tree.
7861  *
7862  * This function is called only from sata_hba_attach(). It does not have to
7863  * be protected by controller mutex, because the hba_attached flag is not set
7864  * yet and no one would be touching this HBA instance other than this thread.
7865  * Determines if port is active and what type of the device is attached
7866  * (if any). Allocates necessary structures for each port.
7867  *
7868  * An AP (Attachement Point) node is created for each SATA device port even
7869  * when there is no device attached.
7870  */
7871 
7872 static 	void
7873 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
7874 {
7875 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
7876 	int			ncport, npmport;
7877 	sata_cport_info_t 	*cportinfo;
7878 	sata_drive_info_t	*drive;
7879 	sata_pmult_info_t	*pminfo;
7880 	sata_pmport_info_t 	*pmportinfo;
7881 	sata_device_t		sata_device;
7882 	int			rval;
7883 	dev_t			minor_number;
7884 	char			name[16];
7885 	clock_t			start_time, cur_time;
7886 
7887 	/*
7888 	 * Probe controller ports first, to find port status and
7889 	 * any port multiplier attached.
7890 	 */
7891 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
7892 		/* allocate cport structure */
7893 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
7894 		ASSERT(cportinfo != NULL);
7895 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
7896 
7897 		mutex_enter(&cportinfo->cport_mutex);
7898 
7899 		cportinfo->cport_addr.cport = ncport;
7900 		cportinfo->cport_addr.pmport = 0;
7901 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
7902 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
7903 		cportinfo->cport_state |= SATA_STATE_PROBING;
7904 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
7905 
7906 		/*
7907 		 * Regardless if a port is usable or not, create
7908 		 * an attachment point
7909 		 */
7910 		mutex_exit(&cportinfo->cport_mutex);
7911 		minor_number =
7912 		    SATA_MAKE_AP_MINOR(ddi_get_instance(dip), ncport, 0, 0);
7913 		(void) sprintf(name, "%d", ncport);
7914 		if (ddi_create_minor_node(dip, name, S_IFCHR,
7915 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
7916 		    DDI_SUCCESS) {
7917 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
7918 			    "cannot create SATA attachment point for port %d",
7919 			    ncport);
7920 		}
7921 
7922 		/* Probe port */
7923 		start_time = ddi_get_lbolt();
7924 	reprobe_cport:
7925 		sata_device.satadev_addr.cport = ncport;
7926 		sata_device.satadev_addr.pmport = 0;
7927 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
7928 		sata_device.satadev_rev = SATA_DEVICE_REV;
7929 
7930 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
7931 		    (dip, &sata_device);
7932 
7933 		mutex_enter(&cportinfo->cport_mutex);
7934 		sata_update_port_scr(&cportinfo->cport_scr, &sata_device);
7935 		if (rval != SATA_SUCCESS) {
7936 			/* Something went wrong? Fail the port */
7937 			cportinfo->cport_state = SATA_PSTATE_FAILED;
7938 			mutex_exit(&cportinfo->cport_mutex);
7939 			continue;
7940 		}
7941 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
7942 		cportinfo->cport_state |= SATA_STATE_PROBED;
7943 		cportinfo->cport_dev_type = sata_device.satadev_type;
7944 
7945 		cportinfo->cport_state |= SATA_STATE_READY;
7946 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
7947 			mutex_exit(&cportinfo->cport_mutex);
7948 			continue;
7949 		}
7950 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
7951 			/*
7952 			 * There is some device attached.
7953 			 * Allocate device info structure
7954 			 */
7955 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
7956 				mutex_exit(&cportinfo->cport_mutex);
7957 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
7958 				    kmem_zalloc(sizeof (sata_drive_info_t),
7959 				    KM_SLEEP);
7960 				mutex_enter(&cportinfo->cport_mutex);
7961 			}
7962 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
7963 			drive->satadrv_addr = cportinfo->cport_addr;
7964 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
7965 			drive->satadrv_type = cportinfo->cport_dev_type;
7966 			drive->satadrv_state = SATA_STATE_UNKNOWN;
7967 
7968 			mutex_exit(&cportinfo->cport_mutex);
7969 			if (sata_add_device(dip, sata_hba_inst, ncport, 0) !=
7970 			    SATA_SUCCESS) {
7971 				/*
7972 				 * Plugged device was not correctly identified.
7973 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
7974 				 */
7975 				cur_time = ddi_get_lbolt();
7976 				if ((cur_time - start_time) <
7977 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
7978 					/* sleep for a while */
7979 					delay(drv_usectohz(
7980 					    SATA_DEV_IDENTIFY_RTR_DLY));
7981 					goto reprobe_cport;
7982 				}
7983 			}
7984 		} else {
7985 			mutex_exit(&cportinfo->cport_mutex);
7986 			ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
7987 			pminfo = kmem_zalloc(sizeof (sata_pmult_info_t),
7988 			    KM_SLEEP);
7989 			mutex_enter(&cportinfo->cport_mutex);
7990 			ASSERT(pminfo != NULL);
7991 			SATA_CPORTINFO_PMULT_INFO(cportinfo) = pminfo;
7992 			pminfo->pmult_addr.cport = cportinfo->cport_addr.cport;
7993 			pminfo->pmult_addr.pmport = SATA_PMULT_HOSTPORT;
7994 			pminfo->pmult_addr.qual = SATA_ADDR_PMPORT;
7995 			pminfo->pmult_num_dev_ports =
7996 			    sata_device.satadev_add_info;
7997 			mutex_init(&pminfo->pmult_mutex, NULL, MUTEX_DRIVER,
7998 			    NULL);
7999 			pminfo->pmult_state = SATA_STATE_PROBING;
8000 			mutex_exit(&cportinfo->cport_mutex);
8001 
8002 			/* Probe Port Multiplier ports */
8003 			for (npmport = 0;
8004 			    npmport < pminfo->pmult_num_dev_ports;
8005 			    npmport++) {
8006 				pmportinfo = kmem_zalloc(
8007 				    sizeof (sata_pmport_info_t), KM_SLEEP);
8008 				mutex_enter(&cportinfo->cport_mutex);
8009 				ASSERT(pmportinfo != NULL);
8010 				pmportinfo->pmport_addr.cport = ncport;
8011 				pmportinfo->pmport_addr.pmport = npmport;
8012 				pmportinfo->pmport_addr.qual =
8013 				    SATA_ADDR_PMPORT;
8014 				pminfo->pmult_dev_port[npmport] = pmportinfo;
8015 
8016 				mutex_init(&pmportinfo->pmport_mutex, NULL,
8017 				    MUTEX_DRIVER, NULL);
8018 
8019 				mutex_exit(&cportinfo->cport_mutex);
8020 
8021 				/* Create an attachment point */
8022 				minor_number = SATA_MAKE_AP_MINOR(
8023 				    ddi_get_instance(dip), ncport, npmport, 1);
8024 				(void) sprintf(name, "%d.%d", ncport, npmport);
8025 				if (ddi_create_minor_node(dip, name, S_IFCHR,
8026 				    minor_number, DDI_NT_SATA_ATTACHMENT_POINT,
8027 				    0) != DDI_SUCCESS) {
8028 					sata_log(sata_hba_inst, CE_WARN,
8029 					    "sata_hba_attach: "
8030 					    "cannot create SATA attachment "
8031 					    "point for port %d pmult port %d",
8032 					    ncport, npmport);
8033 				}
8034 
8035 				start_time = ddi_get_lbolt();
8036 			reprobe_pmport:
8037 				sata_device.satadev_addr.pmport = npmport;
8038 				sata_device.satadev_addr.qual =
8039 				    SATA_ADDR_PMPORT;
8040 
8041 				rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
8042 				    (dip, &sata_device);
8043 				mutex_enter(&cportinfo->cport_mutex);
8044 
8045 				/* sata_update_port_info() */
8046 				sata_update_port_scr(&pmportinfo->pmport_scr,
8047 				    &sata_device);
8048 
8049 				if (rval != SATA_SUCCESS) {
8050 					pmportinfo->pmport_state =
8051 					    SATA_PSTATE_FAILED;
8052 					mutex_exit(&cportinfo->cport_mutex);
8053 					continue;
8054 				}
8055 				pmportinfo->pmport_state &=
8056 				    ~SATA_STATE_PROBING;
8057 				pmportinfo->pmport_state |= SATA_STATE_PROBED;
8058 				pmportinfo->pmport_dev_type =
8059 				    sata_device.satadev_type;
8060 
8061 				pmportinfo->pmport_state |= SATA_STATE_READY;
8062 				if (pmportinfo->pmport_dev_type ==
8063 				    SATA_DTYPE_NONE) {
8064 					mutex_exit(&cportinfo->cport_mutex);
8065 					continue;
8066 				}
8067 				/* Port multipliers cannot be chained */
8068 				ASSERT(pmportinfo->pmport_dev_type !=
8069 				    SATA_DTYPE_PMULT);
8070 				/*
8071 				 * There is something attached to Port
8072 				 * Multiplier device port
8073 				 * Allocate device info structure
8074 				 */
8075 				if (pmportinfo->pmport_sata_drive == NULL) {
8076 					mutex_exit(&cportinfo->cport_mutex);
8077 					pmportinfo->pmport_sata_drive =
8078 					    kmem_zalloc(
8079 					    sizeof (sata_drive_info_t),
8080 					    KM_SLEEP);
8081 					mutex_enter(&cportinfo->cport_mutex);
8082 				}
8083 				drive = pmportinfo->pmport_sata_drive;
8084 				drive->satadrv_addr.cport =
8085 				    pmportinfo->pmport_addr.cport;
8086 				drive->satadrv_addr.pmport = npmport;
8087 				drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
8088 				drive->satadrv_type = pmportinfo->
8089 				    pmport_dev_type;
8090 				drive->satadrv_state = SATA_STATE_UNKNOWN;
8091 
8092 				mutex_exit(&cportinfo->cport_mutex);
8093 				if (sata_add_device(dip, sata_hba_inst, ncport,
8094 				    npmport) != SATA_SUCCESS) {
8095 					/*
8096 					 * Plugged device was not correctly
8097 					 * identified. Retry, within the
8098 					 * SATA_DEV_IDENTIFY_TIMEOUT
8099 					 */
8100 					cur_time = ddi_get_lbolt();
8101 					if ((cur_time - start_time) <
8102 					    drv_usectohz(
8103 					    SATA_DEV_IDENTIFY_TIMEOUT)) {
8104 						/* sleep for a while */
8105 						delay(drv_usectohz(
8106 						    SATA_DEV_IDENTIFY_RTR_DLY));
8107 						goto reprobe_pmport;
8108 					}
8109 				}
8110 			}
8111 			pmportinfo->pmport_state =
8112 			    SATA_STATE_PROBED | SATA_STATE_READY;
8113 		}
8114 	}
8115 }
8116 
8117 /*
8118  * Add SATA device for specified HBA instance & port (SCSI target
8119  * device nodes).
8120  * This function is called (indirectly) only from sata_hba_attach().
8121  * A target node is created when there is a supported type device attached,
8122  * but may be removed if it cannot be put online.
8123  *
8124  * This function cannot be called from an interrupt context.
8125  *
8126  * ONLY DISK TARGET NODES ARE CREATED NOW
8127  *
8128  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
8129  * device identification failed - adding a device could be retried.
8130  *
8131  */
8132 static 	int
8133 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst, int cport,
8134     int pmport)
8135 {
8136 	sata_cport_info_t 	*cportinfo;
8137 	sata_pmult_info_t	*pminfo;
8138 	sata_pmport_info_t	*pmportinfo;
8139 	dev_info_t		*cdip;		/* child dip */
8140 	sata_device_t		sata_device;
8141 	int			rval;
8142 
8143 
8144 
8145 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
8146 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
8147 	mutex_enter(&cportinfo->cport_mutex);
8148 	/*
8149 	 * Some device is attached to a controller port.
8150 	 * We rely on controllers distinquishing between no-device,
8151 	 * attached port multiplier and other kind of attached device.
8152 	 * We need to get Identify Device data and determine
8153 	 * positively the dev type before trying to attach
8154 	 * the target driver.
8155 	 */
8156 	sata_device.satadev_rev = SATA_DEVICE_REV;
8157 	if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
8158 		/*
8159 		 * Not port multiplier.
8160 		 */
8161 		sata_device.satadev_addr = cportinfo->cport_addr;
8162 		sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
8163 		mutex_exit(&cportinfo->cport_mutex);
8164 
8165 		rval = sata_probe_device(sata_hba_inst, &sata_device);
8166 		if (rval != SATA_SUCCESS ||
8167 		    sata_device.satadev_type == SATA_DTYPE_UNKNOWN)
8168 			return (SATA_FAILURE);
8169 
8170 		mutex_enter(&cportinfo->cport_mutex);
8171 		sata_show_drive_info(sata_hba_inst,
8172 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
8173 
8174 		if ((sata_device.satadev_type & SATA_VALID_DEV_TYPE) == 0) {
8175 			/*
8176 			 * Could not determine device type or
8177 			 * a device is not supported.
8178 			 * Degrade this device to unknown.
8179 			 */
8180 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
8181 			mutex_exit(&cportinfo->cport_mutex);
8182 			return (SATA_SUCCESS);
8183 		}
8184 		cportinfo->cport_dev_type = sata_device.satadev_type;
8185 		cportinfo->cport_tgtnode_clean = B_TRUE;
8186 		mutex_exit(&cportinfo->cport_mutex);
8187 
8188 		/*
8189 		 * Initialize device to the desired state. Even if it
8190 		 * fails, the device will still attach but syslog
8191 		 * will show the warning.
8192 		 */
8193 		if (sata_initialize_device(sata_hba_inst,
8194 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS)
8195 			/* Retry */
8196 			(void) sata_initialize_device(sata_hba_inst,
8197 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
8198 
8199 		cdip = sata_create_target_node(pdip, sata_hba_inst,
8200 		    &sata_device.satadev_addr);
8201 		mutex_enter(&cportinfo->cport_mutex);
8202 		if (cdip == NULL) {
8203 			/*
8204 			 * Attaching target node failed.
8205 			 * We retain sata_drive_info structure...
8206 			 */
8207 			mutex_exit(&cportinfo->cport_mutex);
8208 			return (SATA_SUCCESS);
8209 		}
8210 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
8211 		    satadrv_state = SATA_STATE_READY;
8212 	} else {
8213 		/* This must be Port Multiplier type */
8214 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
8215 			SATA_LOG_D((sata_hba_inst, CE_WARN,
8216 			    "sata_add_device: "
8217 			    "unrecognized dev type %x",
8218 			    cportinfo->cport_dev_type));
8219 			mutex_exit(&cportinfo->cport_mutex);
8220 			return (SATA_SUCCESS);
8221 		}
8222 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
8223 		pmportinfo = pminfo->pmult_dev_port[pmport];
8224 		sata_device.satadev_addr = pmportinfo->pmport_addr;
8225 		sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
8226 		mutex_exit(&cportinfo->cport_mutex);
8227 
8228 		rval = sata_probe_device(sata_hba_inst, &sata_device);
8229 		if (rval != SATA_SUCCESS ||
8230 		    sata_device.satadev_type == SATA_DTYPE_UNKNOWN) {
8231 			return (SATA_FAILURE);
8232 		}
8233 		mutex_enter(&cportinfo->cport_mutex);
8234 		sata_show_drive_info(sata_hba_inst,
8235 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
8236 
8237 		if ((sata_device.satadev_type & SATA_VALID_DEV_TYPE) == 0) {
8238 			/*
8239 			 * Could not determine device type.
8240 			 * Degrade this device to unknown.
8241 			 */
8242 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
8243 			mutex_exit(&cportinfo->cport_mutex);
8244 			return (SATA_SUCCESS);
8245 		}
8246 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
8247 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
8248 		mutex_exit(&cportinfo->cport_mutex);
8249 
8250 		/*
8251 		 * Initialize device to the desired state.
8252 		 * Even if it fails, the device will still
8253 		 * attach but syslog will show the warning.
8254 		 */
8255 		if (sata_initialize_device(sata_hba_inst,
8256 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS)
8257 			/* Retry */
8258 			(void) sata_initialize_device(sata_hba_inst,
8259 			    pmportinfo->pmport_sata_drive);
8260 
8261 		cdip = sata_create_target_node(pdip, sata_hba_inst,
8262 		    &sata_device.satadev_addr);
8263 		mutex_enter(&cportinfo->cport_mutex);
8264 		if (cdip == NULL) {
8265 			/*
8266 			 * Attaching target node failed.
8267 			 * We retain sata_drive_info structure...
8268 			 */
8269 			mutex_exit(&cportinfo->cport_mutex);
8270 			return (SATA_SUCCESS);
8271 		}
8272 		pmportinfo->pmport_sata_drive->satadrv_state |=
8273 		    SATA_STATE_READY;
8274 	}
8275 	mutex_exit(&cportinfo->cport_mutex);
8276 	return (SATA_SUCCESS);
8277 }
8278 
8279 
8280 
8281 /*
8282  * Create scsi target node for attached device, create node properties and
8283  * attach the node.
8284  * The node could be removed if the device onlining fails.
8285  *
8286  * A dev_info_t pointer is returned if operation is successful, NULL is
8287  * returned otherwise.
8288  *
8289  * No port multiplier support.
8290  */
8291 
8292 static dev_info_t *
8293 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
8294 			sata_address_t *sata_addr)
8295 {
8296 	dev_info_t *cdip = NULL;
8297 	int rval;
8298 	char *nname = NULL;
8299 	char **compatible = NULL;
8300 	int ncompatible;
8301 	struct scsi_inquiry inq;
8302 	sata_device_t sata_device;
8303 	sata_drive_info_t *sdinfo;
8304 	int target;
8305 	int i;
8306 
8307 	sata_device.satadev_rev = SATA_DEVICE_REV;
8308 	sata_device.satadev_addr = *sata_addr;
8309 
8310 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
8311 
8312 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
8313 
8314 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
8315 	    sata_addr->pmport, sata_addr->qual);
8316 
8317 	if (sdinfo == NULL) {
8318 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8319 		    sata_addr->cport)));
8320 		SATA_LOG_D((sata_hba_inst, CE_WARN,
8321 		    "sata_create_target_node: no sdinfo for target %x",
8322 		    target));
8323 		return (NULL);
8324 	}
8325 
8326 	/*
8327 	 * create or get scsi inquiry data, expected by
8328 	 * scsi_hba_nodename_compatible_get()
8329 	 * SATA hard disks get Identify Data translated into Inguiry Data.
8330 	 * ATAPI devices respond directly to Inquiry request.
8331 	 */
8332 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
8333 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
8334 		    (uint8_t *)&inq);
8335 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8336 		    sata_addr->cport)));
8337 	} else { /* Assume supported ATAPI device */
8338 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8339 		    sata_addr->cport)));
8340 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
8341 		    &inq) == SATA_FAILURE)
8342 			return (NULL);
8343 		/*
8344 		 * Save supported ATAPI transport version
8345 		 */
8346 		sdinfo->satadrv_atapi_trans_ver =
8347 		    SATA_ATAPI_TRANS_VERSION(&inq);
8348 	}
8349 
8350 	/* determine the node name and compatible */
8351 	scsi_hba_nodename_compatible_get(&inq, NULL,
8352 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
8353 
8354 #ifdef SATA_DEBUG
8355 	if (sata_debug_flags & SATA_DBG_NODES) {
8356 		if (nname == NULL) {
8357 			cmn_err(CE_NOTE, "sata_create_target_node: "
8358 			    "cannot determine nodename for target %d\n",
8359 			    target);
8360 		} else {
8361 			cmn_err(CE_WARN, "sata_create_target_node: "
8362 			    "target %d nodename: %s\n", target, nname);
8363 		}
8364 		if (compatible == NULL) {
8365 			cmn_err(CE_WARN,
8366 			    "sata_create_target_node: no compatible name\n");
8367 		} else {
8368 			for (i = 0; i < ncompatible; i++) {
8369 				cmn_err(CE_WARN, "sata_create_target_node: "
8370 				    "compatible name: %s\n", compatible[i]);
8371 			}
8372 		}
8373 	}
8374 #endif
8375 
8376 	/* if nodename can't be determined, log error and exit */
8377 	if (nname == NULL) {
8378 		SATA_LOG_D((sata_hba_inst, CE_WARN,
8379 		    "sata_create_target_node: cannot determine nodename "
8380 		    "for target %d\n", target));
8381 		scsi_hba_nodename_compatible_free(nname, compatible);
8382 		return (NULL);
8383 	}
8384 	/*
8385 	 * Create scsi target node
8386 	 */
8387 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
8388 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
8389 	    "device-type", "scsi");
8390 
8391 	if (rval != DDI_PROP_SUCCESS) {
8392 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
8393 		    "updating device_type prop failed %d", rval));
8394 		goto fail;
8395 	}
8396 
8397 	/*
8398 	 * Create target node properties: target & lun
8399 	 */
8400 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
8401 	if (rval != DDI_PROP_SUCCESS) {
8402 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
8403 		    "updating target prop failed %d", rval));
8404 		goto fail;
8405 	}
8406 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
8407 	if (rval != DDI_PROP_SUCCESS) {
8408 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
8409 		    "updating target prop failed %d", rval));
8410 		goto fail;
8411 	}
8412 
8413 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
8414 		/*
8415 		 * Add "variant" property
8416 		 */
8417 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
8418 		    "variant", "atapi");
8419 		if (rval != DDI_PROP_SUCCESS) {
8420 			SATA_LOG_D((sata_hba_inst, CE_WARN,
8421 			    "sata_create_target_node: variant atapi "
8422 			    "property could not be created: %d", rval));
8423 			goto fail;
8424 		}
8425 	}
8426 	/* decorate the node with compatible */
8427 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
8428 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
8429 		SATA_LOG_D((sata_hba_inst, CE_WARN,
8430 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
8431 		    (void *)cdip));
8432 		goto fail;
8433 	}
8434 
8435 
8436 	/*
8437 	 * Now, try to attach the driver. If probing of the device fails,
8438 	 * the target node may be removed
8439 	 */
8440 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
8441 
8442 	scsi_hba_nodename_compatible_free(nname, compatible);
8443 
8444 	if (rval == NDI_SUCCESS)
8445 		return (cdip);
8446 
8447 	/* target node was removed - are we sure? */
8448 	return (NULL);
8449 
8450 fail:
8451 	scsi_hba_nodename_compatible_free(nname, compatible);
8452 	ddi_prop_remove_all(cdip);
8453 	rval = ndi_devi_free(cdip);
8454 	if (rval != NDI_SUCCESS) {
8455 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
8456 		    "node removal failed %d", rval));
8457 	}
8458 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
8459 	    "cannot create target node for SATA device at port %d",
8460 	    sata_addr->cport);
8461 	return (NULL);
8462 }
8463 
8464 
8465 
8466 /*
8467  * Re-probe sata port, check for a device and attach info
8468  * structures when necessary. Identify Device data is fetched, if possible.
8469  * Assumption: sata address is already validated.
8470  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
8471  * the presence of a device and its type.
8472  *
8473  * flag arg specifies that the function should try multiple times to identify
8474  * device type and to initialize it, or it should return immediately on failure.
8475  * SATA_DEV_IDENTIFY_RETRY - retry
8476  * SATA_DEV_IDENTIFY_NORETRY - no retry
8477  *
8478  * SATA_FAILURE is returned if one of the operations failed.
8479  *
8480  * This function cannot be called in interrupt context - it may sleep.
8481  */
8482 static int
8483 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
8484     int flag)
8485 {
8486 	sata_cport_info_t *cportinfo;
8487 	sata_drive_info_t *sdinfo;
8488 	boolean_t init_device = B_FALSE;
8489 	int prev_device_type = SATA_DTYPE_NONE;
8490 	int prev_device_settings = 0;
8491 	clock_t start_time;
8492 	int retry = B_FALSE;
8493 	int rval;
8494 
8495 	/* We only care about host sata cport for now */
8496 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
8497 	    sata_device->satadev_addr.cport);
8498 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
8499 	if (sdinfo != NULL) {
8500 		/*
8501 		 * We are re-probing port with a previously attached device.
8502 		 * Save previous device type and settings
8503 		 */
8504 		prev_device_type = cportinfo->cport_dev_type;
8505 		prev_device_settings = sdinfo->satadrv_settings;
8506 	}
8507 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
8508 		start_time = ddi_get_lbolt();
8509 		retry = B_TRUE;
8510 	}
8511 retry_probe:
8512 
8513 	/* probe port */
8514 	mutex_enter(&cportinfo->cport_mutex);
8515 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
8516 	cportinfo->cport_state |= SATA_STATE_PROBING;
8517 	mutex_exit(&cportinfo->cport_mutex);
8518 
8519 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
8520 	    (SATA_DIP(sata_hba_inst), sata_device);
8521 
8522 	mutex_enter(&cportinfo->cport_mutex);
8523 	if (rval != SATA_SUCCESS) {
8524 		cportinfo->cport_state = SATA_PSTATE_FAILED;
8525 		mutex_exit(&cportinfo->cport_mutex);
8526 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
8527 		    "SATA port %d probing failed",
8528 		    cportinfo->cport_addr.cport));
8529 		return (SATA_FAILURE);
8530 	}
8531 
8532 	/*
8533 	 * update sata port state and set device type
8534 	 */
8535 	sata_update_port_info(sata_hba_inst, sata_device);
8536 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
8537 
8538 	/*
8539 	 * Sanity check - Port is active? Is the link active?
8540 	 * Is there any device attached?
8541 	 */
8542 	if ((cportinfo->cport_state &
8543 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
8544 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
8545 	    SATA_PORT_DEVLINK_UP) {
8546 		/*
8547 		 * Port in non-usable state or no link active/no device.
8548 		 * Free info structure if necessary (direct attached drive
8549 		 * only, for now!
8550 		 */
8551 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
8552 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
8553 		/* Add here differentiation for device attached or not */
8554 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
8555 		mutex_exit(&cportinfo->cport_mutex);
8556 		if (sdinfo != NULL)
8557 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
8558 		return (SATA_SUCCESS);
8559 	}
8560 
8561 	cportinfo->cport_state |= SATA_STATE_READY;
8562 	cportinfo->cport_dev_type = sata_device->satadev_type;
8563 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
8564 
8565 	/*
8566 	 * If we are re-probing the port, there may be
8567 	 * sata_drive_info structure attached
8568 	 * (or sata_pm_info, if PMult is supported).
8569 	 */
8570 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
8571 		/*
8572 		 * There is no device, so remove device info structure,
8573 		 * if necessary. Direct attached drive only!
8574 		 */
8575 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
8576 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
8577 		if (sdinfo != NULL) {
8578 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
8579 			sata_log(sata_hba_inst, CE_WARN,
8580 			    "SATA device detached "
8581 			    "from port %d", cportinfo->cport_addr.cport);
8582 		}
8583 		mutex_exit(&cportinfo->cport_mutex);
8584 		return (SATA_SUCCESS);
8585 	}
8586 
8587 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
8588 		if (sdinfo == NULL) {
8589 			/*
8590 			 * There is some device attached, but there is
8591 			 * no sata_drive_info structure - allocate one
8592 			 */
8593 			mutex_exit(&cportinfo->cport_mutex);
8594 			sdinfo = kmem_zalloc(
8595 			    sizeof (sata_drive_info_t), KM_SLEEP);
8596 			mutex_enter(&cportinfo->cport_mutex);
8597 			/*
8598 			 * Recheck, that the port state did not change when we
8599 			 * released mutex.
8600 			 */
8601 			if (cportinfo->cport_state & SATA_STATE_READY) {
8602 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
8603 				sdinfo->satadrv_addr = cportinfo->cport_addr;
8604 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
8605 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
8606 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
8607 			} else {
8608 				/*
8609 				 * Port is not in ready state, we
8610 				 * cannot attach a device.
8611 				 */
8612 				mutex_exit(&cportinfo->cport_mutex);
8613 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
8614 				return (SATA_SUCCESS);
8615 			}
8616 			/*
8617 			 * Since we are adding device, presumably new one,
8618 			 * indicate that it  should be initalized,
8619 			 * as well as some internal framework states).
8620 			 */
8621 			init_device = B_TRUE;
8622 		}
8623 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
8624 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
8625 	} else {
8626 		/*
8627 		 * The device is a port multiplier - not handled now.
8628 		 */
8629 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
8630 		mutex_exit(&cportinfo->cport_mutex);
8631 		return (SATA_SUCCESS);
8632 	}
8633 	mutex_exit(&cportinfo->cport_mutex);
8634 	/*
8635 	 * Figure out what kind of device we are really
8636 	 * dealing with.
8637 	 */
8638 	rval = sata_probe_device(sata_hba_inst, sata_device);
8639 
8640 	if (rval == SATA_SUCCESS) {
8641 		/*
8642 		 * If we are dealing with the same type of a device as before,
8643 		 * restore its settings flags.
8644 		 */
8645 		if (sata_device->satadev_type == prev_device_type)
8646 			sdinfo->satadrv_settings = prev_device_settings;
8647 
8648 		/* Set initial device features, if necessary */
8649 		if (init_device == B_TRUE) {
8650 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
8651 		}
8652 		if (rval == SATA_SUCCESS)
8653 			return (rval);
8654 	}
8655 
8656 	if (retry) {
8657 		clock_t cur_time = ddi_get_lbolt();
8658 		/*
8659 		 * A device was not successfully identified or initialized.
8660 		 * Track retry time for device identification.
8661 		 */
8662 		if ((cur_time - start_time) <
8663 		    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
8664 			/* sleep for a while */
8665 			delay(drv_usectohz(SATA_DEV_IDENTIFY_RTR_DLY));
8666 			goto retry_probe;
8667 		}
8668 	}
8669 	return (rval);
8670 }
8671 
8672 /*
8673  * Initialize device
8674  * Specified device is initialized to a default state.
8675  *
8676  * Returns SATA_SUCCESS if all device features are set successfully,
8677  * SATA_FAILURE otherwise
8678  */
8679 static int
8680 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
8681     sata_drive_info_t *sdinfo)
8682 {
8683 	int rval;
8684 
8685 	sata_save_drive_settings(sdinfo);
8686 
8687 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
8688 
8689 	sata_init_write_cache_mode(sdinfo);
8690 
8691 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
8692 
8693 	/* Determine current data transfer mode */
8694 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
8695 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
8696 	} else if ((sdinfo->satadrv_id.ai_validinfo &
8697 	    SATA_VALIDINFO_88) != 0 &&
8698 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
8699 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
8700 	} else if ((sdinfo->satadrv_id.ai_dworddma &
8701 	    SATA_MDMA_SEL_MASK) != 0) {
8702 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
8703 	} else
8704 		/* DMA supported, not no DMA transfer mode is selected !? */
8705 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
8706 
8707 	return (rval);
8708 }
8709 
8710 
8711 /*
8712  * Initialize write cache mode.
8713  *
8714  * The default write cache setting for SATA HDD is provided by sata_write_cache
8715  * static variable. ATAPI CD/DVDs devices have write cache default is
8716  * determined by sata_atapicdvd_write_cache static variable.
8717  * 1 - enable
8718  * 0 - disable
8719  * any other value - current drive setting
8720  *
8721  * Although there is not reason to disable write cache on CD/DVD devices,
8722  * the default setting control is provided for the maximun flexibility.
8723  *
8724  * In the future, it may be overridden by the
8725  * disk-write-cache-enable property setting, if it is defined.
8726  * Returns SATA_SUCCESS if all device features are set successfully,
8727  * SATA_FAILURE otherwise.
8728  */
8729 static void
8730 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
8731 {
8732 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
8733 		if (sata_write_cache == 1)
8734 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
8735 		else if (sata_write_cache == 0)
8736 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
8737 		/*
8738 		 * When sata_write_cache value is not 0 or 1,
8739 		 * a current setting of the drive's write cache is used.
8740 		 */
8741 	} else { /* Assume ATAPI CD/DVD device */
8742 		if (sata_atapicdvd_write_cache == 1)
8743 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
8744 		else if (sata_atapicdvd_write_cache == 0)
8745 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
8746 		/*
8747 		 * When sata_write_cache value is not 0 or 1,
8748 		 * a current setting of the drive's write cache is used.
8749 		 */
8750 	}
8751 }
8752 
8753 
8754 /*
8755  * Validate sata address.
8756  * Specified cport, pmport and qualifier has to match
8757  * passed sata_scsi configuration info.
8758  * The presence of an attached device is not verified.
8759  *
8760  * Returns 0 when address is valid, -1 otherwise.
8761  */
8762 static int
8763 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
8764 	int pmport, int qual)
8765 {
8766 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
8767 		goto invalid_address;
8768 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
8769 		goto invalid_address;
8770 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
8771 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
8772 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
8773 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
8774 		goto invalid_address;
8775 
8776 	return (0);
8777 
8778 invalid_address:
8779 	return (-1);
8780 
8781 }
8782 
8783 /*
8784  * Validate scsi address
8785  * SCSI target address is translated into SATA cport/pmport and compared
8786  * with a controller port/device configuration. LUN has to be 0.
8787  * Returns 0 if a scsi target refers to an attached device,
8788  * returns 1 if address is valid but device is not attached,
8789  * returns -1 if bad address or device is of an unsupported type.
8790  * Upon return sata_device argument is set.
8791  */
8792 static int
8793 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
8794 	struct scsi_address *ap, sata_device_t *sata_device)
8795 {
8796 	int cport, pmport, qual, rval;
8797 
8798 	rval = -1;	/* Invalid address */
8799 	if (ap->a_lun != 0)
8800 		goto out;
8801 
8802 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
8803 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
8804 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
8805 
8806 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
8807 		goto out;
8808 
8809 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
8810 	    0) {
8811 
8812 		sata_cport_info_t *cportinfo;
8813 		sata_pmult_info_t *pmultinfo;
8814 		sata_drive_info_t *sdinfo = NULL;
8815 
8816 		rval = 1;	/* Valid sata address */
8817 
8818 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
8819 		if (qual == SATA_ADDR_DCPORT) {
8820 			if (cportinfo == NULL ||
8821 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
8822 				goto out;
8823 
8824 			if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT ||
8825 			    (cportinfo->cport_dev_type &
8826 			    SATA_VALID_DEV_TYPE) == 0) {
8827 				rval = -1;
8828 				goto out;
8829 			}
8830 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
8831 
8832 		} else if (qual == SATA_ADDR_DPMPORT) {
8833 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
8834 			if (pmultinfo == NULL) {
8835 				rval = -1;
8836 				goto out;
8837 			}
8838 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
8839 			    NULL ||
8840 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
8841 			    pmport) == SATA_DTYPE_NONE)
8842 				goto out;
8843 
8844 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
8845 			    pmport);
8846 		} else {
8847 			rval = -1;
8848 			goto out;
8849 		}
8850 		if ((sdinfo == NULL) ||
8851 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
8852 			goto out;
8853 
8854 		sata_device->satadev_type = sdinfo->satadrv_type;
8855 		sata_device->satadev_addr.qual = qual;
8856 		sata_device->satadev_addr.cport = cport;
8857 		sata_device->satadev_addr.pmport = pmport;
8858 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
8859 		return (0);
8860 	}
8861 out:
8862 	if (rval == 1) {
8863 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
8864 		    "sata_validate_scsi_address: no valid target %x lun %x",
8865 		    ap->a_target, ap->a_lun);
8866 	}
8867 	return (rval);
8868 }
8869 
8870 /*
8871  * Find dip corresponding to passed device number
8872  *
8873  * Returns NULL if invalid device number is passed or device cannot be found,
8874  * Returns dip is device is found.
8875  */
8876 static dev_info_t *
8877 sata_devt_to_devinfo(dev_t dev)
8878 {
8879 	dev_info_t *dip;
8880 #ifndef __lock_lint
8881 	struct devnames *dnp;
8882 	major_t major = getmajor(dev);
8883 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
8884 
8885 	if (major >= devcnt)
8886 		return (NULL);
8887 
8888 	dnp = &devnamesp[major];
8889 	LOCK_DEV_OPS(&(dnp->dn_lock));
8890 	dip = dnp->dn_head;
8891 	while (dip && (ddi_get_instance(dip) != instance)) {
8892 		dip = ddi_get_next(dip);
8893 	}
8894 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
8895 #endif
8896 
8897 	return (dip);
8898 }
8899 
8900 
8901 /*
8902  * Probe device.
8903  * This function issues Identify Device command and initializes local
8904  * sata_drive_info structure if the device can be identified.
8905  * The device type is determined by examining Identify Device
8906  * command response.
8907  * If the sata_hba_inst has linked drive info structure for this
8908  * device address, the Identify Device data is stored into sata_drive_info
8909  * structure linked to the port info structure.
8910  *
8911  * sata_device has to refer to the valid sata port(s) for HBA described
8912  * by sata_hba_inst structure.
8913  *
8914  * Returns:
8915  *	SATA_SUCCESS if device type was successfully probed and port-linked
8916  *		drive info structure was updated;
8917  * 	SATA_FAILURE if there is no device, or device was not probed
8918  *		successully;
8919  *	SATA_RETRY if device probe can be retried later.
8920  * If a device cannot be identified, sata_device's dev_state and dev_type
8921  * fields are set to unknown.
8922  * There are no retries in this function. Any retries should be managed by
8923  * the caller.
8924  */
8925 
8926 
8927 static int
8928 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
8929 {
8930 	sata_drive_info_t *sdinfo;
8931 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
8932 	int rval;
8933 
8934 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
8935 	    sata_device->satadev_addr.cport) &
8936 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
8937 
8938 	sata_device->satadev_type = SATA_DTYPE_NONE;
8939 
8940 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
8941 	    sata_device->satadev_addr.cport)));
8942 
8943 	/* Get pointer to port-linked sata device info structure */
8944 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
8945 	if (sdinfo != NULL) {
8946 		sdinfo->satadrv_state &=
8947 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
8948 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
8949 	} else {
8950 		/* No device to probe */
8951 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8952 		    sata_device->satadev_addr.cport)));
8953 		sata_device->satadev_type = SATA_DTYPE_NONE;
8954 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
8955 		return (SATA_FAILURE);
8956 	}
8957 	/*
8958 	 * Need to issue both types of identify device command and
8959 	 * determine device type by examining retreived data/status.
8960 	 * First, ATA Identify Device.
8961 	 */
8962 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
8963 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
8964 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8965 	    sata_device->satadev_addr.cport)));
8966 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
8967 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
8968 	if (rval == SATA_RETRY) {
8969 		/* We may try to check for ATAPI device */
8970 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
8971 			/*
8972 			 * HBA supports ATAPI - try to issue Identify Packet
8973 			 * Device command.
8974 			 */
8975 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPICD;
8976 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
8977 		}
8978 	}
8979 	if (rval == SATA_SUCCESS) {
8980 		/*
8981 		 * Got something responding positively to ATA Identify Device
8982 		 * or to Identify Packet Device cmd.
8983 		 * Save last used device type.
8984 		 */
8985 		sata_device->satadev_type = new_sdinfo.satadrv_type;
8986 
8987 		/* save device info, if possible */
8988 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
8989 		    sata_device->satadev_addr.cport)));
8990 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
8991 		if (sdinfo == NULL) {
8992 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8993 			    sata_device->satadev_addr.cport)));
8994 			return (SATA_FAILURE);
8995 		}
8996 		/*
8997 		 * Copy drive info into the port-linked drive info structure.
8998 		 */
8999 		*sdinfo = new_sdinfo;
9000 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
9001 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
9002 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
9003 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
9004 			    sata_device->satadev_addr.cport) =
9005 			    sdinfo->satadrv_type;
9006 		else /* SATA_ADDR_DPMPORT */
9007 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
9008 			    sata_device->satadev_addr.cport,
9009 			    sata_device->satadev_addr.pmport) =
9010 			    sdinfo->satadrv_type;
9011 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9012 		    sata_device->satadev_addr.cport)));
9013 		return (SATA_SUCCESS);
9014 	}
9015 
9016 	/*
9017 	 * It may be SATA_RETRY or SATA_FAILURE return.
9018 	 * Looks like we cannot determine the device type at this time.
9019 	 */
9020 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
9021 	    sata_device->satadev_addr.cport)));
9022 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
9023 	if (sdinfo != NULL) {
9024 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
9025 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
9026 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
9027 		sdinfo->satadrv_state = SATA_STATE_PROBED;
9028 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
9029 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
9030 			    sata_device->satadev_addr.cport) =
9031 			    SATA_DTYPE_UNKNOWN;
9032 		else {
9033 			/* SATA_ADDR_DPMPORT */
9034 			if ((SATA_PMULT_INFO(sata_hba_inst,
9035 			    sata_device->satadev_addr.cport) != NULL) &&
9036 			    (SATA_PMPORT_INFO(sata_hba_inst,
9037 			    sata_device->satadev_addr.cport,
9038 			    sata_device->satadev_addr.pmport) != NULL))
9039 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
9040 				    sata_device->satadev_addr.cport,
9041 				    sata_device->satadev_addr.pmport) =
9042 				    SATA_DTYPE_UNKNOWN;
9043 		}
9044 	}
9045 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9046 	    sata_device->satadev_addr.cport)));
9047 	return (rval);
9048 }
9049 
9050 
9051 /*
9052  * Get pointer to sata_drive_info structure.
9053  *
9054  * The sata_device has to contain address (cport, pmport and qualifier) for
9055  * specified sata_scsi structure.
9056  *
9057  * Returns NULL if device address is not valid for this HBA configuration.
9058  * Otherwise, returns a pointer to sata_drive_info structure.
9059  *
9060  * This function should be called with a port mutex held.
9061  */
9062 static sata_drive_info_t *
9063 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
9064     sata_device_t *sata_device)
9065 {
9066 	uint8_t cport = sata_device->satadev_addr.cport;
9067 	uint8_t pmport = sata_device->satadev_addr.pmport;
9068 	uint8_t qual = sata_device->satadev_addr.qual;
9069 
9070 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
9071 		return (NULL);
9072 
9073 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
9074 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
9075 		/* Port not probed yet */
9076 		return (NULL);
9077 
9078 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
9079 		return (NULL);
9080 
9081 	if (qual == SATA_ADDR_DCPORT) {
9082 		/* Request for a device on a controller port */
9083 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
9084 		    SATA_DTYPE_PMULT)
9085 			/* Port multiplier attached */
9086 			return (NULL);
9087 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
9088 	}
9089 	if (qual == SATA_ADDR_DPMPORT) {
9090 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
9091 		    SATA_DTYPE_PMULT)
9092 			return (NULL);
9093 
9094 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
9095 			return (NULL);
9096 
9097 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
9098 	}
9099 
9100 	/* we should not get here */
9101 	return (NULL);
9102 }
9103 
9104 
9105 /*
9106  * sata_identify_device.
9107  * Send Identify Device command to SATA HBA driver.
9108  * If command executes successfully, update sata_drive_info structure pointed
9109  * to by sdinfo argument, including Identify Device data.
9110  * If command fails, invalidate data in sata_drive_info.
9111  *
9112  * Cannot be called from interrupt level.
9113  *
9114  * Returns:
9115  * SATA_SUCCESS if the device was identified as a supported device,
9116  * SATA_RETRY if the device was not identified but could be retried,
9117  * SATA_FAILURE if the device was not identified and identify attempt
9118  *	should not be retried.
9119  */
9120 static int
9121 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
9122     sata_drive_info_t *sdinfo)
9123 {
9124 	uint16_t cfg_word;
9125 	int rval;
9126 
9127 	/* fetch device identify data */
9128 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
9129 	    sdinfo)) != 0)
9130 		goto fail_unknown;
9131 
9132 	cfg_word = sdinfo->satadrv_id.ai_config;
9133 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK &&
9134 	    (cfg_word & SATA_ATA_TYPE_MASK) != SATA_ATA_TYPE) {
9135 		/* Change device type to reflect Identify Device data */
9136 		if (((cfg_word & SATA_ATAPI_TYPE_MASK) ==
9137 		    SATA_ATAPI_TYPE) &&
9138 		    ((cfg_word & SATA_ATAPI_ID_DEV_TYPE) ==
9139 		    SATA_ATAPI_CDROM_DEV)) {
9140 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
9141 		} else {
9142 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
9143 		}
9144 	} else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD &&
9145 	    (((cfg_word & SATA_ATAPI_TYPE_MASK) != SATA_ATAPI_TYPE) ||
9146 	    ((cfg_word & SATA_ATAPI_ID_DEV_TYPE) != SATA_ATAPI_CDROM_DEV))) {
9147 		/* Change device type to reflect Identify Device data ! */
9148 		if ((sdinfo->satadrv_id.ai_config & SATA_ATA_TYPE_MASK) ==
9149 		    SATA_ATA_TYPE) {
9150 			sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
9151 		} else {
9152 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
9153 		}
9154 	}
9155 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9156 		if (sdinfo->satadrv_capacity == 0) {
9157 			/* Non-LBA disk. Too bad... */
9158 			sata_log(sata_hba_inst, CE_WARN,
9159 			    "SATA disk device at port %d does not support LBA",
9160 			    sdinfo->satadrv_addr.cport);
9161 			rval = SATA_FAILURE;
9162 			goto fail_unknown;
9163 		}
9164 	}
9165 #if 0
9166 	/* Left for historical reason */
9167 	/*
9168 	 * Some initial version of SATA spec indicated that at least
9169 	 * UDMA mode 4 has to be supported. It is not metioned in
9170 	 * SerialATA 2.6, so this restriction is removed.
9171 	 */
9172 	/* Check for Ultra DMA modes 6 through 0 being supported */
9173 	for (i = 6; i >= 0; --i) {
9174 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
9175 			break;
9176 	}
9177 
9178 	/*
9179 	 * At least UDMA 4 mode has to be supported. If mode 4 or
9180 	 * higher are not supported by the device, fail this
9181 	 * device.
9182 	 */
9183 	if (i < 4) {
9184 		/* No required Ultra DMA mode supported */
9185 		sata_log(sata_hba_inst, CE_WARN,
9186 		    "SATA disk device at port %d does not support UDMA "
9187 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
9188 		SATA_LOG_D((sata_hba_inst, CE_WARN,
9189 		    "mode 4 or higher required, %d supported", i));
9190 		rval = SATA_FAILURE;
9191 		goto fail_unknown;
9192 	}
9193 #endif
9194 
9195 	return (SATA_SUCCESS);
9196 
9197 fail_unknown:
9198 	/* Invalidate sata_drive_info ? */
9199 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
9200 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
9201 	return (rval);
9202 }
9203 
9204 /*
9205  * Log/display device information
9206  */
9207 static void
9208 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
9209     sata_drive_info_t *sdinfo)
9210 {
9211 	int valid_version;
9212 	char msg_buf[MAXPATHLEN];
9213 	int i;
9214 
9215 	/* Show HBA path */
9216 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
9217 
9218 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
9219 
9220 	if (sdinfo->satadrv_type == SATA_DTYPE_UNKNOWN) {
9221 		(void) sprintf(msg_buf,
9222 		    "Unsupported SATA device type (cfg 0x%x) at ",
9223 		    sdinfo->satadrv_id.ai_config);
9224 	} else {
9225 		(void) sprintf(msg_buf, "SATA %s device at",
9226 		    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
9227 		    "disk":"CD/DVD (ATAPI)");
9228 	}
9229 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
9230 		cmn_err(CE_CONT, "?\t%s port %d\n",
9231 		    msg_buf, sdinfo->satadrv_addr.cport);
9232 	else
9233 		cmn_err(CE_CONT, "?\t%s port %d pmport %d\n",
9234 		    msg_buf, sdinfo->satadrv_addr.cport,
9235 		    sdinfo->satadrv_addr.pmport);
9236 
9237 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
9238 	    sizeof (sdinfo->satadrv_id.ai_model));
9239 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
9240 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
9241 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
9242 
9243 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
9244 	    sizeof (sdinfo->satadrv_id.ai_fw));
9245 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
9246 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
9247 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
9248 
9249 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
9250 	    sizeof (sdinfo->satadrv_id.ai_drvser));
9251 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
9252 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
9253 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9254 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
9255 	} else {
9256 		/* Assuming ATAPI CD/DVD */
9257 		/*
9258 		 * SOme drives do not implement serial number and may
9259 		 * violate the spec by provinding spaces rather than zeros
9260 		 * in serial number field. Scan the buffer to detect it.
9261 		 */
9262 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
9263 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
9264 				break;
9265 		}
9266 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
9267 			cmn_err(CE_CONT, "?\tserial number - none\n");
9268 		} else {
9269 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
9270 		}
9271 	}
9272 
9273 #ifdef SATA_DEBUG
9274 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
9275 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
9276 		int i;
9277 		for (i = 14; i >= 2; i--) {
9278 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
9279 				valid_version = i;
9280 				break;
9281 			}
9282 		}
9283 		cmn_err(CE_CONT,
9284 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
9285 		    valid_version,
9286 		    sdinfo->satadrv_id.ai_majorversion,
9287 		    sdinfo->satadrv_id.ai_minorversion);
9288 	}
9289 #endif
9290 	/* Log some info */
9291 	cmn_err(CE_CONT, "?\tsupported features:\n");
9292 	msg_buf[0] = '\0';
9293 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9294 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
9295 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
9296 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
9297 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
9298 	}
9299 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
9300 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
9301 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
9302 		(void) strlcat(msg_buf, ", Native Command Queueing",
9303 		    MAXPATHLEN);
9304 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
9305 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
9306 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
9307 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
9308 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
9309 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
9310 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
9311 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
9312 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
9313 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
9314 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
9315 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
9316 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
9317 	if (sdinfo->satadrv_features_support &
9318 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
9319 		msg_buf[0] = '\0';
9320 		(void) snprintf(msg_buf, MAXPATHLEN,
9321 		    "Supported queue depth %d",
9322 		    sdinfo->satadrv_queue_depth);
9323 		if (!(sata_func_enable &
9324 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
9325 			(void) strlcat(msg_buf,
9326 			    " - queueing disabled globally", MAXPATHLEN);
9327 		else if (sdinfo->satadrv_queue_depth >
9328 		    sdinfo->satadrv_max_queue_depth) {
9329 			(void) snprintf(&msg_buf[strlen(msg_buf)],
9330 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
9331 			    (int)sdinfo->satadrv_max_queue_depth);
9332 		}
9333 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
9334 	}
9335 
9336 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9337 #ifdef __i386
9338 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
9339 		    sdinfo->satadrv_capacity);
9340 #else
9341 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
9342 		    sdinfo->satadrv_capacity);
9343 #endif
9344 		cmn_err(CE_CONT, "?%s", msg_buf);
9345 	}
9346 }
9347 
9348 
9349 /*
9350  * sata_save_drive_settings extracts current setting of the device and stores
9351  * it for future reference, in case the device setup would need to be restored
9352  * after the device reset.
9353  *
9354  * For all devices read ahead and write cache settings are saved, if the
9355  * device supports these features at all.
9356  * For ATAPI devices the Removable Media Status Notification setting is saved.
9357  */
9358 static void
9359 sata_save_drive_settings(sata_drive_info_t *sdinfo)
9360 {
9361 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_LOOK_AHEAD) ||
9362 	    (sdinfo->satadrv_id.ai_cmdset82 & SATA_WRITE_CACHE)) {
9363 
9364 		/* Current setting of Read Ahead (and Read Cache) */
9365 		if (sdinfo->satadrv_id.ai_features85 & SATA_LOOK_AHEAD)
9366 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
9367 		else
9368 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
9369 
9370 		/* Current setting of Write Cache */
9371 		if (sdinfo->satadrv_id.ai_features85 & SATA_WRITE_CACHE)
9372 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
9373 		else
9374 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
9375 	}
9376 
9377 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
9378 		if (sdinfo->satadrv_id.ai_cmdset83 & SATA_RM_STATUS_NOTIFIC)
9379 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
9380 		else
9381 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
9382 	}
9383 }
9384 
9385 
9386 /*
9387  * sata_check_capacity function determines a disk capacity
9388  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
9389  *
9390  * NOTE: CHS mode is not supported! If a device does not support LBA,
9391  * this function is not called.
9392  *
9393  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
9394  */
9395 static uint64_t
9396 sata_check_capacity(sata_drive_info_t *sdinfo)
9397 {
9398 	uint64_t capacity = 0;
9399 	int i;
9400 
9401 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
9402 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
9403 		/* Capacity valid only for LBA-addressable disk devices */
9404 		return (0);
9405 
9406 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
9407 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
9408 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
9409 		/* LBA48 mode supported and enabled */
9410 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
9411 		    SATA_DEV_F_LBA28;
9412 		for (i = 3;  i >= 0;  --i) {
9413 			capacity <<= 16;
9414 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
9415 		}
9416 	} else {
9417 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
9418 		capacity <<= 16;
9419 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
9420 		if (capacity >= 0x1000000)
9421 			/* LBA28 mode */
9422 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
9423 	}
9424 	return (capacity);
9425 }
9426 
9427 
9428 /*
9429  * Allocate consistent buffer for DMA transfer
9430  *
9431  * Cannot be called from interrupt level or with mutex held - it may sleep.
9432  *
9433  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
9434  */
9435 static struct buf *
9436 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
9437 {
9438 	struct scsi_address ap;
9439 	struct buf *bp;
9440 	ddi_dma_attr_t	cur_dma_attr;
9441 
9442 	ASSERT(spx->txlt_sata_pkt != NULL);
9443 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
9444 	ap.a_target = SATA_TO_SCSI_TARGET(
9445 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
9446 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
9447 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
9448 	ap.a_lun = 0;
9449 
9450 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
9451 	    B_READ, SLEEP_FUNC, NULL);
9452 
9453 	if (bp != NULL) {
9454 		/* Allocate DMA resources for this buffer */
9455 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
9456 		/*
9457 		 * We use a local version of the dma_attr, to account
9458 		 * for a device addressing limitations.
9459 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
9460 		 * will cause dma attributes to be adjusted to a lowest
9461 		 * acceptable level.
9462 		 */
9463 		sata_adjust_dma_attr(NULL,
9464 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
9465 
9466 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
9467 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
9468 			scsi_free_consistent_buf(bp);
9469 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
9470 			bp = NULL;
9471 		}
9472 	}
9473 	return (bp);
9474 }
9475 
9476 /*
9477  * Release local buffer (consistent buffer for DMA transfer) allocated
9478  * via sata_alloc_local_buffer().
9479  */
9480 static void
9481 sata_free_local_buffer(sata_pkt_txlate_t *spx)
9482 {
9483 	ASSERT(spx->txlt_sata_pkt != NULL);
9484 	ASSERT(spx->txlt_dma_cookie_list != NULL);
9485 	ASSERT(spx->txlt_dma_cookie_list_len != 0);
9486 	ASSERT(spx->txlt_buf_dma_handle != NULL);
9487 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
9488 
9489 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
9490 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
9491 
9492 	/* Free DMA resources */
9493 	(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
9494 	ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
9495 	spx->txlt_buf_dma_handle = 0;
9496 
9497 	if (spx->txlt_dma_cookie_list != &spx->txlt_dma_cookie) {
9498 		kmem_free(spx->txlt_dma_cookie_list,
9499 		    spx->txlt_dma_cookie_list_len * sizeof (ddi_dma_cookie_t));
9500 		spx->txlt_dma_cookie_list = NULL;
9501 		spx->txlt_dma_cookie_list_len = 0;
9502 	}
9503 	/* Free buffer */
9504 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
9505 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
9506 }
9507 
9508 
9509 
9510 
9511 /*
9512  * Allocate sata_pkt
9513  * Pkt structure version and embedded strcutures version are initialized.
9514  * sata_pkt and sata_pkt_txlate structures are cross-linked.
9515  *
9516  * Since this may be called in interrupt context by sata_scsi_init_pkt,
9517  * callback argument determines if it can sleep or not.
9518  * Hence, it should not be called from interrupt context.
9519  *
9520  * If successful, non-NULL pointer to a sata pkt is returned.
9521  * Upon failure, NULL pointer is returned.
9522  */
9523 static sata_pkt_t *
9524 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
9525 {
9526 	sata_pkt_t *spkt;
9527 	int kmsflag;
9528 
9529 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
9530 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
9531 	if (spkt == NULL) {
9532 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9533 		    "sata_pkt_alloc: failed"));
9534 		return (NULL);
9535 	}
9536 	spkt->satapkt_rev = SATA_PKT_REV;
9537 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
9538 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
9539 	spkt->satapkt_framework_private = spx;
9540 	spx->txlt_sata_pkt = spkt;
9541 	return (spkt);
9542 }
9543 
9544 /*
9545  * Free sata pkt allocated via sata_pkt_alloc()
9546  */
9547 static void
9548 sata_pkt_free(sata_pkt_txlate_t *spx)
9549 {
9550 	ASSERT(spx->txlt_sata_pkt != NULL);
9551 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
9552 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
9553 	spx->txlt_sata_pkt = NULL;
9554 }
9555 
9556 
9557 /*
9558  * Adjust DMA attributes.
9559  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
9560  * from 8 bits to 16 bits, depending on a command being used.
9561  * Limiting max block count arbitrarily to 256 for all read/write
9562  * commands may affects performance, so check both the device and
9563  * controller capability before adjusting dma attributes.
9564  */
9565 void
9566 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
9567     ddi_dma_attr_t *adj_dma_attr)
9568 {
9569 	uint32_t count_max;
9570 
9571 	/* Copy original attributes */
9572 	*adj_dma_attr = *dma_attr;
9573 	/*
9574 	 * Things to consider: device addressing capability,
9575 	 * "excessive" controller DMA capabilities.
9576 	 * If a device is being probed/initialized, there are
9577 	 * no device info - use default limits then.
9578 	 */
9579 	if (sdinfo == NULL) {
9580 		count_max = dma_attr->dma_attr_granular * 0x100;
9581 		if (dma_attr->dma_attr_count_max > count_max)
9582 			adj_dma_attr->dma_attr_count_max = count_max;
9583 		if (dma_attr->dma_attr_maxxfer > count_max)
9584 			adj_dma_attr->dma_attr_maxxfer = count_max;
9585 		return;
9586 	}
9587 
9588 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9589 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
9590 			/*
9591 			 * 16-bit sector count may be used - we rely on
9592 			 * the assumption that only read and write cmds
9593 			 * will request more than 256 sectors worth of data
9594 			 */
9595 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
9596 		} else {
9597 			/*
9598 			 * 8-bit sector count will be used - default limits
9599 			 * for dma attributes
9600 			 */
9601 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
9602 		}
9603 		/*
9604 		 * Adjust controler dma attributes, if necessary
9605 		 */
9606 		if (dma_attr->dma_attr_count_max > count_max)
9607 			adj_dma_attr->dma_attr_count_max = count_max;
9608 		if (dma_attr->dma_attr_maxxfer > count_max)
9609 			adj_dma_attr->dma_attr_maxxfer = count_max;
9610 	}
9611 }
9612 
9613 
9614 /*
9615  * Allocate DMA resources for the buffer
9616  * This function handles initial DMA resource allocation as well as
9617  * DMA window shift and may be called repeatedly for the same DMA window
9618  * until all DMA cookies in the DMA window are processed.
9619  * To guarantee that there is always a coherent set of cookies to process
9620  * by SATA HBA driver (observing alignment, device granularity, etc.),
9621  * the number of slots for DMA cookies is equal to lesser of  a number of
9622  * cookies in a DMA window and a max number of scatter/gather entries.
9623  *
9624  * Returns DDI_SUCCESS upon successful operation.
9625  * Return failure code of a failing command or DDI_FAILURE when
9626  * internal cleanup failed.
9627  */
9628 static int
9629 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
9630     int (*callback)(caddr_t), caddr_t arg,
9631     ddi_dma_attr_t *cur_dma_attr)
9632 {
9633 	int	rval;
9634 	off_t	offset;
9635 	size_t	size;
9636 	int	max_sg_len, req_len, i;
9637 	uint_t	dma_flags;
9638 	struct buf	*bp;
9639 	uint64_t	cur_txfer_len;
9640 
9641 
9642 	ASSERT(spx->txlt_sata_pkt != NULL);
9643 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
9644 	ASSERT(bp != NULL);
9645 
9646 
9647 	if (spx->txlt_buf_dma_handle == NULL) {
9648 		/*
9649 		 * No DMA resources allocated so far - this is a first call
9650 		 * for this sata pkt.
9651 		 */
9652 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
9653 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
9654 
9655 		if (rval != DDI_SUCCESS) {
9656 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9657 			    "sata_dma_buf_setup: no buf DMA resources %x",
9658 			    rval));
9659 			return (rval);
9660 		}
9661 
9662 		if (bp->b_flags & B_READ)
9663 			dma_flags = DDI_DMA_READ;
9664 		else
9665 			dma_flags = DDI_DMA_WRITE;
9666 
9667 		if (flags & PKT_CONSISTENT)
9668 			dma_flags |= DDI_DMA_CONSISTENT;
9669 
9670 		if (flags & PKT_DMA_PARTIAL)
9671 			dma_flags |= DDI_DMA_PARTIAL;
9672 
9673 		/*
9674 		 * Check buffer alignment and size against dma attributes
9675 		 * Consider dma_attr_align only. There may be requests
9676 		 * with the size lower than device granularity, but they
9677 		 * will not read/write from/to the device, so no adjustment
9678 		 * is necessary. The dma_attr_minxfer theoretically should
9679 		 * be considered, but no HBA driver is checking it.
9680 		 */
9681 		if (IS_P2ALIGNED(bp->b_un.b_addr,
9682 		    cur_dma_attr->dma_attr_align)) {
9683 			rval = ddi_dma_buf_bind_handle(
9684 			    spx->txlt_buf_dma_handle,
9685 			    bp, dma_flags, callback, arg,
9686 			    &spx->txlt_dma_cookie,
9687 			    &spx->txlt_curwin_num_dma_cookies);
9688 		} else { /* Buffer is not aligned */
9689 
9690 			int	(*ddicallback)(caddr_t);
9691 			size_t	bufsz;
9692 
9693 			/* Check id sleeping is allowed */
9694 			ddicallback = (callback == NULL_FUNC) ?
9695 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
9696 
9697 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
9698 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
9699 			    (void *)bp->b_un.b_addr, bp->b_bcount);
9700 
9701 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
9702 				/*
9703 				 * CPU will need to access data in the buffer
9704 				 * (for copying) so map it.
9705 				 */
9706 				bp_mapin(bp);
9707 
9708 			ASSERT(spx->txlt_tmp_buf == NULL);
9709 
9710 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
9711 			rval = ddi_dma_mem_alloc(
9712 			    spx->txlt_buf_dma_handle,
9713 			    bp->b_bcount,
9714 			    &sata_acc_attr,
9715 			    DDI_DMA_STREAMING,
9716 			    ddicallback, NULL,
9717 			    &spx->txlt_tmp_buf,
9718 			    &bufsz,
9719 			    &spx->txlt_tmp_buf_handle);
9720 
9721 			if (rval != DDI_SUCCESS) {
9722 				/* DMA mapping failed */
9723 				(void) ddi_dma_free_handle(
9724 				    &spx->txlt_buf_dma_handle);
9725 				spx->txlt_buf_dma_handle = NULL;
9726 #ifdef SATA_DEBUG
9727 				mbuffail_count++;
9728 #endif
9729 				SATADBG1(SATA_DBG_DMA_SETUP,
9730 				    spx->txlt_sata_hba_inst,
9731 				    "sata_dma_buf_setup: "
9732 				    "buf dma mem alloc failed %x\n", rval);
9733 				return (rval);
9734 			}
9735 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
9736 			    cur_dma_attr->dma_attr_align));
9737 
9738 #ifdef SATA_DEBUG
9739 			mbuf_count++;
9740 
9741 			if (bp->b_bcount != bufsz)
9742 				/*
9743 				 * This will require special handling, because
9744 				 * DMA cookies will be based on the temporary
9745 				 * buffer size, not the original buffer
9746 				 * b_bcount, so the residue may have to
9747 				 * be counted differently.
9748 				 */
9749 				SATADBG2(SATA_DBG_DMA_SETUP,
9750 				    spx->txlt_sata_hba_inst,
9751 				    "sata_dma_buf_setup: bp size %x != "
9752 				    "bufsz %x\n", bp->b_bcount, bufsz);
9753 #endif
9754 			if (dma_flags & DDI_DMA_WRITE) {
9755 				/*
9756 				 * Write operation - copy data into
9757 				 * an aligned temporary buffer. Buffer will be
9758 				 * synced for device by ddi_dma_addr_bind_handle
9759 				 */
9760 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
9761 				    bp->b_bcount);
9762 			}
9763 
9764 			rval = ddi_dma_addr_bind_handle(
9765 			    spx->txlt_buf_dma_handle,
9766 			    NULL,
9767 			    spx->txlt_tmp_buf,
9768 			    bufsz, dma_flags, ddicallback, 0,
9769 			    &spx->txlt_dma_cookie,
9770 			    &spx->txlt_curwin_num_dma_cookies);
9771 		}
9772 
9773 		switch (rval) {
9774 		case DDI_DMA_PARTIAL_MAP:
9775 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
9776 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
9777 			/*
9778 			 * Partial DMA mapping.
9779 			 * Retrieve number of DMA windows for this request.
9780 			 */
9781 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
9782 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
9783 				if (spx->txlt_tmp_buf != NULL) {
9784 					ddi_dma_mem_free(
9785 					    &spx->txlt_tmp_buf_handle);
9786 					spx->txlt_tmp_buf = NULL;
9787 				}
9788 				(void) ddi_dma_unbind_handle(
9789 				    spx->txlt_buf_dma_handle);
9790 				(void) ddi_dma_free_handle(
9791 				    &spx->txlt_buf_dma_handle);
9792 				spx->txlt_buf_dma_handle = NULL;
9793 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9794 				    "sata_dma_buf_setup: numwin failed\n"));
9795 				return (DDI_FAILURE);
9796 			}
9797 			SATADBG2(SATA_DBG_DMA_SETUP,
9798 			    spx->txlt_sata_hba_inst,
9799 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
9800 			    spx->txlt_num_dma_win,
9801 			    spx->txlt_curwin_num_dma_cookies);
9802 			spx->txlt_cur_dma_win = 0;
9803 			break;
9804 
9805 		case DDI_DMA_MAPPED:
9806 			/* DMA fully mapped */
9807 			spx->txlt_num_dma_win = 1;
9808 			spx->txlt_cur_dma_win = 0;
9809 			SATADBG1(SATA_DBG_DMA_SETUP,
9810 			    spx->txlt_sata_hba_inst,
9811 			    "sata_dma_buf_setup: windows: 1 "
9812 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
9813 			break;
9814 
9815 		default:
9816 			/* DMA mapping failed */
9817 			if (spx->txlt_tmp_buf != NULL) {
9818 				ddi_dma_mem_free(
9819 				    &spx->txlt_tmp_buf_handle);
9820 				spx->txlt_tmp_buf = NULL;
9821 			}
9822 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
9823 			spx->txlt_buf_dma_handle = NULL;
9824 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9825 			    "sata_dma_buf_setup: buf dma handle binding "
9826 			    "failed %x\n", rval));
9827 			return (rval);
9828 		}
9829 		spx->txlt_curwin_processed_dma_cookies = 0;
9830 		spx->txlt_dma_cookie_list = NULL;
9831 	} else {
9832 		/*
9833 		 * DMA setup is reused. Check if we need to process more
9834 		 * cookies in current window, or to get next window, if any.
9835 		 */
9836 
9837 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
9838 		    spx->txlt_curwin_num_dma_cookies);
9839 
9840 		if (spx->txlt_curwin_processed_dma_cookies ==
9841 		    spx->txlt_curwin_num_dma_cookies) {
9842 			/*
9843 			 * All cookies from current DMA window were processed.
9844 			 * Get next DMA window.
9845 			 */
9846 			spx->txlt_cur_dma_win++;
9847 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
9848 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
9849 				    spx->txlt_cur_dma_win, &offset, &size,
9850 				    &spx->txlt_dma_cookie,
9851 				    &spx->txlt_curwin_num_dma_cookies);
9852 				spx->txlt_curwin_processed_dma_cookies = 0;
9853 			} else {
9854 				/* No more windows! End of request! */
9855 				/* What to do? - panic for now */
9856 				ASSERT(spx->txlt_cur_dma_win >=
9857 				    spx->txlt_num_dma_win);
9858 
9859 				spx->txlt_curwin_num_dma_cookies = 0;
9860 				spx->txlt_curwin_processed_dma_cookies = 0;
9861 				spx->txlt_sata_pkt->
9862 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
9863 				return (DDI_SUCCESS);
9864 			}
9865 		}
9866 	}
9867 	/* There better be at least one DMA cookie outstanding */
9868 	ASSERT((spx->txlt_curwin_num_dma_cookies -
9869 	    spx->txlt_curwin_processed_dma_cookies) > 0);
9870 
9871 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
9872 		/* The default cookie slot was used in previous run */
9873 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
9874 		spx->txlt_dma_cookie_list = NULL;
9875 		spx->txlt_dma_cookie_list_len = 0;
9876 	}
9877 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
9878 		/*
9879 		 * Processing a new DMA window - set-up dma cookies list.
9880 		 * We may reuse previously allocated cookie array if it is
9881 		 * possible.
9882 		 */
9883 		if (spx->txlt_dma_cookie_list != NULL &&
9884 		    spx->txlt_dma_cookie_list_len <
9885 		    spx->txlt_curwin_num_dma_cookies) {
9886 			/*
9887 			 * New DMA window contains more cookies than
9888 			 * the previous one. We need larger cookie list - free
9889 			 * the old one.
9890 			 */
9891 			(void) kmem_free(spx->txlt_dma_cookie_list,
9892 			    spx->txlt_dma_cookie_list_len *
9893 			    sizeof (ddi_dma_cookie_t));
9894 			spx->txlt_dma_cookie_list = NULL;
9895 			spx->txlt_dma_cookie_list_len = 0;
9896 		}
9897 		if (spx->txlt_dma_cookie_list == NULL) {
9898 			/*
9899 			 * Calculate lesser of number of cookies in this
9900 			 * DMA window and number of s/g entries.
9901 			 */
9902 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
9903 			req_len = MIN(max_sg_len,
9904 			    spx->txlt_curwin_num_dma_cookies);
9905 
9906 			/* Allocate new dma cookie array if necessary */
9907 			if (req_len == 1) {
9908 				/* Only one cookie - no need for a list */
9909 				spx->txlt_dma_cookie_list =
9910 				    &spx->txlt_dma_cookie;
9911 				spx->txlt_dma_cookie_list_len = 1;
9912 			} else {
9913 				/*
9914 				 * More than one cookie - try to allocate space.
9915 				 */
9916 				spx->txlt_dma_cookie_list = kmem_zalloc(
9917 				    sizeof (ddi_dma_cookie_t) * req_len,
9918 				    callback == NULL_FUNC ? KM_NOSLEEP :
9919 				    KM_SLEEP);
9920 				if (spx->txlt_dma_cookie_list == NULL) {
9921 					SATADBG1(SATA_DBG_DMA_SETUP,
9922 					    spx->txlt_sata_hba_inst,
9923 					    "sata_dma_buf_setup: cookie list "
9924 					    "allocation failed\n", NULL);
9925 					/*
9926 					 * We could not allocate space for
9927 					 * neccessary number of dma cookies in
9928 					 * this window, so we fail this request.
9929 					 * Next invocation would try again to
9930 					 * allocate space for cookie list.
9931 					 * Note:Packet residue was not modified.
9932 					 */
9933 					return (DDI_DMA_NORESOURCES);
9934 				} else {
9935 					spx->txlt_dma_cookie_list_len = req_len;
9936 				}
9937 			}
9938 		}
9939 		/*
9940 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
9941 		 * First cookie was already fetched.
9942 		 */
9943 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
9944 		cur_txfer_len =
9945 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
9946 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
9947 		spx->txlt_curwin_processed_dma_cookies++;
9948 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
9949 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
9950 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
9951 			    &spx->txlt_dma_cookie_list[i]);
9952 			cur_txfer_len +=
9953 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
9954 			spx->txlt_curwin_processed_dma_cookies++;
9955 			spx->txlt_sata_pkt->
9956 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
9957 		}
9958 	} else {
9959 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
9960 		    "sata_dma_buf_setup: sliding within DMA window, "
9961 		    "cur cookie %d, total cookies %d\n",
9962 		    spx->txlt_curwin_processed_dma_cookies,
9963 		    spx->txlt_curwin_num_dma_cookies);
9964 
9965 		/*
9966 		 * Not all cookies from the current dma window were used because
9967 		 * of s/g limitation.
9968 		 * There is no need to re-size the list - it was set at
9969 		 * optimal size, or only default entry is used (s/g = 1).
9970 		 */
9971 		if (spx->txlt_dma_cookie_list == NULL) {
9972 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
9973 			spx->txlt_dma_cookie_list_len = 1;
9974 		}
9975 		/*
9976 		 * Since we are processing remaining cookies in a DMA window,
9977 		 * there may be less of them than the number of entries in the
9978 		 * current dma cookie list.
9979 		 */
9980 		req_len = MIN(spx->txlt_dma_cookie_list_len,
9981 		    (spx->txlt_curwin_num_dma_cookies -
9982 		    spx->txlt_curwin_processed_dma_cookies));
9983 
9984 		/* Fetch the next batch of cookies */
9985 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
9986 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
9987 			    &spx->txlt_dma_cookie_list[i]);
9988 			cur_txfer_len +=
9989 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
9990 			spx->txlt_sata_pkt->
9991 			    satapkt_cmd.satacmd_num_dma_cookies++;
9992 			spx->txlt_curwin_processed_dma_cookies++;
9993 		}
9994 	}
9995 
9996 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
9997 
9998 	/* Point sata_cmd to the cookie list */
9999 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
10000 	    &spx->txlt_dma_cookie_list[0];
10001 
10002 	/* Remember number of DMA cookies passed in sata packet */
10003 	spx->txlt_num_dma_cookies =
10004 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
10005 
10006 	ASSERT(cur_txfer_len != 0);
10007 	if (cur_txfer_len <= bp->b_bcount)
10008 		spx->txlt_total_residue -= cur_txfer_len;
10009 	else {
10010 		/*
10011 		 * Temporary DMA buffer has been padded by
10012 		 * ddi_dma_mem_alloc()!
10013 		 * This requires special handling, because DMA cookies are
10014 		 * based on the temporary buffer size, not the b_bcount,
10015 		 * and we have extra bytes to transfer - but the packet
10016 		 * residue has to stay correct because we will copy only
10017 		 * the requested number of bytes.
10018 		 */
10019 		spx->txlt_total_residue -= bp->b_bcount;
10020 	}
10021 
10022 	return (DDI_SUCCESS);
10023 }
10024 
10025 
10026 /*
10027  * Fetch Device Identify data.
10028  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
10029  * command to a device and get the device identify data.
10030  * The device_info structure has to be set to device type (for selecting proper
10031  * device identify command).
10032  *
10033  * Returns:
10034  * SATA_SUCCESS if cmd succeeded
10035  * SATA_RETRY if cmd was rejected and could be retried,
10036  * SATA_FAILURE if cmd failed and should not be retried (port error)
10037  *
10038  * Cannot be called in an interrupt context.
10039  */
10040 
10041 static int
10042 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
10043     sata_drive_info_t *sdinfo)
10044 {
10045 	struct buf *bp;
10046 	sata_pkt_t *spkt;
10047 	sata_cmd_t *scmd;
10048 	sata_pkt_txlate_t *spx;
10049 	int rval;
10050 
10051 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10052 	spx->txlt_sata_hba_inst = sata_hba_inst;
10053 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
10054 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
10055 	if (spkt == NULL) {
10056 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
10057 		return (SATA_RETRY); /* may retry later */
10058 	}
10059 	/* address is needed now */
10060 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10061 
10062 	/*
10063 	 * Allocate buffer for Identify Data return data
10064 	 */
10065 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
10066 	if (bp == NULL) {
10067 		sata_pkt_free(spx);
10068 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
10069 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10070 		    "sata_fetch_device_identify_data: "
10071 		    "cannot allocate buffer for ID"));
10072 		return (SATA_RETRY); /* may retry later */
10073 	}
10074 
10075 	/* Fill sata_pkt */
10076 	sdinfo->satadrv_state = SATA_STATE_PROBING;
10077 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10078 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10079 	/* Synchronous mode, no callback */
10080 	spkt->satapkt_comp = NULL;
10081 	/* Timeout 30s */
10082 	spkt->satapkt_time = sata_default_pkt_time;
10083 
10084 	scmd = &spkt->satapkt_cmd;
10085 	scmd->satacmd_bp = bp;
10086 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
10087 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10088 
10089 	/* Build Identify Device cmd in the sata_pkt */
10090 	scmd->satacmd_addr_type = 0;		/* N/A */
10091 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
10092 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
10093 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
10094 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
10095 	scmd->satacmd_features_reg = 0;		/* N/A */
10096 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
10097 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
10098 		/* Identify Packet Device cmd */
10099 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
10100 	} else {
10101 		/* Identify Device cmd - mandatory for all other devices */
10102 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
10103 	}
10104 
10105 	/* Send pkt to SATA HBA driver */
10106 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
10107 	if (rval == SATA_TRAN_ACCEPTED &&
10108 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
10109 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
10110 		    DDI_DMA_SYNC_FORKERNEL);
10111 		ASSERT(rval == DDI_SUCCESS);
10112 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
10113 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
10114 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10115 			    "SATA disk device at port %d - "
10116 			    "partial Identify Data",
10117 			    sdinfo->satadrv_addr.cport));
10118 			rval = SATA_RETRY; /* may retry later */
10119 			goto fail;
10120 		}
10121 		/* Update sata_drive_info */
10122 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
10123 		    sizeof (sata_id_t));
10124 
10125 		sdinfo->satadrv_features_support = 0;
10126 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10127 			/*
10128 			 * Retrieve capacity (disks only) and addressing mode
10129 			 */
10130 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
10131 		} else {
10132 			/*
10133 			 * For ATAPI devices one would have to issue
10134 			 * Get Capacity cmd for media capacity. Not here.
10135 			 */
10136 			sdinfo->satadrv_capacity = 0;
10137 			/*
10138 			 * Check what cdb length is supported
10139 			 */
10140 			if ((sdinfo->satadrv_id.ai_config &
10141 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
10142 				sdinfo->satadrv_atapi_cdb_len = 16;
10143 			else
10144 				sdinfo->satadrv_atapi_cdb_len = 12;
10145 		}
10146 		/* Setup supported features flags */
10147 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
10148 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
10149 
10150 		/* Check for SATA GEN and NCQ support */
10151 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
10152 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
10153 			/* SATA compliance */
10154 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
10155 				sdinfo->satadrv_features_support |=
10156 				    SATA_DEV_F_NCQ;
10157 			if (sdinfo->satadrv_id.ai_satacap &
10158 			    (SATA_1_SPEED | SATA_2_SPEED)) {
10159 				if (sdinfo->satadrv_id.ai_satacap &
10160 				    SATA_2_SPEED)
10161 					sdinfo->satadrv_features_support |=
10162 					    SATA_DEV_F_SATA2;
10163 				if (sdinfo->satadrv_id.ai_satacap &
10164 				    SATA_1_SPEED)
10165 					sdinfo->satadrv_features_support |=
10166 					    SATA_DEV_F_SATA1;
10167 			} else {
10168 				sdinfo->satadrv_features_support |=
10169 				    SATA_DEV_F_SATA1;
10170 			}
10171 		}
10172 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
10173 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
10174 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
10175 
10176 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
10177 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
10178 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
10179 			++sdinfo->satadrv_queue_depth;
10180 			/* Adjust according to controller capabilities */
10181 			sdinfo->satadrv_max_queue_depth = MIN(
10182 			    sdinfo->satadrv_queue_depth,
10183 			    SATA_QDEPTH(sata_hba_inst));
10184 			/* Adjust according to global queue depth limit */
10185 			sdinfo->satadrv_max_queue_depth = MIN(
10186 			    sdinfo->satadrv_max_queue_depth,
10187 			    sata_current_max_qdepth);
10188 			if (sdinfo->satadrv_max_queue_depth == 0)
10189 				sdinfo->satadrv_max_queue_depth = 1;
10190 		} else
10191 			sdinfo->satadrv_max_queue_depth = 1;
10192 
10193 		rval = SATA_SUCCESS;
10194 	} else {
10195 		/*
10196 		 * Woops, no Identify Data.
10197 		 */
10198 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
10199 			rval = SATA_RETRY; /* may retry later */
10200 		} else if (rval == SATA_TRAN_ACCEPTED) {
10201 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
10202 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
10203 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
10204 			    spkt->satapkt_reason == SATA_PKT_RESET)
10205 				rval = SATA_RETRY; /* may retry later */
10206 			else
10207 				rval = SATA_FAILURE;
10208 		} else {
10209 			rval = SATA_FAILURE;
10210 		}
10211 	}
10212 fail:
10213 	/* Free allocated resources */
10214 	sata_free_local_buffer(spx);
10215 	sata_pkt_free(spx);
10216 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
10217 
10218 	return (rval);
10219 }
10220 
10221 
10222 /*
10223  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
10224  * UDMA mode is checked first, followed by MWDMA mode.
10225  * set correctly, so this function is setting it to the highest supported level.
10226  * Older SATA spec required that the device supports at least DMA 4 mode and
10227  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
10228  * restriction has been removed.
10229  *
10230  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
10231  * Returns SATA_FAILURE if proper DMA mode could not be selected.
10232  *
10233  * NOTE: This function should be called only if DMA mode is supported.
10234  */
10235 static int
10236 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
10237 {
10238 	sata_pkt_t *spkt;
10239 	sata_cmd_t *scmd;
10240 	sata_pkt_txlate_t *spx;
10241 	int i, mode;
10242 	uint8_t subcmd;
10243 	int rval = SATA_SUCCESS;
10244 
10245 	ASSERT(sdinfo != NULL);
10246 	ASSERT(sata_hba_inst != NULL);
10247 
10248 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
10249 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
10250 		/* Find highest Ultra DMA mode supported */
10251 		for (mode = 6; mode >= 0; --mode) {
10252 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
10253 				break;
10254 		}
10255 #if 0
10256 		/* Left for historical reasons */
10257 		/*
10258 		 * Some initial version of SATA spec indicated that at least
10259 		 * UDMA mode 4 has to be supported. It is not mentioned in
10260 		 * SerialATA 2.6, so this restriction is removed.
10261 		 */
10262 		if (mode < 4)
10263 			return (SATA_FAILURE);
10264 #endif
10265 		/* Find UDMA mode currently selected */
10266 		for (i = 6; i >= 0; --i) {
10267 			if (sdinfo->satadrv_id.ai_ultradma & (1 << (i + 8)))
10268 				break;
10269 		}
10270 		if (i >= mode)
10271 			/* Nothing to do */
10272 			return (SATA_SUCCESS);
10273 
10274 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
10275 
10276 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
10277 		/* Find highest MultiWord DMA mode supported */
10278 		for (mode = 2; mode >= 0; --mode) {
10279 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
10280 				break;
10281 		}
10282 		/* Find highest MultiWord DMA mode selected */
10283 		for (i = 2; i >= 0; --i) {
10284 			if (sdinfo->satadrv_id.ai_dworddma & (1 << (i + 8)))
10285 				break;
10286 		}
10287 		if (i >= mode)
10288 			/* Nothing to do */
10289 			return (SATA_SUCCESS);
10290 
10291 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
10292 	} else
10293 		return (SATA_SUCCESS);
10294 
10295 	/*
10296 	 * Set DMA mode via SET FEATURES COMMAND.
10297 	 * Prepare packet for SET FEATURES COMMAND.
10298 	 */
10299 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10300 	spx->txlt_sata_hba_inst = sata_hba_inst;
10301 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
10302 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
10303 	if (spkt == NULL) {
10304 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10305 		    "sata_set_dma_mode: could not set DMA mode %", mode));
10306 		rval = SATA_FAILURE;
10307 		goto done;
10308 	}
10309 	/* Fill sata_pkt */
10310 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10311 	/* Timeout 30s */
10312 	spkt->satapkt_time = sata_default_pkt_time;
10313 	/* Synchronous mode, no callback, interrupts */
10314 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10315 	spkt->satapkt_comp = NULL;
10316 	scmd = &spkt->satapkt_cmd;
10317 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
10318 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10319 	scmd->satacmd_addr_type = 0;
10320 	scmd->satacmd_device_reg = 0;
10321 	scmd->satacmd_status_reg = 0;
10322 	scmd->satacmd_error_reg = 0;
10323 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
10324 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
10325 	scmd->satacmd_sec_count_lsb = subcmd | mode;
10326 
10327 	/* Transfer command to HBA */
10328 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
10329 	    spkt) != SATA_TRAN_ACCEPTED ||
10330 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
10331 		/* Pkt execution failed */
10332 		rval = SATA_FAILURE;
10333 	}
10334 done:
10335 
10336 	/* Free allocated resources */
10337 	if (spkt != NULL)
10338 		sata_pkt_free(spx);
10339 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
10340 
10341 	return (rval);
10342 }
10343 
10344 
10345 /*
10346  * Set device caching mode.
10347  * One of the following operations should be specified:
10348  * SATAC_SF_ENABLE_READ_AHEAD
10349  * SATAC_SF_DISABLE_READ_AHEAD
10350  * SATAC_SF_ENABLE_WRITE_CACHE
10351  * SATAC_SF_DISABLE_WRITE_CACHE
10352  *
10353  * If operation fails, system log messgage is emitted.
10354  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
10355  */
10356 
10357 static int
10358 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
10359     int cache_op)
10360 {
10361 	sata_pkt_t *spkt;
10362 	sata_cmd_t *scmd;
10363 	sata_pkt_txlate_t *spx;
10364 	int rval = SATA_SUCCESS;
10365 	char *infop;
10366 
10367 	ASSERT(sdinfo != NULL);
10368 	ASSERT(sata_hba_inst != NULL);
10369 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
10370 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
10371 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
10372 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
10373 
10374 
10375 	/* Prepare packet for SET FEATURES COMMAND */
10376 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10377 	spx->txlt_sata_hba_inst = sata_hba_inst;
10378 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
10379 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
10380 	if (spkt == NULL) {
10381 		rval = SATA_FAILURE;
10382 		goto failure;
10383 	}
10384 	/* Fill sata_pkt */
10385 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10386 	/* Timeout 30s */
10387 	spkt->satapkt_time = sata_default_pkt_time;
10388 	/* Synchronous mode, no callback, interrupts */
10389 	spkt->satapkt_op_mode =
10390 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10391 	spkt->satapkt_comp = NULL;
10392 	scmd = &spkt->satapkt_cmd;
10393 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
10394 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10395 	scmd->satacmd_addr_type = 0;
10396 	scmd->satacmd_device_reg = 0;
10397 	scmd->satacmd_status_reg = 0;
10398 	scmd->satacmd_error_reg = 0;
10399 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
10400 	scmd->satacmd_features_reg = cache_op;
10401 
10402 	/* Transfer command to HBA */
10403 	if (((*SATA_START_FUNC(sata_hba_inst))(
10404 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
10405 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
10406 		/* Pkt execution failed */
10407 		switch (cache_op) {
10408 		case SATAC_SF_ENABLE_READ_AHEAD:
10409 			infop = "enabling read ahead failed";
10410 			break;
10411 		case SATAC_SF_DISABLE_READ_AHEAD:
10412 			infop = "disabling read ahead failed";
10413 			break;
10414 		case SATAC_SF_ENABLE_WRITE_CACHE:
10415 			infop = "enabling write cache failed";
10416 			break;
10417 		case SATAC_SF_DISABLE_WRITE_CACHE:
10418 			infop = "disabling write cache failed";
10419 			break;
10420 		}
10421 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
10422 		rval = SATA_FAILURE;
10423 	}
10424 failure:
10425 	/* Free allocated resources */
10426 	if (spkt != NULL)
10427 		sata_pkt_free(spx);
10428 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
10429 	return (rval);
10430 }
10431 
10432 /*
10433  * Set Removable Media Status Notification (enable/disable)
10434  * state == 0 , disable
10435  * state != 0 , enable
10436  *
10437  * If operation fails, system log messgage is emitted.
10438  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
10439  */
10440 
10441 static int
10442 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
10443     int state)
10444 {
10445 	sata_pkt_t *spkt;
10446 	sata_cmd_t *scmd;
10447 	sata_pkt_txlate_t *spx;
10448 	int rval = SATA_SUCCESS;
10449 	char *infop;
10450 
10451 	ASSERT(sdinfo != NULL);
10452 	ASSERT(sata_hba_inst != NULL);
10453 
10454 	/* Prepare packet for SET FEATURES COMMAND */
10455 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10456 	spx->txlt_sata_hba_inst = sata_hba_inst;
10457 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
10458 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
10459 	if (spkt == NULL) {
10460 		rval = SATA_FAILURE;
10461 		goto failure;
10462 	}
10463 	/* Fill sata_pkt */
10464 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10465 	/* Timeout 30s */
10466 	spkt->satapkt_time = sata_default_pkt_time;
10467 	/* Synchronous mode, no callback, interrupts */
10468 	spkt->satapkt_op_mode =
10469 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10470 	spkt->satapkt_comp = NULL;
10471 	scmd = &spkt->satapkt_cmd;
10472 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
10473 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10474 	scmd->satacmd_addr_type = 0;
10475 	scmd->satacmd_device_reg = 0;
10476 	scmd->satacmd_status_reg = 0;
10477 	scmd->satacmd_error_reg = 0;
10478 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
10479 	if (state == 0)
10480 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
10481 	else
10482 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
10483 
10484 	/* Transfer command to HBA */
10485 	if (((*SATA_START_FUNC(sata_hba_inst))(
10486 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
10487 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
10488 		/* Pkt execution failed */
10489 		if (state == 0)
10490 			infop = "disabling Removable Media Status "
10491 			    "Notification failed";
10492 		else
10493 			infop = "enabling Removable Media Status "
10494 			    "Notification failed";
10495 
10496 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
10497 		rval = SATA_FAILURE;
10498 	}
10499 failure:
10500 	/* Free allocated resources */
10501 	if (spkt != NULL)
10502 		sata_pkt_free(spx);
10503 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
10504 	return (rval);
10505 }
10506 
10507 
10508 /*
10509  * Update port SCR block
10510  */
10511 static void
10512 sata_update_port_scr(sata_port_scr_t *port_scr, sata_device_t *device)
10513 {
10514 	port_scr->sstatus = device->satadev_scr.sstatus;
10515 	port_scr->serror = device->satadev_scr.serror;
10516 	port_scr->scontrol = device->satadev_scr.scontrol;
10517 	port_scr->sactive = device->satadev_scr.sactive;
10518 	port_scr->snotific = device->satadev_scr.snotific;
10519 }
10520 
10521 /*
10522  * Update state and copy port ss* values from passed sata_device structure.
10523  * sata_address is validated - if not valid, nothing is changed in sata_scsi
10524  * configuration struct.
10525  *
10526  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
10527  * regardless of the state in device argument.
10528  *
10529  * Port mutex should be held while calling this function.
10530  */
10531 static void
10532 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
10533 	sata_device_t *sata_device)
10534 {
10535 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst,
10536 	    sata_device->satadev_addr.cport)));
10537 
10538 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
10539 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
10540 
10541 		sata_cport_info_t *cportinfo;
10542 
10543 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
10544 		    sata_device->satadev_addr.cport)
10545 			return;
10546 
10547 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
10548 		    sata_device->satadev_addr.cport);
10549 		sata_update_port_scr(&cportinfo->cport_scr, sata_device);
10550 
10551 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
10552 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
10553 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
10554 		cportinfo->cport_state |=
10555 		    sata_device->satadev_state & SATA_PSTATE_VALID;
10556 	} else {
10557 		sata_pmport_info_t *pmportinfo;
10558 
10559 		if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT) ||
10560 		    (sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
10561 		    SATA_NUM_PMPORTS(sata_hba_inst,
10562 		    sata_device->satadev_addr.cport) <
10563 		    sata_device->satadev_addr.pmport)
10564 			return;
10565 
10566 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
10567 		    sata_device->satadev_addr.cport,
10568 		    sata_device->satadev_addr.pmport);
10569 		sata_update_port_scr(&pmportinfo->pmport_scr, sata_device);
10570 
10571 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
10572 		pmportinfo->pmport_state &=
10573 		    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF |
10574 		    SATA_PSTATE_FAILED);
10575 		pmportinfo->pmport_state |=
10576 		    sata_device->satadev_state & SATA_PSTATE_VALID;
10577 	}
10578 }
10579 
10580 
10581 
10582 /*
10583  * Extract SATA port specification from an IOCTL argument.
10584  *
10585  * This function return the port the user land send us as is, unless it
10586  * cannot retrieve port spec, then -1 is returned.
10587  *
10588  * Note: Only cport  - no port multiplier port.
10589  */
10590 static int32_t
10591 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
10592 {
10593 	int32_t port;
10594 
10595 	/* Extract port number from nvpair in dca structure  */
10596 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
10597 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
10598 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
10599 		    port));
10600 		port = -1;
10601 	}
10602 
10603 	return (port);
10604 }
10605 
10606 /*
10607  * Get dev_info_t pointer to the device node pointed to by port argument.
10608  * NOTE: target argument is a value used in ioctls to identify
10609  * the AP - it is not a sata_address.
10610  * It is a combination of cport, pmport and address qualifier, encodded same
10611  * way as a scsi target number.
10612  * At this moment it carries only cport number.
10613  *
10614  * No PMult hotplug support.
10615  *
10616  * Returns dev_info_t pointer if target device was found, NULL otherwise.
10617  */
10618 
10619 static dev_info_t *
10620 sata_get_target_dip(dev_info_t *dip, int32_t port)
10621 {
10622 	dev_info_t	*cdip = NULL;
10623 	int		target, tgt;
10624 	int		ncport;
10625 	int 		circ;
10626 
10627 	ncport = port & SATA_CFGA_CPORT_MASK;
10628 	target = SATA_TO_SCSI_TARGET(ncport, 0, SATA_ADDR_DCPORT);
10629 
10630 	ndi_devi_enter(dip, &circ);
10631 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
10632 		dev_info_t *next = ddi_get_next_sibling(cdip);
10633 
10634 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
10635 		    DDI_PROP_DONTPASS, "target", -1);
10636 		if (tgt == -1) {
10637 			/*
10638 			 * This is actually an error condition, but not
10639 			 * a fatal one. Just continue the search.
10640 			 */
10641 			cdip = next;
10642 			continue;
10643 		}
10644 
10645 		if (tgt == target)
10646 			break;
10647 
10648 		cdip = next;
10649 	}
10650 	ndi_devi_exit(dip, circ);
10651 
10652 	return (cdip);
10653 }
10654 
10655 /*
10656  * Get dev_info_t pointer to the device node pointed to by port argument.
10657  * NOTE: target argument is a value used in ioctls to identify
10658  * the AP - it is not a sata_address.
10659  * It is a combination of cport, pmport and address qualifier, encoded same
10660  * way as a scsi target number.
10661  * At this moment it carries only cport number.
10662  *
10663  * No PMult hotplug support.
10664  *
10665  * Returns dev_info_t pointer if target device was found, NULL otherwise.
10666  */
10667 
10668 static dev_info_t *
10669 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
10670 {
10671 	dev_info_t	*cdip = NULL;
10672 	int		target, tgt;
10673 	int 		circ;
10674 
10675 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
10676 
10677 	ndi_devi_enter(dip, &circ);
10678 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
10679 		dev_info_t *next = ddi_get_next_sibling(cdip);
10680 
10681 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
10682 		    DDI_PROP_DONTPASS, "target", -1);
10683 		if (tgt == -1) {
10684 			/*
10685 			 * This is actually an error condition, but not
10686 			 * a fatal one. Just continue the search.
10687 			 */
10688 			cdip = next;
10689 			continue;
10690 		}
10691 
10692 		if (tgt == target)
10693 			break;
10694 
10695 		cdip = next;
10696 	}
10697 	ndi_devi_exit(dip, circ);
10698 
10699 	return (cdip);
10700 }
10701 
10702 /*
10703  * Process sata port disconnect request.
10704  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
10705  * before this request. Nevertheless, if a device is still configured,
10706  * we need to attempt to offline and unconfigure device.
10707  * Regardless of the unconfigure operation results the port is marked as
10708  * deactivated and no access to the attached device is possible.
10709  * If the target node remains because unconfigure operation failed, its state
10710  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
10711  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
10712  * the device and remove old target node.
10713  *
10714  * This function invokes sata_hba_inst->satahba_tran->
10715  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
10716  * If successful, the device structure (if any) attached to the specified port
10717  * is removed and state of the port marked appropriately.
10718  * Failure of the port_deactivate may keep port in the physically active state,
10719  * or may fail the port.
10720  *
10721  * NOTE: Port multiplier code is not completed nor tested.
10722  */
10723 
10724 static int
10725 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
10726     sata_device_t *sata_device)
10727 {
10728 	sata_drive_info_t *sdinfo = NULL;
10729 	sata_cport_info_t *cportinfo = NULL;
10730 	sata_pmport_info_t *pmportinfo = NULL;
10731 	sata_pmult_info_t *pmultinfo = NULL;
10732 	dev_info_t *tdip;
10733 	int cport, pmport, qual;
10734 	int rval = SATA_SUCCESS;
10735 	int rv = 0;
10736 
10737 	cport = sata_device->satadev_addr.cport;
10738 	pmport = sata_device->satadev_addr.pmport;
10739 	qual = sata_device->satadev_addr.qual;
10740 
10741 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
10742 
10743 	/*
10744 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
10745 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
10746 	 * Do the sanity check.
10747 	 */
10748 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
10749 		/* No physical port deactivation supported. */
10750 		return (EINVAL);
10751 	}
10752 
10753 	/* Check the current state of the port */
10754 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10755 	    (SATA_DIP(sata_hba_inst), sata_device);
10756 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10757 	sata_update_port_info(sata_hba_inst, sata_device);
10758 	if (rval != SATA_SUCCESS ||
10759 	    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
10760 		/* Device port status is unknown or it is in failed state */
10761 		if (qual == SATA_ADDR_PMPORT) {
10762 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
10763 			    SATA_PSTATE_FAILED;
10764 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
10765 			    "sata_hba_ioctl: connect: failed to deactivate "
10766 			    "SATA port %d", cport);
10767 		} else {
10768 			SATA_CPORT_STATE(sata_hba_inst, cport) =
10769 			    SATA_PSTATE_FAILED;
10770 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
10771 			    "sata_hba_ioctl: connect: failed to deactivate "
10772 			    "SATA port %d:%d", cport, pmport);
10773 		}
10774 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
10775 		    cport)->cport_mutex);
10776 		return (EIO);
10777 	}
10778 	/*
10779 	 * Set port's dev_state to not ready - this will disable
10780 	 * an access to a potentially attached device.
10781 	 */
10782 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10783 	if (qual == SATA_ADDR_PMPORT) {
10784 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
10785 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
10786 			sdinfo = pmportinfo->pmport_sata_drive;
10787 			ASSERT(sdinfo != NULL);
10788 		}
10789 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
10790 	} else {
10791 		/* Assuming cport */
10792 
10793 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
10794 			if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
10795 				pmultinfo =
10796 				    cportinfo->cport_devp.cport_sata_pmult;
10797 				ASSERT(pmultinfo != NULL);
10798 			} else if (cportinfo->cport_dev_type &
10799 			    SATA_VALID_DEV_TYPE) {
10800 				sdinfo = cportinfo->cport_devp.cport_sata_drive;
10801 				ASSERT(sdinfo != NULL);
10802 			}
10803 		}
10804 		cportinfo->cport_state &= ~SATA_STATE_READY;
10805 	}
10806 	if (sdinfo != NULL) {
10807 		if ((sdinfo->satadrv_type & (SATA_VALID_DEV_TYPE)) != 0) {
10808 			/*
10809 			 * If a target node exists, try to offline
10810 			 * a device and remove target node.
10811 			 */
10812 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
10813 			    cport)->cport_mutex);
10814 			/* We are addressing attached device, not a port */
10815 			sata_device->satadev_addr.qual =
10816 			    sdinfo->satadrv_addr.qual;
10817 			tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
10818 			    &sata_device->satadev_addr);
10819 			if (tdip != NULL && ndi_devi_offline(tdip,
10820 			    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10821 				/*
10822 				 * Problem
10823 				 * The target node remained attached.
10824 				 * This happens when the device file was open
10825 				 * or a node was waiting for resources.
10826 				 * Cannot do anything about it.
10827 				 */
10828 				if (qual == SATA_ADDR_CPORT) {
10829 					SATA_LOG_D((sata_hba_inst, CE_WARN,
10830 					    "sata_hba_ioctl: disconnect: could "
10831 					    "not unconfigure device before "
10832 					    "disconnecting the SATA port %d",
10833 					    cport));
10834 				} else {
10835 					SATA_LOG_D((sata_hba_inst, CE_WARN,
10836 					    "sata_hba_ioctl: disconnect: could "
10837 					    "not unconfigure device before "
10838 					    "disconnecting the SATA port %d:%d",
10839 					    cport, pmport));
10840 				}
10841 				/*
10842 				 * Set DEVICE REMOVED state in the target
10843 				 * node. It will prevent access to the device
10844 				 * even when a new device is attached, until
10845 				 * the old target node is released, removed and
10846 				 * recreated for a new  device.
10847 				 */
10848 				sata_set_device_removed(tdip);
10849 
10850 				/*
10851 				 * Instruct event daemon to try the target
10852 				 * node cleanup later.
10853 				 */
10854 				sata_set_target_node_cleanup(
10855 				    sata_hba_inst, &sata_device->satadev_addr);
10856 			}
10857 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
10858 			    cport)->cport_mutex);
10859 		}
10860 
10861 		/* Remove and release sata_drive info structure. */
10862 		if (pmportinfo != NULL) {
10863 			SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport) =
10864 			    NULL;
10865 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
10866 		} else {
10867 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10868 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10869 		}
10870 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
10871 	}
10872 #if 0
10873 	else if (pmultinfo != NULL) {
10874 		/*
10875 		 * Port Multiplier itself needs special handling.
10876 		 * All device ports need to be processed here!
10877 		 */
10878 	}
10879 #endif
10880 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10881 	/* Just ask HBA driver to deactivate port */
10882 	/*	sata_device->satadev_addr.qual = SATA_ADDR_DCPORT; */
10883 
10884 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
10885 	    (SATA_DIP(sata_hba_inst), sata_device);
10886 
10887 	/*
10888 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
10889 	 * without the hint (to force listener to investivate the state).
10890 	 */
10891 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
10892 	    SE_NO_HINT);
10893 
10894 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10895 	sata_update_port_info(sata_hba_inst, sata_device);
10896 
10897 	if (rval != SATA_SUCCESS) {
10898 		/*
10899 		 * Port deactivation failure - do not
10900 		 * change port state unless the state
10901 		 * returned by HBA indicates a port failure.
10902 		 * NOTE: device structures were released, so devices now are
10903 		 * invisible! Port reset is needed to re-enumerate devices.
10904 		 */
10905 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
10906 			if (pmportinfo != NULL)
10907 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
10908 			else
10909 				cportinfo->cport_state = SATA_PSTATE_FAILED;
10910 			rv = EIO;
10911 		}
10912 	} else {
10913 		/*
10914 		 * Deactivation succeded. From now on the sata framework
10915 		 * will not care what is happening to the device, until
10916 		 * the port is activated again.
10917 		 */
10918 		cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
10919 	}
10920 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10921 	return (rv);
10922 }
10923 
10924 
10925 
10926 /*
10927  * Process sata port connect request
10928  * The sata cfgadm pluging will invoke this operation only if port was found
10929  * in the disconnect state (failed state is also treated as the disconnected
10930  * state).
10931  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
10932  * sata_tran_hotplug_ops->sata_tran_port_activate().
10933  * If successful and a device is found attached to the port,
10934  * the initialization sequence is executed to attach a device structure to
10935  * a port structure. The state of the port and a device would be set
10936  * appropriately.
10937  * The device is not set in configured state (system-wise) by this operation.
10938  *
10939  * Note, that activating the port may generate link events,
10940  * so it is important that following processing and the
10941  * event processing does not interfere with each other!
10942  *
10943  * This operation may remove port failed state and will
10944  * try to make port active and in good standing.
10945  *
10946  * NOTE: Port multiplier code is not completed nor tested.
10947  */
10948 
10949 static int
10950 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
10951     sata_device_t *sata_device)
10952 {
10953 	int cport, pmport, qual;
10954 	int rv = 0;
10955 
10956 	cport = sata_device->satadev_addr.cport;
10957 	pmport = sata_device->satadev_addr.pmport;
10958 	qual = sata_device->satadev_addr.qual;
10959 
10960 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
10961 
10962 	/*
10963 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
10964 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
10965 	 * Perform sanity check now.
10966 	 */
10967 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
10968 		/* No physical port activation supported. */
10969 		return (EINVAL);
10970 	}
10971 
10972 	/* Just ask HBA driver to activate port */
10973 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
10974 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
10975 		/*
10976 		 * Port activation failure.
10977 		 */
10978 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
10979 		    cport)->cport_mutex);
10980 		sata_update_port_info(sata_hba_inst, sata_device);
10981 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
10982 			if (qual == SATA_ADDR_DCPORT) {
10983 				SATA_CPORT_STATE(sata_hba_inst, cport) =
10984 				    SATA_PSTATE_FAILED;
10985 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
10986 				    "sata_hba_ioctl: connect: failed to "
10987 				    "activate SATA port %d", cport);
10988 			} else { /* port multiplier device port */
10989 				SATA_PMPORT_STATE(sata_hba_inst, cport,
10990 				    pmport) = SATA_PSTATE_FAILED;
10991 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
10992 				    "sata_hba_ioctl: connect: failed to "
10993 				    "activate SATA port %d:%d", cport, pmport);
10994 
10995 			}
10996 		}
10997 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
10998 		    cport)->cport_mutex);
10999 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
11000 		    "sata_hba_ioctl: connect: failed to activate SATA "
11001 		    "port %d:%d", cport, pmport);
11002 		return (EIO);
11003 	}
11004 
11005 	/* Virgin port state - will be updated by the port re-probe. */
11006 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11007 	if (qual == SATA_ADDR_CPORT)
11008 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
11009 	else /* port multiplier device port */
11010 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
11011 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11012 
11013 	/*
11014 	 * Probe the port to find its state and attached device.
11015 	 */
11016 	if (sata_reprobe_port(sata_hba_inst, sata_device,
11017 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
11018 		rv = EIO;
11019 
11020 	/*
11021 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11022 	 * without the hint
11023 	 */
11024 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
11025 	    SE_NO_HINT);
11026 
11027 	/*
11028 	 * If there is a device attached to the port, emit
11029 	 * a message.
11030 	 */
11031 	if (qual == SATA_ADDR_CPORT) {
11032 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
11033 		    SATA_DTYPE_NONE)
11034 			sata_log(sata_hba_inst, CE_WARN,
11035 			    "SATA device detected at port %d", cport);
11036 	} else { /* port multiplier device port */
11037 		if (SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) !=
11038 		    SATA_DTYPE_NONE)
11039 			sata_log(sata_hba_inst, CE_WARN,
11040 			    "SATA device detected at port %d:%d",
11041 			    cport, pmport);
11042 	}
11043 
11044 	return (rv);
11045 }
11046 
11047 
11048 /*
11049  * Process sata device unconfigure request.
11050  * The unconfigure operation uses generic nexus operation to
11051  * offline a device. It leaves a target device node attached.
11052  * and obviously sata_drive_info attached as well, because
11053  * from the hardware point of view nothing has changed.
11054  */
11055 static int
11056 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
11057     sata_device_t *sata_device)
11058 {
11059 	int rv = 0;
11060 	dev_info_t *tdip;
11061 
11062 	/* We are addressing attached device, not a port */
11063 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
11064 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
11065 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
11066 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
11067 
11068 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11069 	    &sata_device->satadev_addr)) != NULL) {
11070 
11071 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
11072 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11073 			    "sata_hba_ioctl: unconfigure: "
11074 			    "failed to unconfigure device at SATA port %d:%d",
11075 			    sata_device->satadev_addr.cport,
11076 			    sata_device->satadev_addr.pmport));
11077 			rv = EIO;
11078 		}
11079 		/*
11080 		 * The target node devi_state should be marked with
11081 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
11082 		 * This would be the indication for cfgadm that
11083 		 * the AP node occupant state is 'unconfigured'.
11084 		 */
11085 
11086 	} else {
11087 		/*
11088 		 * This would indicate a failure on the part of cfgadm
11089 		 * to detect correct state of the node prior to this
11090 		 * call - one cannot unconfigure non-existing device.
11091 		 */
11092 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11093 		    "sata_hba_ioctl: unconfigure: "
11094 		    "attempt to unconfigure non-existing device "
11095 		    "at SATA port %d:%d",
11096 		    sata_device->satadev_addr.cport,
11097 		    sata_device->satadev_addr.pmport));
11098 		rv = ENXIO;
11099 	}
11100 	return (rv);
11101 }
11102 
11103 /*
11104  * Process sata device configure request
11105  * If port is in a failed state, operation is aborted - one has to use
11106  * an explicit connect or port activate request to try to get a port into
11107  * non-failed mode. Port reset wil also work in such situation.
11108  * If the port is in disconnected (shutdown) state, the connect operation is
11109  * attempted prior to any other action.
11110  * When port is in the active state, there is a device attached and the target
11111  * node exists, a device was most likely offlined.
11112  * If target node does not exist, a new target node is created. In both cases
11113  * an attempt is made to online (configure) the device.
11114  *
11115  * NOTE: Port multiplier code is not completed nor tested.
11116  */
11117 static int
11118 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
11119     sata_device_t *sata_device)
11120 {
11121 	int cport, pmport, qual;
11122 	int rval;
11123 	boolean_t target = TRUE;
11124 	sata_cport_info_t *cportinfo;
11125 	sata_pmport_info_t *pmportinfo = NULL;
11126 	dev_info_t *tdip;
11127 	sata_drive_info_t *sdinfo;
11128 
11129 	cport = sata_device->satadev_addr.cport;
11130 	pmport = sata_device->satadev_addr.pmport;
11131 	qual = sata_device->satadev_addr.qual;
11132 
11133 	/* Get current port state */
11134 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11135 	    (SATA_DIP(sata_hba_inst), sata_device);
11136 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11137 	sata_update_port_info(sata_hba_inst, sata_device);
11138 
11139 	if (rval != SATA_SUCCESS ||
11140 	    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
11141 		/* Obviously, device on a failed port is not visible */
11142 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11143 		return (ENXIO);
11144 	}
11145 
11146 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11147 	if (qual == SATA_ADDR_PMPORT)
11148 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11149 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11150 
11151 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
11152 		/* need to activate port */
11153 		target = FALSE;
11154 
11155 		/* Sanity check */
11156 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
11157 			return (ENXIO);
11158 
11159 		/* Just let HBA driver to activate port */
11160 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
11161 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
11162 			/*
11163 			 * Port activation failure - do not change port state
11164 			 * unless the state returned by HBA indicates a port
11165 			 * failure.
11166 			 */
11167 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11168 			    cport)->cport_mutex);
11169 			sata_update_port_info(sata_hba_inst, sata_device);
11170 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11171 				if (qual == SATA_ADDR_PMPORT)
11172 					pmportinfo->pmport_state =
11173 					    SATA_PSTATE_FAILED;
11174 				else
11175 					cportinfo->cport_state =
11176 					    SATA_PSTATE_FAILED;
11177 			}
11178 			mutex_exit(&SATA_CPORT_INFO(
11179 			    sata_hba_inst, cport)->cport_mutex);
11180 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11181 			    "sata_hba_ioctl: configure: "
11182 			    "failed to activate SATA port %d:%d",
11183 			    cport, pmport));
11184 			return (EIO);
11185 		}
11186 		/*
11187 		 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11188 		 * without the hint.
11189 		 */
11190 		sata_gen_sysevent(sata_hba_inst,
11191 		    &sata_device->satadev_addr, SE_NO_HINT);
11192 
11193 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11194 		    cport_mutex);
11195 		/* Virgin port state */
11196 		if (qual == SATA_ADDR_PMPORT)
11197 			pmportinfo->pmport_state = 0;
11198 		else
11199 			cportinfo->cport_state = 0;
11200 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11201 	}
11202 	/*
11203 	 * Always reprobe port, to get current device info.
11204 	 */
11205 	if (sata_reprobe_port(sata_hba_inst, sata_device,
11206 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
11207 		return (EIO);
11208 
11209 	if (qual == SATA_ADDR_PMPORT) {
11210 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
11211 		    target == FALSE) {
11212 			/*
11213 			 * That's the transition from "inactive" port
11214 			 * to active one with device attached.
11215 			 */
11216 			sata_log(sata_hba_inst, CE_WARN,
11217 			    "SATA device detected at port %d:%d",
11218 			    cport, pmport);
11219 		}
11220 	} else {
11221 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE &&
11222 		    target == FALSE) {
11223 			/*
11224 			 * When PM is attached to the cport and cport is
11225 			 * activated, every PM device port needs to be reprobed.
11226 			 * We need to emit message for all devices detected
11227 			 * at port multiplier's device ports.
11228 			 * Add such code here.
11229 			 * For now, just inform about device attached to
11230 			 * cport.
11231 			 */
11232 			sata_log(sata_hba_inst, CE_WARN,
11233 			    "SATA device detected at port %d", cport);
11234 		}
11235 	}
11236 
11237 	/*
11238 	 * This is where real configuration operation starts.
11239 	 *
11240 	 * When PM is attached to the cport and cport is activated,
11241 	 * devices attached PM device ports may have to be configured
11242 	 * explicitly. This may change when port multiplier is supported.
11243 	 * For now, configure only disks and other valid target devices.
11244 	 */
11245 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
11246 		return (ENXIO);		/* No device to configure */
11247 	}
11248 
11249 	/*
11250 	 * Here we may have a device in reset condition,
11251 	 * but because we are just configuring it, there is
11252 	 * no need to process the reset other than just
11253 	 * to clear device reset condition in the HBA driver.
11254 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
11255 	 * cause a first command sent the HBA driver with the request
11256 	 * to clear device reset condition.
11257 	 */
11258 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11259 	if (qual == SATA_ADDR_PMPORT)
11260 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
11261 	else
11262 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
11263 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11264 	if (sdinfo == NULL) {
11265 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11266 		return (ENXIO);
11267 	}
11268 	if (sdinfo->satadrv_event_flags &
11269 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
11270 		sdinfo->satadrv_event_flags = 0;
11271 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
11272 	}
11273 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11274 
11275 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11276 	    &sata_device->satadev_addr)) != NULL) {
11277 		/*
11278 		 * Target node exists. Verify, that it belongs
11279 		 * to existing, attached device and not to
11280 		 * a removed device.
11281 		 */
11282 		if (sata_check_device_removed(tdip) == B_TRUE) {
11283 			if (qual == SATA_ADDR_DPMPORT)
11284 				sata_log(sata_hba_inst, CE_WARN,
11285 				    "SATA device at port %d cannot be "
11286 				    "configured. "
11287 				    "Application(s) accessing "
11288 				    "previously attached device "
11289 				    "have to release it before newly "
11290 				    "inserted device can be made accessible.",
11291 				    cport);
11292 			else
11293 				sata_log(sata_hba_inst, CE_WARN,
11294 				    "SATA device at port %d:%d cannot be"
11295 				    "configured. "
11296 				    "Application(s) accessing "
11297 				    "previously attached device "
11298 				    "have to release it before newly "
11299 				    "inserted device can be made accessible.",
11300 				    cport, pmport);
11301 			return (EIO);
11302 		}
11303 		/*
11304 		 * Device was not removed and re-inserted.
11305 		 * Try to online it.
11306 		 */
11307 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
11308 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11309 			    "sata_hba_ioctl: configure: "
11310 			    "onlining device at SATA port "
11311 			    "%d:%d failed", cport, pmport));
11312 			return (EIO);
11313 		}
11314 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11315 		    cport)->cport_mutex);
11316 
11317 		if (qual == SATA_ADDR_DPMPORT)
11318 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
11319 		else
11320 			cportinfo-> cport_tgtnode_clean = B_TRUE;
11321 
11322 		mutex_exit(&SATA_CPORT_INFO(
11323 		    sata_hba_inst, cport)->cport_mutex);
11324 	} else {
11325 		/*
11326 		 * No target node - need to create a new target node.
11327 		 */
11328 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11329 		    cport_mutex);
11330 		if (qual == SATA_ADDR_DPMPORT)
11331 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
11332 		else
11333 			cportinfo-> cport_tgtnode_clean = B_TRUE;
11334 
11335 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11336 		    cport_mutex);
11337 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
11338 		    sata_hba_inst, &sata_device->satadev_addr);
11339 		if (tdip == NULL) {
11340 			/* Configure operation failed */
11341 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11342 			    "sata_hba_ioctl: configure: "
11343 			    "configuring SATA device at port %d:%d "
11344 			    "failed", cport, pmport));
11345 			return (EIO);
11346 		}
11347 	}
11348 	return (0);
11349 }
11350 
11351 
11352 /*
11353  * Process ioctl deactivate port request.
11354  * Arbitrarily unconfigure attached device, if any.
11355  * Even if the unconfigure fails, proceed with the
11356  * port deactivation.
11357  *
11358  * NOTE: Port Multiplier code is not completed and tested.
11359  */
11360 
11361 static int
11362 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
11363     sata_device_t *sata_device)
11364 {
11365 	int cport, pmport, qual;
11366 	int rval, rv = 0;
11367 	sata_cport_info_t *cportinfo;
11368 	sata_pmport_info_t *pmportinfo = NULL;
11369 	dev_info_t *tdip;
11370 	sata_drive_info_t *sdinfo = NULL;
11371 
11372 	/* Sanity check */
11373 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
11374 		return (ENOTSUP);
11375 
11376 	cport = sata_device->satadev_addr.cport;
11377 	pmport = sata_device->satadev_addr.pmport;
11378 	qual = sata_device->satadev_addr.qual;
11379 
11380 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11381 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11382 	if (qual == SATA_ADDR_CPORT) {
11383 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
11384 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
11385 			/*
11386 			 * For now, assume that port multiplier is not
11387 			 * supported, i.e. deal only with valid devices
11388 			 */
11389 			if ((cportinfo->cport_dev_type &
11390 			    SATA_VALID_DEV_TYPE) != 0)
11391 				sdinfo = sata_get_device_info(sata_hba_inst,
11392 				    sata_device);
11393 			/*
11394 			 * If attached device is a port multiplier, we will
11395 			 * have to unconfigure all devices attached to the
11396 			 * port multiplier. Add this code here.
11397 			 */
11398 		}
11399 		cportinfo->cport_state &= ~SATA_STATE_READY;
11400 	} else {
11401 		/* Port multiplier device port */
11402 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11403 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
11404 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
11405 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
11406 			sdinfo = sata_get_device_info(sata_hba_inst,
11407 			    sata_device);
11408 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
11409 	}
11410 
11411 	if (sdinfo != NULL) {
11412 		/*
11413 		 * If a target node exists, try to offline a device and
11414 		 * to remove a target node.
11415 		 */
11416 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11417 		    cport_mutex);
11418 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11419 		    &sata_device->satadev_addr);
11420 		if (tdip != NULL) {
11421 			/* target node exist */
11422 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
11423 			    "sata_hba_ioctl: port deactivate: "
11424 			    "target node exists.", NULL);
11425 
11426 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
11427 			    NDI_SUCCESS) {
11428 				SATA_LOG_D((sata_hba_inst, CE_WARN,
11429 				    "sata_hba_ioctl: port deactivate: "
11430 				    "failed to unconfigure device at port "
11431 				    "%d:%d before deactivating the port",
11432 				    cport, pmport));
11433 				/*
11434 				 * Set DEVICE REMOVED state in the target
11435 				 * node. It will prevent an access to
11436 				 * the device even when a new device is
11437 				 * attached, until the old target node is
11438 				 * released, removed and recreated for a new
11439 				 * device.
11440 				 */
11441 				sata_set_device_removed(tdip);
11442 
11443 				/*
11444 				 * Instruct the event daemon to try the
11445 				 * target node cleanup later.
11446 				 */
11447 				sata_set_target_node_cleanup(sata_hba_inst,
11448 				    &sata_device->satadev_addr);
11449 			}
11450 		}
11451 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11452 		    cport_mutex);
11453 		/*
11454 		 * In any case, remove and release sata_drive_info
11455 		 * structure.
11456 		 */
11457 		if (qual == SATA_ADDR_CPORT) {
11458 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11459 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11460 		} else { /* port multiplier device port */
11461 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11462 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11463 		}
11464 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
11465 	}
11466 	if (qual == SATA_ADDR_CPORT) {
11467 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
11468 		    SATA_STATE_PROBING);
11469 	} else { /* port multiplier device port */
11470 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
11471 		    SATA_STATE_PROBING);
11472 	}
11473 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11474 
11475 	/* Just let HBA driver to deactivate port */
11476 	sata_device->satadev_addr.qual = qual;
11477 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
11478 	    (SATA_DIP(sata_hba_inst), sata_device);
11479 
11480 	/*
11481 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11482 	 * without the hint
11483 	 */
11484 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
11485 	    SE_NO_HINT);
11486 
11487 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11488 	sata_update_port_info(sata_hba_inst, sata_device);
11489 	if (qual == SATA_ADDR_CPORT) {
11490 		if (rval != SATA_SUCCESS) {
11491 			/*
11492 			 * Port deactivation failure - do not change port state
11493 			 * unless the state returned by HBA indicates a port
11494 			 * failure.
11495 			 */
11496 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11497 				SATA_CPORT_STATE(sata_hba_inst, cport) =
11498 				    SATA_PSTATE_FAILED;
11499 			}
11500 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11501 			    "sata_hba_ioctl: port deactivate: "
11502 			    "cannot deactivate SATA port %d", cport));
11503 			rv = EIO;
11504 		} else {
11505 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
11506 		}
11507 	} else {
11508 		if (rval != SATA_SUCCESS) {
11509 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11510 				SATA_PMPORT_STATE(sata_hba_inst, cport,
11511 				    pmport) = SATA_PSTATE_FAILED;
11512 			}
11513 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11514 			    "sata_hba_ioctl: port deactivate: "
11515 			    "cannot deactivate SATA port %d:%d",
11516 			    cport, pmport));
11517 			rv = EIO;
11518 		} else {
11519 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
11520 		}
11521 	}
11522 
11523 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11524 
11525 	return (rv);
11526 }
11527 
11528 /*
11529  * Process ioctl port activate request.
11530  *
11531  * NOTE: Port multiplier code is not completed nor tested.
11532  */
11533 static int
11534 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
11535     sata_device_t *sata_device)
11536 {
11537 	int cport, pmport, qual;
11538 	sata_cport_info_t *cportinfo;
11539 	sata_pmport_info_t *pmportinfo = NULL;
11540 	boolean_t dev_existed = TRUE;
11541 
11542 	/* Sanity check */
11543 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
11544 		return (ENOTSUP);
11545 
11546 	cport = sata_device->satadev_addr.cport;
11547 	pmport = sata_device->satadev_addr.pmport;
11548 	qual = sata_device->satadev_addr.qual;
11549 
11550 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11551 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11552 	if (qual == SATA_ADDR_PMPORT) {
11553 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11554 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
11555 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
11556 			dev_existed = FALSE;
11557 	} else { /* cport */
11558 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
11559 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
11560 			dev_existed = FALSE;
11561 	}
11562 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11563 
11564 	/* Just let HBA driver to activate port, if necessary */
11565 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
11566 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
11567 		/*
11568 		 * Port activation failure - do not change port state unless
11569 		 * the state returned by HBA indicates a port failure.
11570 		 */
11571 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11572 		    cport)->cport_mutex);
11573 		sata_update_port_info(sata_hba_inst, sata_device);
11574 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11575 			if (qual == SATA_ADDR_PMPORT)
11576 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
11577 			else
11578 				cportinfo->cport_state = SATA_PSTATE_FAILED;
11579 
11580 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
11581 			    cport)->cport_mutex);
11582 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11583 			    "sata_hba_ioctl: port activate: cannot activate "
11584 			    "SATA port %d:%d", cport, pmport));
11585 			return (EIO);
11586 		}
11587 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11588 	}
11589 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11590 	if (qual == SATA_ADDR_PMPORT)
11591 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
11592 	else
11593 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
11594 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11595 
11596 	/*
11597 	 * Re-probe port to find its current state and possibly attached device.
11598 	 * Port re-probing may change the cportinfo device type if device is
11599 	 * found attached.
11600 	 * If port probing failed, the device type would be set to
11601 	 * SATA_DTYPE_NONE.
11602 	 */
11603 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
11604 	    SATA_DEV_IDENTIFY_RETRY);
11605 
11606 	/*
11607 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11608 	 * without the hint.
11609 	 */
11610 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
11611 	    SE_NO_HINT);
11612 
11613 	if (dev_existed == FALSE) {
11614 		if (qual == SATA_ADDR_PMPORT &&
11615 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
11616 			/*
11617 			 * That's the transition from the "inactive" port state
11618 			 * or the active port without a device attached to the
11619 			 * active port state with a device attached.
11620 			 */
11621 			sata_log(sata_hba_inst, CE_WARN,
11622 			    "SATA device detected at port %d:%d",
11623 			    cport, pmport);
11624 		} else if (qual == SATA_ADDR_CPORT &&
11625 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
11626 			/*
11627 			 * That's the transition from the "inactive" port state
11628 			 * or the active port without a device attached to the
11629 			 * active port state with a device attached.
11630 			 */
11631 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
11632 				sata_log(sata_hba_inst, CE_WARN,
11633 				    "SATA device detected at port %d", cport);
11634 			} else {
11635 				sata_log(sata_hba_inst, CE_WARN,
11636 				    "SATA port multiplier detected at port %d",
11637 				    cport);
11638 				/*
11639 				 * Because the detected device is a port
11640 				 * multiplier, we need to reprobe every device
11641 				 * port on the port multiplier and show every
11642 				 * device found attached.
11643 				 * Add this code here.
11644 				 */
11645 			}
11646 		}
11647 	}
11648 	return (0);
11649 }
11650 
11651 
11652 
11653 /*
11654  * Process ioctl reset port request.
11655  *
11656  * NOTE: Port multiplier code is not completed nor tested.
11657  */
11658 static int
11659 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
11660     sata_device_t *sata_device)
11661 {
11662 	int cport, pmport, qual;
11663 	int rv = 0;
11664 
11665 	cport = sata_device->satadev_addr.cport;
11666 	pmport = sata_device->satadev_addr.pmport;
11667 	qual = sata_device->satadev_addr.qual;
11668 
11669 	/* Sanity check */
11670 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
11671 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11672 		    "sata_hba_ioctl: sata_hba_tran missing required "
11673 		    "function sata_tran_reset_dport"));
11674 		return (ENOTSUP);
11675 	}
11676 
11677 	/* Ask HBA to reset port */
11678 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
11679 	    sata_device) != SATA_SUCCESS) {
11680 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11681 		    "sata_hba_ioctl: reset port: failed %d:%d",
11682 		    cport, pmport));
11683 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11684 		    cport_mutex);
11685 		sata_update_port_info(sata_hba_inst, sata_device);
11686 		if (qual == SATA_ADDR_CPORT)
11687 			SATA_CPORT_STATE(sata_hba_inst, cport) =
11688 			    SATA_PSTATE_FAILED;
11689 		else
11690 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
11691 			    SATA_PSTATE_FAILED;
11692 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11693 		    cport_mutex);
11694 		rv = EIO;
11695 	}
11696 	/*
11697 	 * Beacuse the port was reset, it should be probed and
11698 	 * attached device reinitialized. At this point the
11699 	 * port state is unknown - it's state is HBA-specific.
11700 	 * Re-probe port to get its state.
11701 	 */
11702 	if (sata_reprobe_port(sata_hba_inst, sata_device,
11703 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
11704 		rv = EIO;
11705 	}
11706 	return (rv);
11707 }
11708 
11709 /*
11710  * Process ioctl reset device request.
11711  *
11712  * NOTE: Port multiplier code is not completed nor tested.
11713  */
11714 static int
11715 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
11716     sata_device_t *sata_device)
11717 {
11718 	sata_drive_info_t *sdinfo;
11719 	int cport, pmport, qual;
11720 	int rv = 0;
11721 
11722 	/* Sanity check */
11723 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
11724 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11725 		    "sata_hba_ioctl: sata_hba_tran missing required "
11726 		    "function sata_tran_reset_dport"));
11727 		return (ENOTSUP);
11728 	}
11729 
11730 	cport = sata_device->satadev_addr.cport;
11731 	pmport = sata_device->satadev_addr.pmport;
11732 	qual = sata_device->satadev_addr.qual;
11733 
11734 	if (qual == SATA_ADDR_CPORT)
11735 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
11736 	else
11737 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
11738 
11739 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11740 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11741 	if (sdinfo == NULL) {
11742 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11743 		return (EINVAL);
11744 	}
11745 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11746 
11747 	/* Ask HBA to reset device */
11748 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
11749 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
11750 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11751 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
11752 		    cport, pmport));
11753 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11754 		    cport_mutex);
11755 		sata_update_port_info(sata_hba_inst, sata_device);
11756 		/*
11757 		 * Device info structure remains attached. Another device reset
11758 		 * or port disconnect/connect and re-probing is
11759 		 * needed to change it's state
11760 		 */
11761 		sdinfo->satadrv_state &= ~SATA_STATE_READY;
11762 		sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
11763 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11764 		rv = EIO;
11765 	}
11766 	/*
11767 	 * If attached device was a port multiplier, some extra processing
11768 	 * may be needed, to bring it back (if port re-probing did not handle
11769 	 * it). Add such code here.
11770 	 */
11771 	return (rv);
11772 }
11773 
11774 
11775 /*
11776  * Process ioctl reset all request.
11777  *
11778  * NOTE: Port multiplier code is not completed nor tested.
11779  */
11780 static int
11781 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
11782 {
11783 	sata_device_t sata_device;
11784 	int rv = 0;
11785 	int tcport;
11786 	int tpmport = 0;
11787 
11788 	sata_device.satadev_rev = SATA_DEVICE_REV;
11789 
11790 	/*
11791 	 * There is no protection here for configured devices.
11792 	 */
11793 	/* Sanity check */
11794 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
11795 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11796 		    "sata_hba_ioctl: sata_hba_tran missing required "
11797 		    "function sata_tran_reset_dport"));
11798 		return (ENOTSUP);
11799 	}
11800 
11801 	/*
11802 	 * Need to lock all ports, not just one.
11803 	 * If any port is locked by event processing, fail the whole operation.
11804 	 * One port is already locked, but for simplicity lock it again.
11805 	 */
11806 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
11807 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
11808 		    cport_mutex);
11809 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
11810 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
11811 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
11812 			    cport_mutex);
11813 			rv = EBUSY;
11814 			break;
11815 		} else {
11816 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
11817 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
11818 			/*
11819 			 * If there is a port multiplier attached, we may need
11820 			 * to lock its port as well. If so, add such code here.
11821 			 */
11822 		}
11823 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
11824 		    cport_mutex);
11825 	}
11826 
11827 	if (rv == 0) {
11828 		/*
11829 		 * All cports were successfully locked.
11830 		 * Reset main SATA controller only for now - no PMult.
11831 		 */
11832 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
11833 
11834 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
11835 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
11836 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11837 			    "sata_hba_ioctl: reset controller failed"));
11838 			return (EIO);
11839 		}
11840 		/*
11841 		 * Because ports were reset, port states are unknown.
11842 		 * They should be re-probed to get their state and
11843 		 * attached devices should be reinitialized.
11844 		 * Add code here to re-probe port multiplier device ports.
11845 		 */
11846 		for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst);
11847 		    tcport++) {
11848 			sata_device.satadev_addr.cport = tcport;
11849 			sata_device.satadev_addr.pmport = tpmport;
11850 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
11851 
11852 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
11853 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
11854 				rv = EIO;
11855 		}
11856 	}
11857 	/*
11858 	 * Unlock all ports
11859 	 */
11860 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
11861 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
11862 		    cport_mutex);
11863 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
11864 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
11865 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
11866 		    cport_mutex);
11867 	}
11868 
11869 	/*
11870 	 * This operation returns EFAULT if either reset
11871 	 * controller failed or a re-probing of any ports failed.
11872 	 */
11873 	return (rv);
11874 }
11875 
11876 
11877 /*
11878  * Process ioctl port self test request.
11879  *
11880  * NOTE: Port multiplier code is not completed nor tested.
11881  */
11882 static int
11883 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
11884     sata_device_t *sata_device)
11885 {
11886 	int cport, pmport, qual;
11887 	int rv = 0;
11888 
11889 	/* Sanity check */
11890 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
11891 		return (ENOTSUP);
11892 
11893 	cport = sata_device->satadev_addr.cport;
11894 	pmport = sata_device->satadev_addr.pmport;
11895 	qual = sata_device->satadev_addr.qual;
11896 
11897 	/*
11898 	 * There is no protection here for a configured
11899 	 * device attached to this port.
11900 	 */
11901 
11902 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
11903 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
11904 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11905 		    "sata_hba_ioctl: port selftest: "
11906 		    "failed port %d:%d", cport, pmport));
11907 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11908 		    cport_mutex);
11909 		sata_update_port_info(sata_hba_inst, sata_device);
11910 		if (qual == SATA_ADDR_CPORT)
11911 			SATA_CPORT_STATE(sata_hba_inst, cport) =
11912 			    SATA_PSTATE_FAILED;
11913 		else /* port ultiplier device port */
11914 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
11915 			    SATA_PSTATE_FAILED;
11916 
11917 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11918 		    cport_mutex);
11919 		return (EIO);
11920 	}
11921 	/*
11922 	 * Beacuse the port was reset in the course of testing, it should be
11923 	 * re-probed and attached device state should be restored. At this
11924 	 * point the port state is unknown - it's state is HBA-specific.
11925 	 * Force port re-probing to get it into a known state.
11926 	 */
11927 	if (sata_reprobe_port(sata_hba_inst, sata_device,
11928 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
11929 		rv = EIO;
11930 	return (rv);
11931 }
11932 
11933 
11934 /*
11935  * sata_cfgadm_state:
11936  * Use the sata port state and state of the target node to figure out
11937  * the cfgadm_state.
11938  *
11939  * The port argument is a value with encoded cport,
11940  * pmport and address qualifier, in the same manner as a scsi target number.
11941  * SCSI_TO_SATA_CPORT macro extracts cport number,
11942  * SCSI_TO_SATA_PMPORT extracts pmport number and
11943  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
11944  *
11945  * For now, support is for cports only - no port multiplier device ports.
11946  */
11947 
11948 static void
11949 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
11950     devctl_ap_state_t *ap_state)
11951 {
11952 	uint16_t	cport;
11953 	int		port_state;
11954 
11955 	/* Cport only */
11956 	cport = SCSI_TO_SATA_CPORT(port);
11957 
11958 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
11959 	if (port_state & SATA_PSTATE_SHUTDOWN ||
11960 	    port_state & SATA_PSTATE_FAILED) {
11961 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
11962 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
11963 		if (port_state & SATA_PSTATE_FAILED)
11964 			ap_state->ap_condition = AP_COND_FAILED;
11965 		else
11966 			ap_state->ap_condition = AP_COND_UNKNOWN;
11967 
11968 		return;
11969 	}
11970 
11971 	/* Need to check pmult device port here as well, when supported */
11972 
11973 	/* Port is enabled and ready */
11974 
11975 	switch (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport)) {
11976 	case SATA_DTYPE_NONE:
11977 	{
11978 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
11979 		ap_state->ap_condition = AP_COND_OK;
11980 		/* No device attached */
11981 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
11982 		break;
11983 	}
11984 	case SATA_DTYPE_UNKNOWN:
11985 	case SATA_DTYPE_ATAPINONCD:
11986 	case SATA_DTYPE_PMULT:	/* Until PMult is supported */
11987 	case SATA_DTYPE_ATADISK:
11988 	case SATA_DTYPE_ATAPICD:
11989 	{
11990 		dev_info_t *tdip = NULL;
11991 		dev_info_t *dip = NULL;
11992 		int circ;
11993 
11994 		dip = SATA_DIP(sata_hba_inst);
11995 		tdip = sata_get_target_dip(dip, port);
11996 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
11997 		if (tdip != NULL) {
11998 			ndi_devi_enter(dip, &circ);
11999 			mutex_enter(&(DEVI(tdip)->devi_lock));
12000 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
12001 				/*
12002 				 * There could be the case where previously
12003 				 * configured and opened device was removed
12004 				 * and unknown device was plugged.
12005 				 * In such case we want to show a device, and
12006 				 * its configured or unconfigured state but
12007 				 * indicate unusable condition untill the
12008 				 * old target node is released and removed.
12009 				 */
12010 				ap_state->ap_condition = AP_COND_UNUSABLE;
12011 			} else {
12012 				ap_state->ap_condition = AP_COND_OK;
12013 			}
12014 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
12015 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
12016 				ap_state->ap_ostate =
12017 				    AP_OSTATE_UNCONFIGURED;
12018 			} else {
12019 				ap_state->ap_ostate =
12020 				    AP_OSTATE_CONFIGURED;
12021 			}
12022 			mutex_exit(&(DEVI(tdip)->devi_lock));
12023 			ndi_devi_exit(dip, circ);
12024 		} else {
12025 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
12026 			ap_state->ap_condition = AP_COND_UNKNOWN;
12027 		}
12028 		break;
12029 	}
12030 	default:
12031 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
12032 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
12033 		ap_state->ap_condition = AP_COND_UNKNOWN;
12034 		/*
12035 		 * This is actually internal error condition (non fatal),
12036 		 * because we have already checked all defined device types.
12037 		 */
12038 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12039 		    "sata_cfgadm_state: Internal error: "
12040 		    "unknown device type"));
12041 		break;
12042 	}
12043 }
12044 
12045 
12046 /*
12047  * Process ioctl get device path request.
12048  *
12049  * NOTE: Port multiplier code is not completed nor tested.
12050  */
12051 static int
12052 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
12053     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12054 {
12055 	char path[MAXPATHLEN];
12056 	uint32_t size;
12057 	dev_info_t *tdip;
12058 
12059 	(void) strcpy(path, "/devices");
12060 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
12061 	    &sata_device->satadev_addr)) == NULL) {
12062 		/*
12063 		 * No such device. If this is a request for a size, do not
12064 		 * return EINVAL for non-existing target, because cfgadm
12065 		 * will then indicate a meaningless ioctl failure.
12066 		 * If this is a request for a path, indicate invalid
12067 		 * argument.
12068 		 */
12069 		if (ioc->get_size == 0)
12070 			return (EINVAL);
12071 	} else {
12072 		(void) ddi_pathname(tdip, path + strlen(path));
12073 	}
12074 	size = strlen(path) + 1;
12075 
12076 	if (ioc->get_size != 0) {
12077 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
12078 		    mode) != 0)
12079 			return (EFAULT);
12080 	} else {
12081 		if (ioc->bufsiz != size)
12082 			return (EINVAL);
12083 
12084 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
12085 		    mode) != 0)
12086 			return (EFAULT);
12087 	}
12088 	return (0);
12089 }
12090 
12091 /*
12092  * Process ioctl get attachment point type request.
12093  *
12094  * NOTE: Port multiplier code is not completed nor tested.
12095  */
12096 static	int
12097 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
12098     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12099 {
12100 	uint32_t	type_len;
12101 	const char	*ap_type;
12102 	int		dev_type;
12103 
12104 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
12105 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
12106 		    sata_device->satadev_addr.cport);
12107 	else /* pmport */
12108 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
12109 		    sata_device->satadev_addr.cport,
12110 		    sata_device->satadev_addr.pmport);
12111 
12112 	switch (dev_type) {
12113 	case SATA_DTYPE_NONE:
12114 		ap_type = "port";
12115 		break;
12116 
12117 	case SATA_DTYPE_ATADISK:
12118 		ap_type = "disk";
12119 		break;
12120 
12121 	case SATA_DTYPE_ATAPICD:
12122 		ap_type = "cd/dvd";
12123 		break;
12124 
12125 	case SATA_DTYPE_PMULT:
12126 		ap_type = "pmult";
12127 		break;
12128 
12129 	case SATA_DTYPE_UNKNOWN:
12130 		ap_type = "unknown";
12131 		break;
12132 
12133 	default:
12134 		ap_type = "unsupported";
12135 		break;
12136 
12137 	} /* end of dev_type switch */
12138 
12139 	type_len = strlen(ap_type) + 1;
12140 
12141 	if (ioc->get_size) {
12142 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
12143 		    mode) != 0)
12144 			return (EFAULT);
12145 	} else {
12146 		if (ioc->bufsiz != type_len)
12147 			return (EINVAL);
12148 
12149 		if (ddi_copyout((void *)ap_type, ioc->buf,
12150 		    ioc->bufsiz, mode) != 0)
12151 			return (EFAULT);
12152 	}
12153 	return (0);
12154 
12155 }
12156 
12157 /*
12158  * Process ioctl get device model info request.
12159  * This operation should return to cfgadm the device model
12160  * information string
12161  *
12162  * NOTE: Port multiplier code is not completed nor tested.
12163  */
12164 static	int
12165 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
12166     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12167 {
12168 	sata_drive_info_t *sdinfo;
12169 	uint32_t info_len;
12170 	char ap_info[SATA_ID_MODEL_LEN + 1];
12171 
12172 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
12173 	    sata_device->satadev_addr.cport)->cport_mutex);
12174 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
12175 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
12176 	else /* port multiplier */
12177 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
12178 
12179 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12180 	if (sdinfo == NULL) {
12181 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12182 		    sata_device->satadev_addr.cport)->cport_mutex);
12183 		return (EINVAL);
12184 	}
12185 
12186 #ifdef	_LITTLE_ENDIAN
12187 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
12188 #else	/* _LITTLE_ENDIAN */
12189 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
12190 #endif	/* _LITTLE_ENDIAN */
12191 
12192 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12193 	    sata_device->satadev_addr.cport)->cport_mutex);
12194 
12195 	ap_info[SATA_ID_MODEL_LEN] = '\0';
12196 
12197 	info_len = strlen(ap_info) + 1;
12198 
12199 	if (ioc->get_size) {
12200 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
12201 		    mode) != 0)
12202 			return (EFAULT);
12203 	} else {
12204 		if (ioc->bufsiz < info_len)
12205 			return (EINVAL);
12206 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
12207 		    mode) != 0)
12208 			return (EFAULT);
12209 	}
12210 	return (0);
12211 }
12212 
12213 
12214 /*
12215  * Process ioctl get device firmware revision info request.
12216  * This operation should return to cfgadm the device firmware revision
12217  * information string
12218  *
12219  * NOTE: Port multiplier code is not completed nor tested.
12220  */
12221 static	int
12222 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
12223     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12224 {
12225 	sata_drive_info_t *sdinfo;
12226 	uint32_t info_len;
12227 	char ap_info[SATA_ID_FW_LEN + 1];
12228 
12229 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
12230 	    sata_device->satadev_addr.cport)->cport_mutex);
12231 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
12232 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
12233 	else /* port multiplier */
12234 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
12235 
12236 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12237 	if (sdinfo == NULL) {
12238 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12239 		    sata_device->satadev_addr.cport)->cport_mutex);
12240 		return (EINVAL);
12241 	}
12242 
12243 #ifdef	_LITTLE_ENDIAN
12244 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
12245 #else	/* _LITTLE_ENDIAN */
12246 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
12247 #endif	/* _LITTLE_ENDIAN */
12248 
12249 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12250 	    sata_device->satadev_addr.cport)->cport_mutex);
12251 
12252 	ap_info[SATA_ID_FW_LEN] = '\0';
12253 
12254 	info_len = strlen(ap_info) + 1;
12255 
12256 	if (ioc->get_size) {
12257 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
12258 		    mode) != 0)
12259 			return (EFAULT);
12260 	} else {
12261 		if (ioc->bufsiz < info_len)
12262 			return (EINVAL);
12263 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
12264 		    mode) != 0)
12265 			return (EFAULT);
12266 	}
12267 	return (0);
12268 }
12269 
12270 
12271 /*
12272  * Process ioctl get device serial number info request.
12273  * This operation should return to cfgadm the device serial number string.
12274  *
12275  * NOTE: Port multiplier code is not completed nor tested.
12276  */
12277 static	int
12278 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
12279     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12280 {
12281 	sata_drive_info_t *sdinfo;
12282 	uint32_t info_len;
12283 	char ap_info[SATA_ID_SERIAL_LEN + 1];
12284 
12285 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
12286 	    sata_device->satadev_addr.cport)->cport_mutex);
12287 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
12288 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
12289 	else /* port multiplier */
12290 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
12291 
12292 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12293 	if (sdinfo == NULL) {
12294 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12295 		    sata_device->satadev_addr.cport)->cport_mutex);
12296 		return (EINVAL);
12297 	}
12298 
12299 #ifdef	_LITTLE_ENDIAN
12300 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
12301 #else	/* _LITTLE_ENDIAN */
12302 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
12303 #endif	/* _LITTLE_ENDIAN */
12304 
12305 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12306 	    sata_device->satadev_addr.cport)->cport_mutex);
12307 
12308 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
12309 
12310 	info_len = strlen(ap_info) + 1;
12311 
12312 	if (ioc->get_size) {
12313 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
12314 		    mode) != 0)
12315 			return (EFAULT);
12316 	} else {
12317 		if (ioc->bufsiz < info_len)
12318 			return (EINVAL);
12319 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
12320 		    mode) != 0)
12321 			return (EFAULT);
12322 	}
12323 	return (0);
12324 }
12325 
12326 
12327 /*
12328  * Preset scsi extended sense data (to NO SENSE)
12329  * First 18 bytes of the sense data are preset to current valid sense
12330  * with a key NO SENSE data.
12331  *
12332  * Returns void
12333  */
12334 static void
12335 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
12336 {
12337 	sense->es_valid = 1;		/* Valid sense */
12338 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
12339 	sense->es_key = KEY_NO_SENSE;
12340 	sense->es_info_1 = 0;
12341 	sense->es_info_2 = 0;
12342 	sense->es_info_3 = 0;
12343 	sense->es_info_4 = 0;
12344 	sense->es_add_len = 10;	/* Additional length - replace with a def */
12345 	sense->es_cmd_info[0] = 0;
12346 	sense->es_cmd_info[1] = 0;
12347 	sense->es_cmd_info[2] = 0;
12348 	sense->es_cmd_info[3] = 0;
12349 	sense->es_add_code = 0;
12350 	sense->es_qual_code = 0;
12351 }
12352 
12353 /*
12354  * Register a legacy cmdk-style devid for the target (disk) device.
12355  *
12356  * Note: This function is called only when the HBA devinfo node has the
12357  * property "use-cmdk-devid-format" set. This property indicates that
12358  * devid compatible with old cmdk (target) driver is to be generated
12359  * for any target device attached to this controller. This will take
12360  * precedence over the devid generated by sd (target) driver.
12361  * This function is derived from cmdk_devid_setup() function in cmdk.c.
12362  */
12363 static void
12364 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
12365 {
12366 	char	*hwid;
12367 	int	modlen;
12368 	int	serlen;
12369 	int	rval;
12370 	ddi_devid_t	devid;
12371 
12372 	/*
12373 	 * device ID is a concatanation of model number, "=", serial number.
12374 	 */
12375 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
12376 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
12377 	    sizeof (sdinfo->satadrv_id.ai_model));
12378 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
12379 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
12380 	if (modlen == 0)
12381 		goto err;
12382 	hwid[modlen++] = '=';
12383 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
12384 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12385 	swab(&hwid[modlen], &hwid[modlen],
12386 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12387 	serlen = sata_check_modser(&hwid[modlen],
12388 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12389 	if (serlen == 0)
12390 		goto err;
12391 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
12392 
12393 	/* initialize/register devid */
12394 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
12395 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS)
12396 		rval = ddi_devid_register(dip, devid);
12397 
12398 	if (rval != DDI_SUCCESS)
12399 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
12400 		    " on port %d", sdinfo->satadrv_addr.cport);
12401 err:
12402 	kmem_free(hwid, LEGACY_HWID_LEN);
12403 }
12404 
12405 /*
12406  * valid model/serial string must contain a non-zero non-space characters.
12407  * trim trailing spaces/NULLs.
12408  */
12409 static int
12410 sata_check_modser(char *buf, int buf_len)
12411 {
12412 	boolean_t ret;
12413 	char *s;
12414 	int i;
12415 	int tb;
12416 	char ch;
12417 
12418 	ret = B_FALSE;
12419 	s = buf;
12420 	for (i = 0; i < buf_len; i++) {
12421 		ch = *s++;
12422 		if (ch != ' ' && ch != '\0')
12423 			tb = i + 1;
12424 		if (ch != ' ' && ch != '\0' && ch != '0')
12425 			ret = B_TRUE;
12426 	}
12427 
12428 	if (ret == B_FALSE)
12429 		return (0); /* invalid string */
12430 
12431 	return (tb); /* return length */
12432 }
12433 
12434 /*
12435  * sata_set_drive_features function compares current device features setting
12436  * with the saved device features settings and, if there is a difference,
12437  * it restores device features setting to the previously saved state.
12438  * It also arbitrarily tries to select the highest supported DMA mode.
12439  * Device Identify or Identify Packet Device data has to be current.
12440  * At the moment read ahead and write cache are considered for all devices.
12441  * For atapi devices, Removable Media Status Notification is set in addition
12442  * to common features.
12443  *
12444  * This function cannot be called in the interrupt context (it may sleep).
12445  *
12446  * The input argument sdinfo should point to the drive info structure
12447  * to be updated after features are set. Note, that only
12448  * device (packet) identify data is updated, not the flags indicating the
12449  * supported features.
12450  *
12451  * Returns TRUE if successful or there was nothing to do. Device Identify data
12452  * in the drive info structure pointed to by the sdinfo argumens is updated
12453  * even when no features were set or changed.
12454  *
12455  * Returns FALSE if device features could not be set.
12456  *
12457  * Note: This function may fail the port, making it inaccessible.
12458  * In such case the explicit port disconnect/connect or physical device
12459  * detach/attach is required to re-evaluate port state again.
12460  */
12461 
12462 static int
12463 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
12464     sata_drive_info_t *sdinfo, int restore)
12465 {
12466 	int rval = SATA_SUCCESS;
12467 	sata_drive_info_t new_sdinfo;
12468 	char *finfo = "sata_set_drive_features: cannot";
12469 	char *finfox;
12470 	int cache_op;
12471 
12472 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
12473 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
12474 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
12475 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
12476 		/*
12477 		 * Cannot get device identification - retry later
12478 		 */
12479 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12480 		    "%s fetch device identify data\n", finfo));
12481 		return (SATA_FAILURE);
12482 	}
12483 	finfox = (restore != 0) ? " restore device features" :
12484 	    " initialize device features\n";
12485 
12486 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12487 		/* Arbitrarily set UDMA mode */
12488 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
12489 		    SATA_SUCCESS) {
12490 			SATA_LOG_D((sata_hba_inst, CE_WARN,
12491 			    "%s set UDMA mode\n", finfo));
12492 			return (SATA_FAILURE);
12493 		}
12494 	} else { /* Assume SATA ATAPI CD/DVD */
12495 		/*  Set Removable Media Status Notification, if necessary */
12496 		if ((new_sdinfo.satadrv_id.ai_cmdset83 &
12497 		    SATA_RM_STATUS_NOTIFIC) != 0 && restore != 0) {
12498 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
12499 			    (!(new_sdinfo.satadrv_id.ai_features86 &
12500 			    SATA_RM_STATUS_NOTIFIC))) ||
12501 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
12502 			    (new_sdinfo.satadrv_id.ai_features86 &
12503 			    SATA_RM_STATUS_NOTIFIC))) {
12504 				/* Current setting does not match saved one */
12505 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
12506 				    sdinfo->satadrv_settings &
12507 				    SATA_DEV_RMSN) != SATA_SUCCESS)
12508 					rval = SATA_FAILURE;
12509 			}
12510 		}
12511 		/*
12512 		 * We have to set Multiword DMA or UDMA, if it is supported, as
12513 		 * we want to use DMA transfer mode whenever possible.
12514 		 * Some devices require explicit setting of the DMA mode.
12515 		 */
12516 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
12517 			/* Set highest supported DMA mode */
12518 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
12519 			    SATA_SUCCESS) {
12520 				SATA_LOG_D((sata_hba_inst, CE_WARN,
12521 				    "%s set UDMA mode\n", finfo));
12522 				rval = SATA_FAILURE;
12523 			}
12524 		}
12525 	}
12526 
12527 	if (!(new_sdinfo.satadrv_id.ai_cmdset82 & SATA_LOOK_AHEAD) &&
12528 	    !(new_sdinfo.satadrv_id.ai_cmdset82 & SATA_WRITE_CACHE)) {
12529 		/* None of the features is supported - do nothing */
12530 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
12531 		    "settable features not supported\n", NULL);
12532 		goto update_sdinfo;
12533 	}
12534 
12535 	if (((new_sdinfo.satadrv_id.ai_features85 & SATA_LOOK_AHEAD) &&
12536 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
12537 	    ((new_sdinfo.satadrv_id.ai_features85 & SATA_WRITE_CACHE) &&
12538 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
12539 		/* Nothing to do */
12540 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
12541 		    "no device features to set\n", NULL);
12542 		goto update_sdinfo;
12543 	}
12544 
12545 	if (!((new_sdinfo.satadrv_id.ai_features85 & SATA_LOOK_AHEAD) &&
12546 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD))) {
12547 		if (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) {
12548 			/* Enable read ahead / read cache */
12549 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
12550 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
12551 			    "enabling read cache\n", NULL);
12552 		} else {
12553 			/* Disable read ahead  / read cache */
12554 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
12555 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
12556 			    "disabling read cache\n", NULL);
12557 		}
12558 
12559 		/* Try to set read cache mode */
12560 		if (sata_set_cache_mode(sata_hba_inst, &new_sdinfo,
12561 		    cache_op) != SATA_SUCCESS) {
12562 			/* Pkt execution failed */
12563 			rval = SATA_FAILURE;
12564 		}
12565 	}
12566 
12567 	if (!((new_sdinfo.satadrv_id.ai_features85 & SATA_WRITE_CACHE) &&
12568 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
12569 		if (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) {
12570 			/* Enable write cache */
12571 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
12572 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
12573 			    "enabling write cache\n", NULL);
12574 		} else {
12575 			/* Disable write cache */
12576 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
12577 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
12578 			    "disabling write cache\n", NULL);
12579 		}
12580 		/* Try to set write cache mode */
12581 		if (sata_set_cache_mode(sata_hba_inst, &new_sdinfo,
12582 		    cache_op) != SATA_SUCCESS) {
12583 			/* Pkt execution failed */
12584 			rval = SATA_FAILURE;
12585 		}
12586 	}
12587 
12588 	if (rval == SATA_FAILURE)
12589 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12590 		    "%s %s", finfo, finfox));
12591 update_sdinfo:
12592 	/*
12593 	 * We need to fetch Device Identify data again
12594 	 */
12595 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
12596 		/*
12597 		 * Cannot get device identification - retry later
12598 		 */
12599 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12600 		    "%s re-fetch device identify data\n", finfo));
12601 		rval = SATA_FAILURE;
12602 	}
12603 	/* Copy device sata info. */
12604 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
12605 
12606 	return (rval);
12607 }
12608 
12609 
12610 /*
12611  *
12612  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
12613  * unable to determine.
12614  *
12615  * Cannot be called in an interrupt context.
12616  *
12617  * Called by sata_build_lsense_page_2f()
12618  */
12619 
12620 static int
12621 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
12622     sata_drive_info_t *sdinfo)
12623 {
12624 	sata_pkt_t *spkt;
12625 	sata_cmd_t *scmd;
12626 	sata_pkt_txlate_t *spx;
12627 	int rval;
12628 
12629 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
12630 	spx->txlt_sata_hba_inst = sata_hba_inst;
12631 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
12632 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
12633 	if (spkt == NULL) {
12634 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12635 		return (-1);
12636 	}
12637 	/* address is needed now */
12638 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12639 
12640 
12641 	/* Fill sata_pkt */
12642 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12643 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
12644 	/* Synchronous mode, no callback */
12645 	spkt->satapkt_comp = NULL;
12646 	/* Timeout 30s */
12647 	spkt->satapkt_time = sata_default_pkt_time;
12648 
12649 	scmd = &spkt->satapkt_cmd;
12650 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
12651 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
12652 
12653 	/* Set up which registers need to be returned */
12654 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
12655 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
12656 
12657 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
12658 	scmd->satacmd_addr_type = 0;		/* N/A */
12659 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
12660 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
12661 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
12662 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
12663 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
12664 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
12665 	scmd->satacmd_cmd_reg = SATAC_SMART;
12666 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12667 	    sdinfo->satadrv_addr.cport)));
12668 
12669 
12670 	/* Send pkt to SATA HBA driver */
12671 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
12672 	    SATA_TRAN_ACCEPTED ||
12673 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
12674 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12675 		    sdinfo->satadrv_addr.cport)));
12676 		/*
12677 		 * Whoops, no SMART RETURN STATUS
12678 		 */
12679 		rval = -1;
12680 	} else {
12681 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12682 		    sdinfo->satadrv_addr.cport)));
12683 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
12684 			rval = -1;
12685 			goto fail;
12686 		}
12687 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
12688 			rval = -1;
12689 			goto fail;
12690 		}
12691 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
12692 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
12693 			rval = 0;
12694 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
12695 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
12696 			rval = 1;
12697 		else {
12698 			rval = -1;
12699 			goto fail;
12700 		}
12701 	}
12702 fail:
12703 	/* Free allocated resources */
12704 	sata_pkt_free(spx);
12705 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
12706 
12707 	return (rval);
12708 }
12709 
12710 /*
12711  *
12712  * Returns 0 if succeeded, -1 otherwise
12713  *
12714  * Cannot be called in an interrupt context.
12715  *
12716  */
12717 static int
12718 sata_fetch_smart_data(
12719 	sata_hba_inst_t *sata_hba_inst,
12720 	sata_drive_info_t *sdinfo,
12721 	struct smart_data *smart_data)
12722 {
12723 	sata_pkt_t *spkt;
12724 	sata_cmd_t *scmd;
12725 	sata_pkt_txlate_t *spx;
12726 	int rval;
12727 
12728 #if ! defined(lint)
12729 	ASSERT(sizeof (struct smart_data) == 512);
12730 #endif
12731 
12732 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
12733 	spx->txlt_sata_hba_inst = sata_hba_inst;
12734 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
12735 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
12736 	if (spkt == NULL) {
12737 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12738 		return (-1);
12739 	}
12740 	/* address is needed now */
12741 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12742 
12743 
12744 	/* Fill sata_pkt */
12745 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12746 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
12747 	/* Synchronous mode, no callback */
12748 	spkt->satapkt_comp = NULL;
12749 	/* Timeout 30s */
12750 	spkt->satapkt_time = sata_default_pkt_time;
12751 
12752 	scmd = &spkt->satapkt_cmd;
12753 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
12754 
12755 	/*
12756 	 * Allocate buffer for SMART data
12757 	 */
12758 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
12759 	    sizeof (struct smart_data));
12760 	if (scmd->satacmd_bp == NULL) {
12761 		sata_pkt_free(spx);
12762 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12763 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12764 		    "sata_fetch_smart_data: "
12765 		    "cannot allocate buffer"));
12766 		return (-1);
12767 	}
12768 
12769 
12770 	/* Build SMART_READ_DATA cmd in the sata_pkt */
12771 	scmd->satacmd_addr_type = 0;		/* N/A */
12772 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
12773 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
12774 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
12775 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
12776 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
12777 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
12778 	scmd->satacmd_cmd_reg = SATAC_SMART;
12779 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12780 	    sdinfo->satadrv_addr.cport)));
12781 
12782 	/* Send pkt to SATA HBA driver */
12783 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
12784 	    SATA_TRAN_ACCEPTED ||
12785 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
12786 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12787 		    sdinfo->satadrv_addr.cport)));
12788 		/*
12789 		 * Whoops, no SMART DATA available
12790 		 */
12791 		rval = -1;
12792 		goto fail;
12793 	} else {
12794 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12795 		    sdinfo->satadrv_addr.cport)));
12796 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
12797 		    DDI_DMA_SYNC_FORKERNEL);
12798 		ASSERT(rval == DDI_SUCCESS);
12799 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
12800 		    sizeof (struct smart_data));
12801 	}
12802 
12803 fail:
12804 	/* Free allocated resources */
12805 	sata_free_local_buffer(spx);
12806 	sata_pkt_free(spx);
12807 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
12808 
12809 	return (rval);
12810 }
12811 
12812 /*
12813  * Used by LOG SENSE page 0x10
12814  *
12815  * return 0 for success, -1 otherwise
12816  *
12817  */
12818 static int
12819 sata_ext_smart_selftest_read_log(
12820 	sata_hba_inst_t *sata_hba_inst,
12821 	sata_drive_info_t *sdinfo,
12822 	struct smart_ext_selftest_log *ext_selftest_log,
12823 	uint16_t block_num)
12824 {
12825 	sata_pkt_txlate_t *spx;
12826 	sata_pkt_t *spkt;
12827 	sata_cmd_t *scmd;
12828 	int rval;
12829 
12830 #if ! defined(lint)
12831 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
12832 #endif
12833 
12834 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
12835 	spx->txlt_sata_hba_inst = sata_hba_inst;
12836 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
12837 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
12838 	if (spkt == NULL) {
12839 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12840 		return (-1);
12841 	}
12842 	/* address is needed now */
12843 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12844 
12845 
12846 	/* Fill sata_pkt */
12847 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12848 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
12849 	/* Synchronous mode, no callback */
12850 	spkt->satapkt_comp = NULL;
12851 	/* Timeout 30s */
12852 	spkt->satapkt_time = sata_default_pkt_time;
12853 
12854 	scmd = &spkt->satapkt_cmd;
12855 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
12856 
12857 	/*
12858 	 * Allocate buffer for SMART extended self-test log
12859 	 */
12860 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
12861 	    sizeof (struct smart_ext_selftest_log));
12862 	if (scmd->satacmd_bp == NULL) {
12863 		sata_pkt_free(spx);
12864 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12865 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12866 		    "sata_ext_smart_selftest_log: "
12867 		    "cannot allocate buffer"));
12868 		return (-1);
12869 	}
12870 
12871 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
12872 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
12873 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
12874 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
12875 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
12876 	scmd->satacmd_lba_low_msb = 0;
12877 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
12878 	scmd->satacmd_lba_mid_msb = block_num >> 8;
12879 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
12880 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
12881 
12882 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12883 	    sdinfo->satadrv_addr.cport)));
12884 
12885 	/* Send pkt to SATA HBA driver */
12886 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
12887 	    SATA_TRAN_ACCEPTED ||
12888 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
12889 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12890 		    sdinfo->satadrv_addr.cport)));
12891 
12892 		/*
12893 		 * Whoops, no SMART selftest log info available
12894 		 */
12895 		rval = -1;
12896 		goto fail;
12897 	} else {
12898 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12899 		    sdinfo->satadrv_addr.cport)));
12900 
12901 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
12902 		    DDI_DMA_SYNC_FORKERNEL);
12903 		ASSERT(rval == DDI_SUCCESS);
12904 		bcopy(scmd->satacmd_bp->b_un.b_addr,
12905 		    (uint8_t *)ext_selftest_log,
12906 		    sizeof (struct smart_ext_selftest_log));
12907 		rval = 0;
12908 	}
12909 
12910 fail:
12911 	/* Free allocated resources */
12912 	sata_free_local_buffer(spx);
12913 	sata_pkt_free(spx);
12914 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
12915 
12916 	return (rval);
12917 }
12918 
12919 /*
12920  * Returns 0 for success, -1 otherwise
12921  *
12922  * SMART self-test log data is returned in buffer pointed to by selftest_log
12923  */
12924 static int
12925 sata_smart_selftest_log(
12926 	sata_hba_inst_t *sata_hba_inst,
12927 	sata_drive_info_t *sdinfo,
12928 	struct smart_selftest_log *selftest_log)
12929 {
12930 	sata_pkt_t *spkt;
12931 	sata_cmd_t *scmd;
12932 	sata_pkt_txlate_t *spx;
12933 	int rval;
12934 
12935 #if ! defined(lint)
12936 	ASSERT(sizeof (struct smart_selftest_log) == 512);
12937 #endif
12938 
12939 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
12940 	spx->txlt_sata_hba_inst = sata_hba_inst;
12941 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
12942 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
12943 	if (spkt == NULL) {
12944 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12945 		return (-1);
12946 	}
12947 	/* address is needed now */
12948 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12949 
12950 
12951 	/* Fill sata_pkt */
12952 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12953 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
12954 	/* Synchronous mode, no callback */
12955 	spkt->satapkt_comp = NULL;
12956 	/* Timeout 30s */
12957 	spkt->satapkt_time = sata_default_pkt_time;
12958 
12959 	scmd = &spkt->satapkt_cmd;
12960 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
12961 
12962 	/*
12963 	 * Allocate buffer for SMART SELFTEST LOG
12964 	 */
12965 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
12966 	    sizeof (struct smart_selftest_log));
12967 	if (scmd->satacmd_bp == NULL) {
12968 		sata_pkt_free(spx);
12969 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12970 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12971 		    "sata_smart_selftest_log: "
12972 		    "cannot allocate buffer"));
12973 		return (-1);
12974 	}
12975 
12976 	/* Build SMART_READ_LOG cmd in the sata_pkt */
12977 	scmd->satacmd_addr_type = 0;		/* N/A */
12978 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
12979 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
12980 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
12981 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
12982 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
12983 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
12984 	scmd->satacmd_cmd_reg = SATAC_SMART;
12985 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12986 	    sdinfo->satadrv_addr.cport)));
12987 
12988 	/* Send pkt to SATA HBA driver */
12989 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
12990 	    SATA_TRAN_ACCEPTED ||
12991 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
12992 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12993 		    sdinfo->satadrv_addr.cport)));
12994 		/*
12995 		 * Whoops, no SMART DATA available
12996 		 */
12997 		rval = -1;
12998 		goto fail;
12999 	} else {
13000 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13001 		    sdinfo->satadrv_addr.cport)));
13002 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13003 		    DDI_DMA_SYNC_FORKERNEL);
13004 		ASSERT(rval == DDI_SUCCESS);
13005 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
13006 		    sizeof (struct smart_selftest_log));
13007 		rval = 0;
13008 	}
13009 
13010 fail:
13011 	/* Free allocated resources */
13012 	sata_free_local_buffer(spx);
13013 	sata_pkt_free(spx);
13014 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13015 
13016 	return (rval);
13017 }
13018 
13019 
13020 /*
13021  * Returns 0 for success, -1 otherwise
13022  *
13023  * SMART READ LOG data is returned in buffer pointed to by smart_log
13024  */
13025 static int
13026 sata_smart_read_log(
13027 	sata_hba_inst_t *sata_hba_inst,
13028 	sata_drive_info_t *sdinfo,
13029 	uint8_t *smart_log,		/* where the data should be returned */
13030 	uint8_t which_log,		/* which log should be returned */
13031 	uint8_t log_size)		/* # of 512 bytes in log */
13032 {
13033 	sata_pkt_t *spkt;
13034 	sata_cmd_t *scmd;
13035 	sata_pkt_txlate_t *spx;
13036 	int rval;
13037 
13038 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13039 	spx->txlt_sata_hba_inst = sata_hba_inst;
13040 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13041 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13042 	if (spkt == NULL) {
13043 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13044 		return (-1);
13045 	}
13046 	/* address is needed now */
13047 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13048 
13049 
13050 	/* Fill sata_pkt */
13051 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13052 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13053 	/* Synchronous mode, no callback */
13054 	spkt->satapkt_comp = NULL;
13055 	/* Timeout 30s */
13056 	spkt->satapkt_time = sata_default_pkt_time;
13057 
13058 	scmd = &spkt->satapkt_cmd;
13059 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13060 
13061 	/*
13062 	 * Allocate buffer for SMART READ LOG
13063 	 */
13064 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
13065 	if (scmd->satacmd_bp == NULL) {
13066 		sata_pkt_free(spx);
13067 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13068 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13069 		    "sata_smart_read_log: " "cannot allocate buffer"));
13070 		return (-1);
13071 	}
13072 
13073 	/* Build SMART_READ_LOG cmd in the sata_pkt */
13074 	scmd->satacmd_addr_type = 0;		/* N/A */
13075 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
13076 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
13077 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
13078 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
13079 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
13080 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13081 	scmd->satacmd_cmd_reg = SATAC_SMART;
13082 
13083 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13084 	    sdinfo->satadrv_addr.cport)));
13085 
13086 	/* Send pkt to SATA HBA driver */
13087 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13088 	    SATA_TRAN_ACCEPTED ||
13089 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13090 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13091 		    sdinfo->satadrv_addr.cport)));
13092 
13093 		/*
13094 		 * Whoops, no SMART DATA available
13095 		 */
13096 		rval = -1;
13097 		goto fail;
13098 	} else {
13099 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13100 		    sdinfo->satadrv_addr.cport)));
13101 
13102 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13103 		    DDI_DMA_SYNC_FORKERNEL);
13104 		ASSERT(rval == DDI_SUCCESS);
13105 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
13106 		rval = 0;
13107 	}
13108 
13109 fail:
13110 	/* Free allocated resources */
13111 	sata_free_local_buffer(spx);
13112 	sata_pkt_free(spx);
13113 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13114 
13115 	return (rval);
13116 }
13117 
13118 /*
13119  * Used by LOG SENSE page 0x10
13120  *
13121  * return 0 for success, -1 otherwise
13122  *
13123  */
13124 static int
13125 sata_read_log_ext_directory(
13126 	sata_hba_inst_t *sata_hba_inst,
13127 	sata_drive_info_t *sdinfo,
13128 	struct read_log_ext_directory *logdir)
13129 {
13130 	sata_pkt_txlate_t *spx;
13131 	sata_pkt_t *spkt;
13132 	sata_cmd_t *scmd;
13133 	int rval;
13134 
13135 #if ! defined(lint)
13136 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
13137 #endif
13138 
13139 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13140 	spx->txlt_sata_hba_inst = sata_hba_inst;
13141 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13142 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13143 	if (spkt == NULL) {
13144 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13145 		return (-1);
13146 	}
13147 
13148 	/* Fill sata_pkt */
13149 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13150 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13151 	/* Synchronous mode, no callback */
13152 	spkt->satapkt_comp = NULL;
13153 	/* Timeout 30s */
13154 	spkt->satapkt_time = sata_default_pkt_time;
13155 
13156 	scmd = &spkt->satapkt_cmd;
13157 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13158 
13159 	/*
13160 	 * Allocate buffer for SMART READ LOG EXTENDED command
13161 	 */
13162 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
13163 	    sizeof (struct read_log_ext_directory));
13164 	if (scmd->satacmd_bp == NULL) {
13165 		sata_pkt_free(spx);
13166 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13167 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13168 		    "sata_read_log_ext_directory: "
13169 		    "cannot allocate buffer"));
13170 		return (-1);
13171 	}
13172 
13173 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
13174 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
13175 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
13176 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
13177 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
13178 	scmd->satacmd_lba_low_msb = 0;
13179 	scmd->satacmd_lba_mid_lsb = 0;
13180 	scmd->satacmd_lba_mid_msb = 0;
13181 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13182 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
13183 
13184 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13185 	    sdinfo->satadrv_addr.cport)));
13186 
13187 	/* Send pkt to SATA HBA driver */
13188 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13189 	    SATA_TRAN_ACCEPTED ||
13190 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13191 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13192 		    sdinfo->satadrv_addr.cport)));
13193 		/*
13194 		 * Whoops, no SMART selftest log info available
13195 		 */
13196 		rval = -1;
13197 		goto fail;
13198 	} else {
13199 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13200 		    sdinfo->satadrv_addr.cport)));
13201 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13202 		    DDI_DMA_SYNC_FORKERNEL);
13203 		ASSERT(rval == DDI_SUCCESS);
13204 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
13205 		    sizeof (struct read_log_ext_directory));
13206 		rval = 0;
13207 	}
13208 
13209 fail:
13210 	/* Free allocated resources */
13211 	sata_free_local_buffer(spx);
13212 	sata_pkt_free(spx);
13213 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13214 
13215 	return (rval);
13216 }
13217 
13218 /*
13219  * Set up error retrieval sata command for NCQ command error data
13220  * recovery.
13221  *
13222  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
13223  * returns SATA_FAILURE otherwise.
13224  */
13225 static int
13226 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
13227 {
13228 #ifndef __lock_lint
13229 	_NOTE(ARGUNUSED(sdinfo))
13230 #endif
13231 
13232 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
13233 	sata_cmd_t *scmd;
13234 	struct buf *bp;
13235 
13236 	/* Operation modes are up to the caller */
13237 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13238 
13239 	/* Synchronous mode, no callback - may be changed by the caller */
13240 	spkt->satapkt_comp = NULL;
13241 	spkt->satapkt_time = sata_default_pkt_time;
13242 
13243 	scmd = &spkt->satapkt_cmd;
13244 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
13245 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13246 
13247 	/*
13248 	 * Allocate dma_able buffer error data.
13249 	 * Buffer allocation will take care of buffer alignment and other DMA
13250 	 * attributes.
13251 	 */
13252 	bp = sata_alloc_local_buffer(spx,
13253 	    sizeof (struct sata_ncq_error_recovery_page));
13254 	if (bp == NULL)
13255 		return (SATA_FAILURE);
13256 
13257 	bp_mapin(bp); /* make data buffer accessible */
13258 	scmd->satacmd_bp = bp;
13259 
13260 	/*
13261 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
13262 	 * before accessing it. Handle is in usual place in translate struct.
13263 	 */
13264 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
13265 
13266 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
13267 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
13268 
13269 	return (SATA_SUCCESS);
13270 }
13271 
13272 /*
13273  * sata_xlate_errors() is used to translate (S)ATA error
13274  * information to SCSI information returned in the SCSI
13275  * packet.
13276  */
13277 static void
13278 sata_xlate_errors(sata_pkt_txlate_t *spx)
13279 {
13280 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
13281 	struct scsi_extended_sense *sense;
13282 
13283 	scsipkt->pkt_reason = CMD_INCOMPLETE;
13284 	*scsipkt->pkt_scbp = STATUS_CHECK;
13285 	sense = sata_arq_sense(spx);
13286 
13287 	switch (spx->txlt_sata_pkt->satapkt_reason) {
13288 	case SATA_PKT_PORT_ERROR:
13289 		/*
13290 		 * We have no device data. Assume no data transfered.
13291 		 */
13292 		sense->es_key = KEY_HARDWARE_ERROR;
13293 		break;
13294 
13295 	case SATA_PKT_DEV_ERROR:
13296 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
13297 		    SATA_STATUS_ERR) {
13298 			/*
13299 			 * determine dev error reason from error
13300 			 * reg content
13301 			 */
13302 			sata_decode_device_error(spx, sense);
13303 			break;
13304 		}
13305 		/* No extended sense key - no info available */
13306 		break;
13307 
13308 	case SATA_PKT_TIMEOUT:
13309 		scsipkt->pkt_reason = CMD_TIMEOUT;
13310 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
13311 		/* No extended sense key */
13312 		break;
13313 
13314 	case SATA_PKT_ABORTED:
13315 		scsipkt->pkt_reason = CMD_ABORTED;
13316 		scsipkt->pkt_statistics |= STAT_ABORTED;
13317 		/* No extended sense key */
13318 		break;
13319 
13320 	case SATA_PKT_RESET:
13321 		/*
13322 		 * pkt aborted either by an explicit reset request from
13323 		 * a host, or due to error recovery
13324 		 */
13325 		scsipkt->pkt_reason = CMD_RESET;
13326 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
13327 		break;
13328 
13329 	default:
13330 		scsipkt->pkt_reason = CMD_TRAN_ERR;
13331 		break;
13332 	}
13333 }
13334 
13335 
13336 
13337 
13338 /*
13339  * Log sata message
13340  * dev pathname msg line preceeds the logged message.
13341  */
13342 
13343 static	void
13344 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
13345 {
13346 	char pathname[128];
13347 	dev_info_t *dip;
13348 	va_list ap;
13349 
13350 	mutex_enter(&sata_log_mutex);
13351 
13352 	va_start(ap, fmt);
13353 	(void) vsprintf(sata_log_buf, fmt, ap);
13354 	va_end(ap);
13355 
13356 	if (sata_hba_inst != NULL) {
13357 		dip = SATA_DIP(sata_hba_inst);
13358 		(void) ddi_pathname(dip, pathname);
13359 	} else {
13360 		pathname[0] = 0;
13361 	}
13362 	if (level == CE_CONT) {
13363 		if (sata_debug_flags == 0)
13364 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
13365 		else
13366 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
13367 	} else {
13368 		if (level != CE_NOTE) {
13369 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
13370 		} else if (sata_msg) {
13371 			cmn_err(level, "%s:\n %s", pathname,
13372 			    sata_log_buf);
13373 		}
13374 	}
13375 
13376 	mutex_exit(&sata_log_mutex);
13377 }
13378 
13379 
13380 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
13381 
13382 /*
13383  * Start or terminate the thread, depending on flag arg and current state
13384  */
13385 static void
13386 sata_event_thread_control(int startstop)
13387 {
13388 	static 	int sata_event_thread_terminating = 0;
13389 	static 	int sata_event_thread_starting = 0;
13390 	int i;
13391 
13392 	mutex_enter(&sata_event_mutex);
13393 
13394 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
13395 	    sata_event_thread_terminating == 1)) {
13396 		mutex_exit(&sata_event_mutex);
13397 		return;
13398 	}
13399 	if (startstop == 1 && sata_event_thread_starting == 1) {
13400 		mutex_exit(&sata_event_mutex);
13401 		return;
13402 	}
13403 	if (startstop == 1 && sata_event_thread_terminating == 1) {
13404 		sata_event_thread_starting = 1;
13405 		/* wait til terminate operation completes */
13406 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
13407 		while (sata_event_thread_terminating == 1) {
13408 			if (i-- <= 0) {
13409 				sata_event_thread_starting = 0;
13410 				mutex_exit(&sata_event_mutex);
13411 #ifdef SATA_DEBUG
13412 				cmn_err(CE_WARN, "sata_event_thread_control: "
13413 				    "timeout waiting for thread to terminate");
13414 #endif
13415 				return;
13416 			}
13417 			mutex_exit(&sata_event_mutex);
13418 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
13419 			mutex_enter(&sata_event_mutex);
13420 		}
13421 	}
13422 	if (startstop == 1) {
13423 		if (sata_event_thread == NULL) {
13424 			sata_event_thread = thread_create(NULL, 0,
13425 			    (void (*)())sata_event_daemon,
13426 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
13427 		}
13428 		sata_event_thread_starting = 0;
13429 		mutex_exit(&sata_event_mutex);
13430 		return;
13431 	}
13432 
13433 	/*
13434 	 * If we got here, thread may need to be terminated
13435 	 */
13436 	if (sata_event_thread != NULL) {
13437 		int i;
13438 		/* Signal event thread to go away */
13439 		sata_event_thread_terminating = 1;
13440 		sata_event_thread_terminate = 1;
13441 		cv_signal(&sata_event_cv);
13442 		/*
13443 		 * Wait til daemon terminates.
13444 		 */
13445 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
13446 		while (sata_event_thread_terminate == 1) {
13447 			mutex_exit(&sata_event_mutex);
13448 			if (i-- <= 0) {
13449 				/* Daemon did not go away !!! */
13450 #ifdef SATA_DEBUG
13451 				cmn_err(CE_WARN, "sata_event_thread_control: "
13452 				    "cannot terminate event daemon thread");
13453 #endif
13454 				mutex_enter(&sata_event_mutex);
13455 				break;
13456 			}
13457 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
13458 			mutex_enter(&sata_event_mutex);
13459 		}
13460 		sata_event_thread_terminating = 0;
13461 	}
13462 	ASSERT(sata_event_thread_terminating == 0);
13463 	ASSERT(sata_event_thread_starting == 0);
13464 	mutex_exit(&sata_event_mutex);
13465 }
13466 
13467 
13468 /*
13469  * SATA HBA event notification function.
13470  * Events reported by SATA HBA drivers per HBA instance relate to a change in
13471  * a port and/or device state or a controller itself.
13472  * Events for different addresses/addr types cannot be combined.
13473  * A warning message is generated for each event type.
13474  * Events are not processed by this function, so only the
13475  * event flag(s)is set for an affected entity and the event thread is
13476  * waken up. Event daemon thread processes all events.
13477  *
13478  * NOTE: Since more than one event may be reported at the same time, one
13479  * cannot determine a sequence of events when opposite event are reported, eg.
13480  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
13481  * is taking precedence over reported events, i.e. may cause ignoring some
13482  * events.
13483  */
13484 #define	SATA_EVENT_MAX_MSG_LENGTH	79
13485 
13486 void
13487 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
13488 {
13489 	sata_hba_inst_t *sata_hba_inst = NULL;
13490 	sata_address_t *saddr;
13491 	sata_drive_info_t *sdinfo;
13492 	sata_port_stats_t *pstats;
13493 	int cport, pmport;
13494 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
13495 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
13496 	char *lcp;
13497 	static char *err_msg_evnt_1 =
13498 	    "sata_hba_event_notify: invalid port event 0x%x ";
13499 	static char *err_msg_evnt_2 =
13500 	    "sata_hba_event_notify: invalid device event 0x%x ";
13501 	int linkevent;
13502 
13503 	/*
13504 	 * There is a possibility that an event will be generated on HBA
13505 	 * that has not completed attachment or is detaching.
13506 	 * HBA driver should prevent this, but just in case it does not,
13507 	 * we need to ignore events for such HBA.
13508 	 */
13509 	mutex_enter(&sata_mutex);
13510 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
13511 	    sata_hba_inst = sata_hba_inst->satahba_next) {
13512 		if (SATA_DIP(sata_hba_inst) == dip)
13513 			if (sata_hba_inst->satahba_attached == 1)
13514 				break;
13515 	}
13516 	mutex_exit(&sata_mutex);
13517 	if (sata_hba_inst == NULL)
13518 		/* HBA not attached */
13519 		return;
13520 
13521 	ASSERT(sata_device != NULL);
13522 
13523 	/*
13524 	 * Validate address before - do not proceed with invalid address.
13525 	 */
13526 	saddr = &sata_device->satadev_addr;
13527 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
13528 		return;
13529 	if (saddr->qual == SATA_ADDR_PMPORT ||
13530 	    saddr->qual == SATA_ADDR_DPMPORT)
13531 		/* Port Multiplier not supported yet */
13532 		return;
13533 
13534 	cport = saddr->cport;
13535 	pmport = saddr->pmport;
13536 
13537 	buf1[0] = buf2[0] = '\0';
13538 
13539 	/*
13540 	 * Events refer to devices, ports and controllers - each has
13541 	 * unique address. Events for different addresses cannot be combined.
13542 	 */
13543 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
13544 
13545 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
13546 
13547 		/* qualify this event(s) */
13548 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
13549 			/* Invalid event for the device port */
13550 			(void) sprintf(buf2, err_msg_evnt_1,
13551 			    event & SATA_EVNT_PORT_EVENTS);
13552 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
13553 			goto event_info;
13554 		}
13555 		if (saddr->qual == SATA_ADDR_CPORT) {
13556 			/* Controller's device port event */
13557 
13558 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
13559 			    cport_event_flags |=
13560 			    event & SATA_EVNT_PORT_EVENTS;
13561 			pstats =
13562 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
13563 			    cport_stats;
13564 		} else {
13565 			/* Port multiplier's device port event */
13566 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
13567 			    pmport_event_flags |=
13568 			    event & SATA_EVNT_PORT_EVENTS;
13569 			pstats =
13570 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
13571 			    pmport_stats;
13572 		}
13573 
13574 		/*
13575 		 * Add to statistics and log the message. We have to do it
13576 		 * here rather than in the event daemon, because there may be
13577 		 * multiple events occuring before they are processed.
13578 		 */
13579 		linkevent = event &
13580 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
13581 		if (linkevent) {
13582 			if (linkevent == (SATA_EVNT_LINK_LOST |
13583 			    SATA_EVNT_LINK_ESTABLISHED)) {
13584 				/* This is likely event combination */
13585 				(void) strlcat(buf1, "link lost/established, ",
13586 				    SATA_EVENT_MAX_MSG_LENGTH);
13587 
13588 				if (pstats->link_lost < 0xffffffffffffffffULL)
13589 					pstats->link_lost++;
13590 				if (pstats->link_established <
13591 				    0xffffffffffffffffULL)
13592 					pstats->link_established++;
13593 				linkevent = 0;
13594 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
13595 				(void) strlcat(buf1, "link lost, ",
13596 				    SATA_EVENT_MAX_MSG_LENGTH);
13597 
13598 				if (pstats->link_lost < 0xffffffffffffffffULL)
13599 					pstats->link_lost++;
13600 			} else {
13601 				(void) strlcat(buf1, "link established, ",
13602 				    SATA_EVENT_MAX_MSG_LENGTH);
13603 				if (pstats->link_established <
13604 				    0xffffffffffffffffULL)
13605 					pstats->link_established++;
13606 			}
13607 		}
13608 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
13609 			(void) strlcat(buf1, "device attached, ",
13610 			    SATA_EVENT_MAX_MSG_LENGTH);
13611 			if (pstats->device_attached < 0xffffffffffffffffULL)
13612 				pstats->device_attached++;
13613 		}
13614 		if (event & SATA_EVNT_DEVICE_DETACHED) {
13615 			(void) strlcat(buf1, "device detached, ",
13616 			    SATA_EVENT_MAX_MSG_LENGTH);
13617 			if (pstats->device_detached < 0xffffffffffffffffULL)
13618 				pstats->device_detached++;
13619 		}
13620 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
13621 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
13622 			    "port %d power level changed", cport);
13623 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
13624 				pstats->port_pwr_changed++;
13625 		}
13626 
13627 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
13628 			/* There should be no other events for this address */
13629 			(void) sprintf(buf2, err_msg_evnt_1,
13630 			    event & ~SATA_EVNT_PORT_EVENTS);
13631 		}
13632 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
13633 
13634 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
13635 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
13636 
13637 		/* qualify this event */
13638 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
13639 			/* Invalid event for a device */
13640 			(void) sprintf(buf2, err_msg_evnt_2,
13641 			    event & SATA_EVNT_DEVICE_RESET);
13642 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
13643 			goto event_info;
13644 		}
13645 		/* drive event */
13646 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
13647 		if (sdinfo != NULL) {
13648 			if (event & SATA_EVNT_DEVICE_RESET) {
13649 				(void) strlcat(buf1, "device reset, ",
13650 				    SATA_EVENT_MAX_MSG_LENGTH);
13651 				if (sdinfo->satadrv_stats.drive_reset <
13652 				    0xffffffffffffffffULL)
13653 					sdinfo->satadrv_stats.drive_reset++;
13654 				sdinfo->satadrv_event_flags |=
13655 				    SATA_EVNT_DEVICE_RESET;
13656 			}
13657 		}
13658 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
13659 			/* Invalid event for a device */
13660 			(void) sprintf(buf2, err_msg_evnt_2,
13661 			    event & ~SATA_EVNT_DRIVE_EVENTS);
13662 		}
13663 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
13664 	} else {
13665 		if (saddr->qual != SATA_ADDR_NULL) {
13666 			/* Wrong address qualifier */
13667 			SATA_LOG_D((sata_hba_inst, CE_WARN,
13668 			    "sata_hba_event_notify: invalid address 0x%x",
13669 			    *(uint32_t *)saddr));
13670 			return;
13671 		}
13672 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
13673 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
13674 			/* Invalid event for the controller */
13675 			SATA_LOG_D((sata_hba_inst, CE_WARN,
13676 			    "sata_hba_event_notify: invalid event 0x%x for "
13677 			    "controller",
13678 			    event & SATA_EVNT_CONTROLLER_EVENTS));
13679 			return;
13680 		}
13681 		buf1[0] = '\0';
13682 		/* This may be a frequent and not interesting event */
13683 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
13684 		    "controller power level changed\n", NULL);
13685 
13686 		mutex_enter(&sata_hba_inst->satahba_mutex);
13687 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
13688 		    0xffffffffffffffffULL)
13689 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
13690 
13691 		sata_hba_inst->satahba_event_flags |=
13692 		    SATA_EVNT_PWR_LEVEL_CHANGED;
13693 		mutex_exit(&sata_hba_inst->satahba_mutex);
13694 	}
13695 	/*
13696 	 * If we got here, there is something to do with this HBA
13697 	 * instance.
13698 	 */
13699 	mutex_enter(&sata_hba_inst->satahba_mutex);
13700 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
13701 	mutex_exit(&sata_hba_inst->satahba_mutex);
13702 	mutex_enter(&sata_mutex);
13703 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
13704 	mutex_exit(&sata_mutex);
13705 
13706 	/* Tickle event thread */
13707 	mutex_enter(&sata_event_mutex);
13708 	if (sata_event_thread_active == 0)
13709 		cv_signal(&sata_event_cv);
13710 	mutex_exit(&sata_event_mutex);
13711 
13712 event_info:
13713 	if (buf1[0] != '\0') {
13714 		lcp = strrchr(buf1, ',');
13715 		if (lcp != NULL)
13716 			*lcp = '\0';
13717 	}
13718 	if (saddr->qual == SATA_ADDR_CPORT ||
13719 	    saddr->qual == SATA_ADDR_DCPORT) {
13720 		if (buf1[0] != '\0') {
13721 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
13722 			    cport, buf1);
13723 		}
13724 		if (buf2[0] != '\0') {
13725 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
13726 			    cport, buf2);
13727 		}
13728 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
13729 	    saddr->qual == SATA_ADDR_DPMPORT) {
13730 		if (buf1[0] != '\0') {
13731 			sata_log(sata_hba_inst, CE_NOTE,
13732 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
13733 		}
13734 		if (buf2[0] != '\0') {
13735 			sata_log(sata_hba_inst, CE_NOTE,
13736 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
13737 		}
13738 	}
13739 }
13740 
13741 
13742 /*
13743  * Event processing thread.
13744  * Arg is a pointer to the sata_hba_list pointer.
13745  * It is not really needed, because sata_hba_list is global and static
13746  */
13747 static void
13748 sata_event_daemon(void *arg)
13749 {
13750 #ifndef __lock_lint
13751 	_NOTE(ARGUNUSED(arg))
13752 #endif
13753 	sata_hba_inst_t *sata_hba_inst;
13754 	clock_t lbolt;
13755 
13756 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
13757 	    "SATA event daemon started\n", NULL);
13758 loop:
13759 	/*
13760 	 * Process events here. Walk through all registered HBAs
13761 	 */
13762 	mutex_enter(&sata_mutex);
13763 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
13764 	    sata_hba_inst = sata_hba_inst->satahba_next) {
13765 		ASSERT(sata_hba_inst != NULL);
13766 		mutex_enter(&sata_hba_inst->satahba_mutex);
13767 		if (sata_hba_inst->satahba_attached != 1 ||
13768 		    (sata_hba_inst->satahba_event_flags &
13769 		    SATA_EVNT_SKIP) != 0) {
13770 			mutex_exit(&sata_hba_inst->satahba_mutex);
13771 			continue;
13772 		}
13773 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
13774 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
13775 			mutex_exit(&sata_hba_inst->satahba_mutex);
13776 			mutex_exit(&sata_mutex);
13777 			/* Got the controller with pending event */
13778 			sata_process_controller_events(sata_hba_inst);
13779 			/*
13780 			 * Since global mutex was released, there is a
13781 			 * possibility that HBA list has changed, so start
13782 			 * over from the top. Just processed controller
13783 			 * will be passed-over because of the SKIP flag.
13784 			 */
13785 			goto loop;
13786 		}
13787 		mutex_exit(&sata_hba_inst->satahba_mutex);
13788 	}
13789 	/* Clear SKIP flag in all controllers */
13790 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
13791 	    sata_hba_inst = sata_hba_inst->satahba_next) {
13792 		mutex_enter(&sata_hba_inst->satahba_mutex);
13793 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
13794 		mutex_exit(&sata_hba_inst->satahba_mutex);
13795 	}
13796 	mutex_exit(&sata_mutex);
13797 
13798 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
13799 	    "SATA EVENT DAEMON suspending itself", NULL);
13800 
13801 #ifdef SATA_DEBUG
13802 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
13803 		sata_log(sata_hba_inst, CE_WARN,
13804 		    "SATA EVENTS PROCESSING DISABLED\n");
13805 		thread_exit(); /* Daemon will not run again */
13806 	}
13807 #endif
13808 	mutex_enter(&sata_event_mutex);
13809 	sata_event_thread_active = 0;
13810 	mutex_exit(&sata_event_mutex);
13811 	/*
13812 	 * Go to sleep/suspend itself and wake up either because new event or
13813 	 * wait timeout. Exit if there is a termination request (driver
13814 	 * unload).
13815 	 */
13816 	do {
13817 		lbolt = ddi_get_lbolt();
13818 		lbolt += drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
13819 		mutex_enter(&sata_event_mutex);
13820 		(void) cv_timedwait(&sata_event_cv, &sata_event_mutex, lbolt);
13821 
13822 		if (sata_event_thread_active != 0) {
13823 			mutex_exit(&sata_event_mutex);
13824 			continue;
13825 		}
13826 
13827 		/* Check if it is time to go away */
13828 		if (sata_event_thread_terminate == 1) {
13829 			/*
13830 			 * It is up to the thread setting above flag to make
13831 			 * sure that this thread is not killed prematurely.
13832 			 */
13833 			sata_event_thread_terminate = 0;
13834 			sata_event_thread = NULL;
13835 			mutex_exit(&sata_event_mutex);
13836 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
13837 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
13838 			thread_exit();  { _NOTE(NOT_REACHED) }
13839 		}
13840 		mutex_exit(&sata_event_mutex);
13841 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
13842 
13843 	mutex_enter(&sata_event_mutex);
13844 	sata_event_thread_active = 1;
13845 	mutex_exit(&sata_event_mutex);
13846 
13847 	mutex_enter(&sata_mutex);
13848 	sata_event_pending &= ~SATA_EVNT_MAIN;
13849 	mutex_exit(&sata_mutex);
13850 
13851 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
13852 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
13853 
13854 	goto loop;
13855 }
13856 
13857 /*
13858  * Specific HBA instance event processing.
13859  *
13860  * NOTE: At the moment, device event processing is limited to hard disks
13861  * only.
13862  * cports only are supported - no pmports.
13863  */
13864 static void
13865 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
13866 {
13867 	int ncport;
13868 	uint32_t event_flags;
13869 	sata_address_t *saddr;
13870 
13871 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
13872 	    "Processing controller %d event(s)",
13873 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
13874 
13875 	mutex_enter(&sata_hba_inst->satahba_mutex);
13876 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
13877 	event_flags = sata_hba_inst->satahba_event_flags;
13878 	mutex_exit(&sata_hba_inst->satahba_mutex);
13879 	/*
13880 	 * Process controller power change first
13881 	 * HERE
13882 	 */
13883 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
13884 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
13885 
13886 	/*
13887 	 * Search through ports/devices to identify affected port/device.
13888 	 * We may have to process events for more than one port/device.
13889 	 */
13890 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
13891 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
13892 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
13893 		    cport_event_flags;
13894 		/* Check if port was locked by IOCTL processing */
13895 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
13896 			/*
13897 			 * We ignore port events because port is busy
13898 			 * with AP control processing. Set again
13899 			 * controller and main event flag, so that
13900 			 * events may be processed by the next daemon
13901 			 * run.
13902 			 */
13903 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
13904 			mutex_enter(&sata_hba_inst->satahba_mutex);
13905 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
13906 			mutex_exit(&sata_hba_inst->satahba_mutex);
13907 			mutex_enter(&sata_mutex);
13908 			sata_event_pending |= SATA_EVNT_MAIN;
13909 			mutex_exit(&sata_mutex);
13910 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
13911 			    "Event processing postponed until "
13912 			    "AP control processing completes",
13913 			    NULL);
13914 			/* Check other ports */
13915 			continue;
13916 		} else {
13917 			/*
13918 			 * Set BSY flag so that AP control would not
13919 			 * interfere with events processing for
13920 			 * this port.
13921 			 */
13922 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
13923 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
13924 		}
13925 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
13926 
13927 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
13928 
13929 		if ((event_flags &
13930 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
13931 			/*
13932 			 * Got port event.
13933 			 * We need some hierarchy of event processing as they
13934 			 * are affecting each other:
13935 			 * 1. port failed
13936 			 * 2. device detached/attached
13937 			 * 3. link events - link events may trigger device
13938 			 *    detached or device attached events in some
13939 			 *    circumstances.
13940 			 * 4. port power level changed
13941 			 */
13942 			if (event_flags & SATA_EVNT_PORT_FAILED) {
13943 				sata_process_port_failed_event(sata_hba_inst,
13944 				    saddr);
13945 			}
13946 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
13947 				sata_process_device_detached(sata_hba_inst,
13948 				    saddr);
13949 			}
13950 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
13951 				sata_process_device_attached(sata_hba_inst,
13952 				    saddr);
13953 			}
13954 			if (event_flags &
13955 			    (SATA_EVNT_LINK_ESTABLISHED |
13956 			    SATA_EVNT_LINK_LOST)) {
13957 				sata_process_port_link_events(sata_hba_inst,
13958 				    saddr);
13959 			}
13960 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
13961 				sata_process_port_pwr_change(sata_hba_inst,
13962 				    saddr);
13963 			}
13964 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
13965 				sata_process_target_node_cleanup(
13966 				    sata_hba_inst, saddr);
13967 			}
13968 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
13969 				sata_process_device_autoonline(
13970 				    sata_hba_inst, saddr);
13971 			}
13972 		}
13973 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
13974 		    SATA_DTYPE_NONE) {
13975 			/* May have device event */
13976 			sata_process_device_reset(sata_hba_inst, saddr);
13977 		}
13978 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
13979 		/* Release PORT_BUSY flag */
13980 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
13981 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
13982 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
13983 
13984 	} /* End of loop through the controller SATA ports */
13985 }
13986 
13987 /*
13988  * Process HBA power level change reported by HBA driver.
13989  * Not implemented at this time - event is ignored.
13990  */
13991 static void
13992 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
13993 {
13994 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
13995 	    "Processing controller power level change", NULL);
13996 
13997 	/* Ignoring it for now */
13998 	mutex_enter(&sata_hba_inst->satahba_mutex);
13999 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
14000 	mutex_exit(&sata_hba_inst->satahba_mutex);
14001 }
14002 
14003 /*
14004  * Process port power level change reported by HBA driver.
14005  * Not implemented at this time - event is ignored.
14006  */
14007 static void
14008 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
14009     sata_address_t *saddr)
14010 {
14011 	sata_cport_info_t *cportinfo;
14012 
14013 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14014 	    "Processing port power level change", NULL);
14015 
14016 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14017 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14018 	/* Reset event flag */
14019 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
14020 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14021 }
14022 
14023 /*
14024  * Process port failure reported by HBA driver.
14025  * cports support only - no pmports.
14026  */
14027 static void
14028 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
14029     sata_address_t *saddr)
14030 {
14031 	sata_cport_info_t *cportinfo;
14032 
14033 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14034 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14035 	/* Reset event flag first */
14036 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
14037 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
14038 	if ((cportinfo->cport_state &
14039 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
14040 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14041 		    cport_mutex);
14042 		return;
14043 	}
14044 	/* Fail the port */
14045 	cportinfo->cport_state = SATA_PSTATE_FAILED;
14046 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14047 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
14048 }
14049 
14050 /*
14051  * Device Reset Event processing.
14052  * The seqeunce is managed by 3 stage flags:
14053  * - reset event reported,
14054  * - reset event being processed,
14055  * - request to clear device reset state.
14056  */
14057 static void
14058 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
14059     sata_address_t *saddr)
14060 {
14061 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
14062 	sata_drive_info_t *sdinfo;
14063 	sata_cport_info_t *cportinfo;
14064 	sata_device_t sata_device;
14065 	int rval;
14066 
14067 	/* We only care about host sata cport for now */
14068 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14069 
14070 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14071 
14072 	/* If the port is in SHUTDOWN or FAILED state, ignore reset event. */
14073 	if ((cportinfo->cport_state &
14074 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
14075 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14076 		    cport_mutex);
14077 		return;
14078 	}
14079 
14080 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
14081 	    SATA_VALID_DEV_TYPE) == 0) {
14082 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14083 		    cport_mutex);
14084 		return;
14085 	}
14086 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
14087 	if (sdinfo == NULL) {
14088 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14089 		    cport_mutex);
14090 		return;
14091 	}
14092 
14093 	if ((sdinfo->satadrv_event_flags &
14094 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
14095 		/* Nothing to do */
14096 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14097 		    cport_mutex);
14098 		return;
14099 	}
14100 #ifdef SATA_DEBUG
14101 	if ((sdinfo->satadrv_event_flags &
14102 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
14103 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
14104 		/* Something is weird - new device reset event */
14105 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14106 		    "Overlapping device reset events!", NULL);
14107 	}
14108 #endif
14109 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14110 	    "Processing port %d device reset", saddr->cport);
14111 
14112 	/* Clear event flag */
14113 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
14114 
14115 	/* It seems that we always need to check the port state first */
14116 	sata_device.satadev_rev = SATA_DEVICE_REV;
14117 	sata_device.satadev_addr = *saddr;
14118 	/*
14119 	 * We have to exit mutex, because the HBA probe port function may
14120 	 * block on its own mutex.
14121 	 */
14122 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14123 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14124 	    (SATA_DIP(sata_hba_inst), &sata_device);
14125 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14126 	sata_update_port_info(sata_hba_inst, &sata_device);
14127 	if (rval != SATA_SUCCESS) {
14128 		/* Something went wrong? Fail the port */
14129 		cportinfo->cport_state = SATA_PSTATE_FAILED;
14130 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14131 		    cport_mutex);
14132 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14133 		    "SATA port %d probing failed",
14134 		    saddr->cport));
14135 		return;
14136 	}
14137 	if ((sata_device.satadev_scr.sstatus  &
14138 	    SATA_PORT_DEVLINK_UP_MASK) !=
14139 	    SATA_PORT_DEVLINK_UP ||
14140 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
14141 		/*
14142 		 * No device to process, anymore. Some other event processing
14143 		 * would or have already performed port info cleanup.
14144 		 * To be safe (HBA may need it), request clearing device
14145 		 * reset condition.
14146 		 */
14147 		sdinfo->satadrv_event_flags = 0;
14148 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
14149 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14150 		    cport_mutex);
14151 		return;
14152 	}
14153 
14154 	/* Mark device reset processing as active */
14155 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
14156 
14157 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
14158 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14159 
14160 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
14161 	    SATA_FAILURE) {
14162 		/*
14163 		 * Restoring drive setting failed.
14164 		 * Probe the port first, to check if the port state has changed
14165 		 */
14166 		sata_device.satadev_rev = SATA_DEVICE_REV;
14167 		sata_device.satadev_addr = *saddr;
14168 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
14169 		/* probe port */
14170 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14171 		    (SATA_DIP(sata_hba_inst), &sata_device);
14172 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14173 		    cport_mutex);
14174 		if (rval == SATA_SUCCESS &&
14175 		    (sata_device.satadev_state &
14176 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
14177 		    (sata_device.satadev_scr.sstatus  &
14178 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
14179 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
14180 			/*
14181 			 * We may retry this a bit later - in-process reset
14182 			 * condition should be already set.
14183 			 */
14184 			if ((cportinfo->cport_dev_type &
14185 			    SATA_VALID_DEV_TYPE) != 0 &&
14186 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
14187 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14188 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14189 				    saddr->cport)->cport_mutex);
14190 				mutex_enter(&sata_hba_inst->satahba_mutex);
14191 				sata_hba_inst->satahba_event_flags |=
14192 				    SATA_EVNT_MAIN;
14193 				mutex_exit(&sata_hba_inst->satahba_mutex);
14194 				mutex_enter(&sata_mutex);
14195 				sata_event_pending |= SATA_EVNT_MAIN;
14196 				mutex_exit(&sata_mutex);
14197 				return;
14198 			}
14199 		} else {
14200 			/*
14201 			 * No point of retrying - some other event processing
14202 			 * would or already did port info cleanup.
14203 			 * To be safe (HBA may need it),
14204 			 * request clearing device reset condition.
14205 			 */
14206 			sdinfo->satadrv_event_flags = 0;
14207 			sdinfo->satadrv_event_flags |=
14208 			    SATA_EVNT_CLEAR_DEVICE_RESET;
14209 		}
14210 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14211 		    cport_mutex);
14212 		return;
14213 	}
14214 
14215 	/*
14216 	 * Raise the flag indicating that the next sata command could
14217 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
14218 	 * reset is reported.
14219 	 */
14220 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14221 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0 &&
14222 	    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
14223 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14224 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
14225 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
14226 	}
14227 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14228 }
14229 
14230 
14231 /*
14232  * Port Link Events processing.
14233  * Every link established event may involve device reset (due to
14234  * COMRESET signal, equivalent of the hard reset) so arbitrarily
14235  * set device reset event for an attached device (if any).
14236  * If the port is in SHUTDOWN or FAILED state, ignore link events.
14237  *
14238  * The link established event processing varies, depending on the state
14239  * of the target node, HBA hotplugging capabilities, state of the port.
14240  * If the link is not active, the link established event is ignored.
14241  * If HBA cannot detect device attachment and there is no target node,
14242  * the link established event triggers device attach event processing.
14243  * Else, link established event triggers device reset event processing.
14244  *
14245  * The link lost event processing varies, depending on a HBA hotplugging
14246  * capability and the state of the port (link active or not active).
14247  * If the link is active, the lost link event is ignored.
14248  * If HBA cannot detect device removal, the lost link event triggers
14249  * device detached event processing after link lost timeout.
14250  * Else, the event is ignored.
14251  *
14252  * NOTE: Only cports are processed for now, i.e. no port multiplier ports
14253  */
14254 static void
14255 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
14256     sata_address_t *saddr)
14257 {
14258 	sata_device_t sata_device;
14259 	sata_cport_info_t *cportinfo;
14260 	sata_drive_info_t *sdinfo;
14261 	uint32_t event_flags;
14262 	int rval;
14263 
14264 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14265 	    "Processing port %d link event(s)", saddr->cport);
14266 
14267 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14268 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14269 	event_flags = cportinfo->cport_event_flags;
14270 
14271 	/* Reset event flags first */
14272 	cportinfo->cport_event_flags &=
14273 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
14274 
14275 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
14276 	if ((cportinfo->cport_state &
14277 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
14278 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14279 		    cport_mutex);
14280 		return;
14281 	}
14282 
14283 	/*
14284 	 * For the sanity sake get current port state.
14285 	 * Set device address only. Other sata_device fields should be
14286 	 * set by HBA driver.
14287 	 */
14288 	sata_device.satadev_rev = SATA_DEVICE_REV;
14289 	sata_device.satadev_addr = *saddr;
14290 	/*
14291 	 * We have to exit mutex, because the HBA probe port function may
14292 	 * block on its own mutex.
14293 	 */
14294 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14295 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14296 	    (SATA_DIP(sata_hba_inst), &sata_device);
14297 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14298 	sata_update_port_info(sata_hba_inst, &sata_device);
14299 	if (rval != SATA_SUCCESS) {
14300 		/* Something went wrong? Fail the port */
14301 		cportinfo->cport_state = SATA_PSTATE_FAILED;
14302 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14303 		    cport_mutex);
14304 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14305 		    "SATA port %d probing failed",
14306 		    saddr->cport));
14307 		/*
14308 		 * We may want to release device info structure, but
14309 		 * it is not necessary.
14310 		 */
14311 		return;
14312 	} else {
14313 		/* port probed successfully */
14314 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
14315 	}
14316 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
14317 
14318 		if ((sata_device.satadev_scr.sstatus &
14319 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
14320 			/* Ignore event */
14321 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14322 			    "Ignoring port %d link established event - "
14323 			    "link down",
14324 			    saddr->cport);
14325 			goto linklost;
14326 		}
14327 
14328 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14329 		    "Processing port %d link established event",
14330 		    saddr->cport);
14331 
14332 		/*
14333 		 * For the sanity sake check if a device is attached - check
14334 		 * return state of a port probing.
14335 		 */
14336 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
14337 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
14338 			/*
14339 			 * HBA port probe indicated that there is a device
14340 			 * attached. Check if the framework had device info
14341 			 * structure attached for this device.
14342 			 */
14343 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14344 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
14345 				    NULL);
14346 
14347 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14348 				if ((sdinfo->satadrv_type &
14349 				    SATA_VALID_DEV_TYPE) != 0) {
14350 					/*
14351 					 * Dev info structure is present.
14352 					 * If dev_type is set to known type in
14353 					 * the framework's drive info struct
14354 					 * then the device existed before and
14355 					 * the link was probably lost
14356 					 * momentarily - in such case
14357 					 * we may want to check device
14358 					 * identity.
14359 					 * Identity check is not supported now.
14360 					 *
14361 					 * Link established event
14362 					 * triggers device reset event.
14363 					 */
14364 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
14365 					    satadrv_event_flags |=
14366 					    SATA_EVNT_DEVICE_RESET;
14367 				}
14368 			} else if (cportinfo->cport_dev_type ==
14369 			    SATA_DTYPE_NONE) {
14370 				/*
14371 				 * We got new device attached! If HBA does not
14372 				 * generate device attached events, trigger it
14373 				 * here.
14374 				 */
14375 				if (!(SATA_FEATURES(sata_hba_inst) &
14376 				    SATA_CTLF_HOTPLUG)) {
14377 					cportinfo->cport_event_flags |=
14378 					    SATA_EVNT_DEVICE_ATTACHED;
14379 				}
14380 			}
14381 			/* Reset link lost timeout */
14382 			cportinfo->cport_link_lost_time = 0;
14383 		}
14384 	}
14385 linklost:
14386 	if (event_flags & SATA_EVNT_LINK_LOST) {
14387 		if ((sata_device.satadev_scr.sstatus &
14388 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
14389 			/* Ignore event */
14390 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14391 			    "Ignoring port %d link lost event - link is up",
14392 			    saddr->cport);
14393 			goto done;
14394 		}
14395 #ifdef SATA_DEBUG
14396 		if (cportinfo->cport_link_lost_time == 0) {
14397 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14398 			    "Processing port %d link lost event",
14399 			    saddr->cport);
14400 		}
14401 #endif
14402 		/*
14403 		 * When HBA cannot generate device attached/detached events,
14404 		 * we need to track link lost time and eventually generate
14405 		 * device detach event.
14406 		 */
14407 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
14408 			/* We are tracking link lost time */
14409 			if (cportinfo->cport_link_lost_time == 0) {
14410 				/* save current time (lbolt value) */
14411 				cportinfo->cport_link_lost_time =
14412 				    ddi_get_lbolt();
14413 				/* just keep link lost event */
14414 				cportinfo->cport_event_flags |=
14415 				    SATA_EVNT_LINK_LOST;
14416 			} else {
14417 				clock_t cur_time = ddi_get_lbolt();
14418 				if ((cur_time -
14419 				    cportinfo->cport_link_lost_time) >=
14420 				    drv_usectohz(
14421 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
14422 					/* trigger device detach event */
14423 					cportinfo->cport_event_flags |=
14424 					    SATA_EVNT_DEVICE_DETACHED;
14425 					cportinfo->cport_link_lost_time = 0;
14426 					SATADBG1(SATA_DBG_EVENTS,
14427 					    sata_hba_inst,
14428 					    "Triggering port %d "
14429 					    "device detached event",
14430 					    saddr->cport);
14431 				} else {
14432 					/* keep link lost event */
14433 					cportinfo->cport_event_flags |=
14434 					    SATA_EVNT_LINK_LOST;
14435 				}
14436 			}
14437 		}
14438 		/*
14439 		 * We could change port state to disable/delay access to
14440 		 * the attached device until the link is recovered.
14441 		 */
14442 	}
14443 done:
14444 	event_flags = cportinfo->cport_event_flags;
14445 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14446 	if (event_flags != 0) {
14447 		mutex_enter(&sata_hba_inst->satahba_mutex);
14448 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
14449 		mutex_exit(&sata_hba_inst->satahba_mutex);
14450 		mutex_enter(&sata_mutex);
14451 		sata_event_pending |= SATA_EVNT_MAIN;
14452 		mutex_exit(&sata_mutex);
14453 	}
14454 }
14455 
14456 /*
14457  * Device Detached Event processing.
14458  * Port is probed to find if a device is really gone. If so,
14459  * the device info structure is detached from the SATA port info structure
14460  * and released.
14461  * Port status is updated.
14462  *
14463  * NOTE: Process cports event only, no port multiplier ports.
14464  */
14465 static void
14466 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
14467     sata_address_t *saddr)
14468 {
14469 	sata_cport_info_t *cportinfo;
14470 	sata_drive_info_t *sdevinfo;
14471 	sata_device_t sata_device;
14472 	dev_info_t *tdip;
14473 	int rval;
14474 
14475 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14476 	    "Processing port %d device detached", saddr->cport);
14477 
14478 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14479 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14480 	/* Clear event flag */
14481 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
14482 
14483 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
14484 	if ((cportinfo->cport_state &
14485 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
14486 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14487 		    cport_mutex);
14488 		return;
14489 	}
14490 	/* For sanity, re-probe the port */
14491 	sata_device.satadev_rev = SATA_DEVICE_REV;
14492 	sata_device.satadev_addr = *saddr;
14493 
14494 	/*
14495 	 * We have to exit mutex, because the HBA probe port function may
14496 	 * block on its own mutex.
14497 	 */
14498 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14499 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14500 	    (SATA_DIP(sata_hba_inst), &sata_device);
14501 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14502 	sata_update_port_info(sata_hba_inst, &sata_device);
14503 	if (rval != SATA_SUCCESS) {
14504 		/* Something went wrong? Fail the port */
14505 		cportinfo->cport_state = SATA_PSTATE_FAILED;
14506 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14507 		    cport_mutex);
14508 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14509 		    "SATA port %d probing failed",
14510 		    saddr->cport));
14511 		/*
14512 		 * We may want to release device info structure, but
14513 		 * it is not necessary.
14514 		 */
14515 		return;
14516 	} else {
14517 		/* port probed successfully */
14518 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
14519 	}
14520 	/*
14521 	 * Check if a device is still attached. For sanity, check also
14522 	 * link status - if no link, there is no device.
14523 	 */
14524 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
14525 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
14526 	    SATA_DTYPE_NONE) {
14527 		/*
14528 		 * Device is still attached - ignore detach event.
14529 		 */
14530 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14531 		    cport_mutex);
14532 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14533 		    "Ignoring detach - device still attached to port %d",
14534 		    sata_device.satadev_addr.cport);
14535 		return;
14536 	}
14537 	/*
14538 	 * We need to detach and release device info structure here
14539 	 */
14540 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
14541 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14542 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14543 		(void) kmem_free((void *)sdevinfo,
14544 		    sizeof (sata_drive_info_t));
14545 	}
14546 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14547 	/*
14548 	 * Device cannot be reached anymore, even if the target node may be
14549 	 * still present.
14550 	 */
14551 
14552 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14553 	sata_log(sata_hba_inst, CE_WARN, "SATA device detached at port %d",
14554 	    sata_device.satadev_addr.cport);
14555 
14556 	/*
14557 	 * Try to offline a device and remove target node if it still exists
14558 	 */
14559 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport);
14560 	if (tdip != NULL) {
14561 		/*
14562 		 * Target node exists.  Unconfigure device then remove
14563 		 * the target node (one ndi operation).
14564 		 */
14565 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
14566 			/*
14567 			 * PROBLEM - no device, but target node remained
14568 			 * This happens when the file was open or node was
14569 			 * waiting for resources.
14570 			 */
14571 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14572 			    "sata_process_device_detached: "
14573 			    "Failed to remove target node for "
14574 			    "detached SATA device."));
14575 			/*
14576 			 * Set target node state to DEVI_DEVICE_REMOVED.
14577 			 * But re-check first that the node still exists.
14578 			 */
14579 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
14580 			    saddr->cport);
14581 			if (tdip != NULL) {
14582 				sata_set_device_removed(tdip);
14583 				/*
14584 				 * Instruct event daemon to retry the
14585 				 * cleanup later.
14586 				 */
14587 				sata_set_target_node_cleanup(sata_hba_inst,
14588 				    &sata_device.satadev_addr);
14589 			}
14590 		}
14591 	}
14592 	/*
14593 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14594 	 * with the hint: SE_HINT_REMOVE
14595 	 */
14596 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
14597 }
14598 
14599 
14600 /*
14601  * Device Attached Event processing.
14602  * Port state is checked to verify that a device is really attached. If so,
14603  * the device info structure is created and attached to the SATA port info
14604  * structure.
14605  *
14606  * If attached device cannot be identified or set-up, the retry for the
14607  * attach processing is set-up. Subsequent daemon run would try again to
14608  * identify the device, until the time limit is reached
14609  * (SATA_DEV_IDENTIFY_TIMEOUT).
14610  *
14611  * This function cannot be called in interrupt context (it may sleep).
14612  *
14613  * NOTE: Process cports event only, no port multiplier ports.
14614  */
14615 static void
14616 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
14617     sata_address_t *saddr)
14618 {
14619 	sata_cport_info_t *cportinfo;
14620 	sata_drive_info_t *sdevinfo;
14621 	sata_device_t sata_device;
14622 	dev_info_t *tdip;
14623 	uint32_t event_flags;
14624 	int rval;
14625 
14626 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14627 	    "Processing port %d device attached", saddr->cport);
14628 
14629 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14630 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14631 
14632 	/* Clear attach event flag first */
14633 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
14634 
14635 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
14636 	if ((cportinfo->cport_state &
14637 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
14638 		cportinfo->cport_dev_attach_time = 0;
14639 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14640 		    cport_mutex);
14641 		return;
14642 	}
14643 
14644 	/*
14645 	 * If the sata_drive_info structure is found attached to the port info,
14646 	 * despite the fact the device was removed and now it is re-attached,
14647 	 * the old drive info structure was not removed.
14648 	 * Arbitrarily release device info structure.
14649 	 */
14650 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
14651 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14652 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14653 		(void) kmem_free((void *)sdevinfo,
14654 		    sizeof (sata_drive_info_t));
14655 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14656 		    "Arbitrarily detaching old device info.", NULL);
14657 	}
14658 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14659 
14660 	/* For sanity, re-probe the port */
14661 	sata_device.satadev_rev = SATA_DEVICE_REV;
14662 	sata_device.satadev_addr = *saddr;
14663 
14664 	/*
14665 	 * We have to exit mutex, because the HBA probe port function may
14666 	 * block on its own mutex.
14667 	 */
14668 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14669 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14670 	    (SATA_DIP(sata_hba_inst), &sata_device);
14671 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14672 	sata_update_port_info(sata_hba_inst, &sata_device);
14673 	if (rval != SATA_SUCCESS) {
14674 		/* Something went wrong? Fail the port */
14675 		cportinfo->cport_state = SATA_PSTATE_FAILED;
14676 		cportinfo->cport_dev_attach_time = 0;
14677 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14678 		    cport_mutex);
14679 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14680 		    "SATA port %d probing failed",
14681 		    saddr->cport));
14682 		return;
14683 	} else {
14684 		/* port probed successfully */
14685 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
14686 	}
14687 	/*
14688 	 * Check if a device is still attached. For sanity, check also
14689 	 * link status - if no link, there is no device.
14690 	 */
14691 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
14692 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
14693 	    SATA_DTYPE_NONE) {
14694 		/*
14695 		 * No device - ignore attach event.
14696 		 */
14697 		cportinfo->cport_dev_attach_time = 0;
14698 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14699 		    cport_mutex);
14700 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14701 		    "Ignoring attach - no device connected to port %d",
14702 		    sata_device.satadev_addr.cport);
14703 		return;
14704 	}
14705 
14706 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14707 	/*
14708 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14709 	 * with the hint: SE_HINT_INSERT
14710 	 */
14711 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
14712 
14713 	/*
14714 	 * Port reprobing will take care of the creation of the device
14715 	 * info structure and determination of the device type.
14716 	 */
14717 	sata_device.satadev_addr = *saddr;
14718 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
14719 	    SATA_DEV_IDENTIFY_NORETRY);
14720 
14721 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14722 	    cport_mutex);
14723 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
14724 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
14725 		/* Some device is attached to the port */
14726 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
14727 			/*
14728 			 * A device was not successfully attached.
14729 			 * Track retry time for device identification.
14730 			 */
14731 			if (cportinfo->cport_dev_attach_time != 0) {
14732 				clock_t cur_time = ddi_get_lbolt();
14733 				/*
14734 				 * If the retry time limit was not exceeded,
14735 				 * reinstate attach event.
14736 				 */
14737 				if ((cur_time -
14738 				    cportinfo->cport_dev_attach_time) <
14739 				    drv_usectohz(
14740 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
14741 					/* OK, restore attach event */
14742 					cportinfo->cport_event_flags |=
14743 					    SATA_EVNT_DEVICE_ATTACHED;
14744 				} else {
14745 					/* Timeout - cannot identify device */
14746 					cportinfo->cport_dev_attach_time = 0;
14747 					sata_log(sata_hba_inst,
14748 					    CE_WARN,
14749 					    "Cannot identify SATA device "
14750 					    "at port %d - device will not be "
14751 					    "attached.",
14752 					    saddr->cport);
14753 				}
14754 			} else {
14755 				/*
14756 				 * Start tracking time for device
14757 				 * identification.
14758 				 * Save current time (lbolt value).
14759 				 */
14760 				cportinfo->cport_dev_attach_time =
14761 				    ddi_get_lbolt();
14762 				/* Restore attach event */
14763 				cportinfo->cport_event_flags |=
14764 				    SATA_EVNT_DEVICE_ATTACHED;
14765 			}
14766 		} else {
14767 			/*
14768 			 * If device was successfully attached, the subsequent
14769 			 * action depends on a state of the
14770 			 * sata_auto_online variable. If it is set to zero.
14771 			 * an explicit 'configure' command will be needed to
14772 			 * configure it. If its value is non-zero, we will
14773 			 * attempt to online (configure) the device.
14774 			 * First, log the message indicating that a device
14775 			 * was attached.
14776 			 */
14777 			cportinfo->cport_dev_attach_time = 0;
14778 			sata_log(sata_hba_inst, CE_WARN,
14779 			    "SATA device detected at port %d", saddr->cport);
14780 
14781 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
14782 				sata_drive_info_t new_sdinfo;
14783 
14784 				/* Log device info data */
14785 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
14786 				    cportinfo));
14787 				sata_show_drive_info(sata_hba_inst,
14788 				    &new_sdinfo);
14789 			}
14790 
14791 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14792 			    saddr->cport)->cport_mutex);
14793 
14794 			/*
14795 			 * Make sure that there is no target node for that
14796 			 * device. If so, release it. It should not happen,
14797 			 * unless we had problem removing the node when
14798 			 * device was detached.
14799 			 */
14800 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
14801 			    saddr->cport);
14802 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14803 			    saddr->cport)->cport_mutex);
14804 			if (tdip != NULL) {
14805 
14806 #ifdef SATA_DEBUG
14807 				if ((cportinfo->cport_event_flags &
14808 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
14809 					sata_log(sata_hba_inst, CE_WARN,
14810 					    "sata_process_device_attached: "
14811 					    "old device target node exists!");
14812 #endif
14813 				/*
14814 				 * target node exists - try to unconfigure
14815 				 * device and remove the node.
14816 				 */
14817 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14818 				    saddr->cport)->cport_mutex);
14819 				rval = ndi_devi_offline(tdip,
14820 				    NDI_DEVI_REMOVE);
14821 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14822 				    saddr->cport)->cport_mutex);
14823 
14824 				if (rval == NDI_SUCCESS) {
14825 					cportinfo->cport_event_flags &=
14826 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
14827 					cportinfo->cport_tgtnode_clean = B_TRUE;
14828 				} else {
14829 					/*
14830 					 * PROBLEM - the target node remained
14831 					 * and it belongs to a previously
14832 					 * attached device.
14833 					 * This happens when the file was open
14834 					 * or the node was waiting for
14835 					 * resources at the time the
14836 					 * associated device was removed.
14837 					 * Instruct event daemon to retry the
14838 					 * cleanup later.
14839 					 */
14840 					sata_log(sata_hba_inst,
14841 					    CE_WARN,
14842 					    "Application(s) accessing "
14843 					    "previously attached SATA "
14844 					    "device have to release "
14845 					    "it before newly inserted "
14846 					    "device can be made accessible.",
14847 					    saddr->cport);
14848 					cportinfo->cport_event_flags |=
14849 					    SATA_EVNT_TARGET_NODE_CLEANUP;
14850 					cportinfo->cport_tgtnode_clean =
14851 					    B_FALSE;
14852 				}
14853 			}
14854 			if (sata_auto_online != 0) {
14855 				cportinfo->cport_event_flags |=
14856 				    SATA_EVNT_AUTOONLINE_DEVICE;
14857 			}
14858 
14859 		}
14860 	} else {
14861 		cportinfo->cport_dev_attach_time = 0;
14862 	}
14863 
14864 	event_flags = cportinfo->cport_event_flags;
14865 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14866 	if (event_flags != 0) {
14867 		mutex_enter(&sata_hba_inst->satahba_mutex);
14868 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
14869 		mutex_exit(&sata_hba_inst->satahba_mutex);
14870 		mutex_enter(&sata_mutex);
14871 		sata_event_pending |= SATA_EVNT_MAIN;
14872 		mutex_exit(&sata_mutex);
14873 	}
14874 }
14875 
14876 
14877 /*
14878  * Device Target Node Cleanup Event processing.
14879  * If the target node associated with a sata port device is in
14880  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
14881  * If the target node cannot be removed, the event flag is left intact,
14882  * so that event daemon may re-run this function later.
14883  *
14884  * This function cannot be called in interrupt context (it may sleep).
14885  *
14886  * NOTE: Processes cport events only, not port multiplier ports.
14887  */
14888 static void
14889 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
14890     sata_address_t *saddr)
14891 {
14892 	sata_cport_info_t *cportinfo;
14893 	dev_info_t *tdip;
14894 
14895 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14896 	    "Processing port %d device target node cleanup", saddr->cport);
14897 
14898 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14899 
14900 	/*
14901 	 * Check if there is target node for that device and it is in the
14902 	 * DEVI_DEVICE_REMOVED state. If so, release it.
14903 	 */
14904 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport);
14905 	if (tdip != NULL) {
14906 		/*
14907 		 * target node exists - check if it is target node of
14908 		 * a removed device.
14909 		 */
14910 		if (sata_check_device_removed(tdip) == B_TRUE) {
14911 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14912 			    "sata_process_target_node_cleanup: "
14913 			    "old device target node exists!", NULL);
14914 			/*
14915 			 * Unconfigure and remove the target node
14916 			 */
14917 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
14918 			    NDI_SUCCESS) {
14919 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14920 				    saddr->cport)->cport_mutex);
14921 				cportinfo->cport_event_flags &=
14922 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
14923 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14924 				    saddr->cport)->cport_mutex);
14925 				return;
14926 			}
14927 			/*
14928 			 * Event daemon will retry the cleanup later.
14929 			 */
14930 			mutex_enter(&sata_hba_inst->satahba_mutex);
14931 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
14932 			mutex_exit(&sata_hba_inst->satahba_mutex);
14933 			mutex_enter(&sata_mutex);
14934 			sata_event_pending |= SATA_EVNT_MAIN;
14935 			mutex_exit(&sata_mutex);
14936 		}
14937 	} else {
14938 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14939 		    saddr->cport)->cport_mutex);
14940 		cportinfo->cport_event_flags &=
14941 		    ~SATA_EVNT_TARGET_NODE_CLEANUP;
14942 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14943 		    saddr->cport)->cport_mutex);
14944 	}
14945 }
14946 
14947 /*
14948  * Device AutoOnline Event processing.
14949  * If attached device is to be onlined, an attempt is made to online this
14950  * device, but only if there is no lingering (old) target node present.
14951  * If the device cannot be onlined, the event flag is left intact,
14952  * so that event daemon may re-run this function later.
14953  *
14954  * This function cannot be called in interrupt context (it may sleep).
14955  *
14956  * NOTE: Processes cport events only, not port multiplier ports.
14957  */
14958 static void
14959 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
14960     sata_address_t *saddr)
14961 {
14962 	sata_cport_info_t *cportinfo;
14963 	sata_drive_info_t *sdinfo;
14964 	sata_device_t sata_device;
14965 	dev_info_t *tdip;
14966 
14967 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14968 	    "Processing port %d attached device auto-onlining", saddr->cport);
14969 
14970 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14971 
14972 	/*
14973 	 * Check if device is present and recognized. If not, reset event.
14974 	 */
14975 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14976 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
14977 		/* Nothing to online */
14978 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
14979 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14980 		    saddr->cport)->cport_mutex);
14981 		return;
14982 	}
14983 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14984 
14985 	/*
14986 	 * Check if there is target node for this device and if it is in the
14987 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
14988 	 * the event for later processing.
14989 	 */
14990 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport);
14991 	if (tdip != NULL) {
14992 		/*
14993 		 * target node exists - check if it is target node of
14994 		 * a removed device.
14995 		 */
14996 		if (sata_check_device_removed(tdip) == B_TRUE) {
14997 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14998 			    "sata_process_device_autoonline: "
14999 			    "old device target node exists!", NULL);
15000 			/*
15001 			 * Event daemon will retry device onlining later.
15002 			 */
15003 			mutex_enter(&sata_hba_inst->satahba_mutex);
15004 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
15005 			mutex_exit(&sata_hba_inst->satahba_mutex);
15006 			mutex_enter(&sata_mutex);
15007 			sata_event_pending |= SATA_EVNT_MAIN;
15008 			mutex_exit(&sata_mutex);
15009 			return;
15010 		}
15011 		/*
15012 		 * If the target node is not in the 'removed" state, assume
15013 		 * that it belongs to this device. There is nothing more to do,
15014 		 * but reset the event.
15015 		 */
15016 	} else {
15017 
15018 		/*
15019 		 * Try to online the device
15020 		 * If there is any reset-related event, remove it. We are
15021 		 * configuring the device and no state restoring is needed.
15022 		 */
15023 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15024 		    saddr->cport)->cport_mutex);
15025 		sata_device.satadev_addr = *saddr;
15026 		if (saddr->qual == SATA_ADDR_CPORT)
15027 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
15028 		else
15029 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
15030 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
15031 		if (sdinfo != NULL) {
15032 			if (sdinfo->satadrv_event_flags &
15033 			    (SATA_EVNT_DEVICE_RESET |
15034 			    SATA_EVNT_INPROC_DEVICE_RESET))
15035 				sdinfo->satadrv_event_flags = 0;
15036 			sdinfo->satadrv_event_flags |=
15037 			    SATA_EVNT_CLEAR_DEVICE_RESET;
15038 
15039 			/* Need to create a new target node. */
15040 			cportinfo->cport_tgtnode_clean = B_TRUE;
15041 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15042 			    saddr->cport)->cport_mutex);
15043 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
15044 			    sata_hba_inst, &sata_device.satadev_addr);
15045 			if (tdip == NULL) {
15046 				/*
15047 				 * Configure (onlining) failed.
15048 				 * We will NOT retry
15049 				 */
15050 				SATA_LOG_D((sata_hba_inst, CE_WARN,
15051 				    "sata_process_device_autoonline: "
15052 				    "configuring SATA device at port %d failed",
15053 				    saddr->cport));
15054 			}
15055 		} else {
15056 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15057 			    saddr->cport)->cport_mutex);
15058 		}
15059 
15060 	}
15061 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15062 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
15063 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15064 	    saddr->cport)->cport_mutex);
15065 }
15066 
15067 
15068 static void
15069 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
15070     int hint)
15071 {
15072 	char ap[MAXPATHLEN];
15073 	nvlist_t *ev_attr_list = NULL;
15074 	int err;
15075 
15076 	/* Allocate and build sysevent attribute list */
15077 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
15078 	if (err != 0) {
15079 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15080 		    "sata_gen_sysevent: "
15081 		    "cannot allocate memory for sysevent attributes\n"));
15082 		return;
15083 	}
15084 	/* Add hint attribute */
15085 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
15086 	if (err != 0) {
15087 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15088 		    "sata_gen_sysevent: "
15089 		    "failed to add DR_HINT attr for sysevent"));
15090 		nvlist_free(ev_attr_list);
15091 		return;
15092 	}
15093 	/*
15094 	 * Add AP attribute.
15095 	 * Get controller pathname and convert it into AP pathname by adding
15096 	 * a target number.
15097 	 */
15098 	(void) snprintf(ap, MAXPATHLEN, "/devices");
15099 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
15100 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
15101 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
15102 
15103 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
15104 	if (err != 0) {
15105 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15106 		    "sata_gen_sysevent: "
15107 		    "failed to add DR_AP_ID attr for sysevent"));
15108 		nvlist_free(ev_attr_list);
15109 		return;
15110 	}
15111 
15112 	/* Generate/log sysevent */
15113 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
15114 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
15115 	if (err != DDI_SUCCESS) {
15116 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15117 		    "sata_gen_sysevent: "
15118 		    "cannot log sysevent, err code %x\n", err));
15119 	}
15120 
15121 	nvlist_free(ev_attr_list);
15122 }
15123 
15124 
15125 
15126 
15127 /*
15128  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
15129  */
15130 static void
15131 sata_set_device_removed(dev_info_t *tdip)
15132 {
15133 	int circ;
15134 
15135 	ASSERT(tdip != NULL);
15136 
15137 	ndi_devi_enter(tdip, &circ);
15138 	mutex_enter(&DEVI(tdip)->devi_lock);
15139 	DEVI_SET_DEVICE_REMOVED(tdip);
15140 	mutex_exit(&DEVI(tdip)->devi_lock);
15141 	ndi_devi_exit(tdip, circ);
15142 }
15143 
15144 
15145 /*
15146  * Set internal event instructing event daemon to try
15147  * to perform the target node cleanup.
15148  */
15149 static void
15150 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
15151     sata_address_t *saddr)
15152 {
15153 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15154 	SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
15155 	    SATA_EVNT_TARGET_NODE_CLEANUP;
15156 	SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_tgtnode_clean =
15157 	    B_FALSE;
15158 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15159 	mutex_enter(&sata_hba_inst->satahba_mutex);
15160 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
15161 	mutex_exit(&sata_hba_inst->satahba_mutex);
15162 	mutex_enter(&sata_mutex);
15163 	sata_event_pending |= SATA_EVNT_MAIN;
15164 	mutex_exit(&sata_mutex);
15165 }
15166 
15167 
15168 /*
15169  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
15170  * i.e. check if the target node state indicates that it belongs to a removed
15171  * device.
15172  *
15173  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
15174  * B_FALSE otherwise.
15175  *
15176  * NOTE: No port multiplier support.
15177  */
15178 static boolean_t
15179 sata_check_device_removed(dev_info_t *tdip)
15180 {
15181 	ASSERT(tdip != NULL);
15182 
15183 	if (DEVI_IS_DEVICE_REMOVED(tdip))
15184 		return (B_TRUE);
15185 	else
15186 		return (B_FALSE);
15187 }
15188