xref: /titanic_51/usr/src/uts/common/io/sata/impl/sata.c (revision 16f94f589e38fe7d164f5a85c2e9425b18c2e28d)
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 2006 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  * NOTE: THIS VERSION DOES NOT SUPPORT ATAPI DEVICES,
34  * although there is some code related to these devices.
35  *
36  */
37 #include <sys/conf.h>
38 #include <sys/file.h>
39 #include <sys/ddi.h>
40 #include <sys/sunddi.h>
41 #include <sys/modctl.h>
42 #include <sys/cmn_err.h>
43 #include <sys/errno.h>
44 #include <sys/thread.h>
45 #include <sys/kstat.h>
46 #include <sys/note.h>
47 #include <sys/sysevent.h>
48 #include <sys/sysevent/eventdefs.h>
49 #include <sys/sysevent/dr.h>
50 #include <sys/taskq.h>
51 
52 #include <sys/sata/impl/sata.h>
53 #include <sys/sata/sata_hba.h>
54 #include <sys/sata/sata_defs.h>
55 #include <sys/sata/sata_cfgadm.h>
56 
57 
58 /* Debug flags - defined in sata.h */
59 int	sata_debug_flags = 0;
60 /*
61  * Flags enabling selected SATA HBA framework functionality
62  */
63 #define	SATA_ENABLE_QUEUING		1
64 #define	SATA_ENABLE_NCQ			2
65 #define	SATA_ENABLE_PROCESS_EVENTS	4
66 int sata_func_enable =
67 	SATA_ENABLE_PROCESS_EVENTS | SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ;
68 
69 #ifdef SATA_DEBUG
70 #define	SATA_LOG_D(args)	sata_log args
71 uint64_t mbuf_count = 0;
72 uint64_t mbuffail_count = 0;
73 #else
74 #define	SATA_LOG_D(arg)
75 #endif
76 
77 
78 /*
79  * SATA cb_ops functions
80  */
81 static 	int sata_hba_open(dev_t *, int, int, cred_t *);
82 static 	int sata_hba_close(dev_t, int, int, cred_t *);
83 static 	int sata_hba_ioctl(dev_t, int, intptr_t, int, cred_t *,	int *);
84 
85 /*
86  * SCSA required entry points
87  */
88 static	int sata_scsi_tgt_init(dev_info_t *, dev_info_t *,
89     scsi_hba_tran_t *, struct scsi_device *);
90 static	int sata_scsi_tgt_probe(struct scsi_device *,
91     int (*callback)(void));
92 static void sata_scsi_tgt_free(dev_info_t *, dev_info_t *,
93     scsi_hba_tran_t *, struct scsi_device *);
94 static 	int sata_scsi_start(struct scsi_address *, struct scsi_pkt *);
95 static 	int sata_scsi_abort(struct scsi_address *, struct scsi_pkt *);
96 static 	int sata_scsi_reset(struct scsi_address *, int);
97 static 	int sata_scsi_getcap(struct scsi_address *, char *, int);
98 static 	int sata_scsi_setcap(struct scsi_address *, char *, int, int);
99 static 	struct scsi_pkt *sata_scsi_init_pkt(struct scsi_address *,
100     struct scsi_pkt *, struct buf *, int, int, int, int, int (*)(caddr_t),
101     caddr_t);
102 static 	void sata_scsi_destroy_pkt(struct scsi_address *, struct scsi_pkt *);
103 static 	void sata_scsi_dmafree(struct scsi_address *, struct scsi_pkt *);
104 static 	void sata_scsi_sync_pkt(struct scsi_address *, struct scsi_pkt *);
105 
106 
107 /*
108  * Local functions
109  */
110 static 	void sata_remove_hba_instance(dev_info_t *);
111 static 	int sata_validate_sata_hba_tran(dev_info_t *, sata_hba_tran_t *);
112 static 	void sata_probe_ports(sata_hba_inst_t *);
113 static 	int sata_reprobe_port(sata_hba_inst_t *, sata_device_t *, int);
114 static 	int sata_add_device(dev_info_t *, sata_hba_inst_t *, int cport,
115     int pmport);
116 static 	dev_info_t *sata_create_target_node(dev_info_t *, sata_hba_inst_t *,
117     sata_address_t *);
118 static 	int sata_validate_scsi_address(sata_hba_inst_t *,
119     struct scsi_address *, sata_device_t *);
120 static 	int sata_validate_sata_address(sata_hba_inst_t *, int, int, int);
121 static	sata_pkt_t *sata_pkt_alloc(sata_pkt_txlate_t *, int (*)(caddr_t));
122 static	void sata_pkt_free(sata_pkt_txlate_t *);
123 static	int sata_dma_buf_setup(sata_pkt_txlate_t *, int, int (*)(caddr_t),
124     caddr_t, ddi_dma_attr_t *);
125 static	int sata_probe_device(sata_hba_inst_t *, sata_device_t *);
126 static	sata_drive_info_t *sata_get_device_info(sata_hba_inst_t *,
127     sata_device_t *);
128 static 	int sata_identify_device(sata_hba_inst_t *, sata_drive_info_t *);
129 static	struct buf *sata_alloc_local_buffer(sata_pkt_txlate_t *, int);
130 static 	void sata_free_local_buffer(sata_pkt_txlate_t *);
131 static 	uint64_t sata_check_capacity(sata_drive_info_t *);
132 void 	sata_adjust_dma_attr(sata_drive_info_t *, ddi_dma_attr_t *,
133     ddi_dma_attr_t *);
134 static 	int sata_fetch_device_identify_data(sata_hba_inst_t *,
135     sata_drive_info_t *);
136 static	void sata_update_port_info(sata_hba_inst_t *, sata_device_t *);
137 static	void sata_update_port_scr(sata_port_scr_t *, sata_device_t *);
138 static	int sata_set_udma_mode(sata_hba_inst_t *, sata_drive_info_t *);
139 static	int sata_set_cache_mode(sata_hba_inst_t *, sata_drive_info_t *, int);
140 static	int sata_set_drive_features(sata_hba_inst_t *,
141     sata_drive_info_t *, int flag);
142 static	void sata_init_write_cache_mode(sata_drive_info_t *sdinfo);
143 static	int sata_initialize_device(sata_hba_inst_t *, sata_drive_info_t *);
144 
145 /* Event processing functions */
146 static	void sata_event_daemon(void *);
147 static	void sata_event_thread_control(int);
148 static	void sata_process_controller_events(sata_hba_inst_t *sata_hba_inst);
149 static	void sata_process_device_reset(sata_hba_inst_t *, sata_address_t *);
150 static	void sata_process_port_failed_event(sata_hba_inst_t *,
151     sata_address_t *);
152 static	void sata_process_port_link_events(sata_hba_inst_t *,
153     sata_address_t *);
154 static	void sata_process_device_detached(sata_hba_inst_t *, sata_address_t *);
155 static	void sata_process_device_attached(sata_hba_inst_t *, sata_address_t *);
156 static	void sata_process_port_pwr_change(sata_hba_inst_t *, sata_address_t *);
157 static	void sata_process_cntrl_pwr_level_change(sata_hba_inst_t *);
158 
159 /* Local functions for ioctl */
160 static	int32_t sata_get_port_num(sata_hba_inst_t *,  struct devctl_iocdata *);
161 static	void sata_cfgadm_state(sata_hba_inst_t *, int32_t,
162     devctl_ap_state_t *);
163 static	dev_info_t *sata_get_target_dip(dev_info_t *, int32_t);
164 static	dev_info_t *sata_devt_to_devinfo(dev_t);
165 
166 /* Local translation functions */
167 static	int sata_txlt_inquiry(sata_pkt_txlate_t *);
168 static	int sata_txlt_test_unit_ready(sata_pkt_txlate_t *);
169 static	int sata_txlt_start_stop_unit(sata_pkt_txlate_t *);
170 static	int sata_txlt_read_capacity(sata_pkt_txlate_t *);
171 static	int sata_txlt_request_sense(sata_pkt_txlate_t *);
172 static 	int sata_txlt_read(sata_pkt_txlate_t *);
173 static 	int sata_txlt_write(sata_pkt_txlate_t *);
174 static 	int sata_txlt_atapi(sata_pkt_txlate_t *);
175 static 	int sata_txlt_log_sense(sata_pkt_txlate_t *);
176 static 	int sata_txlt_log_select(sata_pkt_txlate_t *);
177 static 	int sata_txlt_mode_sense(sata_pkt_txlate_t *);
178 static 	int sata_txlt_mode_select(sata_pkt_txlate_t *);
179 static 	int sata_txlt_synchronize_cache(sata_pkt_txlate_t *);
180 static 	int sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *);
181 
182 static 	int sata_hba_start(sata_pkt_txlate_t *, int *);
183 static	int sata_txlt_invalid_command(sata_pkt_txlate_t *);
184 static	int sata_txlt_lba_out_of_range(sata_pkt_txlate_t *);
185 static 	void sata_txlt_rw_completion(sata_pkt_t *);
186 static 	void sata_txlt_atapi_completion(sata_pkt_t *);
187 static 	void sata_txlt_nodata_cmd_completion(sata_pkt_t *);
188 
189 static 	struct scsi_extended_sense *sata_immediate_error_response(
190     sata_pkt_txlate_t *, int);
191 static	struct scsi_extended_sense *sata_arq_sense(sata_pkt_txlate_t *);
192 
193 /* Local functions */
194 static	void sata_identdev_to_inquiry(sata_hba_inst_t *, sata_drive_info_t *,
195     uint8_t *);
196 static	int sata_build_msense_page_1(sata_drive_info_t *, int, uint8_t *);
197 static	int sata_build_msense_page_8(sata_drive_info_t *, int, uint8_t *);
198 static	int sata_build_msense_page_1a(sata_drive_info_t *, int, uint8_t *);
199 static	int sata_build_msense_page_1c(sata_drive_info_t *, int, uint8_t *);
200 static	int sata_mode_select_page_8(sata_pkt_txlate_t *,
201     struct mode_cache_scsi3 *, int, int *, int *, int *);
202 static	int sata_mode_select_page_1c(sata_pkt_txlate_t *,
203     struct mode_info_excpt_page *, int, int *, int *, int *);
204 static	int sata_build_lsense_page_0(sata_drive_info_t *, uint8_t *);
205 static	int sata_build_lsense_page_10(sata_drive_info_t *, uint8_t *,
206     sata_hba_inst_t *);
207 static	int sata_build_lsense_page_2f(sata_drive_info_t *, uint8_t *,
208     sata_hba_inst_t *);
209 static	int sata_build_lsense_page_30(sata_drive_info_t *, uint8_t *,
210     sata_hba_inst_t *);
211 static	void sata_save_drive_settings(sata_drive_info_t *);
212 static	void sata_show_drive_info(sata_hba_inst_t *, sata_drive_info_t *);
213 static	void sata_log(sata_hba_inst_t *, uint_t, char *fmt, ...);
214 static int sata_fetch_smart_return_status(sata_hba_inst_t *,
215     sata_drive_info_t *);
216 static int sata_fetch_smart_data(sata_hba_inst_t *, sata_drive_info_t *,
217     struct smart_data *);
218 static int sata_smart_selftest_log(sata_hba_inst_t *,
219     sata_drive_info_t *,
220     struct smart_selftest_log *);
221 static int sata_ext_smart_selftest_read_log(sata_hba_inst_t *,
222     sata_drive_info_t *, struct smart_ext_selftest_log *, uint16_t);
223 static	int sata_smart_read_log(sata_hba_inst_t *, sata_drive_info_t *,
224     uint8_t *, uint8_t, uint8_t);
225 static	int sata_read_log_ext_directory(sata_hba_inst_t *, sata_drive_info_t *,
226     struct read_log_ext_directory *);
227 static	void sata_gen_sysevent(sata_hba_inst_t *, sata_address_t *, int);
228 static	void sata_xlate_errors(sata_pkt_txlate_t *);
229 
230 /*
231  * SATA Framework will ignore SATA HBA driver cb_ops structure and
232  * register following one with SCSA framework.
233  * Open & close are provided, so scsi framework will not use its own
234  */
235 static struct cb_ops sata_cb_ops = {
236 	sata_hba_open,			/* open */
237 	sata_hba_close,			/* close */
238 	nodev,				/* strategy */
239 	nodev,				/* print */
240 	nodev,				/* dump */
241 	nodev,				/* read */
242 	nodev,				/* write */
243 	sata_hba_ioctl,			/* ioctl */
244 	nodev,				/* devmap */
245 	nodev,				/* mmap */
246 	nodev,				/* segmap */
247 	nochpoll,			/* chpoll */
248 	ddi_prop_op,			/* cb_prop_op */
249 	0,				/* streamtab */
250 	D_NEW | D_MP,			/* cb_flag */
251 	CB_REV,				/* rev */
252 	nodev,				/* aread */
253 	nodev				/* awrite */
254 };
255 
256 
257 extern struct mod_ops mod_miscops;
258 extern uchar_t	scsi_cdb_size[];
259 
260 static struct modlmisc modlmisc = {
261 	&mod_miscops,			/* Type of module */
262 	"Generic SATA Driver v%I%"	/* module name */
263 };
264 
265 
266 static struct modlinkage modlinkage = {
267 	MODREV_1,
268 	(void *)&modlmisc,
269 	NULL
270 };
271 
272 /*
273  * Default sata pkt timeout. Used when a target driver scsi_pkt time is zero,
274  * i.e. when scsi_pkt has not timeout specified.
275  */
276 static int sata_default_pkt_time = 60;	/* 60 seconds */
277 
278 /*
279  * Intermediate buffer device access attributes - they are required,
280  * but not necessarily used.
281  */
282 static ddi_device_acc_attr_t sata_acc_attr = {
283 	DDI_DEVICE_ATTR_V0,
284 	DDI_STRUCTURE_LE_ACC,
285 	DDI_STRICTORDER_ACC
286 };
287 
288 
289 /*
290  * Mutexes protecting structures in multithreaded operations.
291  * Because events are relatively rare, a single global mutex protecting
292  * data structures should be sufficient. To increase performance, add
293  * separate mutex per each sata port and use global mutex only to protect
294  * common data structures.
295  */
296 static	kmutex_t sata_mutex;		/* protects sata_hba_list */
297 static	kmutex_t sata_log_mutex;	/* protects log */
298 
299 static 	char sata_log_buf[256];
300 
301 /* Default write cache setting */
302 int sata_write_cache = 1;
303 
304 /*
305  * Linked list of HBA instances
306  */
307 static 	sata_hba_inst_t *sata_hba_list = NULL;
308 static 	sata_hba_inst_t *sata_hba_list_tail = NULL;
309 /*
310  * Pointer to per-instance SATA HBA soft structure is stored in sata_hba_tran
311  * structure and in sata soft state.
312  */
313 
314 /*
315  * Event daemon related variables
316  */
317 static 	kmutex_t sata_event_mutex;
318 static 	kcondvar_t sata_event_cv;
319 static 	kthread_t *sata_event_thread = NULL;
320 static 	int sata_event_thread_terminate = 0;
321 static 	int sata_event_pending = 0;
322 static 	int sata_event_thread_active = 0;
323 extern 	pri_t minclsyspri;
324 
325 /*
326  * NCQ specific data
327  */
328 static const sata_cmd_t sata_rle_cmd = {
329 	SATA_CMD_REV,
330 	NULL,
331 	{
332 		SATA_DIR_READ
333 	},
334 	ATA_ADDR_LBA48,
335 	0,
336 	0,
337 	0,
338 	0,
339 	0,
340 	1,
341 	READ_LOG_EXT_NCQ_ERROR_RECOVERY,
342 	0,
343 	0,
344 	0,
345 	SATAC_READ_LOG_EXT,
346 	0,
347 	0,
348 	0,
349 };
350 
351 /* Warlock directives */
352 
353 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran))
354 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_device))
355 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_ops))
356 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_extended_sense))
357 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_arq_status))
358 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_attr))
359 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_cookie_t))
360 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", devctl_ap_state))
361 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_list))
362 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_list))
363 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_next))
364 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_prev))
365 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", \
366     sata_hba_inst::satahba_scsi_tran))
367 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_tran))
368 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_dip))
369 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_hba_inst::satahba_attached))
370 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_inst::satahba_dev_port))
371 _NOTE(MUTEX_PROTECTS_DATA(sata_hba_inst::satahba_mutex,
372     sata_hba_inst::satahba_event_flags))
373 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
374     sata_cport_info::cport_devp))
375 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_devp))
376 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_cport_info::cport_addr))
377 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
378     sata_cport_info::cport_dev_type))
379 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_dev_type))
380 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
381     sata_cport_info::cport_state))
382 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_state))
383 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_dev_type))
384 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_sata_drive))
385 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_dev_port))
386 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_num_dev_ports))
387 #ifdef SATA_DEBUG
388 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuf_count))
389 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuffail_count))
390 #endif
391 
392 /* End of warlock directives */
393 
394 /* ************** loadable module configuration functions ************** */
395 
396 int
397 _init()
398 {
399 	int rval;
400 
401 	mutex_init(&sata_mutex, NULL, MUTEX_DRIVER, NULL);
402 	mutex_init(&sata_event_mutex, NULL, MUTEX_DRIVER, NULL);
403 	mutex_init(&sata_log_mutex, NULL, MUTEX_DRIVER, NULL);
404 	cv_init(&sata_event_cv, NULL, CV_DRIVER, NULL);
405 	if ((rval = mod_install(&modlinkage)) != 0) {
406 #ifdef SATA_DEBUG
407 		cmn_err(CE_WARN, "sata: _init: mod_install failed\n");
408 #endif
409 		mutex_destroy(&sata_log_mutex);
410 		cv_destroy(&sata_event_cv);
411 		mutex_destroy(&sata_event_mutex);
412 		mutex_destroy(&sata_mutex);
413 	}
414 	return (rval);
415 }
416 
417 int
418 _fini()
419 {
420 	int rval;
421 
422 	if ((rval = mod_remove(&modlinkage)) != 0)
423 		return (rval);
424 
425 	mutex_destroy(&sata_log_mutex);
426 	cv_destroy(&sata_event_cv);
427 	mutex_destroy(&sata_event_mutex);
428 	mutex_destroy(&sata_mutex);
429 	return (rval);
430 }
431 
432 int
433 _info(struct modinfo *modinfop)
434 {
435 	return (mod_info(&modlinkage, modinfop));
436 }
437 
438 
439 
440 /* ********************* SATA HBA entry points ********************* */
441 
442 
443 /*
444  * Called by SATA HBA from _init().
445  * Registers HBA driver instance/sata framework pair with scsi framework, by
446  * calling scsi_hba_init().
447  *
448  * SATA HBA driver cb_ops are ignored - SATA HBA framework cb_ops are used
449  * instead. SATA HBA framework cb_ops pointer overwrites SATA HBA driver
450  * cb_ops pointer in SATA HBA driver dev_ops structure.
451  * SATA HBA framework cb_ops supplies cb_open cb_close and cb_ioctl vectors.
452  *
453  * Return status of the scsi_hba_init() is returned to a calling SATA HBA
454  * driver.
455  */
456 int
457 sata_hba_init(struct modlinkage *modlp)
458 {
459 	int rval;
460 	struct dev_ops *hba_ops;
461 
462 	SATADBG1(SATA_DBG_HBA_IF, NULL,
463 	    "sata_hba_init: name %s \n",
464 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
465 	/*
466 	 * Fill-up cb_ops and dev_ops when necessary
467 	 */
468 	hba_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
469 	/*
470 	 * Provide pointer to SATA dev_ops
471 	 */
472 	hba_ops->devo_cb_ops = &sata_cb_ops;
473 
474 	/*
475 	 * Register SATA HBA with SCSI framework
476 	 */
477 	if ((rval = scsi_hba_init(modlp)) != 0) {
478 		SATADBG1(SATA_DBG_HBA_IF, NULL,
479 		    "sata_hba_init: scsi hba init failed\n", NULL);
480 		return (rval);
481 	}
482 
483 	return (0);
484 }
485 
486 
487 /* HBA attach stages */
488 #define	HBA_ATTACH_STAGE_SATA_HBA_INST	1
489 #define	HBA_ATTACH_STAGE_SCSI_ATTACHED	2
490 #define	HBA_ATTACH_STAGE_SETUP		4
491 #define	HBA_ATTACH_STAGE_LINKED		8
492 
493 
494 /*
495  *
496  * Called from SATA HBA driver's attach routine to attach an instance of
497  * the HBA.
498  *
499  * For DDI_ATTACH command:
500  * sata_hba_inst structure is allocated here and initialized with pointers to
501  * SATA framework implementation of required scsi tran functions.
502  * The scsi_tran's tran_hba_private field is used by SATA Framework to point
503  * to the soft structure (sata_hba_inst) allocated by SATA framework for
504  * SATA HBA instance related data.
505  * The scsi_tran's tran_hba_private field is used by SATA framework to
506  * store a pointer to per-HBA-instance of sata_hba_inst structure.
507  * The sata_hba_inst structure is cross-linked to scsi tran structure.
508  * Among other info, a pointer to sata_hba_tran structure is stored in
509  * sata_hba_inst. The sata_hba_inst structures for different HBA instances are
510  * linked together into the list, pointed to by sata_hba_list.
511  * On the first HBA instance attach the sata event thread is initialized.
512  * Attachment points are created for all SATA ports of the HBA being attached.
513  * All HBA instance's SATA ports are probed and type of plugged devices is
514  * determined. For each device of a supported type, a target node is created.
515  *
516  * DDI_SUCCESS is returned when attachment process is successful,
517  * DDI_FAILURE is returned otherwise.
518  *
519  * For DDI_RESUME command:
520  * Not implemented at this time (postponed until phase 2 of the development).
521  */
522 int
523 sata_hba_attach(dev_info_t *dip, sata_hba_tran_t *sata_tran,
524     ddi_attach_cmd_t cmd)
525 {
526 	sata_hba_inst_t	*sata_hba_inst;
527 	scsi_hba_tran_t *scsi_tran = NULL;
528 	int hba_attach_state = 0;
529 	char taskq_name[MAXPATHLEN];
530 
531 	SATADBG3(SATA_DBG_HBA_IF, NULL,
532 	    "sata_hba_attach: node %s (%s%d)\n",
533 	    ddi_node_name(dip), ddi_driver_name(dip),
534 	    ddi_get_instance(dip));
535 
536 	if (cmd == DDI_RESUME) {
537 		/*
538 		 * Postponed until phase 2 of the development
539 		 */
540 		return (DDI_FAILURE);
541 	}
542 
543 	if (cmd != DDI_ATTACH) {
544 		return (DDI_FAILURE);
545 	}
546 
547 	/* cmd == DDI_ATTACH */
548 
549 	if (sata_validate_sata_hba_tran(dip, sata_tran) != SATA_SUCCESS) {
550 		SATA_LOG_D((NULL, CE_WARN,
551 		    "sata_hba_attach: invalid sata_hba_tran"));
552 		return (DDI_FAILURE);
553 	}
554 	/*
555 	 * Allocate and initialize SCSI tran structure.
556 	 * SATA copy of tran_bus_config is provided to create port nodes.
557 	 */
558 	scsi_tran = scsi_hba_tran_alloc(dip, SCSI_HBA_CANSLEEP);
559 	if (scsi_tran == NULL)
560 		return (DDI_FAILURE);
561 	/*
562 	 * Allocate soft structure for SATA HBA instance.
563 	 * There is a separate softstate for each HBA instance.
564 	 */
565 	sata_hba_inst = kmem_zalloc(sizeof (struct sata_hba_inst), KM_SLEEP);
566 	ASSERT(sata_hba_inst != NULL); /* this should not fail */
567 	mutex_init(&sata_hba_inst->satahba_mutex, NULL, MUTEX_DRIVER, NULL);
568 	hba_attach_state |= HBA_ATTACH_STAGE_SATA_HBA_INST;
569 
570 	/*
571 	 * scsi_trans's tran_hba_private is used by SATA Framework to point to
572 	 * soft structure allocated by SATA framework for
573 	 * SATA HBA instance related data.
574 	 */
575 	scsi_tran->tran_hba_private	= sata_hba_inst;
576 	scsi_tran->tran_tgt_private	= NULL;
577 
578 	scsi_tran->tran_tgt_init	= sata_scsi_tgt_init;
579 	scsi_tran->tran_tgt_probe	= sata_scsi_tgt_probe;
580 	scsi_tran->tran_tgt_free	= sata_scsi_tgt_free;
581 
582 	scsi_tran->tran_start		= sata_scsi_start;
583 	scsi_tran->tran_reset		= sata_scsi_reset;
584 	scsi_tran->tran_abort		= sata_scsi_abort;
585 	scsi_tran->tran_getcap		= sata_scsi_getcap;
586 	scsi_tran->tran_setcap		= sata_scsi_setcap;
587 	scsi_tran->tran_init_pkt	= sata_scsi_init_pkt;
588 	scsi_tran->tran_destroy_pkt	= sata_scsi_destroy_pkt;
589 
590 	scsi_tran->tran_dmafree		= sata_scsi_dmafree;
591 	scsi_tran->tran_sync_pkt	= sata_scsi_sync_pkt;
592 
593 	scsi_tran->tran_reset_notify	= NULL;
594 	scsi_tran->tran_get_bus_addr	= NULL;
595 	scsi_tran->tran_quiesce		= NULL;
596 	scsi_tran->tran_unquiesce	= NULL;
597 	scsi_tran->tran_bus_reset	= NULL;
598 
599 	if (scsi_hba_attach_setup(dip, sata_tran->sata_tran_hba_dma_attr,
600 	    scsi_tran, 0) != DDI_SUCCESS) {
601 #ifdef SATA_DEBUG
602 		cmn_err(CE_WARN, "?SATA: %s%d hba scsi attach failed",
603 		    ddi_driver_name(dip), ddi_get_instance(dip));
604 #endif
605 		goto fail;
606 	}
607 	hba_attach_state |= HBA_ATTACH_STAGE_SCSI_ATTACHED;
608 
609 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "sata")) {
610 		if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
611 		    "sata", 1) != DDI_PROP_SUCCESS) {
612 			SATA_LOG_D((NULL, CE_WARN, "sata_hba_attach: "
613 			    "failed to create hba sata prop"));
614 			goto fail;
615 		}
616 	}
617 
618 	/*
619 	 * Save pointers in hba instance soft state.
620 	 */
621 	sata_hba_inst->satahba_scsi_tran = scsi_tran;
622 	sata_hba_inst->satahba_tran = sata_tran;
623 	sata_hba_inst->satahba_dip = dip;
624 
625 	/*
626 	 * Create a task queue to handle emulated commands completion
627 	 * Use node name, dash, instance number as the queue name.
628 	 */
629 	taskq_name[0] = '\0';
630 	(void) strlcat(taskq_name, DEVI(dip)->devi_node_name,
631 	    sizeof (taskq_name));
632 	(void) snprintf(taskq_name + strlen(taskq_name),
633 	    sizeof (taskq_name) - strlen(taskq_name),
634 	    "-%d", DEVI(dip)->devi_instance);
635 	sata_hba_inst->satahba_taskq = taskq_create(taskq_name, 1,
636 	    minclsyspri, 1, sata_tran->sata_tran_hba_num_cports,
637 	    TASKQ_DYNAMIC);
638 
639 	hba_attach_state |= HBA_ATTACH_STAGE_SETUP;
640 
641 	/*
642 	 * Create events thread if not created yet.
643 	 */
644 	sata_event_thread_control(1);
645 
646 	/*
647 	 * Link this hba instance into the list.
648 	 */
649 	mutex_enter(&sata_mutex);
650 
651 
652 	sata_hba_inst->satahba_next = NULL;
653 	sata_hba_inst->satahba_prev = sata_hba_list_tail;
654 	if (sata_hba_list == NULL) {
655 		sata_hba_list = sata_hba_inst;
656 	}
657 	if (sata_hba_list_tail != NULL) {
658 		sata_hba_list_tail->satahba_next = sata_hba_inst;
659 	}
660 	sata_hba_list_tail = sata_hba_inst;
661 	mutex_exit(&sata_mutex);
662 	hba_attach_state |= HBA_ATTACH_STAGE_LINKED;
663 
664 	/*
665 	 * Create SATA HBA devctl minor node for sata_hba_open, close, ioctl
666 	 * SATA HBA driver should not use its own open/close entry points.
667 	 *
668 	 * Make sure that instance number doesn't overflow
669 	 * when forming minor numbers.
670 	 */
671 	ASSERT(ddi_get_instance(dip) <= (L_MAXMIN >> INST_MINOR_SHIFT));
672 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
673 	    INST2DEVCTL(ddi_get_instance(dip)),
674 	    DDI_NT_SATA_NEXUS, 0) != DDI_SUCCESS) {
675 #ifdef SATA_DEBUG
676 		cmn_err(CE_WARN, "sata_hba_attach: "
677 		    "cannot create devctl minor node");
678 #endif
679 		goto fail;
680 	}
681 
682 
683 	/*
684 	 * Set-up kstats here, if necessary.
685 	 * (postponed until phase 2 of the development).
686 	 */
687 
688 
689 	/*
690 	 * Probe controller ports. This operation will describe a current
691 	 * controller/port/multipliers/device configuration and will create
692 	 * attachment points.
693 	 * We may end-up with just a controller with no devices attached.
694 	 * For the ports with a supported device attached, device target nodes
695 	 * are created and devices are initialized.
696 	 */
697 	sata_probe_ports(sata_hba_inst);
698 
699 	sata_hba_inst->satahba_attached = 1;
700 	return (DDI_SUCCESS);
701 
702 fail:
703 	if (hba_attach_state & HBA_ATTACH_STAGE_LINKED) {
704 		(void) sata_remove_hba_instance(dip);
705 		if (sata_hba_list == NULL)
706 			sata_event_thread_control(0);
707 	}
708 
709 	if (hba_attach_state & HBA_ATTACH_STAGE_SETUP) {
710 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
711 		taskq_destroy(sata_hba_inst->satahba_taskq);
712 	}
713 
714 	if (hba_attach_state & HBA_ATTACH_STAGE_SCSI_ATTACHED)
715 		(void) scsi_hba_detach(dip);
716 
717 	if (hba_attach_state & HBA_ATTACH_STAGE_SATA_HBA_INST) {
718 		mutex_destroy(&sata_hba_inst->satahba_mutex);
719 		kmem_free((void *)sata_hba_inst,
720 		    sizeof (struct sata_hba_inst));
721 		scsi_hba_tran_free(scsi_tran);
722 	}
723 
724 	sata_log(NULL, CE_WARN, "?SATA: %s%d hba attach failed",
725 	    ddi_driver_name(dip), ddi_get_instance(dip));
726 
727 	return (DDI_FAILURE);
728 }
729 
730 
731 /*
732  * Called by SATA HBA from to detach an instance of the driver.
733  *
734  * For DDI_DETACH command:
735  * Free local structures allocated for SATA HBA instance during
736  * sata_hba_attach processing.
737  *
738  * Returns DDI_SUCCESS when HBA was detached, DDI_FAILURE otherwise.
739  *
740  * For DDI_SUSPEND command:
741  * Not implemented at this time (postponed until phase 2 of the development)
742  * Returnd DDI_SUCCESS.
743  *
744  * When the last HBA instance is detached, the event daemon is terminated.
745  *
746  * NOTE: cport support only, no port multiplier support.
747  */
748 int
749 sata_hba_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
750 {
751 	dev_info_t	*tdip;
752 	sata_hba_inst_t	*sata_hba_inst;
753 	scsi_hba_tran_t *scsi_hba_tran;
754 	sata_cport_info_t *cportinfo;
755 	sata_drive_info_t *sdinfo;
756 	int ncport;
757 
758 	SATADBG3(SATA_DBG_HBA_IF, NULL, "sata_hba_detach: node %s (%s%d)\n",
759 	    ddi_node_name(dip), ddi_driver_name(dip), ddi_get_instance(dip));
760 
761 	switch (cmd) {
762 	case DDI_DETACH:
763 
764 		if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
765 			return (DDI_FAILURE);
766 
767 		sata_hba_inst = scsi_hba_tran->tran_hba_private;
768 		if (sata_hba_inst == NULL)
769 			return (DDI_FAILURE);
770 
771 		if (scsi_hba_detach(dip) == DDI_FAILURE) {
772 			sata_hba_inst->satahba_attached = 1;
773 			return (DDI_FAILURE);
774 		}
775 
776 		/*
777 		 * Free all target nodes - at this point
778 		 * devices should be at least offlined
779 		 * otherwise scsi_hba_detach() should not be called.
780 		 */
781 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
782 		    ncport++) {
783 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
784 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
785 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
786 				if (sdinfo != NULL) {
787 					tdip = sata_get_target_dip(dip,
788 					    ncport);
789 					if (tdip != NULL) {
790 						if (ndi_devi_offline(tdip,
791 						    NDI_DEVI_REMOVE) !=
792 						    NDI_SUCCESS) {
793 							SATA_LOG_D((
794 							    sata_hba_inst,
795 							    CE_WARN,
796 							    "sata_hba_detach: "
797 							    "Target node not "
798 							    "removed !"));
799 							return (DDI_FAILURE);
800 						}
801 					}
802 				}
803 			}
804 		}
805 		/*
806 		 * Disable sata event daemon processing for this HBA
807 		 */
808 		sata_hba_inst->satahba_attached = 0;
809 
810 		/*
811 		 * Remove event daemon thread, if it is last HBA instance.
812 		 */
813 
814 		mutex_enter(&sata_mutex);
815 		if (sata_hba_list->satahba_next == NULL) {
816 			mutex_exit(&sata_mutex);
817 			sata_event_thread_control(0);
818 			mutex_enter(&sata_mutex);
819 		}
820 		mutex_exit(&sata_mutex);
821 
822 		/* Remove this HBA instance from the HBA list */
823 		sata_remove_hba_instance(dip);
824 
825 		/*
826 		 * At this point there should be no target nodes attached.
827 		 * Detach and destroy device and port info structures.
828 		 */
829 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
830 		    ncport++) {
831 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
832 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
833 				sdinfo =
834 				    cportinfo->cport_devp.cport_sata_drive;
835 				if (sdinfo != NULL) {
836 					/* Release device structure */
837 					kmem_free(sdinfo,
838 					    sizeof (sata_drive_info_t));
839 				}
840 				/* Release cport info */
841 				mutex_destroy(&cportinfo->cport_mutex);
842 				kmem_free(cportinfo,
843 				    sizeof (sata_cport_info_t));
844 			}
845 		}
846 
847 		scsi_hba_tran_free(sata_hba_inst->satahba_scsi_tran);
848 
849 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
850 
851 		taskq_destroy(sata_hba_inst->satahba_taskq);
852 
853 		mutex_destroy(&sata_hba_inst->satahba_mutex);
854 		kmem_free((void *)sata_hba_inst,
855 		    sizeof (struct sata_hba_inst));
856 
857 		return (DDI_SUCCESS);
858 
859 	case DDI_SUSPEND:
860 		/*
861 		 * Postponed until phase 2
862 		 */
863 		return (DDI_FAILURE);
864 
865 	default:
866 		return (DDI_FAILURE);
867 	}
868 }
869 
870 
871 /*
872  * Called by an HBA drive from _fini() routine.
873  * Unregisters SATA HBA instance/SATA framework pair from the scsi framework.
874  */
875 void
876 sata_hba_fini(struct modlinkage *modlp)
877 {
878 	SATADBG1(SATA_DBG_HBA_IF, NULL,
879 	    "sata_hba_fini: name %s\n",
880 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
881 
882 	scsi_hba_fini(modlp);
883 }
884 
885 
886 /*
887  * Default open and close routine for sata_hba framework.
888  *
889  */
890 /*
891  * Open devctl node.
892  *
893  * Returns:
894  * 0 if node was open successfully, error code otherwise.
895  *
896  *
897  */
898 
899 static int
900 sata_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
901 {
902 #ifndef __lock_lint
903 	_NOTE(ARGUNUSED(credp))
904 #endif
905 	int rv = 0;
906 	dev_info_t *dip;
907 	scsi_hba_tran_t *scsi_hba_tran;
908 	sata_hba_inst_t	*sata_hba_inst;
909 
910 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_open: entered", NULL);
911 
912 	if (otyp != OTYP_CHR)
913 		return (EINVAL);
914 
915 	dip = sata_devt_to_devinfo(*devp);
916 	if (dip == NULL)
917 		return (ENXIO);
918 
919 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
920 		return (ENXIO);
921 
922 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
923 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
924 		return (ENXIO);
925 
926 	mutex_enter(&sata_mutex);
927 	if (flags & FEXCL) {
928 		if (sata_hba_inst->satahba_open_flag != 0) {
929 			rv = EBUSY;
930 		} else {
931 			sata_hba_inst->satahba_open_flag =
932 			    SATA_DEVCTL_EXOPENED;
933 		}
934 	} else {
935 		if (sata_hba_inst->satahba_open_flag == SATA_DEVCTL_EXOPENED) {
936 			rv = EBUSY;
937 		} else {
938 			sata_hba_inst->satahba_open_flag =
939 			    SATA_DEVCTL_SOPENED;
940 		}
941 	}
942 	mutex_exit(&sata_mutex);
943 
944 	return (rv);
945 }
946 
947 
948 /*
949  * Close devctl node.
950  * Returns:
951  * 0 if node was closed successfully, error code otherwise.
952  *
953  */
954 
955 static int
956 sata_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
957 {
958 #ifndef __lock_lint
959 	_NOTE(ARGUNUSED(credp))
960 	_NOTE(ARGUNUSED(flag))
961 #endif
962 	dev_info_t *dip;
963 	scsi_hba_tran_t *scsi_hba_tran;
964 	sata_hba_inst_t	*sata_hba_inst;
965 
966 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_close: entered", NULL);
967 
968 	if (otyp != OTYP_CHR)
969 		return (EINVAL);
970 
971 	dip = sata_devt_to_devinfo(dev);
972 	if (dip == NULL)
973 		return (ENXIO);
974 
975 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
976 		return (ENXIO);
977 
978 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
979 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
980 		return (ENXIO);
981 
982 	mutex_enter(&sata_mutex);
983 	sata_hba_inst->satahba_open_flag = 0;
984 	mutex_exit(&sata_mutex);
985 	return (0);
986 }
987 
988 
989 
990 /*
991  * Standard IOCTL commands for SATA hotplugging.
992  * Implemented DEVCTL_AP commands:
993  * DEVCTL_AP_CONNECT
994  * DEVCTL_AP_DISCONNECT
995  * DEVCTL_AP_CONFIGURE
996  * DEVCTL_UNCONFIGURE
997  * DEVCTL_AP_CONTROL
998  *
999  * Commands passed to default ndi ioctl handler:
1000  * DEVCTL_DEVICE_GETSTATE
1001  * DEVCTL_DEVICE_ONLINE
1002  * DEVCTL_DEVICE_OFFLINE
1003  * DEVCTL_DEVICE_REMOVE
1004  * DEVCTL_DEVICE_INSERT
1005  * DEVCTL_BUS_GETSTATE
1006  *
1007  * All other cmds are passed to HBA if it provide ioctl handler, or failed
1008  * if not.
1009  *
1010  * Returns:
1011  * 0 if successful,
1012  * error code if operation failed.
1013  *
1014  * NOTE: Port Multiplier is not supported.
1015  *
1016  */
1017 
1018 static int
1019 sata_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
1020     int *rvalp)
1021 {
1022 #ifndef __lock_lint
1023 	_NOTE(ARGUNUSED(credp))
1024 	_NOTE(ARGUNUSED(rvalp))
1025 #endif
1026 	int rv = 0;
1027 	int32_t	comp_port = -1;
1028 	dev_info_t *dip, *tdip;
1029 	devctl_ap_state_t ap_state;
1030 	struct devctl_iocdata *dcp = NULL;
1031 	scsi_hba_tran_t *scsi_hba_tran;
1032 	sata_hba_inst_t *sata_hba_inst;
1033 	sata_device_t sata_device;
1034 	sata_drive_info_t *sdinfo;
1035 	sata_cport_info_t *cportinfo;
1036 	int cport, pmport, qual;
1037 	int rval = SATA_SUCCESS;
1038 
1039 	dip = sata_devt_to_devinfo(dev);
1040 	if (dip == NULL)
1041 		return (ENXIO);
1042 
1043 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1044 		return (ENXIO);
1045 
1046 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1047 	if (sata_hba_inst == NULL)
1048 		return (ENXIO);
1049 
1050 	if (sata_hba_inst->satahba_tran == NULL)
1051 		return (ENXIO);
1052 
1053 	switch (cmd) {
1054 
1055 	case DEVCTL_DEVICE_GETSTATE:
1056 	case DEVCTL_DEVICE_ONLINE:
1057 	case DEVCTL_DEVICE_OFFLINE:
1058 	case DEVCTL_DEVICE_REMOVE:
1059 	case DEVCTL_BUS_GETSTATE:
1060 		/*
1061 		 * There may be more cases that we want to pass to default
1062 		 * handler rather then fail them.
1063 		 */
1064 		return (ndi_devctl_ioctl(dip, cmd, arg, mode, 0));
1065 	}
1066 
1067 	/* read devctl ioctl data */
1068 	if (cmd != DEVCTL_AP_CONTROL) {
1069 		if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS)
1070 			return (EFAULT);
1071 
1072 		if ((comp_port = sata_get_port_num(sata_hba_inst, dcp)) ==
1073 		    -1) {
1074 			if (dcp)
1075 				ndi_dc_freehdl(dcp);
1076 			return (EINVAL);
1077 		}
1078 
1079 		cport = SCSI_TO_SATA_CPORT(comp_port);
1080 		pmport = SCSI_TO_SATA_PMPORT(comp_port);
1081 		/* Only cport is considered now, i.e. SATA_ADDR_CPORT */
1082 		qual = SATA_ADDR_CPORT;
1083 		if (sata_validate_sata_address(sata_hba_inst, cport, pmport,
1084 		    qual) != 0) {
1085 			ndi_dc_freehdl(dcp);
1086 			return (EINVAL);
1087 		}
1088 
1089 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1090 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1091 		    cport_mutex);
1092 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1093 			/*
1094 			 * Cannot process ioctl request now. Come back later.
1095 			 */
1096 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1097 			    cport_mutex);
1098 			ndi_dc_freehdl(dcp);
1099 			return (EBUSY);
1100 		}
1101 		/* Block event processing for this port */
1102 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1103 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1104 
1105 		sata_device.satadev_addr.cport = cport;
1106 		sata_device.satadev_addr.pmport = pmport;
1107 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
1108 		sata_device.satadev_rev = SATA_DEVICE_REV;
1109 	}
1110 
1111 	switch (cmd) {
1112 
1113 	case DEVCTL_AP_DISCONNECT:
1114 		/*
1115 		 * Normally, cfgadm sata plugin will try to offline
1116 		 * (unconfigure) device before this request. Nevertheless,
1117 		 * if a device is still configured, we need to
1118 		 * attempt to offline and unconfigure device first, and we will
1119 		 * deactivate the port regardless of the unconfigure
1120 		 * operation results.
1121 		 *
1122 		 * DEVCTL_AP_DISCONNECT invokes
1123 		 * sata_hba_inst->satahba_tran->
1124 		 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
1125 		 * If successful, the device structure (if any) attached
1126 		 * to a port is removed and state of the port marked
1127 		 * appropriately.
1128 		 * Failure of the port_deactivate may keep port in
1129 		 * the active state, or may fail the port.
1130 		 */
1131 
1132 		/* Check the current state of the port */
1133 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
1134 		    (dip, &sata_device);
1135 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1136 		    cport_mutex);
1137 		sata_update_port_info(sata_hba_inst, &sata_device);
1138 		if (rval != SATA_SUCCESS ||
1139 		    (sata_device.satadev_state & SATA_PSTATE_FAILED)) {
1140 			cportinfo->cport_state = SATA_PSTATE_FAILED;
1141 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1142 			    cport_mutex);
1143 			rv = EIO;
1144 			break;
1145 		}
1146 		/* Sanity check */
1147 		if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
1148 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1149 			    cport_mutex);
1150 			/* No physical port deactivation supported. */
1151 			break;
1152 		}
1153 
1154 		/*
1155 		 * set port's dev_state to not ready - this will disable
1156 		 * an access to an attached device.
1157 		 */
1158 		cportinfo->cport_state &= ~SATA_STATE_READY;
1159 
1160 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
1161 			sdinfo = cportinfo->cport_devp.cport_sata_drive;
1162 			ASSERT(sdinfo != NULL);
1163 			if ((sdinfo->satadrv_type &
1164 			    (SATA_VALID_DEV_TYPE))) {
1165 				/*
1166 				 * If a target node exists, try to offline
1167 				 * a device and remove target node.
1168 				 */
1169 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
1170 				    cport)->cport_mutex);
1171 				tdip = sata_get_target_dip(dip, comp_port);
1172 				if (tdip != NULL) {
1173 					/* target node exist */
1174 					if (ndi_devi_offline(tdip,
1175 					    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
1176 						/*
1177 						 * Problem
1178 						 * A target node remained
1179 						 * attached. This happens when
1180 						 * the file was open or a node
1181 						 * was waiting for resources.
1182 						 * Cannot do anything about it.
1183 						 */
1184 						SATA_LOG_D((sata_hba_inst,
1185 						    CE_WARN,
1186 						    "sata_hba_ioctl: "
1187 						    "disconnect: cannot "
1188 						    "remove target node!!!"));
1189 					}
1190 				}
1191 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
1192 				    cport)->cport_mutex);
1193 				/*
1194 				 * Remove and release sata_drive_info
1195 				 * structure.
1196 				 */
1197 				if (SATA_CPORTINFO_DRV_INFO(cportinfo) !=
1198 				    NULL) {
1199 					SATA_CPORTINFO_DRV_INFO(cportinfo) =
1200 					    NULL;
1201 					(void) kmem_free((void *)sdinfo,
1202 					    sizeof (sata_drive_info_t));
1203 					cportinfo->cport_dev_type =
1204 					    SATA_DTYPE_NONE;
1205 				}
1206 			}
1207 			/*
1208 			 * Note: PMult info requires different handling.
1209 			 * Put PMult handling code here, when PMult is
1210 			 * supported.
1211 			 */
1212 
1213 		}
1214 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1215 		/* Just ask HBA driver to deactivate port */
1216 		sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
1217 
1218 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
1219 		    (dip, &sata_device);
1220 
1221 		/*
1222 		 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
1223 		 * without the hint.
1224 		 */
1225 		sata_gen_sysevent(sata_hba_inst,
1226 		    &sata_device.satadev_addr, SE_NO_HINT);
1227 
1228 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1229 		    cport_mutex);
1230 		sata_update_port_info(sata_hba_inst, &sata_device);
1231 
1232 		if (rval != SATA_SUCCESS) {
1233 			/*
1234 			 * Port deactivation failure - do not
1235 			 * change port state unless the state
1236 			 * returned by HBA indicates a port failure.
1237 			 */
1238 			if (sata_device.satadev_state & SATA_PSTATE_FAILED)
1239 				cportinfo->cport_state = SATA_PSTATE_FAILED;
1240 			rv = EIO;
1241 		} else {
1242 			/*
1243 			 * Deactivation succeded. From now on the framework
1244 			 * will not know what is happening to the device, until
1245 			 * the port is activated again.
1246 			 */
1247 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
1248 		}
1249 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1250 		break;
1251 
1252 	case DEVCTL_AP_UNCONFIGURE:
1253 
1254 		/*
1255 		 * The unconfigure operation uses generic nexus operation to
1256 		 * offline a device. It leaves a target device node attached.
1257 		 * and obviously sata_drive_info attached as well, because
1258 		 * from the hardware point of view nothing has changed.
1259 		 */
1260 		if ((tdip = sata_get_target_dip(dip, comp_port)) != NULL) {
1261 
1262 			if (ndi_devi_offline(tdip, NDI_UNCONFIG) !=
1263 			    NDI_SUCCESS) {
1264 				SATA_LOG_D((sata_hba_inst, CE_WARN,
1265 				    "sata_hba_ioctl: unconfigure: "
1266 				    "failed to unconfigure "
1267 				    "device at cport %d", cport));
1268 				rv = EIO;
1269 			}
1270 			/*
1271 			 * The target node devi_state should be marked with
1272 			 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
1273 			 * This would be the indication for cfgadm that
1274 			 * the AP node occupant state is 'unconfigured'.
1275 			 */
1276 
1277 		} else {
1278 			/*
1279 			 * This would indicate a failure on the part of cfgadm
1280 			 * to detect correct state of the node prior to this
1281 			 * call - one cannot unconfigure non-existing device.
1282 			 */
1283 			SATA_LOG_D((sata_hba_inst, CE_WARN,
1284 			    "sata_hba_ioctl: unconfigure: "
1285 			    "attempt to unconfigure non-existing device "
1286 			    "at cport %d", cport));
1287 			rv = ENXIO;
1288 		}
1289 
1290 		break;
1291 
1292 	case DEVCTL_AP_CONNECT:
1293 	{
1294 		/*
1295 		 * The sata cfgadm pluging will invoke this operation only if
1296 		 * port was found in the disconnect state (failed state
1297 		 * is also treated as the disconnected state).
1298 		 * DEVCTL_AP_CONNECT would invoke
1299 		 * sata_hba_inst->satahba_tran->
1300 		 * sata_tran_hotplug_ops->sata_tran_port_activate().
1301 		 * If successful and a device is found attached to the port,
1302 		 * the initialization sequence is executed to attach
1303 		 * a device structure to a port structure. The device is not
1304 		 * set in configured state (system-wise) by this operation.
1305 		 * The state of the port and a device would be set
1306 		 * appropriately.
1307 		 *
1308 		 * Note, that activating the port may generate link events,
1309 		 * so is is important that following processing and the
1310 		 * event processing does not interfere with each other!
1311 		 *
1312 		 * This operation may remove port failed state and will
1313 		 * try to make port active and in good standing.
1314 		 */
1315 
1316 		/* We only care about host sata cport for now */
1317 
1318 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) != NULL) {
1319 			/* Just let HBA driver to activate port */
1320 
1321 			if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
1322 			    (dip, &sata_device) != SATA_SUCCESS) {
1323 				/*
1324 				 * Port activation failure.
1325 				 */
1326 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
1327 				    cport)->cport_mutex);
1328 				sata_update_port_info(sata_hba_inst,
1329 				    &sata_device);
1330 				if (sata_device.satadev_state &
1331 				    SATA_PSTATE_FAILED) {
1332 					cportinfo->cport_state =
1333 					    SATA_PSTATE_FAILED;
1334 				}
1335 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
1336 				    cport)->cport_mutex);
1337 				SATA_LOG_D((sata_hba_inst, CE_WARN,
1338 				    "sata_hba_ioctl: connect: "
1339 				    "failed to activate SATA cport %d",
1340 				    cport));
1341 				rv = EIO;
1342 				break;
1343 			}
1344 		}
1345 		/* Virgin port state - will be updated by the port re-probe. */
1346 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
1347 		    cport)->cport_mutex);
1348 		cportinfo->cport_state = 0;
1349 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
1350 		    cport)->cport_mutex);
1351 
1352 		/*
1353 		 * Probe the port to find its state and attached device.
1354 		 */
1355 		if (sata_reprobe_port(sata_hba_inst, &sata_device,
1356 		    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
1357 			rv = EIO;
1358 		/*
1359 		 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
1360 		 * without the hint
1361 		 */
1362 		sata_gen_sysevent(sata_hba_inst,
1363 		    &sata_device.satadev_addr, SE_NO_HINT);
1364 		/*
1365 		 * If there is a device attached to the port, emit
1366 		 * a message.
1367 		 */
1368 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
1369 			sata_log(sata_hba_inst, CE_WARN,
1370 			    "SATA device detected at port %d", cport);
1371 		}
1372 		break;
1373 	}
1374 
1375 	case DEVCTL_AP_CONFIGURE:
1376 	{
1377 		boolean_t target = TRUE;
1378 
1379 		/*
1380 		 * A port may be in an active or shutdown state.
1381 		 * If port is in a failed state, operation is aborted - one
1382 		 * has to use explicit connect or port activate request
1383 		 * to try to get a port into non-failed mode.
1384 		 *
1385 		 * If a port is in a shutdown state, arbitrarily invoke
1386 		 * sata_tran_port_activate() prior to any other operation.
1387 		 *
1388 		 * Verify that port state is READY and there is a device
1389 		 * of a supported type attached to this port.
1390 		 * If target node exists, a device was most likely offlined.
1391 		 * If target node does not exist, create a target node an
1392 		 * attempt to online it.
1393 		 *		 *
1394 		 * NO PMult or devices beyond PMult are supported yet.
1395 		 */
1396 
1397 		/* We only care about host controller's sata cport for now. */
1398 		if (cportinfo->cport_state & SATA_PSTATE_FAILED) {
1399 			rv = ENXIO;
1400 			break;
1401 		}
1402 		/* Check the current state of the port */
1403 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
1404 
1405 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
1406 		    (dip, &sata_device);
1407 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1408 		    cport_mutex);
1409 		sata_update_port_info(sata_hba_inst, &sata_device);
1410 		if (rval != SATA_SUCCESS ||
1411 		    (sata_device.satadev_state & SATA_PSTATE_FAILED)) {
1412 			cportinfo->cport_state = SATA_PSTATE_FAILED;
1413 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1414 			    cport_mutex);
1415 			rv = EIO;
1416 			break;
1417 		}
1418 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN) {
1419 			target = FALSE;
1420 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1421 			    cport_mutex);
1422 
1423 			if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) != NULL) {
1424 				/* Just let HBA driver to activate port */
1425 				if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
1426 				    (dip, &sata_device) != SATA_SUCCESS) {
1427 					/*
1428 					 * Port activation failure - do not
1429 					 * change port state unless the state
1430 					 * returned by HBA indicates a port
1431 					 * failure.
1432 					 */
1433 					mutex_enter(&SATA_CPORT_INFO(
1434 					    sata_hba_inst, cport)->cport_mutex);
1435 					sata_update_port_info(sata_hba_inst,
1436 					    &sata_device);
1437 					if (sata_device.satadev_state &
1438 					    SATA_PSTATE_FAILED) {
1439 						cportinfo->cport_state =
1440 						    SATA_PSTATE_FAILED;
1441 					}
1442 					mutex_exit(&SATA_CPORT_INFO(
1443 					    sata_hba_inst, cport)->cport_mutex);
1444 					SATA_LOG_D((sata_hba_inst, CE_WARN,
1445 					    "sata_hba_ioctl: configure: "
1446 					    "failed to activate SATA cport %d",
1447 					    cport));
1448 					rv = EIO;
1449 					break;
1450 				}
1451 			}
1452 			/*
1453 			 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
1454 			 * without the hint.
1455 			 */
1456 			sata_gen_sysevent(sata_hba_inst,
1457 			    &sata_device.satadev_addr, SE_NO_HINT);
1458 
1459 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1460 			    cport_mutex);
1461 			/* Virgin port state */
1462 			cportinfo->cport_state = 0;
1463 		}
1464 		/*
1465 		 * Always reprobe port, to get current device info.
1466 		 */
1467 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1468 		if (sata_reprobe_port(sata_hba_inst, &sata_device,
1469 		    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
1470 			rv = EIO;
1471 			break;
1472 		}
1473 		if (target == FALSE &&
1474 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
1475 			/*
1476 			 * That's the transition from "inactive" port
1477 			 * to active one with device attached.
1478 			 */
1479 			sata_log(sata_hba_inst, CE_WARN,
1480 			    "SATA device detected at port %d",
1481 			    cport);
1482 		}
1483 
1484 		/*
1485 		 * This is where real configure starts.
1486 		 * Change following check for PMult support.
1487 		 */
1488 		if (!(sata_device.satadev_type & SATA_VALID_DEV_TYPE)) {
1489 			/* No device to configure */
1490 			rv = ENXIO; /* No device to configure */
1491 			break;
1492 		}
1493 
1494 		/*
1495 		 * Here we may have a device in reset condition,
1496 		 * but because we are just configuring it, there is
1497 		 * no need to process the reset other than just
1498 		 * to clear device reset condition in the HBA driver.
1499 		 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
1500 		 * cause a first command sent the HBA driver with the request
1501 		 * to clear device reset condition.
1502 		 */
1503 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1504 		    cport_mutex);
1505 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
1506 		if (sdinfo == NULL) {
1507 			rv = ENXIO;
1508 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1509 			    cport_mutex);
1510 			break;
1511 		}
1512 		if (sdinfo->satadrv_event_flags &
1513 		    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET))
1514 			sdinfo->satadrv_event_flags = 0;
1515 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
1516 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1517 
1518 		if ((tdip = sata_get_target_dip(dip, comp_port)) != NULL) {
1519 			/* target node still exists */
1520 			if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
1521 				SATA_LOG_D((sata_hba_inst, CE_WARN,
1522 				    "sata_hba_ioctl: configure: "
1523 				    "onlining device at cport %d failed",
1524 				    cport));
1525 				rv = EIO;
1526 				break;
1527 			}
1528 		} else {
1529 			/*
1530 			 * No target node - need to create a new target node.
1531 			 */
1532 			tdip = sata_create_target_node(dip, sata_hba_inst,
1533 			    &sata_device.satadev_addr);
1534 			if (tdip == NULL) {
1535 				/* configure failed */
1536 				SATA_LOG_D((sata_hba_inst, CE_WARN,
1537 				    "sata_hba_ioctl: configure: "
1538 				    "configuring device at cport %d "
1539 				    "failed", cport));
1540 				rv = EIO;
1541 				break;
1542 			}
1543 		}
1544 
1545 		break;
1546 	}
1547 
1548 	case DEVCTL_AP_GETSTATE:
1549 
1550 		sata_cfgadm_state(sata_hba_inst, comp_port, &ap_state);
1551 
1552 		ap_state.ap_last_change = (time_t)-1;
1553 		ap_state.ap_error_code = 0;
1554 		ap_state.ap_in_transition = 0;
1555 
1556 		/* Copy the return AP-state information to the user space */
1557 		if (ndi_dc_return_ap_state(&ap_state, dcp) != NDI_SUCCESS) {
1558 			rv = EFAULT;
1559 		}
1560 		break;
1561 
1562 	case DEVCTL_AP_CONTROL:
1563 	{
1564 		/*
1565 		 * Generic devctl for hardware specific functionality
1566 		 */
1567 		sata_ioctl_data_t	ioc;
1568 
1569 		ASSERT(dcp == NULL);
1570 
1571 		/* Copy in user ioctl data first */
1572 #ifdef _MULTI_DATAMODEL
1573 		if (ddi_model_convert_from(mode & FMODELS) ==
1574 		    DDI_MODEL_ILP32) {
1575 
1576 			sata_ioctl_data_32_t	ioc32;
1577 
1578 			if (ddi_copyin((void *)arg, (void *)&ioc32,
1579 			    sizeof (ioc32), mode) != 0) {
1580 				rv = EFAULT;
1581 				break;
1582 			}
1583 			ioc.cmd 	= (uint_t)ioc32.cmd;
1584 			ioc.port	= (uint_t)ioc32.port;
1585 			ioc.get_size	= (uint_t)ioc32.get_size;
1586 			ioc.buf		= (caddr_t)(uintptr_t)ioc32.buf;
1587 			ioc.bufsiz	= (uint_t)ioc32.bufsiz;
1588 			ioc.misc_arg	= (uint_t)ioc32.misc_arg;
1589 		} else
1590 #endif /* _MULTI_DATAMODEL */
1591 		if (ddi_copyin((void *)arg, (void *)&ioc, sizeof (ioc),
1592 		    mode) != 0) {
1593 			return (EFAULT);
1594 		}
1595 
1596 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
1597 		    "sata_hba_ioctl: DEVCTL_AP_CONTROL "
1598 		    "cmd 0x%x, port 0x%x", ioc.cmd, ioc.port);
1599 
1600 		/*
1601 		 * To avoid BE/LE and 32/64 issues, a get_size always returns
1602 		 * a 32-bit number.
1603 		 */
1604 		if (ioc.get_size != 0 && ioc.bufsiz != (sizeof (uint32_t))) {
1605 			return (EINVAL);
1606 		}
1607 		/* validate address */
1608 		cport = SCSI_TO_SATA_CPORT(ioc.port);
1609 		pmport = SCSI_TO_SATA_PMPORT(ioc.port);
1610 		qual = SCSI_TO_SATA_ADDR_QUAL(ioc.port);
1611 
1612 		/* Override address qualifier - handle cport only for now */
1613 		qual = SATA_ADDR_CPORT;
1614 
1615 		if (sata_validate_sata_address(sata_hba_inst, cport,
1616 		    pmport, qual) != 0)
1617 			return (EINVAL);
1618 
1619 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1620 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1621 		    cport_mutex);
1622 		/* Is the port locked by event processing daemon ? */
1623 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1624 			/*
1625 			 * Cannot process ioctl request now. Come back later
1626 			 */
1627 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1628 			    cport_mutex);
1629 			return (EBUSY);
1630 		}
1631 		/* Block event processing for this port */
1632 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1633 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1634 
1635 
1636 		sata_device.satadev_addr.cport = cport;
1637 		sata_device.satadev_addr.pmport = pmport;
1638 		sata_device.satadev_rev = SATA_DEVICE_REV;
1639 
1640 		switch (ioc.cmd) {
1641 
1642 		case SATA_CFGA_RESET_PORT:
1643 			/*
1644 			 * There is no protection here for configured
1645 			 * device.
1646 			 */
1647 
1648 			/* Sanity check */
1649 			if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
1650 				SATA_LOG_D((sata_hba_inst, CE_WARN,
1651 				    "sata_hba_ioctl: "
1652 				    "sata_hba_tran missing required "
1653 				    "function sata_tran_reset_dport"));
1654 				rv = EINVAL;
1655 				break;
1656 			}
1657 
1658 			/* handle cport only for now */
1659 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
1660 			if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
1661 			    (dip, &sata_device) != SATA_SUCCESS) {
1662 				SATA_LOG_D((sata_hba_inst, CE_WARN,
1663 				    "sata_hba_ioctl: reset port: "
1664 				    "failed cport %d pmport %d",
1665 				    cport, pmport));
1666 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
1667 				    cport)->cport_mutex);
1668 				sata_update_port_info(sata_hba_inst,
1669 				    &sata_device);
1670 				SATA_CPORT_STATE(sata_hba_inst, cport) =
1671 				    SATA_PSTATE_FAILED;
1672 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
1673 				    cport)->cport_mutex);
1674 				rv = EIO;
1675 			}
1676 			/*
1677 			 * Since the port was reset, it should be probed and
1678 			 * attached device reinitialized. At this point the
1679 			 * port state is unknown - it's state is HBA-specific.
1680 			 * Re-probe port to get its state.
1681 			 */
1682 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
1683 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
1684 				rv = EIO;
1685 				break;
1686 			}
1687 			break;
1688 
1689 		case SATA_CFGA_RESET_DEVICE:
1690 			/*
1691 			 * There is no protection here for configured
1692 			 * device.
1693 			 */
1694 
1695 			/* Sanity check */
1696 			if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
1697 				SATA_LOG_D((sata_hba_inst, CE_WARN,
1698 				    "sata_hba_ioctl: "
1699 				    "sata_hba_tran missing required "
1700 				    "function sata_tran_reset_dport"));
1701 				rv = EINVAL;
1702 				break;
1703 			}
1704 
1705 			/* handle only device attached to cports, for now */
1706 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
1707 
1708 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1709 			    cport_mutex);
1710 			sdinfo = sata_get_device_info(sata_hba_inst,
1711 			    &sata_device);
1712 			if (sdinfo == NULL) {
1713 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
1714 				    cport)->cport_mutex);
1715 				rv = EINVAL;
1716 				break;
1717 			}
1718 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1719 			    cport_mutex);
1720 
1721 			/* only handle cport for now */
1722 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
1723 			if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
1724 			    (dip, &sata_device) != SATA_SUCCESS) {
1725 				SATA_LOG_D((sata_hba_inst, CE_WARN,
1726 				    "sata_hba_ioctl: reset device: failed "
1727 				    "cport %d pmport %d", cport, pmport));
1728 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
1729 				    cport)->cport_mutex);
1730 				sata_update_port_info(sata_hba_inst,
1731 				    &sata_device);
1732 				/*
1733 				 * Device info structure remains
1734 				 * attached. Another device reset or
1735 				 * port disconnect/connect and re-probing is
1736 				 * needed to change it's state
1737 				 */
1738 				sdinfo->satadrv_state &= ~SATA_STATE_READY;
1739 				sdinfo->satadrv_state |=
1740 				    SATA_DSTATE_FAILED;
1741 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
1742 				    cport)->cport_mutex);
1743 				rv = EIO;
1744 			}
1745 			/*
1746 			 * Since the device was reset, we expect reset event
1747 			 * to be reported and processed.
1748 			 */
1749 			break;
1750 
1751 		case SATA_CFGA_RESET_ALL:
1752 		{
1753 			int tcport;
1754 
1755 			/*
1756 			 * There is no protection here for configured
1757 			 * devices.
1758 			 */
1759 			/* Sanity check */
1760 			if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
1761 				SATA_LOG_D((sata_hba_inst, CE_WARN,
1762 				    "sata_hba_ioctl: "
1763 				    "sata_hba_tran missing required "
1764 				    "function sata_tran_reset_dport"));
1765 				rv = EINVAL;
1766 				break;
1767 			}
1768 
1769 			/*
1770 			 * Need to lock all ports, not just one.
1771 			 * If any port is locked by event processing, fail
1772 			 * the whole operation.
1773 			 * One port is already locked, but for simplicity
1774 			 * lock it again.
1775 			 */
1776 			for (tcport = 0;
1777 			    tcport < SATA_NUM_CPORTS(sata_hba_inst);
1778 			    tcport++) {
1779 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
1780 				    tcport)->cport_mutex);
1781 				if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
1782 				    cport_event_flags) &
1783 				    SATA_EVNT_LOCK_PORT_BUSY) != 0) {
1784 					rv = EBUSY;
1785 					mutex_exit(
1786 					    &SATA_CPORT_INFO(sata_hba_inst,
1787 					    tcport)->cport_mutex);
1788 					break;
1789 				} else {
1790 					SATA_CPORT_INFO(sata_hba_inst,
1791 					    tcport)->cport_event_flags |=
1792 					    SATA_APCTL_LOCK_PORT_BUSY;
1793 				}
1794 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
1795 				    tcport)->cport_mutex);
1796 			}
1797 
1798 			if (rv == 0) {
1799 				/*
1800 				 * All cports successfully locked.
1801 				 * Reset main SATA controller only for now -
1802 				 * no PMult.
1803 				 */
1804 				sata_device.satadev_addr.qual =
1805 				    SATA_ADDR_CNTRL;
1806 
1807 				if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
1808 				    (dip, &sata_device) != SATA_SUCCESS) {
1809 					SATA_LOG_D((sata_hba_inst, CE_WARN,
1810 					    "sata_hba_ioctl: reset controller "
1811 					    "failed"));
1812 					rv = EIO;
1813 				}
1814 
1815 				/*
1816 				 * Since ports were reset, they should be
1817 				 * re-probed and attached devices
1818 				 * reinitialized.
1819 				 * At this point port states are unknown,
1820 				 * Re-probe ports to get their state -
1821 				 * cports only for now.
1822 				 */
1823 				for (tcport = 0;
1824 				    tcport < SATA_NUM_CPORTS(sata_hba_inst);
1825 				    tcport++) {
1826 					sata_device.satadev_addr.cport =
1827 					    tcport;
1828 					sata_device.satadev_addr.qual =
1829 					    SATA_ADDR_CPORT;
1830 
1831 					if (sata_reprobe_port(sata_hba_inst,
1832 					    &sata_device,
1833 					    SATA_DEV_IDENTIFY_RETRY) !=
1834 					    SATA_SUCCESS)
1835 						rv = EIO;
1836 
1837 				}
1838 			}
1839 			/*
1840 			 * Unlock all ports
1841 			 */
1842 			for (tcport = 0;
1843 			    tcport < SATA_NUM_CPORTS(sata_hba_inst);
1844 			    tcport++) {
1845 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
1846 				    tcport)->cport_mutex);
1847 				SATA_CPORT_INFO(sata_hba_inst, tcport)->
1848 				    cport_event_flags &=
1849 				    ~SATA_APCTL_LOCK_PORT_BUSY;
1850 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
1851 				    tcport)->cport_mutex);
1852 			}
1853 
1854 			/*
1855 			 * This operation returns EFAULT if either reset
1856 			 * controller failed or a re-probbing of any ports
1857 			 * failed.
1858 			 * We return here, because common return is for
1859 			 * a single cport operation.
1860 			 */
1861 			return (rv);
1862 		}
1863 
1864 		case SATA_CFGA_PORT_DEACTIVATE:
1865 			/* Sanity check */
1866 			if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
1867 				rv = ENOTSUP;
1868 				break;
1869 			}
1870 			/*
1871 			 * Arbitrarily unconfigure attached device, if any.
1872 			 * Even if the unconfigure fails, proceed with the
1873 			 * port deactivation.
1874 			 */
1875 
1876 			/* Handle only device attached to cports, for now */
1877 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
1878 
1879 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1880 			    cport_mutex);
1881 			cportinfo->cport_state &= ~SATA_STATE_READY;
1882 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
1883 				/*
1884 				 * Handle only device attached to cports,
1885 				 * for now
1886 				 */
1887 				sata_device.satadev_addr.qual =
1888 				    SATA_ADDR_DCPORT;
1889 				sdinfo = sata_get_device_info(sata_hba_inst,
1890 				    &sata_device);
1891 				if (sdinfo != NULL &&
1892 				    (sdinfo->satadrv_type &
1893 				    SATA_VALID_DEV_TYPE)) {
1894 					/*
1895 					 * If a target node exists, try to
1896 					 * offline a device and remove target
1897 					 * node.
1898 					 */
1899 					mutex_exit(&SATA_CPORT_INFO(
1900 					    sata_hba_inst, cport)->cport_mutex);
1901 					tdip = sata_get_target_dip(dip, cport);
1902 					if (tdip != NULL) {
1903 						/* target node exist */
1904 						SATADBG1(SATA_DBG_IOCTL_IF,
1905 						    sata_hba_inst,
1906 						    "sata_hba_ioctl: "
1907 						    "port deactivate: "
1908 						    "target node exists.",
1909 						    NULL);
1910 
1911 						if (ndi_devi_offline(tdip,
1912 						    NDI_UNCONFIG) !=
1913 						    NDI_SUCCESS) {
1914 							SATA_LOG_D((
1915 							    sata_hba_inst,
1916 							    CE_WARN,
1917 							    "sata_hba_ioctl:"
1918 							    "port deactivate: "
1919 							    "failed to "
1920 							    "unconfigure "
1921 							    "device at cport "
1922 							    "%d", cport));
1923 						}
1924 						if (ndi_devi_offline(tdip,
1925 						    NDI_DEVI_REMOVE) !=
1926 						    NDI_SUCCESS) {
1927 							/*
1928 							 * Problem;
1929 							 * target node remained
1930 							 * attached.
1931 							 * Too bad...
1932 							 */
1933 							SATA_LOG_D((
1934 							    sata_hba_inst,
1935 							    CE_WARN,
1936 							    "sata_hba_ioctl: "
1937 							    "port deactivate: "
1938 							    "failed to "
1939 							    "unconfigure "
1940 							    "device at "
1941 							    "cport %d",
1942 							    cport));
1943 						}
1944 					}
1945 					mutex_enter(&SATA_CPORT_INFO(
1946 					    sata_hba_inst, cport)->cport_mutex);
1947 					/*
1948 					 * In any case,
1949 					 * remove and release sata_drive_info
1950 					 * structure.
1951 					 * (cport attached device ony, for now)
1952 					 */
1953 					SATA_CPORTINFO_DRV_INFO(cportinfo) =
1954 					    NULL;
1955 					(void) kmem_free((void *)sdinfo,
1956 					    sizeof (sata_drive_info_t));
1957 					cportinfo->cport_dev_type =
1958 					    SATA_DTYPE_NONE;
1959 				}
1960 				/*
1961 				 * Note: PMult info requires different
1962 				 * handling. This comment is a placeholder for
1963 				 * a code handling PMult, to be implemented
1964 				 * in phase 2.
1965 				 */
1966 			}
1967 			cportinfo->cport_state &= ~(SATA_STATE_PROBED |
1968 			    SATA_STATE_PROBING);
1969 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1970 			    cport_mutex);
1971 			/* handle cport only for now */
1972 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
1973 			/* Just let HBA driver to deactivate port */
1974 			rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
1975 			    (dip, &sata_device);
1976 			/*
1977 			 * Generate sysevent -
1978 			 * EC_DR / ESC_DR_AP_STATE_CHANGE
1979 			 * without the hint
1980 			 */
1981 			sata_gen_sysevent(sata_hba_inst,
1982 			    &sata_device.satadev_addr, SE_NO_HINT);
1983 
1984 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1985 			    cport_mutex);
1986 			sata_update_port_info(sata_hba_inst, &sata_device);
1987 			if (rval != SATA_SUCCESS) {
1988 				/*
1989 				 * Port deactivation failure - do not
1990 				 * change port state unless the state
1991 				 * returned by HBA indicates a port failure.
1992 				 */
1993 				if (sata_device.satadev_state &
1994 				    SATA_PSTATE_FAILED) {
1995 					SATA_CPORT_STATE(sata_hba_inst,
1996 					    cport) = SATA_PSTATE_FAILED;
1997 				}
1998 				SATA_LOG_D((sata_hba_inst, CE_WARN,
1999 				    "sata_hba_ioctl: port deactivate: "
2000 				    "cannot deactivate SATA cport %d",
2001 				    cport));
2002 				rv = EIO;
2003 			} else {
2004 				cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
2005 			}
2006 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
2007 			    cport_mutex);
2008 
2009 			break;
2010 
2011 		case SATA_CFGA_PORT_ACTIVATE:
2012 		{
2013 			boolean_t dev_existed = TRUE;
2014 
2015 			/* Sanity check */
2016 			if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
2017 				rv = ENOTSUP;
2018 				break;
2019 			}
2020 			/* handle cport only for now */
2021 			if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
2022 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
2023 				dev_existed = FALSE;
2024 
2025 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2026 			/* Just let HBA driver to activate port */
2027 			if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
2028 			    (dip, &sata_device) != SATA_SUCCESS) {
2029 				/*
2030 				 * Port activation failure - do not
2031 				 * change port state unless the state
2032 				 * returned by HBA indicates a port failure.
2033 				 */
2034 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
2035 				    cport)->cport_mutex);
2036 				sata_update_port_info(sata_hba_inst,
2037 				    &sata_device);
2038 				if (sata_device.satadev_state &
2039 				    SATA_PSTATE_FAILED) {
2040 					SATA_CPORT_STATE(sata_hba_inst,
2041 					    cport) = SATA_PSTATE_FAILED;
2042 				}
2043 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
2044 				    cport)->cport_mutex);
2045 				SATA_LOG_D((sata_hba_inst, CE_WARN,
2046 				    "sata_hba_ioctl: port activate: "
2047 				    "cannot activate SATA cport %d",
2048 				    cport));
2049 				rv = EIO;
2050 				break;
2051 			}
2052 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
2053 			    cport_mutex);
2054 			cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
2055 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
2056 			    cport_mutex);
2057 
2058 			/*
2059 			 * Re-probe port to find its current state and
2060 			 * possibly attached device.
2061 			 * Port re-probing may change the cportinfo device
2062 			 * type if device is found attached.
2063 			 * If port probing failed, the device type would be
2064 			 * set to SATA_DTYPE_NONE.
2065 			 */
2066 			(void) sata_reprobe_port(sata_hba_inst, &sata_device,
2067 			    SATA_DEV_IDENTIFY_RETRY);
2068 
2069 			/*
2070 			 * Generate sysevent -
2071 			 * EC_DR / ESC_DR_AP_STATE_CHANGE
2072 			 * without the hint.
2073 			 */
2074 			sata_gen_sysevent(sata_hba_inst,
2075 			    &sata_device.satadev_addr, SE_NO_HINT);
2076 
2077 			if (dev_existed == FALSE &&
2078 			    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
2079 				/*
2080 				 * That's the transition from "inactive" port
2081 				 * state or active port without a device
2082 				 * attached to the active port state with
2083 				 * a device attached.
2084 				 */
2085 				sata_log(sata_hba_inst, CE_WARN,
2086 				    "SATA device detected at port %d", cport);
2087 			}
2088 
2089 			break;
2090 		}
2091 
2092 		case SATA_CFGA_PORT_SELF_TEST:
2093 
2094 			/* Sanity check */
2095 			if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL) {
2096 				rv = ENOTSUP;
2097 				break;
2098 			}
2099 			/*
2100 			 * There is no protection here for a configured
2101 			 * device attached to this port.
2102 			 */
2103 
2104 			/* only handle cport for now */
2105 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2106 
2107 			if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
2108 			    (dip, &sata_device) != SATA_SUCCESS) {
2109 				SATA_LOG_D((sata_hba_inst, CE_WARN,
2110 				    "sata_hba_ioctl: port selftest: "
2111 				    "failed cport %d pmport %d",
2112 				    cport, pmport));
2113 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
2114 				    cport)->cport_mutex);
2115 				sata_update_port_info(sata_hba_inst,
2116 				    &sata_device);
2117 				SATA_CPORT_STATE(sata_hba_inst, cport) =
2118 				    SATA_PSTATE_FAILED;
2119 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
2120 				    cport)->cport_mutex);
2121 				rv = EIO;
2122 				break;
2123 			}
2124 			/*
2125 			 * Since the port was reset, it should be probed and
2126 			 * attached device reinitialized. At this point the
2127 			 * port state is unknown - it's state is HBA-specific.
2128 			 * Force port re-probing to get it into a known state.
2129 			 */
2130 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
2131 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
2132 				rv = EIO;
2133 				break;
2134 			}
2135 			break;
2136 
2137 		case SATA_CFGA_GET_DEVICE_PATH:
2138 		{
2139 			char		path[MAXPATHLEN];
2140 			uint32_t	size;
2141 
2142 			(void) strcpy(path, "/devices");
2143 			if ((tdip = sata_get_target_dip(dip, ioc.port)) ==
2144 			    NULL) {
2145 
2146 				/*
2147 				 * No such device.
2148 				 * If this is a request for a size, do not
2149 				 * return EINVAL for non-exisiting target,
2150 				 * because cfgadm will indicate a meaningless
2151 				 * ioctl failure.
2152 				 * If this is a real request for a path,
2153 				 * indicate invalid argument.
2154 				 */
2155 				if (!ioc.get_size) {
2156 					rv = EINVAL;
2157 					break;
2158 				}
2159 			} else {
2160 				(void) ddi_pathname(tdip, path + strlen(path));
2161 			}
2162 			size = strlen(path) + 1;
2163 
2164 			if (ioc.get_size) {
2165 				if (ddi_copyout((void *)&size,
2166 				    ioc.buf, ioc.bufsiz, mode) != 0) {
2167 					rv = EFAULT;
2168 				}
2169 			} else {
2170 				if (ioc.bufsiz != size) {
2171 					rv = EINVAL;
2172 				} else if (ddi_copyout((void *)&path,
2173 				    ioc.buf, ioc.bufsiz, mode) != 0) {
2174 					rv = EFAULT;
2175 				}
2176 			}
2177 			break;
2178 		}
2179 
2180 		case SATA_CFGA_GET_AP_TYPE:
2181 		{
2182 			uint32_t	type_len;
2183 			const char	*ap_type;
2184 
2185 			/* cport only, no port multiplier support */
2186 			switch (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport)) {
2187 			case SATA_DTYPE_NONE:
2188 				ap_type = "port";
2189 				break;
2190 
2191 			case SATA_DTYPE_ATADISK:
2192 				ap_type = "disk";
2193 				break;
2194 
2195 			case SATA_DTYPE_ATAPICD:
2196 				ap_type = "cd/dvd";
2197 				break;
2198 
2199 			case SATA_DTYPE_PMULT:
2200 				ap_type = "pmult";
2201 				break;
2202 
2203 			case SATA_DTYPE_UNKNOWN:
2204 				ap_type = "unknown";
2205 				break;
2206 
2207 			default:
2208 				ap_type = "unsupported";
2209 				break;
2210 
2211 			} /* end of dev_type switch */
2212 
2213 			type_len = strlen(ap_type) + 1;
2214 
2215 			if (ioc.get_size) {
2216 				if (ddi_copyout((void *)&type_len,
2217 				    ioc.buf, ioc.bufsiz, mode) != 0) {
2218 					rv = EFAULT;
2219 					break;
2220 				}
2221 			} else {
2222 				if (ioc.bufsiz != type_len) {
2223 					rv = EINVAL;
2224 					break;
2225 				}
2226 				if (ddi_copyout((void *)ap_type, ioc.buf,
2227 				    ioc.bufsiz, mode) != 0) {
2228 					rv = EFAULT;
2229 					break;
2230 				}
2231 			}
2232 
2233 			break;
2234 		}
2235 
2236 		case SATA_CFGA_GET_MODEL_INFO:
2237 		{
2238 			uint32_t info_len;
2239 			char ap_info[sizeof (sdinfo->satadrv_id.ai_model) + 1];
2240 
2241 			/*
2242 			 * This operation should return to cfgadm the
2243 			 * device model information string
2244 			 */
2245 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
2246 			    cport_mutex);
2247 			/* only handle device connected to cport for now */
2248 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
2249 			sdinfo = sata_get_device_info(sata_hba_inst,
2250 			    &sata_device);
2251 			if (sdinfo == NULL) {
2252 				rv = EINVAL;
2253 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
2254 				    cport)->cport_mutex);
2255 				break;
2256 			}
2257 			bcopy(sdinfo->satadrv_id.ai_model, ap_info,
2258 			    sizeof (sdinfo->satadrv_id.ai_model));
2259 			swab(ap_info, ap_info,
2260 			    sizeof (sdinfo->satadrv_id.ai_model));
2261 			ap_info[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
2262 
2263 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
2264 			    cport_mutex);
2265 
2266 			info_len = strlen(ap_info) + 1;
2267 
2268 			if (ioc.get_size) {
2269 				if (ddi_copyout((void *)&info_len,
2270 				    ioc.buf, ioc.bufsiz, mode) != 0) {
2271 					rv = EFAULT;
2272 					break;
2273 				}
2274 			} else {
2275 				if (ioc.bufsiz < info_len) {
2276 					rv = EINVAL;
2277 					break;
2278 				}
2279 				if (ddi_copyout((void *)ap_info, ioc.buf,
2280 				    ioc.bufsiz, mode) != 0) {
2281 					rv = EFAULT;
2282 					break;
2283 				}
2284 			}
2285 
2286 			break;
2287 		}
2288 
2289 		case SATA_CFGA_GET_REVFIRMWARE_INFO:
2290 		{
2291 			uint32_t info_len;
2292 			char ap_info[
2293 			    sizeof (sdinfo->satadrv_id.ai_fw) + 1];
2294 
2295 			/*
2296 			 * This operation should return to cfgadm the
2297 			 * device firmware revision information string
2298 			 */
2299 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
2300 			    cport_mutex);
2301 			/* only handle device connected to cport for now */
2302 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
2303 
2304 			sdinfo = sata_get_device_info(sata_hba_inst,
2305 			    &sata_device);
2306 			if (sdinfo == NULL) {
2307 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
2308 				    cport)->cport_mutex);
2309 				rv = EINVAL;
2310 				break;
2311 			}
2312 			bcopy(sdinfo->satadrv_id.ai_fw, ap_info,
2313 			    sizeof (sdinfo->satadrv_id.ai_fw));
2314 			swab(ap_info, ap_info,
2315 			    sizeof (sdinfo->satadrv_id.ai_fw));
2316 			ap_info[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
2317 
2318 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
2319 			    cport_mutex);
2320 
2321 			info_len = strlen(ap_info) + 1;
2322 
2323 			if (ioc.get_size) {
2324 				if (ddi_copyout((void *)&info_len,
2325 				    ioc.buf, ioc.bufsiz, mode) != 0) {
2326 					rv = EFAULT;
2327 					break;
2328 				}
2329 			} else {
2330 				if (ioc.bufsiz < info_len) {
2331 					rv = EINVAL;
2332 					break;
2333 				}
2334 				if (ddi_copyout((void *)ap_info, ioc.buf,
2335 				    ioc.bufsiz, mode) != 0) {
2336 					rv = EFAULT;
2337 					break;
2338 				}
2339 			}
2340 
2341 			break;
2342 		}
2343 
2344 		case SATA_CFGA_GET_SERIALNUMBER_INFO:
2345 		{
2346 			uint32_t info_len;
2347 			char ap_info[
2348 			    sizeof (sdinfo->satadrv_id.ai_drvser) + 1];
2349 
2350 			/*
2351 			 * This operation should return to cfgadm the
2352 			 * device serial number information string
2353 			 */
2354 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
2355 			    cport_mutex);
2356 			/* only handle device connected to cport for now */
2357 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
2358 
2359 			sdinfo = sata_get_device_info(sata_hba_inst,
2360 			    &sata_device);
2361 			if (sdinfo == NULL) {
2362 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
2363 				    cport)->cport_mutex);
2364 				rv = EINVAL;
2365 				break;
2366 			}
2367 			bcopy(sdinfo->satadrv_id.ai_drvser, ap_info,
2368 			    sizeof (sdinfo->satadrv_id.ai_drvser));
2369 			swab(ap_info, ap_info,
2370 			    sizeof (sdinfo->satadrv_id.ai_drvser));
2371 			ap_info[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
2372 
2373 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
2374 			    cport_mutex);
2375 
2376 			info_len = strlen(ap_info) + 1;
2377 
2378 			if (ioc.get_size) {
2379 				if (ddi_copyout((void *)&info_len,
2380 				    ioc.buf, ioc.bufsiz, mode) != 0) {
2381 					rv = EFAULT;
2382 					break;
2383 				}
2384 			} else {
2385 				if (ioc.bufsiz < info_len) {
2386 					rv = EINVAL;
2387 					break;
2388 				}
2389 				if (ddi_copyout((void *)ap_info, ioc.buf,
2390 				    ioc.bufsiz, mode) != 0) {
2391 					rv = EFAULT;
2392 					break;
2393 				}
2394 			}
2395 
2396 			break;
2397 		}
2398 
2399 		default:
2400 			rv = EINVAL;
2401 			break;
2402 
2403 		} /* End of DEVCTL_AP_CONTROL cmd switch */
2404 
2405 		break;
2406 	}
2407 
2408 	default:
2409 	{
2410 		/*
2411 		 * If we got here, we got an IOCTL that SATA HBA Framework
2412 		 * does not recognize. Pass ioctl to HBA driver, in case
2413 		 * it could process it.
2414 		 */
2415 		sata_hba_tran_t *sata_tran = sata_hba_inst->satahba_tran;
2416 		dev_info_t	*mydip = SATA_DIP(sata_hba_inst);
2417 
2418 		SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
2419 		    "IOCTL 0x%2x not supported in SATA framework, "
2420 		    "passthrough to HBA", cmd);
2421 
2422 		if (sata_tran->sata_tran_ioctl == NULL) {
2423 			rv = EINVAL;
2424 			break;
2425 		}
2426 		rval = (*sata_tran->sata_tran_ioctl)(mydip, cmd, arg);
2427 		if (rval != 0) {
2428 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
2429 			    "IOCTL 0x%2x failed in HBA", cmd);
2430 			rv = rval;
2431 		}
2432 		break;
2433 	}
2434 
2435 	} /* End of main IOCTL switch */
2436 
2437 	if (dcp) {
2438 		ndi_dc_freehdl(dcp);
2439 	}
2440 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
2441 	cportinfo->cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
2442 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
2443 
2444 	return (rv);
2445 }
2446 
2447 
2448 
2449 
2450 /* ****************** SCSA required entry points *********************** */
2451 
2452 /*
2453  * Implementation of scsi tran_tgt_init.
2454  * sata_scsi_tgt_init() initializes scsi_device structure
2455  *
2456  * If successful, DDI_SUCCESS is returned.
2457  * DDI_FAILURE is returned if addressed device does not exist
2458  */
2459 
2460 static int
2461 sata_scsi_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
2462     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
2463 {
2464 #ifndef __lock_lint
2465 	_NOTE(ARGUNUSED(hba_dip))
2466 #endif
2467 	sata_device_t		sata_device;
2468 	sata_drive_info_t	*sdinfo;
2469 	sata_hba_inst_t		*sata_hba_inst;
2470 
2471 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
2472 
2473 	/* Validate scsi device address */
2474 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
2475 	    &sata_device) != 0)
2476 		return (DDI_FAILURE);
2477 
2478 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2479 	    sata_device.satadev_addr.cport)));
2480 
2481 	/* sata_device now contains a valid sata address */
2482 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
2483 	if (sdinfo == NULL) {
2484 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2485 		    sata_device.satadev_addr.cport)));
2486 		return (DDI_FAILURE);
2487 	}
2488 	if (sata_device.satadev_type == SATA_DTYPE_ATAPICD) {
2489 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2490 		    sata_device.satadev_addr.cport)));
2491 		if (ndi_prop_update_string(DDI_DEV_T_NONE, tgt_dip,
2492 		    "variant", "atapi") != DDI_PROP_SUCCESS) {
2493 			SATA_LOG_D((sata_hba_inst, CE_WARN,
2494 			    "sata_scsi_tgt_init: variant atapi "
2495 			    "property could not be created"));
2496 			return (DDI_FAILURE);
2497 		}
2498 		return (DDI_SUCCESS);
2499 	}
2500 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2501 	    sata_device.satadev_addr.cport)));
2502 	return (DDI_SUCCESS);
2503 }
2504 
2505 /*
2506  * Implementation of scsi tran_tgt_probe.
2507  * Probe target, by calling default scsi routine scsi_hba_probe()
2508  */
2509 static int
2510 sata_scsi_tgt_probe(struct scsi_device *sd, int (*callback)(void))
2511 {
2512 	sata_hba_inst_t *sata_hba_inst =
2513 	    (sata_hba_inst_t *)(sd->sd_address.a_hba_tran->tran_hba_private);
2514 	int rval;
2515 
2516 	rval = scsi_hba_probe(sd, callback);
2517 
2518 	if (rval == SCSIPROBE_EXISTS) {
2519 		/*
2520 		 * Set property "pm-capable" on the target device node, so that
2521 		 * the target driver will not try to fetch scsi cycle counters
2522 		 * before enabling device power-management.
2523 		 */
2524 		if ((ddi_prop_update_int(DDI_DEV_T_NONE, sd->sd_dev,
2525 		    "pm-capable", 1)) != DDI_PROP_SUCCESS) {
2526 			sata_log(sata_hba_inst, CE_WARN,
2527 			"device at port %d: will not be power-managed ",
2528 			SCSI_TO_SATA_CPORT(sd->sd_address.a_target));
2529 			SATA_LOG_D((sata_hba_inst, CE_WARN,
2530 			"failure updating pm-capable property"));
2531 		}
2532 	}
2533 	return (rval);
2534 }
2535 
2536 /*
2537  * Implementation of scsi tran_tgt_free.
2538  * Release all resources allocated for scsi_device
2539  */
2540 static void
2541 sata_scsi_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
2542     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
2543 {
2544 #ifndef __lock_lint
2545 	_NOTE(ARGUNUSED(hba_dip))
2546 #endif
2547 	sata_device_t		sata_device;
2548 	sata_drive_info_t	*sdinfo;
2549 	sata_hba_inst_t		*sata_hba_inst;
2550 
2551 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
2552 
2553 	/* Validate scsi device address */
2554 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
2555 	    &sata_device) != 0)
2556 		return;
2557 
2558 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2559 	    sata_device.satadev_addr.cport)));
2560 
2561 	/* sata_device now should contain a valid sata address */
2562 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
2563 	if (sdinfo == NULL) {
2564 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2565 		    sata_device.satadev_addr.cport)));
2566 		return;
2567 	}
2568 	/*
2569 	 * We did not allocate any resources in sata_scsi_tgt_init()
2570 	 * other than property for ATAPI device, if any
2571 	 */
2572 	if (sata_device.satadev_type == SATA_DTYPE_ATAPICD) {
2573 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2574 		    sata_device.satadev_addr.cport)));
2575 		if (ndi_prop_remove(DDI_DEV_T_NONE, tgt_dip, "variant") !=
2576 		    DDI_PROP_SUCCESS)
2577 			SATA_LOG_D((sata_hba_inst, CE_WARN,
2578 			    "sata_scsi_tgt_free: variant atapi "
2579 			    "property could not be removed"));
2580 	} else {
2581 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2582 		    sata_device.satadev_addr.cport)));
2583 	}
2584 }
2585 
2586 /*
2587  * Implementation of scsi tran_init_pkt
2588  * Upon successful return, scsi pkt buffer has DMA resources allocated.
2589  *
2590  * It seems that we should always allocate pkt, even if the address is
2591  * for non-existing device - just use some default for dma_attr.
2592  * The reason is that there is no way to communicate this to a caller here.
2593  * Subsequent call to sata_scsi_start may fail appropriately.
2594  * Simply returning NULL does not seem to discourage a target driver...
2595  *
2596  * Returns a pointer to initialized scsi_pkt, or NULL otherwise.
2597  */
2598 static struct scsi_pkt *
2599 sata_scsi_init_pkt(struct scsi_address *ap, struct scsi_pkt *pkt,
2600     struct buf *bp, int cmdlen, int statuslen, int tgtlen, int flags,
2601     int (*callback)(caddr_t), caddr_t arg)
2602 {
2603 	sata_hba_inst_t *sata_hba_inst =
2604 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2605 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
2606 	sata_device_t sata_device;
2607 	sata_drive_info_t *sdinfo;
2608 	sata_pkt_txlate_t *spx;
2609 	ddi_dma_attr_t cur_dma_attr;
2610 	int rval;
2611 	boolean_t new_pkt = TRUE;
2612 
2613 	ASSERT(ap->a_hba_tran->tran_hba_dip == dip);
2614 
2615 	/*
2616 	 * We need to translate the address, even if it could be
2617 	 * a bogus one, for a non-existing device
2618 	 */
2619 	sata_device.satadev_addr.qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
2620 	sata_device.satadev_addr.cport = SCSI_TO_SATA_CPORT(ap->a_target);
2621 	sata_device.satadev_addr.pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2622 	sata_device.satadev_rev = SATA_DEVICE_REV;
2623 
2624 	if (pkt == NULL) {
2625 		/*
2626 		 * Have to allocate a brand new scsi packet.
2627 		 * We need to operate with auto request sense enabled.
2628 		 */
2629 		pkt = scsi_hba_pkt_alloc(dip, ap, cmdlen,
2630 		    MAX(statuslen, sizeof (struct scsi_arq_status)),
2631 		    tgtlen, sizeof (sata_pkt_txlate_t), callback, arg);
2632 
2633 		if (pkt == NULL)
2634 			return (NULL);
2635 
2636 		/* Fill scsi packet structure */
2637 		pkt->pkt_comp		= (void (*)())NULL;
2638 		pkt->pkt_time		= 0;
2639 		pkt->pkt_resid		= 0;
2640 		pkt->pkt_statistics	= 0;
2641 		pkt->pkt_reason		= 0;
2642 
2643 		/*
2644 		 * pkt_hba_private will point to sata pkt txlate structure
2645 		 */
2646 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2647 		bzero(spx, sizeof (sata_pkt_txlate_t));
2648 
2649 		spx->txlt_scsi_pkt = pkt;
2650 		spx->txlt_sata_hba_inst = sata_hba_inst;
2651 
2652 		/* Allocate sata_pkt */
2653 		spx->txlt_sata_pkt = sata_pkt_alloc(spx, callback);
2654 		if (spx->txlt_sata_pkt == NULL) {
2655 			/* Could not allocate sata pkt */
2656 			scsi_hba_pkt_free(ap, pkt);
2657 			return (NULL);
2658 		}
2659 		/* Set sata address */
2660 		spx->txlt_sata_pkt->satapkt_device.satadev_addr =
2661 		    sata_device.satadev_addr;
2662 		spx->txlt_sata_pkt->satapkt_device.satadev_rev =
2663 		    sata_device.satadev_rev;
2664 
2665 		if ((bp == NULL) || (bp->b_bcount == 0))
2666 			return (pkt);
2667 
2668 		spx->txlt_total_residue = bp->b_bcount;
2669 	} else {
2670 		new_pkt = FALSE;
2671 		/*
2672 		 * Packet was preallocated/initialized by previous call
2673 		 */
2674 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2675 
2676 		if ((bp == NULL) || (bp->b_bcount == 0)) {
2677 			return (pkt);
2678 		}
2679 		ASSERT(spx->txlt_buf_dma_handle != NULL);
2680 
2681 		/* Pkt is available already: spx->txlt_scsi_pkt == pkt; */
2682 	}
2683 
2684 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
2685 
2686 	/*
2687 	 * We use an adjusted version of the dma_attr, to account
2688 	 * for device addressing limitations.
2689 	 * sata_adjust_dma_attr() will handle sdinfo == NULL which may
2690 	 * happen when a device is not yet configured.
2691 	 */
2692 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2693 	    sata_device.satadev_addr.cport)));
2694 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
2695 	    &spx->txlt_sata_pkt->satapkt_device);
2696 	/* NULL sdinfo may be passsed to sata_adjust_dma_attr() */
2697 	sata_adjust_dma_attr(sdinfo,
2698 	    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
2699 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2700 	    sata_device.satadev_addr.cport)));
2701 	/*
2702 	 * Allocate necessary DMA resources for the packet's buffer
2703 	 */
2704 	if ((rval = sata_dma_buf_setup(spx, flags, callback, arg,
2705 	    &cur_dma_attr)) != DDI_SUCCESS) {
2706 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2707 		sata_pkt_free(spx);
2708 		/*
2709 		 * If a DMA allocation request fails with
2710 		 * DDI_DMA_NOMAPPING, indicate the error by calling
2711 		 * bioerror(9F) with bp and an error code of EFAULT.
2712 		 * If a DMA allocation request fails with
2713 		 * DDI_DMA_TOOBIG, indicate the error by calling
2714 		 * bioerror(9F) with bp and an error code of EINVAL.
2715 		 */
2716 		switch (rval) {
2717 		case DDI_DMA_NORESOURCES:
2718 			bioerror(bp, 0);
2719 			break;
2720 		case DDI_DMA_NOMAPPING:
2721 		case DDI_DMA_BADATTR:
2722 			bioerror(bp, EFAULT);
2723 			break;
2724 		case DDI_DMA_TOOBIG:
2725 		default:
2726 			bioerror(bp, EINVAL);
2727 			break;
2728 		}
2729 		if (new_pkt == TRUE)
2730 			scsi_hba_pkt_free(ap, pkt);
2731 		return (NULL);
2732 	}
2733 	/* Set number of bytes that are not yet accounted for */
2734 	pkt->pkt_resid = spx->txlt_total_residue;
2735 	ASSERT(pkt->pkt_resid >= 0);
2736 
2737 	return (pkt);
2738 }
2739 
2740 /*
2741  * Implementation of scsi tran_start.
2742  * Translate scsi cmd into sata operation and return status.
2743  * Supported scsi commands:
2744  * SCMD_INQUIRY
2745  * SCMD_TEST_UNIT_READY
2746  * SCMD_START_STOP
2747  * SCMD_READ_CAPACITY
2748  * SCMD_REQUEST_SENSE
2749  * SCMD_LOG_SENSE_G1
2750  * SCMD_LOG_SELECT_G1
2751  * SCMD_MODE_SENSE	(specific pages)
2752  * SCMD_MODE_SENSE_G1	(specific pages)
2753  * SCMD_MODE_SELECT	(specific pages)
2754  * SCMD_MODE_SELECT_G1	(specific pages)
2755  * SCMD_SYNCHRONIZE_CACHE
2756  * SCMD_SYNCHRONIZE_CACHE_G1
2757  * SCMD_READ
2758  * SCMD_READ_G1
2759  * SCMD_READ_G4
2760  * SCMD_READ_G5
2761  * SCMD_WRITE
2762  * SCMD_WRITE_G1
2763  * SCMD_WRITE_G4
2764  * SCMD_WRITE_G5
2765  * SCMD_SEEK		(noop)
2766  * SCMD_SDIAG
2767  *
2768  * All other commands are rejected as unsupported.
2769  *
2770  * Returns:
2771  * TRAN_ACCEPT if command was executed successfully or accepted by HBA driver
2772  * for execution.
2773  * TRAN_BADPKT if cmd was directed to invalid address.
2774  * TRAN_FATAL_ERROR is command was rejected due to hardware error, including
2775  * unexpected removal of a device or some other unspecified error.
2776  * TRAN_BUSY if command could not be executed becasue HBA driver or SATA
2777  * framework was busy performing some other operation(s).
2778  *
2779  */
2780 static int
2781 sata_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
2782 {
2783 	sata_hba_inst_t *sata_hba_inst =
2784 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2785 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2786 	sata_drive_info_t *sdinfo;
2787 	struct buf *bp;
2788 	int cport;
2789 	int rval;
2790 
2791 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2792 	    "sata_scsi_start: cmd 0x%02x\n", pkt->pkt_cdbp[0]);
2793 
2794 	ASSERT(spx != NULL &&
2795 	    spx->txlt_scsi_pkt == pkt && spx->txlt_sata_pkt != NULL);
2796 
2797 	/*
2798 	 * Mutex-protected section below is just to identify device type
2799 	 * and switch to ATAPI processing, if necessary
2800 	 */
2801 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
2802 
2803 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2804 
2805 	sdinfo = sata_get_device_info(sata_hba_inst,
2806 	    &spx->txlt_sata_pkt->satapkt_device);
2807 	if (sdinfo == NULL) {
2808 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2809 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
2810 		return (TRAN_FATAL_ERROR);
2811 	}
2812 
2813 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
2814 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2815 		rval = sata_txlt_atapi(spx);
2816 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2817 		    "sata_scsi_start atapi: rval %d\n", rval);
2818 		return (rval);
2819 	}
2820 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2821 
2822 	/* ATA Disk commands processing starts here */
2823 
2824 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2825 
2826 	switch (pkt->pkt_cdbp[0]) {
2827 
2828 	case SCMD_INQUIRY:
2829 		/* Mapped to identify device */
2830 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2831 			bp_mapin(bp);
2832 		rval = sata_txlt_inquiry(spx);
2833 		break;
2834 
2835 	case SCMD_TEST_UNIT_READY:
2836 		/*
2837 		 * SAT "SATA to ATA Translation" doc specifies translation
2838 		 * to ATA CHECK POWER MODE.
2839 		 */
2840 		rval = sata_txlt_test_unit_ready(spx);
2841 		break;
2842 
2843 	case SCMD_START_STOP:
2844 		/* Mapping depends on the command */
2845 		rval = sata_txlt_start_stop_unit(spx);
2846 		break;
2847 
2848 	case SCMD_READ_CAPACITY:
2849 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2850 			bp_mapin(bp);
2851 		rval = sata_txlt_read_capacity(spx);
2852 		break;
2853 
2854 	case SCMD_REQUEST_SENSE:
2855 		/*
2856 		 * Always No Sense, since we force ARQ
2857 		 */
2858 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2859 			bp_mapin(bp);
2860 		rval = sata_txlt_request_sense(spx);
2861 		break;
2862 
2863 	case SCMD_LOG_SENSE_G1:
2864 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2865 			bp_mapin(bp);
2866 		rval = sata_txlt_log_sense(spx);
2867 		break;
2868 
2869 	case SCMD_LOG_SELECT_G1:
2870 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2871 			bp_mapin(bp);
2872 		rval = sata_txlt_log_select(spx);
2873 		break;
2874 
2875 	case SCMD_MODE_SENSE:
2876 	case SCMD_MODE_SENSE_G1:
2877 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2878 			bp_mapin(bp);
2879 		rval = sata_txlt_mode_sense(spx);
2880 		break;
2881 
2882 
2883 	case SCMD_MODE_SELECT:
2884 	case SCMD_MODE_SELECT_G1:
2885 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2886 			bp_mapin(bp);
2887 		rval = sata_txlt_mode_select(spx);
2888 		break;
2889 
2890 	case SCMD_SYNCHRONIZE_CACHE:
2891 	case SCMD_SYNCHRONIZE_CACHE_G1:
2892 		rval = sata_txlt_synchronize_cache(spx);
2893 		break;
2894 
2895 	case SCMD_READ:
2896 	case SCMD_READ_G1:
2897 	case SCMD_READ_G4:
2898 	case SCMD_READ_G5:
2899 		rval = sata_txlt_read(spx);
2900 		break;
2901 
2902 	case SCMD_WRITE:
2903 	case SCMD_WRITE_G1:
2904 	case SCMD_WRITE_G4:
2905 	case SCMD_WRITE_G5:
2906 		rval = sata_txlt_write(spx);
2907 		break;
2908 
2909 	case SCMD_SEEK:
2910 		rval = sata_txlt_nodata_cmd_immediate(spx);
2911 		break;
2912 
2913 		/* Other cases will be filed later */
2914 		/* postponed until phase 2 of the development */
2915 	default:
2916 		rval = sata_txlt_invalid_command(spx);
2917 		break;
2918 	}
2919 
2920 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2921 	    "sata_scsi_start: rval %d\n", rval);
2922 
2923 	return (rval);
2924 }
2925 
2926 /*
2927  * Implementation of scsi tran_abort.
2928  * Abort specific pkt or all packets.
2929  *
2930  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2931  *
2932  * May be called from an interrupt level.
2933  */
2934 static int
2935 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2936 {
2937 	sata_hba_inst_t *sata_hba_inst =
2938 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2939 	sata_device_t	sata_device;
2940 	sata_pkt_t	*sata_pkt;
2941 
2942 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2943 	    "sata_scsi_abort: %s at target: 0x%x\n",
2944 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2945 
2946 	/* Validate address */
2947 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2948 		/* Invalid address */
2949 		return (0);
2950 
2951 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2952 	    sata_device.satadev_addr.cport)));
2953 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2954 		/* invalid address */
2955 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2956 		    sata_device.satadev_addr.cport)));
2957 		return (0);
2958 	}
2959 	if (scsi_pkt == NULL) {
2960 		/*
2961 		 * Abort all packets.
2962 		 * Although we do not have specific packet, we still need
2963 		 * dummy packet structure to pass device address to HBA.
2964 		 * Allocate one, without sleeping. Fail if pkt cannot be
2965 		 * allocated.
2966 		 */
2967 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2968 		if (sata_pkt == NULL) {
2969 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2970 			    sata_device.satadev_addr.cport)));
2971 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2972 			    "could not allocate sata_pkt"));
2973 			return (0);
2974 		}
2975 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2976 		sata_pkt->satapkt_device = sata_device;
2977 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2978 	} else {
2979 		if (scsi_pkt->pkt_ha_private == NULL) {
2980 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2981 			    sata_device.satadev_addr.cport)));
2982 			return (0); /* Bad scsi pkt */
2983 		}
2984 		/* extract pointer to sata pkt */
2985 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2986 		    txlt_sata_pkt;
2987 	}
2988 
2989 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2990 	    sata_device.satadev_addr.cport)));
2991 	/* Send abort request to HBA */
2992 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2993 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2994 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2995 	    SATA_SUCCESS) {
2996 		if (scsi_pkt == NULL)
2997 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2998 		/* Success */
2999 		return (1);
3000 	}
3001 	/* Else, something did not go right */
3002 	if (scsi_pkt == NULL)
3003 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
3004 	/* Failure */
3005 	return (0);
3006 }
3007 
3008 
3009 /*
3010  * Implementation os scsi tran_reset.
3011  * RESET_ALL request is translated into port reset.
3012  * RESET_TARGET requests is translated into a device reset,
3013  * RESET_LUN request is accepted only for LUN 0 and translated into
3014  * device reset.
3015  * The target reset should cause all HBA active and queued packets to
3016  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
3017  * the return. HBA should report reset event for the device.
3018  *
3019  * Returns 1 upon success, 0 upon failure.
3020  */
3021 static int
3022 sata_scsi_reset(struct scsi_address *ap, int level)
3023 {
3024 	sata_hba_inst_t	*sata_hba_inst =
3025 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
3026 	sata_device_t	sata_device;
3027 	int		val;
3028 
3029 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
3030 	    "sata_scsi_reset: level %d target: 0x%x\n",
3031 	    level, ap->a_target);
3032 
3033 	/* Validate address */
3034 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
3035 	if (val == -1)
3036 		/* Invalid address */
3037 		return (0);
3038 
3039 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
3040 	    sata_device.satadev_addr.cport)));
3041 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
3042 		/* invalid address */
3043 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
3044 		    sata_device.satadev_addr.cport)));
3045 		return (0);
3046 	}
3047 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
3048 	    sata_device.satadev_addr.cport)));
3049 	if (level == RESET_ALL) {
3050 		/* port reset - cport only */
3051 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
3052 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
3053 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
3054 			return (1);
3055 		else
3056 			return (0);
3057 
3058 	} else if (val == 0 &&
3059 	    (level == RESET_TARGET || level == RESET_LUN)) {
3060 		/* reset device (device attached) */
3061 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
3062 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
3063 			return (1);
3064 		else
3065 			return (0);
3066 	}
3067 	return (0);
3068 }
3069 
3070 
3071 /*
3072  * Implementation of scsi tran_getcap (get transport/device capabilities).
3073  * Supported capabilities:
3074  * auto-rqsense		(always supported)
3075  * tagged-qing		(supported if HBA supports it)
3076  * untagged-qing	(could be supported if disk supports it, but because
3077  *			 caching behavior allowing untagged queuing actually
3078  *			 results in reduced performance.  sd tries to throttle
3079  *			 back to only 3 outstanding commands, which may
3080  *			 work for real SCSI disks, but with read ahead
3081  *			 caching, having more than 1 outstanding command
3082  *			 results in cache thrashing.)
3083  * dma_max
3084  * interconnect-type	(INTERCONNECT_SATA)
3085  *
3086  * Request for other capabilities is rejected as unsupported.
3087  *
3088  * Returns supported capability value, or -1 if capability is unsuppported or
3089  * the address is invalid (no device).
3090  */
3091 
3092 static int
3093 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
3094 {
3095 
3096 	sata_hba_inst_t 	*sata_hba_inst =
3097 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
3098 	sata_device_t		sata_device;
3099 	sata_drive_info_t	*sdinfo;
3100 	ddi_dma_attr_t		adj_dma_attr;
3101 	int 			rval;
3102 
3103 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
3104 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
3105 	    ap->a_target, cap);
3106 
3107 	/*
3108 	 * We want to process the capabilities on per port granularity.
3109 	 * So, we are specifically restricting ourselves to whom != 0
3110 	 * to exclude the controller wide handling.
3111 	 */
3112 	if (cap == NULL || whom == 0)
3113 		return (-1);
3114 
3115 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
3116 		/* Invalid address */
3117 		return (-1);
3118 	}
3119 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
3120 	    sata_device.satadev_addr.cport)));
3121 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
3122 	    NULL) {
3123 		/* invalid address */
3124 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
3125 		    sata_device.satadev_addr.cport)));
3126 		return (0);
3127 	}
3128 
3129 	switch (scsi_hba_lookup_capstr(cap)) {
3130 	case SCSI_CAP_ARQ:
3131 		rval = 1;		/* ARQ supported, turned on */
3132 		break;
3133 
3134 	case SCSI_CAP_SECTOR_SIZE:
3135 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
3136 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
3137 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
3138 			rval = SATA_ATAPI_SECTOR_SIZE;
3139 		else rval = -1;
3140 		break;
3141 
3142 	/*
3143 	 * untagged queuing cause a performance inversion because of
3144 	 * the way sd operates.  Because of this reason we do not
3145 	 * use it when available.
3146 	 */
3147 #if defined(_UNTAGGED_QING_SUPPORTED)
3148 	case SCSI_CAP_UNTAGGED_QING:
3149 		if (SATA_QDEPTH(sata_hba_inst) > 1)
3150 			rval = 1;	/* Untagged queuing supported */
3151 		else
3152 			rval = -1;	/* Untagged queuing not supported */
3153 		break;
3154 #endif
3155 
3156 	case SCSI_CAP_TAGGED_QING:
3157 		/* This can TCQ or NCQ */
3158 		if (sata_func_enable & SATA_ENABLE_QUEUING &&
3159 		    ((sdinfo->satadrv_features_support & SATA_DEV_F_TCQ &&
3160 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_QCMD) ||
3161 		    (sata_func_enable & SATA_ENABLE_NCQ &&
3162 		    sdinfo->satadrv_features_support & SATA_DEV_F_NCQ &&
3163 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_NCQ)))
3164 			rval = 1;	/* Tagged queuing supported */
3165 		else
3166 			rval = -1;	/* Tagged queuing not supported */
3167 		break;
3168 
3169 	case SCSI_CAP_DMA_MAX:
3170 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
3171 		    &adj_dma_attr);
3172 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
3173 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
3174 		break;
3175 
3176 	case SCSI_CAP_INTERCONNECT_TYPE:
3177 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
3178 		break;
3179 
3180 	default:
3181 		rval = -1;
3182 		break;
3183 	}
3184 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
3185 	    sata_device.satadev_addr.cport)));
3186 	return (rval);
3187 }
3188 
3189 /*
3190  * Implementation of scsi tran_setcap
3191  *
3192  * All supported capabilities are fixed/unchangeable.
3193  * Returns 0 for all supported capabilities and valid device, -1 otherwise.
3194  */
3195 static int
3196 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
3197 {
3198 #ifndef __lock_lint
3199 	_NOTE(ARGUNUSED(value))
3200 #endif
3201 	sata_hba_inst_t	*sata_hba_inst =
3202 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
3203 	sata_device_t	sata_device;
3204 	int		rval;
3205 
3206 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
3207 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
3208 
3209 	/*
3210 	 * We want to process the capabilities on per port granularity.
3211 	 * So, we are specifically restricting ourselves to whom != 0
3212 	 * to exclude the controller wide handling.
3213 	 */
3214 	if (cap == NULL || whom == 0) {
3215 		return (-1);
3216 	}
3217 
3218 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
3219 		/* Invalid address */
3220 		return (-1);
3221 	}
3222 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
3223 	    sata_device.satadev_addr.cport)));
3224 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
3225 		/* invalid address */
3226 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
3227 		    sata_device.satadev_addr.cport)));
3228 		return (0);
3229 	}
3230 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
3231 	    sata_device.satadev_addr.cport)));
3232 
3233 	switch (scsi_hba_lookup_capstr(cap)) {
3234 	case SCSI_CAP_ARQ:
3235 	case SCSI_CAP_SECTOR_SIZE:
3236 	case SCSI_CAP_TAGGED_QING:
3237 	case SCSI_CAP_DMA_MAX:
3238 	case SCSI_CAP_INTERCONNECT_TYPE:
3239 #if defined(_UNTAGGED_QING_SUPPORTED)
3240 	case SCSI_CAP_UNTAGGED_QING:
3241 		rval = 0;		/* Capability cannot be changed */
3242 		break;
3243 #endif
3244 
3245 	default:
3246 		rval = -1;
3247 		break;
3248 	}
3249 	return (rval);
3250 }
3251 
3252 /*
3253  * Implementations of scsi tran_destroy_pkt.
3254  * Free resources allocated by sata_scsi_init_pkt()
3255  */
3256 static void
3257 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3258 {
3259 	sata_pkt_txlate_t *spx;
3260 
3261 	ASSERT(pkt != NULL);
3262 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3263 
3264 	if (spx->txlt_buf_dma_handle != NULL) {
3265 		if (spx->txlt_tmp_buf != NULL)  {
3266 		    ASSERT(spx->txlt_tmp_buf_handle != 0);
3267 			/*
3268 			 * Intermediate DMA buffer was allocated.
3269 			 * Free allocated buffer and associated access handle.
3270 			 */
3271 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
3272 			spx->txlt_tmp_buf = NULL;
3273 		}
3274 		/*
3275 		 * Free DMA resources - cookies and handles
3276 		 */
3277 		ASSERT(spx->txlt_dma_cookie_list != NULL);
3278 		(void) kmem_free(spx->txlt_dma_cookie_list,
3279 		    spx->txlt_dma_cookie_list_len * sizeof (ddi_dma_cookie_t));
3280 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
3281 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
3282 	}
3283 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
3284 	sata_pkt_free(spx);
3285 
3286 	scsi_hba_pkt_free(ap, pkt);
3287 }
3288 
3289 /*
3290  * Implementation of scsi tran_dmafree.
3291  * Free DMA resources allocated by sata_scsi_init_pkt()
3292  */
3293 
3294 static void
3295 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
3296 {
3297 #ifndef __lock_lint
3298 	_NOTE(ARGUNUSED(ap))
3299 #endif
3300 	sata_pkt_txlate_t *spx;
3301 
3302 	ASSERT(pkt != NULL);
3303 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3304 
3305 	if (spx->txlt_buf_dma_handle != NULL) {
3306 		/*
3307 		 * Free DMA resources - cookies and handles
3308 		 */
3309 		ASSERT(spx->txlt_dma_cookie_list != NULL);
3310 		(void) kmem_free(spx->txlt_dma_cookie_list,
3311 		    spx->txlt_dma_cookie_list_len * sizeof (ddi_dma_cookie_t));
3312 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
3313 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
3314 	}
3315 }
3316 
3317 /*
3318  * Implementation of scsi tran_sync_pkt.
3319  *
3320  * The assumption below is that pkt is unique - there is no need to check ap
3321  *
3322  * Synchronize DMA buffer and, if the intermediate buffer is used, copy data
3323  * into/from the real buffer.
3324  */
3325 static void
3326 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3327 {
3328 #ifndef __lock_lint
3329 	_NOTE(ARGUNUSED(ap))
3330 #endif
3331 	int rval;
3332 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3333 	struct buf *bp;
3334 	int direction;
3335 
3336 	ASSERT(spx != NULL);
3337 	if (spx->txlt_buf_dma_handle != NULL) {
3338 		direction = spx->txlt_sata_pkt->
3339 		    satapkt_cmd.satacmd_flags.sata_data_direction;
3340 		if (spx->txlt_sata_pkt != NULL &&
3341 		    direction != SATA_DIR_NODATA_XFER) {
3342 			if (spx->txlt_tmp_buf != NULL) {
3343 				/* Intermediate DMA buffer used */
3344 				bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3345 
3346 				if (direction & SATA_DIR_WRITE) {
3347 					bcopy(bp->b_un.b_addr,
3348 					    spx->txlt_tmp_buf, bp->b_bcount);
3349 				}
3350 			}
3351 			/* Sync the buffer for device or for CPU */
3352 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle,   0, 0,
3353 			    (direction & SATA_DIR_WRITE) ?
3354 			    DDI_DMA_SYNC_FORDEV :  DDI_DMA_SYNC_FORCPU);
3355 			ASSERT(rval == DDI_SUCCESS);
3356 			if (spx->txlt_tmp_buf != NULL &&
3357 			    !(direction & SATA_DIR_WRITE)) {
3358 				/* Intermediate DMA buffer used for read */
3359 				bcopy(spx->txlt_tmp_buf,
3360 				    bp->b_un.b_addr, bp->b_bcount);
3361 			}
3362 
3363 		}
3364 	}
3365 }
3366 
3367 
3368 
3369 /* *******************  SATA - SCSI Translation functions **************** */
3370 /*
3371  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
3372  * translation.
3373  */
3374 
3375 /*
3376  * Checks if a device exists and can be access and translates common
3377  * scsi_pkt data to sata_pkt data.
3378  *
3379  * Returns TRAN_ACCEPT if device exists and sata_pkt was set-up.
3380  * Returns other TRAN_XXXXX values when error occured.
3381  *
3382  * This function should be called with port mutex held.
3383  */
3384 static int
3385 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx)
3386 {
3387 	sata_drive_info_t *sdinfo;
3388 	sata_device_t sata_device;
3389 	const struct sata_cmd_flags sata_initial_cmd_flags = {
3390 		SATA_DIR_NODATA_XFER,
3391 		/* all other values to 0/FALSE */
3392 	};
3393 
3394 	/* Validate address */
3395 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
3396 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
3397 
3398 	case -1:
3399 		/* Invalid address or invalid device type */
3400 		return (TRAN_BADPKT);
3401 	case 1:
3402 		/* valid address but no device - it has disappeared ? */
3403 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
3404 		return (TRAN_FATAL_ERROR);
3405 	default:
3406 		/* all OK */
3407 		break;
3408 	}
3409 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3410 	    &spx->txlt_sata_pkt->satapkt_device);
3411 
3412 	/*
3413 	 * If device is in reset condition, reject the packet with
3414 	 * TRAN_BUSY
3415 	 */
3416 	if (sdinfo->satadrv_event_flags &
3417 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
3418 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3419 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3420 		    "sata_scsi_start: rejecting command because "
3421 		    "of device reset state\n", NULL);
3422 		return (TRAN_BUSY);
3423 	}
3424 
3425 	/*
3426 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
3427 	 * sata_scsi_pkt_init() because pkt init had to work also with
3428 	 * non-existing devices.
3429 	 * Now we know that the packet was set-up for a real device, so its
3430 	 * type is known.
3431 	 */
3432 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
3433 
3434 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
3435 
3436 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3437 
3438 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3439 		/* Synchronous execution */
3440 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
3441 		    SATA_OPMODE_POLLING;
3442 	} else {
3443 		/* Asynchronous execution */
3444 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
3445 		    SATA_OPMODE_INTERRUPTS;
3446 	}
3447 	/* Convert queuing information */
3448 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
3449 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
3450 		    B_TRUE;
3451 	else if (spx->txlt_scsi_pkt->pkt_flags &
3452 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
3453 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
3454 		    B_TRUE;
3455 
3456 	/* Always limit pkt time */
3457 	if (spx->txlt_scsi_pkt->pkt_time == 0)
3458 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
3459 	else
3460 		/* Pass on scsi_pkt time */
3461 		spx->txlt_sata_pkt->satapkt_time =
3462 		    spx->txlt_scsi_pkt->pkt_time;
3463 
3464 	return (TRAN_ACCEPT);
3465 }
3466 
3467 
3468 /*
3469  * Translate ATA(ATAPI) Identify (Packet) Device data to SCSI Inquiry data.
3470  * SATA Identify Device data has to be valid in sata_rive_info.
3471  * Buffer has to accomodate the inquiry length (36 bytes).
3472  *
3473  * This function should be called with a port mutex held.
3474  */
3475 static	void
3476 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
3477     sata_drive_info_t *sdinfo, uint8_t *buf)
3478 {
3479 
3480 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
3481 	struct sata_id *sid = &sdinfo->satadrv_id;
3482 
3483 	/* Start with a nice clean slate */
3484 	bzero((void *)inq, sizeof (struct scsi_inquiry));
3485 
3486 	/* Rely on the dev_type for setting paripheral qualifier */
3487 	/* Does DTYPE_RODIRECT apply to CD/DVD R/W devices ? */
3488 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3489 	    DTYPE_DIRECT : DTYPE_RODIRECT;
3490 
3491 	inq->inq_rmb = sid->ai_config & SATA_REM_MEDIA ? 1 : 0;
3492 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
3493 	inq->inq_iso = 0;	/* ISO version */
3494 	inq->inq_ecma = 0;	/* ECMA version */
3495 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
3496 	inq->inq_aenc = 0;	/* Async event notification cap. */
3497 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg ??? */
3498 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
3499 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
3500 	inq->inq_len = 31;	/* Additional length */
3501 	inq->inq_dualp = 0;	/* dual port device - NO */
3502 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
3503 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
3504 	inq->inq_linked = 0;	/* Supports linked commands - NO */
3505 				/*
3506 				 * Queuing support - controller has to
3507 				 * support some sort of command queuing.
3508 				 */
3509 	if (SATA_QDEPTH(sata_hba_inst) > 1)
3510 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
3511 	else
3512 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
3513 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
3514 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
3515 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
3516 
3517 #ifdef _LITTLE_ENDIAN
3518 	/* Swap text fields to match SCSI format */
3519 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3520 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3521 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3522 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
3523 	else
3524 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
3525 #else
3526 	bcopy(sid->ai_model, inq->inq_vid, 8);		/* Vendor ID */
3527 	bcopy(&sid->ai_model[8], inq->inq_pid, 16);	/* Product ID */
3528 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3529 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
3530 	else
3531 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
3532 #endif
3533 }
3534 
3535 
3536 /*
3537  * Scsi response set up for invalid command (command not supported)
3538  *
3539  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3540  */
3541 static int
3542 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
3543 {
3544 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3545 	struct scsi_extended_sense *sense;
3546 
3547 	scsipkt->pkt_reason = CMD_CMPLT;
3548 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3549 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3550 
3551 	*scsipkt->pkt_scbp = STATUS_CHECK;
3552 
3553 	sense = sata_arq_sense(spx);
3554 	sense->es_key = KEY_ILLEGAL_REQUEST;
3555 	sense->es_add_code = SD_SCSI_INVALID_COMMAND_CODE;
3556 
3557 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3558 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3559 
3560 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3561 	    scsipkt->pkt_comp != NULL)
3562 		/* scsi callback required */
3563 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3564 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3565 		    (void *)spx->txlt_scsi_pkt,
3566 		    TQ_SLEEP) == 0)
3567 			/* Scheduling the callback failed */
3568 			return (TRAN_BUSY);
3569 	return (TRAN_ACCEPT);
3570 }
3571 
3572 /*
3573  * Scsi response setup for
3574  * emulated non-data command that requires no action/return data
3575  *
3576  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3577  */
3578 static 	int
3579 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3580 {
3581 	int rval;
3582 
3583 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3584 
3585 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
3586 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3587 		return (rval);
3588 	}
3589 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3590 
3591 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3592 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3593 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3594 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3595 
3596 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3597 	    "Scsi_pkt completion reason %x\n",
3598 	    spx->txlt_scsi_pkt->pkt_reason);
3599 
3600 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3601 	    spx->txlt_scsi_pkt->pkt_comp != NULL)
3602 		/* scsi callback required */
3603 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3604 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3605 		    (void *)spx->txlt_scsi_pkt,
3606 		    TQ_SLEEP) == 0)
3607 			/* Scheduling the callback failed */
3608 			return (TRAN_BUSY);
3609 	return (TRAN_ACCEPT);
3610 }
3611 
3612 
3613 /*
3614  * SATA translate command: Inquiry / Identify Device
3615  * Use cached Identify Device data for now, rather then issuing actual
3616  * Device Identify cmd request. If device is detached and re-attached,
3617  * asynchromous event processing should fetch and refresh Identify Device
3618  * data.
3619  * Two VPD pages are supported now:
3620  * Vital Product Data page
3621  * Unit Serial Number page
3622  *
3623  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3624  */
3625 
3626 #define	EVPD			1	/* Extended Vital Product Data flag */
3627 #define	CMDDT			2	/* Command Support Data - Obsolete */
3628 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VDP Pages Page COde */
3629 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3630 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3631 
3632 static int
3633 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3634 {
3635 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3636 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3637 	sata_drive_info_t *sdinfo;
3638 	struct scsi_extended_sense *sense;
3639 	int count;
3640 	uint8_t *p;
3641 	int i, j;
3642 	uint8_t page_buf[0xff]; /* Max length */
3643 	int rval;
3644 
3645 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3646 
3647 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
3648 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3649 		return (rval);
3650 	}
3651 
3652 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3653 	    &spx->txlt_sata_pkt->satapkt_device);
3654 
3655 	ASSERT(sdinfo != NULL);
3656 
3657 	scsipkt->pkt_reason = CMD_CMPLT;
3658 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3659 		STATE_SENT_CMD | STATE_GOT_STATUS;
3660 
3661 	/* Reject not supported request */
3662 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3663 		*scsipkt->pkt_scbp = STATUS_CHECK;
3664 		sense = sata_arq_sense(spx);
3665 		sense->es_key = KEY_ILLEGAL_REQUEST;
3666 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
3667 		goto done;
3668 	}
3669 
3670 	/* Valid Inquiry request */
3671 	*scsipkt->pkt_scbp = STATUS_GOOD;
3672 
3673 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3674 
3675 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3676 		/* Standard Inquiry Data request */
3677 			struct scsi_inquiry inq;
3678 			unsigned int bufsize;
3679 
3680 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3681 			    sdinfo, (uint8_t *)&inq);
3682 			/* Copy no more than requested */
3683 			count = MIN(bp->b_bcount,
3684 			    sizeof (struct scsi_inquiry));
3685 			bufsize = scsipkt->pkt_cdbp[4];
3686 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3687 			count = MIN(count, bufsize);
3688 			bcopy(&inq, bp->b_un.b_addr, count);
3689 
3690 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3691 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3692 			    bufsize - count : 0;
3693 		} else {
3694 			/*
3695 			 * peripheral_qualifier = 0;
3696 			 *
3697 			 * We are dealing only with HD and will be
3698 			 * dealing with CD/DVD devices soon
3699 			 */
3700 			uint8_t peripheral_device_type =
3701 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3702 				DTYPE_DIRECT : DTYPE_RODIRECT;
3703 
3704 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3705 			case INQUIRY_SUP_VPD_PAGE:
3706 				/*
3707 				 * Request for suported Vital Product Data
3708 				 * pages - assuming only 2 page codes
3709 				 * supported
3710 				 */
3711 				page_buf[0] = peripheral_device_type;
3712 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3713 				page_buf[2] = 0;
3714 				page_buf[3] = 2; /* page length */
3715 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3716 				page_buf[5] = INQUIRY_USN_PAGE;
3717 				/* Copy no more than requested */
3718 				count = MIN(bp->b_bcount, 6);
3719 				bcopy(page_buf, bp->b_un.b_addr, count);
3720 				break;
3721 			case INQUIRY_USN_PAGE:
3722 				/*
3723 				 * Request for Unit Serial Number page
3724 				 */
3725 				page_buf[0] = peripheral_device_type;
3726 				page_buf[1] = INQUIRY_USN_PAGE;
3727 				page_buf[2] = 0;
3728 				page_buf[3] = 20; /* remaining page length */
3729 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3730 #ifdef	_LITTLE_ENDIAN
3731 				swab(p, &page_buf[4], 20);
3732 #else
3733 				bcopy(p, &page_buf[4], 20);
3734 #endif
3735 				for (i = 0; i < 20; i++) {
3736 					if (page_buf[4 + i] == '\0' ||
3737 					    page_buf[4 + i] == '\040') {
3738 						break;
3739 					}
3740 				}
3741 				/*
3742 				 * 'i' contains string length.
3743 				 *
3744 				 * Least significant character of the serial
3745 				 * number shall appear as the last byte,
3746 				 * according to SBC-3 spec.
3747 				 */
3748 				p = &page_buf[20 + 4 - 1];
3749 				for (j = i; j > 0; j--, p--) {
3750 					*p = *(p - 20 + i);
3751 				}
3752 				p = &page_buf[4];
3753 				for (j = 20 - i; j > 0; j--) {
3754 					*p++ = '\040';
3755 				}
3756 				count = MIN(bp->b_bcount, 24);
3757 				bcopy(page_buf, bp->b_un.b_addr, count);
3758 				break;
3759 
3760 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3761 				/*
3762 				 * We may want to implement this page, when
3763 				 * identifiers are common for SATA devices
3764 				 * But not now.
3765 				 */
3766 				/*FALLTHRU*/
3767 
3768 			default:
3769 				/* Request for unsupported VPD page */
3770 				*scsipkt->pkt_scbp = STATUS_CHECK;
3771 				sense = sata_arq_sense(spx);
3772 				sense->es_key = KEY_ILLEGAL_REQUEST;
3773 				sense->es_add_code =
3774 				    SD_SCSI_INVALID_FIELD_IN_CDB;
3775 				goto done;
3776 			}
3777 		}
3778 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3779 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3780 		    scsipkt->pkt_cdbp[4] - count : 0;
3781 	}
3782 done:
3783 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3784 
3785 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3786 	    "Scsi_pkt completion reason %x\n",
3787 	    scsipkt->pkt_reason);
3788 
3789 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3790 	    scsipkt->pkt_comp != NULL) {
3791 		/* scsi callback required */
3792 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3793 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3794 		    TQ_SLEEP) == 0)
3795 			/* Scheduling the callback failed */
3796 			return (TRAN_BUSY);
3797 	}
3798 	return (TRAN_ACCEPT);
3799 }
3800 
3801 /*
3802  * SATA translate command: Request Sense
3803  * emulated command (ATA version so far, no ATAPI)
3804  * Always NO SENSE, because any sense data should be reported by ARQ sense.
3805  *
3806  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3807  */
3808 static int
3809 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3810 {
3811 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3812 	struct scsi_extended_sense sense;
3813 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3814 	int rval;
3815 
3816 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3817 
3818 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
3819 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3820 		return (rval);
3821 	}
3822 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3823 
3824 
3825 	scsipkt->pkt_reason = CMD_CMPLT;
3826 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3827 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3828 	*scsipkt->pkt_scbp = STATUS_GOOD;
3829 
3830 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3831 		int count = MIN(bp->b_bcount,
3832 		    sizeof (struct scsi_extended_sense));
3833 		bzero(&sense, sizeof (struct scsi_extended_sense));
3834 		sense.es_valid = 0;	/* Valid LBA */
3835 		sense.es_class = 7;	/* Response code 0x70 - current err */
3836 		sense.es_key = KEY_NO_SENSE;
3837 		sense.es_add_len = 6;	/* Additional length */
3838 		/* Copy no more than requested */
3839 		bcopy(&sense, bp->b_un.b_addr, count);
3840 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3841 		scsipkt->pkt_resid = 0;
3842 	}
3843 
3844 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3845 	    "Scsi_pkt completion reason %x\n",
3846 	    scsipkt->pkt_reason);
3847 
3848 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3849 	    scsipkt->pkt_comp != NULL)
3850 		/* scsi callback required */
3851 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3852 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3853 		    TQ_SLEEP) == 0)
3854 			/* Scheduling the callback failed */
3855 			return (TRAN_BUSY);
3856 	return (TRAN_ACCEPT);
3857 }
3858 
3859 /*
3860  * SATA translate command: Test Unit Ready
3861  * At the moment this is an emulated command (ATA version so far, no ATAPI).
3862  * May be translated into Check Power Mode command in the future
3863  *
3864  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3865  */
3866 static int
3867 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3868 {
3869 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3870 	struct scsi_extended_sense *sense;
3871 	int power_state;
3872 	int rval;
3873 
3874 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3875 
3876 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
3877 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3878 		return (rval);
3879 	}
3880 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3881 
3882 	/* At this moment, emulate it rather than execute anything */
3883 	power_state = SATA_PWRMODE_ACTIVE;
3884 
3885 	scsipkt->pkt_reason = CMD_CMPLT;
3886 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3887 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3888 
3889 	switch (power_state) {
3890 	case SATA_PWRMODE_ACTIVE:
3891 	case SATA_PWRMODE_IDLE:
3892 		*scsipkt->pkt_scbp = STATUS_GOOD;
3893 		break;
3894 	default:
3895 		/* PWR mode standby */
3896 		*scsipkt->pkt_scbp = STATUS_CHECK;
3897 		sense = sata_arq_sense(spx);
3898 		sense->es_key = KEY_NOT_READY;
3899 		sense->es_add_code = SD_SCSI_LU_NOT_READY;
3900 		break;
3901 	}
3902 
3903 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3904 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3905 
3906 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3907 	    scsipkt->pkt_comp != NULL)
3908 		/* scsi callback required */
3909 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3910 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3911 		    TQ_SLEEP) == 0)
3912 			/* Scheduling the callback failed */
3913 			return (TRAN_BUSY);
3914 
3915 	return (TRAN_ACCEPT);
3916 }
3917 
3918 
3919 /*
3920  * SATA translate command: Start Stop Unit
3921  * Translation depends on a command:
3922  *	Start Unit translated into Idle Immediate
3923  *	Stop Unit translated into Standby Immediate
3924  *	Unload Media / NOT SUPPORTED YET
3925  *	Load Media / NOT SUPPROTED YET
3926  * Power condition bits are ignored, so is Immediate bit
3927  * Requesting synchronous execution.
3928  *
3929  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
3930  * appropriate values in scsi_pkt fields.
3931  */
3932 static int
3933 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
3934 {
3935 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3936 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3937 	struct scsi_extended_sense *sense;
3938 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3939 	int cport = SATA_TXLT_CPORT(spx);
3940 	int rval;
3941 	int synch;
3942 
3943 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3944 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
3945 
3946 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3947 
3948 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
3949 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3950 		return (rval);
3951 	}
3952 
3953 	if (scsipkt->pkt_cdbp[4] & 2) {
3954 		/* Load/Unload Media - invalid request */
3955 		*scsipkt->pkt_scbp = STATUS_CHECK;
3956 		sense = sata_arq_sense(spx);
3957 		sense->es_key = KEY_ILLEGAL_REQUEST;
3958 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
3959 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3960 
3961 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3962 		    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3963 
3964 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3965 		    scsipkt->pkt_comp != NULL)
3966 			/* scsi callback required */
3967 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3968 			    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3969 			    TQ_SLEEP) == 0)
3970 				/* Scheduling the callback failed */
3971 				return (TRAN_BUSY);
3972 
3973 		return (TRAN_ACCEPT);
3974 	}
3975 	scmd->satacmd_addr_type = 0;
3976 	scmd->satacmd_sec_count_lsb = 0;
3977 	scmd->satacmd_lba_low_lsb = 0;
3978 	scmd->satacmd_lba_mid_lsb = 0;
3979 	scmd->satacmd_lba_high_lsb = 0;
3980 	scmd->satacmd_features_reg = 0;
3981 	scmd->satacmd_device_reg = 0;
3982 	scmd->satacmd_status_reg = 0;
3983 	if (scsipkt->pkt_cdbp[4] & 1) {
3984 		/* Start Unit */
3985 		scmd->satacmd_cmd_reg = SATAC_IDLE_IM;
3986 	} else {
3987 		/* Stop Unit */
3988 		scmd->satacmd_cmd_reg = SATAC_STANDBY_IM;
3989 	}
3990 
3991 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
3992 		/* Need to set-up a callback function */
3993 		spx->txlt_sata_pkt->satapkt_comp =
3994 		    sata_txlt_nodata_cmd_completion;
3995 		synch = FALSE;
3996 	} else {
3997 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
3998 		synch = TRUE;
3999 	}
4000 
4001 	/* Transfer command to HBA */
4002 	if (sata_hba_start(spx, &rval) != 0) {
4003 		/* Pkt not accepted for execution */
4004 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4005 		return (rval);
4006 	}
4007 
4008 	/*
4009 	 * If execution is non-synchronous,
4010 	 * a callback function will handle potential errors, translate
4011 	 * the response and will do a callback to a target driver.
4012 	 * If it was synchronous, check execution status using the same
4013 	 * framework callback.
4014 	 */
4015 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4016 	if (synch) {
4017 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4018 		    "synchronous execution status %x\n",
4019 		    spx->txlt_sata_pkt->satapkt_reason);
4020 
4021 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
4022 	}
4023 	return (TRAN_ACCEPT);
4024 
4025 }
4026 
4027 
4028 /*
4029  * SATA translate command:  Read Capacity.
4030  * Emulated command for SATA disks.
4031  * Capacity is retrieved from cached Idenifty Device data.
4032  * Identify Device data shows effective disk capacity, not the native
4033  * capacity, which may be limitted by Set Max Address command.
4034  * This is ATA version (non-ATAPI).
4035  *
4036  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4037  */
4038 static int
4039 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
4040 {
4041 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4042 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4043 	sata_drive_info_t *sdinfo;
4044 	uint64_t val;
4045 	uchar_t *rbuf;
4046 	int rval;
4047 
4048 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4049 	    "sata_txlt_read_capacity: ", NULL);
4050 
4051 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4052 
4053 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
4054 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4055 		return (rval);
4056 	}
4057 
4058 	scsipkt->pkt_reason = CMD_CMPLT;
4059 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4060 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4061 	*scsipkt->pkt_scbp = STATUS_GOOD;
4062 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4063 		sdinfo = sata_get_device_info(
4064 		    spx->txlt_sata_hba_inst,
4065 		    &spx->txlt_sata_pkt->satapkt_device);
4066 		/* Last logical block address */
4067 		val = sdinfo->satadrv_capacity - 1;
4068 		rbuf = (uchar_t *)bp->b_un.b_addr;
4069 		/* Need to swap endians to match scsi format */
4070 		rbuf[0] = (val >> 24) & 0xff;
4071 		rbuf[1] = (val >> 16) & 0xff;
4072 		rbuf[2] = (val >> 8) & 0xff;
4073 		rbuf[3] = val & 0xff;
4074 		/* block size - always 512 bytes, for now */
4075 		rbuf[4] = 0;
4076 		rbuf[5] = 0;
4077 		rbuf[6] = 0x02;
4078 		rbuf[7] = 0;
4079 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4080 		scsipkt->pkt_resid = 0;
4081 
4082 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
4083 		    sdinfo->satadrv_capacity -1);
4084 	}
4085 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4086 	/*
4087 	 * If a callback was requested, do it now.
4088 	 */
4089 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4090 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4091 
4092 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4093 	    scsipkt->pkt_comp != NULL)
4094 		/* scsi callback required */
4095 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4096 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4097 		    TQ_SLEEP) == 0)
4098 			/* Scheduling the callback failed */
4099 			return (TRAN_BUSY);
4100 
4101 	return (TRAN_ACCEPT);
4102 }
4103 
4104 /*
4105  * SATA translate command: Mode Sense.
4106  * Translated into appropriate SATA command or emulated.
4107  * Saved Values Page Control (03) are not supported.
4108  *
4109  * NOTE: only caching mode sense page is currently implemented.
4110  *
4111  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4112  */
4113 
4114 static int
4115 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4116 {
4117 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4118 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4119 	sata_drive_info_t *sdinfo;
4120 	sata_id_t *sata_id;
4121 	struct scsi_extended_sense *sense;
4122 	int 		len, bdlen, count, alc_len;
4123 	int		pc;	/* Page Control code */
4124 	uint8_t		*buf;	/* mode sense buffer */
4125 	int		rval;
4126 
4127 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4128 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
4129 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4130 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4131 
4132 	buf = kmem_zalloc(1024, KM_SLEEP);
4133 
4134 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4135 
4136 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
4137 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4138 		kmem_free(buf, 1024);
4139 		return (rval);
4140 	}
4141 
4142 	scsipkt->pkt_reason = CMD_CMPLT;
4143 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4144 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4145 
4146 	pc = scsipkt->pkt_cdbp[2] >> 6;
4147 
4148 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4149 		len = 0;
4150 		bdlen = 0;
4151 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
4152 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
4153 			    (scsipkt->pkt_cdbp[0] & 0x10))
4154 				bdlen = 16;
4155 			else
4156 				bdlen = 8;
4157 		}
4158 		/* Build mode parameter header */
4159 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4160 			/* 4-byte mode parameter header */
4161 			buf[len++] = 0;   	/* mode data length */
4162 			buf[len++] = 0;		/* medium type */
4163 			buf[len++] = 0;		/* dev-specific param */
4164 			buf[len++] = bdlen;	/* Block Descriptor length */
4165 		} else {
4166 			/* 8-byte mode parameter header */
4167 			buf[len++] = 0;		/* mode data length */
4168 			buf[len++] = 0;
4169 			buf[len++] = 0;		/* medium type */
4170 			buf[len++] = 0;		/* dev-specific param */
4171 			if (bdlen == 16)
4172 				buf[len++] = 1;	/* long lba descriptor */
4173 			else
4174 				buf[len++] = 0;
4175 			buf[len++] = 0;
4176 			buf[len++] = 0;		/* Block Descriptor length */
4177 			buf[len++] = bdlen;
4178 		}
4179 
4180 		sdinfo = sata_get_device_info(
4181 		    spx->txlt_sata_hba_inst,
4182 		    &spx->txlt_sata_pkt->satapkt_device);
4183 
4184 		/* Build block descriptor only if not disabled (DBD) */
4185 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
4186 			/* Block descriptor - direct-access device format */
4187 			if (bdlen == 8) {
4188 				/* build regular block descriptor */
4189 				buf[len++] =
4190 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4191 				buf[len++] =
4192 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4193 				buf[len++] =
4194 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4195 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4196 				buf[len++] = 0; /* density code */
4197 				buf[len++] = 0;
4198 				if (sdinfo->satadrv_type ==
4199 				    SATA_DTYPE_ATADISK)
4200 					buf[len++] = 2;
4201 				else
4202 					/* ATAPI */
4203 					buf[len++] = 8;
4204 				buf[len++] = 0;
4205 			} else if (bdlen == 16) {
4206 				/* Long LBA Accepted */
4207 				/* build long lba block descriptor */
4208 #ifndef __lock_lint
4209 				buf[len++] =
4210 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
4211 				buf[len++] =
4212 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
4213 				buf[len++] =
4214 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
4215 				buf[len++] =
4216 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
4217 #endif
4218 				buf[len++] =
4219 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4220 				buf[len++] =
4221 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4222 				buf[len++] =
4223 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4224 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4225 				buf[len++] = 0;
4226 				buf[len++] = 0; /* density code */
4227 				buf[len++] = 0;
4228 				buf[len++] = 0;
4229 				if (sdinfo->satadrv_type ==
4230 				    SATA_DTYPE_ATADISK)
4231 					buf[len++] = 2;
4232 				else
4233 					/* ATAPI */
4234 					buf[len++] = 8;
4235 				buf[len++] = 0;
4236 			}
4237 		}
4238 
4239 		sata_id = &sdinfo->satadrv_id;
4240 
4241 		/*
4242 		 * Add requested pages.
4243 		 * Page 3 and 4 are obsolete and we are not supporting them.
4244 		 * We deal now with:
4245 		 * caching (read/write cache control).
4246 		 * We should eventually deal with following mode pages:
4247 		 * error recovery  (0x01),
4248 		 * power condition (0x1a),
4249 		 * exception control page (enables SMART) (0x1c),
4250 		 * enclosure management (ses),
4251 		 * protocol-specific port mode (port control).
4252 		 */
4253 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
4254 		case MODEPAGE_RW_ERRRECOV:
4255 			/* DAD_MODE_ERR_RECOV */
4256 			/* R/W recovery */
4257 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4258 			break;
4259 		case MODEPAGE_CACHING:
4260 			/* DAD_MODE_CACHE */
4261 			/* Reject not supported request for saved parameters */
4262 			if (pc == 3) {
4263 				*scsipkt->pkt_scbp = STATUS_CHECK;
4264 				sense = sata_arq_sense(spx);
4265 				sense->es_key = KEY_ILLEGAL_REQUEST;
4266 				sense->es_add_code =
4267 				    SD_SCSI_SAVING_PARAMS_NOT_SUP;
4268 				goto done;
4269 			}
4270 
4271 			/* caching */
4272 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4273 			break;
4274 		case MODEPAGE_INFO_EXCPT:
4275 			/* exception cntrl */
4276 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4277 				len += sata_build_msense_page_1c(sdinfo, pc,
4278 				    buf+len);
4279 			}
4280 			else
4281 				goto err;
4282 			break;
4283 		case MODEPAGE_POWER_COND:
4284 			/* DAD_MODE_POWER_COND */
4285 			/* power condition */
4286 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4287 			break;
4288 		case MODEPAGE_ALLPAGES:
4289 			/* all pages */
4290 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4291 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4292 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4293 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4294 				len += sata_build_msense_page_1c(sdinfo, pc,
4295 				    buf+len);
4296 			}
4297 			break;
4298 		default:
4299 		err:
4300 			/* Invalid request */
4301 			*scsipkt->pkt_scbp = STATUS_CHECK;
4302 			sense = sata_arq_sense(spx);
4303 			sense->es_key = KEY_ILLEGAL_REQUEST;
4304 			sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
4305 			goto done;
4306 		}
4307 
4308 		/* fix total mode data length */
4309 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4310 			/* 4-byte mode parameter header */
4311 			buf[0] = len - 1;   	/* mode data length */
4312 		} else {
4313 			buf[0] = (len -2) >> 8;
4314 			buf[1] = (len -2) & 0xff;
4315 		}
4316 
4317 
4318 		/* Check allocation length */
4319 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4320 			alc_len = scsipkt->pkt_cdbp[4];
4321 		} else {
4322 			alc_len = scsipkt->pkt_cdbp[7];
4323 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4324 		}
4325 		/*
4326 		 * We do not check for possible parameters truncation
4327 		 * (alc_len < len) assuming that the target driver works
4328 		 * correctly. Just avoiding overrun.
4329 		 * Copy no more than requested and possible, buffer-wise.
4330 		 */
4331 		count = MIN(alc_len, len);
4332 		count = MIN(bp->b_bcount, count);
4333 		bcopy(buf, bp->b_un.b_addr, count);
4334 
4335 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4336 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4337 	}
4338 	*scsipkt->pkt_scbp = STATUS_GOOD;
4339 done:
4340 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4341 	(void) kmem_free(buf, 1024);
4342 
4343 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4344 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4345 
4346 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4347 	    scsipkt->pkt_comp != NULL)
4348 		/* scsi callback required */
4349 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4350 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4351 		    TQ_SLEEP) == 0)
4352 			/* Scheduling the callback failed */
4353 			return (TRAN_BUSY);
4354 
4355 	return (TRAN_ACCEPT);
4356 }
4357 
4358 
4359 /*
4360  * SATA translate command: Mode Select.
4361  * Translated into appropriate SATA command or emulated.
4362  * Saving parameters is not supported.
4363  * Changing device capacity is not supported (although theoretically
4364  * possible by executing SET FEATURES/SET MAX ADDRESS)
4365  *
4366  * Assumption is that the target driver is working correctly.
4367  *
4368  * More than one SATA command may be executed to perform operations specified
4369  * by mode select pages. The first error terminates further execution.
4370  * Operations performed successully are not backed-up in such case.
4371  *
4372  * NOTE: only caching mode select page is implemented.
4373  * Caching setup is remembered so it could be re-stored in case of
4374  * an unexpected device reset.
4375  *
4376  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4377  */
4378 
4379 static int
4380 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
4381 {
4382 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4383 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4384 	struct scsi_extended_sense *sense;
4385 	int len, pagelen, count, pllen;
4386 	uint8_t *buf;	/* mode select buffer */
4387 	int rval, stat;
4388 	uint_t nointr_flag;
4389 	int dmod = 0;
4390 
4391 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4392 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
4393 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4394 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4395 
4396 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4397 
4398 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
4399 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4400 		return (rval);
4401 	}
4402 
4403 	rval = TRAN_ACCEPT;
4404 
4405 	scsipkt->pkt_reason = CMD_CMPLT;
4406 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4407 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4408 
4409 	/* Reject not supported request */
4410 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
4411 		*scsipkt->pkt_scbp = STATUS_CHECK;
4412 		sense = sata_arq_sense(spx);
4413 		sense->es_key = KEY_ILLEGAL_REQUEST;
4414 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
4415 		goto done;
4416 	}
4417 
4418 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4419 		pllen = scsipkt->pkt_cdbp[4];
4420 	} else {
4421 		pllen = scsipkt->pkt_cdbp[7];
4422 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
4423 	}
4424 
4425 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
4426 
4427 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
4428 		buf = (uint8_t *)bp->b_un.b_addr;
4429 		count = MIN(bp->b_bcount, pllen);
4430 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4431 		scsipkt->pkt_resid = 0;
4432 		pllen = count;
4433 
4434 		/*
4435 		 * Check the header to skip the block descriptor(s) - we
4436 		 * do not support setting device capacity.
4437 		 * Existing macros do not recognize long LBA dscriptor,
4438 		 * hence manual calculation.
4439 		 */
4440 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4441 			/* 6-bytes CMD, 4 bytes header */
4442 			if (count <= 4)
4443 				goto done;		/* header only */
4444 			len = buf[3] + 4;
4445 		} else {
4446 			/* 10-bytes CMD, 8 bytes header */
4447 			if (count <= 8)
4448 				goto done;		/* header only */
4449 			len = buf[6];
4450 			len = (len << 8) + buf[7] + 8;
4451 		}
4452 		if (len >= count)
4453 			goto done;	/* header + descriptor(s) only */
4454 
4455 		pllen -= len;		/* remaining data length */
4456 
4457 		/*
4458 		 * We may be executing SATA command and want to execute it
4459 		 * in SYNCH mode, regardless of scsi_pkt setting.
4460 		 * Save scsi_pkt setting and indicate SYNCH mode
4461 		 */
4462 		nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
4463 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4464 		    scsipkt->pkt_comp != NULL) {
4465 			scsipkt->pkt_flags |= FLAG_NOINTR;
4466 		}
4467 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
4468 
4469 		/*
4470 		 * len is now the offset to a first mode select page
4471 		 * Process all pages
4472 		 */
4473 		while (pllen > 0) {
4474 			switch ((int)buf[len]) {
4475 			case MODEPAGE_CACHING:
4476 				/* No support for SP (saving) */
4477 				if (scsipkt->pkt_cdbp[1] & 0x01) {
4478 					*scsipkt->pkt_scbp = STATUS_CHECK;
4479 					sense = sata_arq_sense(spx);
4480 					sense->es_key = KEY_ILLEGAL_REQUEST;
4481 					sense->es_add_code =
4482 					    SD_SCSI_INVALID_FIELD_IN_CDB;
4483 					goto done;
4484 				}
4485 				stat = sata_mode_select_page_8(spx,
4486 				    (struct mode_cache_scsi3 *)&buf[len],
4487 				    pllen, &pagelen, &rval, &dmod);
4488 				/*
4489 				 * The pagelen value indicates the number of
4490 				 * parameter bytes already processed.
4491 				 * The rval is the return value from
4492 				 * sata_tran_start().
4493 				 * The stat indicates the overall status of
4494 				 * the operation(s).
4495 				 */
4496 				if (stat != SATA_SUCCESS)
4497 					/*
4498 					 * Page processing did not succeed -
4499 					 * all error info is already set-up,
4500 					 * just return
4501 					 */
4502 					pllen = 0; /* this breaks the loop */
4503 				else {
4504 					len += pagelen;
4505 					pllen -= pagelen;
4506 				}
4507 				break;
4508 
4509 			case MODEPAGE_INFO_EXCPT:
4510 				stat = sata_mode_select_page_1c(spx,
4511 				    (struct mode_info_excpt_page *)&buf[len],
4512 				    pllen, &pagelen, &rval, &dmod);
4513 				/*
4514 				 * The pagelen value indicates the number of
4515 				 * parameter bytes already processed.
4516 				 * The rval is the return value from
4517 				 * sata_tran_start().
4518 				 * The stat indicates the overall status of
4519 				 * the operation(s).
4520 				 */
4521 				if (stat != SATA_SUCCESS)
4522 					/*
4523 					 * Page processing did not succeed -
4524 					 * all error info is already set-up,
4525 					 * just return
4526 					 */
4527 					pllen = 0; /* this breaks the loop */
4528 				else {
4529 					len += pagelen;
4530 					pllen -= pagelen;
4531 				}
4532 				break;
4533 
4534 			default:
4535 				*scsipkt->pkt_scbp = STATUS_CHECK;
4536 				sense = sata_arq_sense(spx);
4537 				sense->es_key = KEY_ILLEGAL_REQUEST;
4538 				sense->es_add_code =
4539 				    SD_SCSI_INVALID_FIELD_IN_PARAMETER_LIST;
4540 				goto done;
4541 			}
4542 		}
4543 	}
4544 done:
4545 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4546 	/*
4547 	 * If device parameters were modified, fetch and store the new
4548 	 * Identify Device data. Since port mutex could have been released
4549 	 * for accessing HBA driver, we need to re-check device existence.
4550 	 */
4551 	if (dmod != 0) {
4552 		sata_drive_info_t new_sdinfo, *sdinfo;
4553 		int rv;
4554 
4555 		new_sdinfo.satadrv_addr =
4556 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
4557 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
4558 		    &new_sdinfo);
4559 
4560 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4561 		/*
4562 		 * Since port mutex could have been released when
4563 		 * accessing HBA driver, we need to re-check that the
4564 		 * framework still holds the device info structure.
4565 		 */
4566 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4567 		    &spx->txlt_sata_pkt->satapkt_device);
4568 		if (sdinfo != NULL) {
4569 			/*
4570 			 * Device still has info structure in the
4571 			 * sata framework. Copy newly fetched info
4572 			 */
4573 			if (rv == 0) {
4574 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
4575 				sata_save_drive_settings(sdinfo);
4576 			} else {
4577 				/*
4578 				 * Could not fetch new data - invalidate
4579 				 * sata_drive_info. That makes device
4580 				 * unusable.
4581 				 */
4582 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
4583 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
4584 			}
4585 		}
4586 		if (rv != 0 || sdinfo == NULL) {
4587 			/*
4588 			 * This changes the overall mode select completion
4589 			 * reason to a failed one !!!!!
4590 			 */
4591 			*scsipkt->pkt_scbp = STATUS_CHECK;
4592 			sense = sata_arq_sense(spx);
4593 			scsipkt->pkt_reason = CMD_INCOMPLETE;
4594 			rval = TRAN_ACCEPT;
4595 		}
4596 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4597 	}
4598 	/* Restore the scsi pkt flags */
4599 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
4600 	scsipkt->pkt_flags |= nointr_flag;
4601 
4602 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4603 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4604 
4605 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4606 	    scsipkt->pkt_comp != NULL)
4607 		/* scsi callback required */
4608 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4609 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4610 		    TQ_SLEEP) == 0)
4611 			/* Scheduling the callback failed */
4612 			return (TRAN_BUSY);
4613 
4614 	return (rval);
4615 }
4616 
4617 
4618 
4619 /*
4620  * Translate command: Log Sense
4621  */
4622 static 	int
4623 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
4624 {
4625 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4626 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4627 	sata_drive_info_t *sdinfo;
4628 	struct scsi_extended_sense *sense;
4629 	int 		len, count, alc_len;
4630 	int		pc;	/* Page Control code */
4631 	int		page_code;	/* Page code */
4632 	uint8_t		*buf;	/* log sense buffer */
4633 	int		rval;
4634 #define	MAX_LOG_SENSE_PAGE_SIZE	512
4635 
4636 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4637 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
4638 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4639 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4640 
4641 	buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
4642 
4643 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4644 
4645 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
4646 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4647 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4648 		return (rval);
4649 	}
4650 
4651 	scsipkt->pkt_reason = CMD_CMPLT;
4652 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4653 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4654 
4655 	pc = scsipkt->pkt_cdbp[2] >> 6;
4656 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
4657 
4658 	/* Reject not supported request for all but cumulative values */
4659 	switch (pc) {
4660 	case PC_CUMULATIVE_VALUES:
4661 		break;
4662 	default:
4663 		*scsipkt->pkt_scbp = STATUS_CHECK;
4664 		sense = sata_arq_sense(spx);
4665 		sense->es_key = KEY_ILLEGAL_REQUEST;
4666 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
4667 		goto done;
4668 	}
4669 
4670 	switch (page_code) {
4671 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
4672 	case PAGE_CODE_SELF_TEST_RESULTS:
4673 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
4674 	case PAGE_CODE_SMART_READ_DATA:
4675 		break;
4676 	default:
4677 		*scsipkt->pkt_scbp = STATUS_CHECK;
4678 		sense = sata_arq_sense(spx);
4679 		sense->es_key = KEY_ILLEGAL_REQUEST;
4680 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
4681 		goto done;
4682 	}
4683 
4684 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4685 		sata_id_t *sata_id;
4686 		len = 0;
4687 
4688 		/* Build log parameter header */
4689 		buf[len++] = page_code;	/* page code as in the CDB */
4690 		buf[len++] = 0;		/* reserved */
4691 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
4692 		buf[len++] = 0;		/* (LSB) */
4693 
4694 		sdinfo = sata_get_device_info(
4695 		    spx->txlt_sata_hba_inst,
4696 		    &spx->txlt_sata_pkt->satapkt_device);
4697 
4698 
4699 		/*
4700 		 * Add requested pages.
4701 		 */
4702 		switch (page_code) {
4703 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
4704 			len = sata_build_lsense_page_0(sdinfo, buf + len);
4705 			break;
4706 		case PAGE_CODE_SELF_TEST_RESULTS:
4707 			sata_id = &sdinfo->satadrv_id;
4708 			if ((! (sata_id->ai_cmdset84 &
4709 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
4710 			    (! (sata_id->ai_features87 &
4711 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
4712 				*scsipkt->pkt_scbp = STATUS_CHECK;
4713 				sense = sata_arq_sense(spx);
4714 				sense->es_key = KEY_ILLEGAL_REQUEST;
4715 				sense->es_add_code =
4716 				    SD_SCSI_INVALID_FIELD_IN_CDB;
4717 
4718 				goto done;
4719 			}
4720 			len = sata_build_lsense_page_10(sdinfo, buf + len,
4721 			    spx->txlt_sata_hba_inst);
4722 			break;
4723 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
4724 			sata_id = &sdinfo->satadrv_id;
4725 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
4726 				*scsipkt->pkt_scbp = STATUS_CHECK;
4727 				sense = sata_arq_sense(spx);
4728 				sense->es_key = KEY_ILLEGAL_REQUEST;
4729 				sense->es_add_code =
4730 				    SD_SCSI_INVALID_FIELD_IN_CDB;
4731 
4732 				goto done;
4733 			}
4734 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
4735 				*scsipkt->pkt_scbp = STATUS_CHECK;
4736 				sense = sata_arq_sense(spx);
4737 				sense->es_key = KEY_ABORTED_COMMAND;
4738 				sense->es_add_code =
4739 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
4740 				sense->es_qual_code =
4741 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
4742 
4743 				goto done;
4744 			}
4745 
4746 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
4747 			    spx->txlt_sata_hba_inst);
4748 			break;
4749 		case PAGE_CODE_SMART_READ_DATA:
4750 			sata_id = &sdinfo->satadrv_id;
4751 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
4752 				*scsipkt->pkt_scbp = STATUS_CHECK;
4753 				sense = sata_arq_sense(spx);
4754 				sense->es_key = KEY_ILLEGAL_REQUEST;
4755 				sense->es_add_code =
4756 				    SD_SCSI_INVALID_FIELD_IN_CDB;
4757 
4758 				goto done;
4759 			}
4760 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
4761 				*scsipkt->pkt_scbp = STATUS_CHECK;
4762 				sense = sata_arq_sense(spx);
4763 				sense->es_key = KEY_ABORTED_COMMAND;
4764 				sense->es_add_code =
4765 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
4766 				sense->es_qual_code =
4767 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
4768 
4769 				goto done;
4770 			}
4771 
4772 			/* This page doesn't include a page header */
4773 			len = sata_build_lsense_page_30(sdinfo, buf,
4774 			    spx->txlt_sata_hba_inst);
4775 			goto no_header;
4776 		default:
4777 			/* Invalid request */
4778 			*scsipkt->pkt_scbp = STATUS_CHECK;
4779 			sense = sata_arq_sense(spx);
4780 			sense->es_key = KEY_ILLEGAL_REQUEST;
4781 			sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
4782 			goto done;
4783 		}
4784 
4785 		/* set parameter log sense data length */
4786 		buf[2] = len >> 8;	/* log sense length (MSB) */
4787 		buf[3] = len & 0xff;	/* log sense length (LSB) */
4788 
4789 		len += SCSI_LOG_PAGE_HDR_LEN;
4790 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
4791 
4792 no_header:
4793 		/* Check allocation length */
4794 		alc_len = scsipkt->pkt_cdbp[7];
4795 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4796 
4797 		/*
4798 		 * We do not check for possible parameters truncation
4799 		 * (alc_len < len) assuming that the target driver works
4800 		 * correctly. Just avoiding overrun.
4801 		 * Copy no more than requested and possible, buffer-wise.
4802 		 */
4803 		count = MIN(alc_len, len);
4804 		count = MIN(bp->b_bcount, count);
4805 		bcopy(buf, bp->b_un.b_addr, count);
4806 
4807 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4808 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4809 	}
4810 	*scsipkt->pkt_scbp = STATUS_GOOD;
4811 done:
4812 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4813 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4814 
4815 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4816 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4817 
4818 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4819 	    scsipkt->pkt_comp != NULL)
4820 		/* scsi callback required */
4821 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4822 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4823 		    TQ_SLEEP) == 0)
4824 			/* Scheduling the callback failed */
4825 			return (TRAN_BUSY);
4826 
4827 	return (TRAN_ACCEPT);
4828 }
4829 
4830 /*
4831  * Translate command: Log Select
4832  * Not implemented at this time - returns invalid command response.
4833  */
4834 static 	int
4835 sata_txlt_log_select(sata_pkt_txlate_t *spx)
4836 {
4837 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4838 	    "sata_txlt_log_select\n", NULL);
4839 
4840 	return (sata_txlt_invalid_command(spx));
4841 }
4842 
4843 
4844 /*
4845  * Translate command: Read (various types).
4846  * Translated into appropriate type of ATA READ command
4847  * (NO ATAPI implementation yet).
4848  * Both the device capabilities and requested operation mode are
4849  * considered.
4850  *
4851  * Following scsi cdb fields are ignored:
4852  * rdprotect, dpo, fua, fua_nv, group_number.
4853  *
4854  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
4855  * enable variable sata_func_enable), the capability of the controller and
4856  * capability of a device are checked and if both support queueing, read
4857  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
4858  * command rather than plain READ_XXX command.
4859  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
4860  * both the controller and device suport such functionality, the read
4861  * request will be translated to READ_FPDMA_QUEUED command.
4862  *
4863  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4864  * appropriate values in scsi_pkt fields.
4865  */
4866 static int
4867 sata_txlt_read(sata_pkt_txlate_t *spx)
4868 {
4869 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4870 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4871 	sata_drive_info_t *sdinfo;
4872 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
4873 	int cport = SATA_TXLT_CPORT(spx);
4874 	uint16_t sec_count;
4875 	uint64_t lba;
4876 	int rval;
4877 	int synch;
4878 
4879 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4880 
4881 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
4882 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4883 		return (rval);
4884 	}
4885 
4886 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4887 	    &spx->txlt_sata_pkt->satapkt_device);
4888 
4889 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
4890 	/*
4891 	 * Build cmd block depending on the device capability and
4892 	 * requested operation mode.
4893 	 * Do not bother with non-dma mode.
4894 	 */
4895 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
4896 	case SCMD_READ:
4897 		/* 6-byte scsi read cmd : 0x08 */
4898 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
4899 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
4900 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4901 		sec_count = scsipkt->pkt_cdbp[4];
4902 		/* sec_count 0 will be interpreted as 256 by a device */
4903 		break;
4904 	case SCMD_READ_G1:
4905 		/* 10-bytes scsi read command : 0x28 */
4906 		lba = scsipkt->pkt_cdbp[2];
4907 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4908 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4909 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4910 		sec_count = scsipkt->pkt_cdbp[7];
4911 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4912 		break;
4913 	case SCMD_READ_G5:
4914 		/* 12-bytes scsi read command : 0xA8 */
4915 		lba = scsipkt->pkt_cdbp[2];
4916 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4917 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4918 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4919 		sec_count = scsipkt->pkt_cdbp[6];
4920 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
4921 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4922 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
4923 		break;
4924 	case SCMD_READ_G4:
4925 		/* 16-bytes scsi read command : 0x88 */
4926 		lba = scsipkt->pkt_cdbp[2];
4927 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4928 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4929 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4930 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
4931 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
4932 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
4933 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
4934 		sec_count = scsipkt->pkt_cdbp[10];
4935 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
4936 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
4937 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
4938 		break;
4939 	default:
4940 		/* Unsupported command */
4941 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4942 		return (sata_txlt_invalid_command(spx));
4943 	}
4944 
4945 	/*
4946 	 * Check if specified address exceeds device capacity
4947 	 */
4948 	if ((lba >= sdinfo->satadrv_capacity) ||
4949 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
4950 		/* LBA out of range */
4951 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4952 		return (sata_txlt_lba_out_of_range(spx));
4953 	}
4954 
4955 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
4956 	scmd->satacmd_device_reg = SATA_ADH_LBA;
4957 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
4958 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
4959 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
4960 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
4961 		scmd->satacmd_sec_count_msb = sec_count >> 8;
4962 #ifndef __lock_lint
4963 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
4964 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
4965 		scmd->satacmd_lba_high_msb = lba >> 40;
4966 #endif
4967 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
4968 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
4969 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
4970 	}
4971 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
4972 	scmd->satacmd_lba_low_lsb = lba & 0xff;
4973 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
4974 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
4975 	scmd->satacmd_features_reg = 0;
4976 	scmd->satacmd_status_reg = 0;
4977 	scmd->satacmd_error_reg = 0;
4978 
4979 	/*
4980 	 * Check if queueing commands should be used and switch
4981 	 * to appropriate command if possible
4982 	 */
4983 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
4984 		boolean_t using_queuing;
4985 
4986 		/* Queuing supported by controller and device? */
4987 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
4988 		    (sdinfo->satadrv_features_support &
4989 		    SATA_DEV_F_NCQ) &&
4990 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4991 		    SATA_CTLF_NCQ)) {
4992 			using_queuing = B_TRUE;
4993 
4994 			/* NCQ supported - use FPDMA READ */
4995 			scmd->satacmd_cmd_reg =
4996 			    SATAC_READ_FPDMA_QUEUED;
4997 			scmd->satacmd_features_reg_ext =
4998 			    scmd->satacmd_sec_count_msb;
4999 			scmd->satacmd_sec_count_msb = 0;
5000 			scmd->satacmd_rle_sata_cmd = &sata_rle_cmd;
5001 		} else if ((sdinfo->satadrv_features_support &
5002 		    SATA_DEV_F_TCQ) &&
5003 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5004 		    SATA_CTLF_QCMD)) {
5005 			using_queuing = B_TRUE;
5006 
5007 			/* Legacy queueing */
5008 			if (sdinfo->satadrv_features_support &
5009 			    SATA_DEV_F_LBA48) {
5010 				scmd->satacmd_cmd_reg =
5011 				    SATAC_READ_DMA_QUEUED_EXT;
5012 				scmd->satacmd_features_reg_ext =
5013 				    scmd->satacmd_sec_count_msb;
5014 				scmd->satacmd_sec_count_msb = 0;
5015 			} else {
5016 				scmd->satacmd_cmd_reg =
5017 				    SATAC_READ_DMA_QUEUED;
5018 			}
5019 		} else	/* Queuing not supported */
5020 			using_queuing = B_FALSE;
5021 
5022 		/*
5023 		 * If queuing, the sector count goes in the features register
5024 		 * and the secount count will contain the tag.
5025 		 */
5026 		if (using_queuing) {
5027 			scmd->satacmd_features_reg =
5028 			    scmd->satacmd_sec_count_lsb;
5029 			scmd->satacmd_sec_count_lsb = 0;
5030 			scmd->satacmd_flags.sata_queued = B_TRUE;
5031 		}
5032 	}
5033 
5034 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
5035 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
5036 	    scmd->satacmd_cmd_reg, lba, sec_count);
5037 
5038 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5039 		/* Need callback function */
5040 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5041 		synch = FALSE;
5042 	} else
5043 		synch = TRUE;
5044 
5045 	/* Transfer command to HBA */
5046 	if (sata_hba_start(spx, &rval) != 0) {
5047 		/* Pkt not accepted for execution */
5048 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5049 		return (rval);
5050 	}
5051 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5052 	/*
5053 	 * If execution is non-synchronous,
5054 	 * a callback function will handle potential errors, translate
5055 	 * the response and will do a callback to a target driver.
5056 	 * If it was synchronous, check execution status using the same
5057 	 * framework callback.
5058 	 */
5059 	if (synch) {
5060 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5061 		    "synchronous execution status %x\n",
5062 		    spx->txlt_sata_pkt->satapkt_reason);
5063 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5064 	}
5065 	return (TRAN_ACCEPT);
5066 }
5067 
5068 
5069 /*
5070  * SATA translate command: Write (various types)
5071  * Translated into appropriate type of ATA WRITE command
5072  * (NO ATAPI implementation yet).
5073  * Both the device capabilities and requested operation mode are
5074  * considered.
5075  *
5076  * Following scsi cdb fields are ignored:
5077  * rwprotect, dpo, fua, fua_nv, group_number.
5078  *
5079  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5080  * appropriate values in scsi_pkt fields.
5081  */
5082 static int
5083 sata_txlt_write(sata_pkt_txlate_t *spx)
5084 {
5085 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5086 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5087 	sata_drive_info_t *sdinfo;
5088 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5089 	int cport = SATA_TXLT_CPORT(spx);
5090 	uint16_t sec_count;
5091 	uint64_t lba;
5092 	int rval;
5093 	int synch;
5094 
5095 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5096 
5097 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
5098 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5099 		return (rval);
5100 	}
5101 
5102 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5103 	    &spx->txlt_sata_pkt->satapkt_device);
5104 
5105 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5106 	/*
5107 	 * Build cmd block depending on the device capability and
5108 	 * requested operation mode.
5109 	 * Do not bother with non-dma mode.
5110 	 */
5111 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5112 	case SCMD_WRITE:
5113 		/* 6-byte scsi read cmd : 0x0A */
5114 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5115 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5116 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5117 		sec_count = scsipkt->pkt_cdbp[4];
5118 		/* sec_count 0 will be interpreted as 256 by a device */
5119 		break;
5120 	case SCMD_WRITE_G1:
5121 		/* 10-bytes scsi write command : 0x2A */
5122 		lba = scsipkt->pkt_cdbp[2];
5123 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5124 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5125 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5126 		sec_count = scsipkt->pkt_cdbp[7];
5127 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5128 		break;
5129 	case SCMD_WRITE_G5:
5130 		/* 12-bytes scsi read command : 0xAA */
5131 		lba = scsipkt->pkt_cdbp[2];
5132 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5133 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5134 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5135 		sec_count = scsipkt->pkt_cdbp[6];
5136 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5137 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5138 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5139 		break;
5140 	case SCMD_WRITE_G4:
5141 		/* 16-bytes scsi write command : 0x8A */
5142 		lba = scsipkt->pkt_cdbp[2];
5143 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5144 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5145 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5146 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5147 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5148 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5149 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5150 		sec_count = scsipkt->pkt_cdbp[10];
5151 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5152 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5153 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5154 		break;
5155 	default:
5156 		/* Unsupported command */
5157 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5158 		return (sata_txlt_invalid_command(spx));
5159 	}
5160 
5161 	/*
5162 	 * Check if specified address and length exceeds device capacity
5163 	 */
5164 	if ((lba >= sdinfo->satadrv_capacity) ||
5165 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5166 		/* LBA out of range */
5167 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5168 		return (sata_txlt_lba_out_of_range(spx));
5169 	}
5170 
5171 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5172 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5173 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
5174 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5175 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5176 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
5177 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5178 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5179 #ifndef __lock_lint
5180 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5181 		scmd->satacmd_lba_high_msb = lba >> 40;
5182 #endif
5183 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5184 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5185 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5186 	}
5187 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5188 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5189 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5190 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5191 	scmd->satacmd_features_reg = 0;
5192 	scmd->satacmd_status_reg = 0;
5193 	scmd->satacmd_error_reg = 0;
5194 
5195 	/*
5196 	 * Check if queueing commands should be used and switch
5197 	 * to appropriate command if possible
5198 	 */
5199 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5200 		boolean_t using_queuing;
5201 
5202 		/* Queuing supported by controller and device? */
5203 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5204 		    (sdinfo->satadrv_features_support &
5205 		    SATA_DEV_F_NCQ) &&
5206 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5207 		    SATA_CTLF_NCQ)) {
5208 			using_queuing = B_TRUE;
5209 
5210 			/* NCQ supported - use FPDMA WRITE */
5211 			scmd->satacmd_cmd_reg =
5212 			    SATAC_WRITE_FPDMA_QUEUED;
5213 			scmd->satacmd_features_reg_ext =
5214 			    scmd->satacmd_sec_count_msb;
5215 			scmd->satacmd_sec_count_msb = 0;
5216 			scmd->satacmd_rle_sata_cmd = &sata_rle_cmd;
5217 		} else if ((sdinfo->satadrv_features_support &
5218 		    SATA_DEV_F_TCQ) &&
5219 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5220 		    SATA_CTLF_QCMD)) {
5221 			using_queuing = B_TRUE;
5222 
5223 			/* Legacy queueing */
5224 			if (sdinfo->satadrv_features_support &
5225 			    SATA_DEV_F_LBA48) {
5226 				scmd->satacmd_cmd_reg =
5227 				    SATAC_WRITE_DMA_QUEUED_EXT;
5228 				scmd->satacmd_features_reg_ext =
5229 				    scmd->satacmd_sec_count_msb;
5230 				scmd->satacmd_sec_count_msb = 0;
5231 			} else {
5232 				scmd->satacmd_cmd_reg =
5233 				    SATAC_WRITE_DMA_QUEUED;
5234 			}
5235 		} else	/* Queuing not supported */
5236 			using_queuing = B_FALSE;
5237 
5238 		if (using_queuing) {
5239 			scmd->satacmd_features_reg =
5240 			    scmd->satacmd_sec_count_lsb;
5241 			scmd->satacmd_sec_count_lsb = 0;
5242 			scmd->satacmd_flags.sata_queued = B_TRUE;
5243 		}
5244 	}
5245 
5246 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5247 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
5248 	    scmd->satacmd_cmd_reg, lba, sec_count);
5249 
5250 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5251 		/* Need callback function */
5252 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5253 		synch = FALSE;
5254 	} else
5255 		synch = TRUE;
5256 
5257 	/* Transfer command to HBA */
5258 	if (sata_hba_start(spx, &rval) != 0) {
5259 		/* Pkt not accepted for execution */
5260 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5261 		return (rval);
5262 	}
5263 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5264 
5265 	/*
5266 	 * If execution is non-synchronous,
5267 	 * a callback function will handle potential errors, translate
5268 	 * the response and will do a callback to a target driver.
5269 	 * If it was synchronous, check execution status using the same
5270 	 * framework callback.
5271 	 */
5272 	if (synch) {
5273 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5274 		    "synchronous execution status %x\n",
5275 		    spx->txlt_sata_pkt->satapkt_reason);
5276 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5277 	}
5278 	return (TRAN_ACCEPT);
5279 }
5280 
5281 
5282 /*
5283  * NOTE: NOT FUNCTIONAL IMPLEMENTATION. THIS IS A PLACEHOLDER for the function
5284  * that will be fixed in phase 2 of the development.
5285  * Currently ATAPI is not supported. ATAPI devices are threated as not-valid
5286  * devices.
5287  * This function is not called, since scsi_sata_start() will bail-out prior
5288  * to calling it.
5289  */
5290 static int
5291 sata_txlt_atapi(sata_pkt_txlate_t *spx)
5292 {
5293 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5294 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5295 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5296 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5297 	int cport = SATA_TXLT_CPORT(spx);
5298 	int rval;
5299 	int synch;
5300 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
5301 
5302 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5303 
5304 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
5305 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5306 		return (rval);
5307 	}
5308 
5309 	/*
5310 	 * scmd->satacmd_flags.sata_data_direction default -
5311 	 * SATA_DIR_NODATA_XFER - is set by
5312 	 * sata_txlt_generic_pkt_info().
5313 	 */
5314 	if (scmd->satacmd_bp) {
5315 		if (scmd->satacmd_bp->b_flags & B_READ) {
5316 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5317 		} else {
5318 			scmd->satacmd_flags.sata_data_direction =
5319 			    SATA_DIR_WRITE;
5320 		}
5321 	}
5322 
5323 	scmd->satacmd_acdb_len = scsi_cdb_size[GETGROUP(cdbp)];
5324 	scmd->satacmd_cmd_reg = SATAC_PACKET;
5325 	bcopy(cdbp, scmd->satacmd_acdb,  16);
5326 
5327 	/*
5328 	 * For non-read/write commands we need to
5329 	 * map buffer
5330 	 */
5331 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5332 	case SCMD_READ:
5333 	case SCMD_READ_G1:
5334 	case SCMD_READ_G5:
5335 	case SCMD_READ_G4:
5336 	case SCMD_WRITE:
5337 	case SCMD_WRITE_G1:
5338 	case SCMD_WRITE_G5:
5339 	case SCMD_WRITE_G4:
5340 		break;
5341 	default:
5342 		if (bp->b_flags & (B_PHYS | B_PAGEIO))
5343 			bp_mapin(bp);
5344 		break;
5345 	}
5346 
5347 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5348 		/* Need callback function */
5349 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
5350 		synch = FALSE;
5351 	} else
5352 		synch = TRUE;
5353 
5354 	/* Transfer command to HBA */
5355 	if (sata_hba_start(spx, &rval) != 0) {
5356 		/* Pkt not accepted for execution */
5357 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5358 		return (rval);
5359 	}
5360 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5361 	/*
5362 	 * If execution is non-synchronous,
5363 	 * a callback function will handle potential errors, translate
5364 	 * the response and will do a callback to a target driver.
5365 	 * If it was synchronous, check execution status using the same
5366 	 * framework callback.
5367 	 */
5368 	if (synch) {
5369 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5370 		    "synchronous execution status %x\n",
5371 		    spx->txlt_sata_pkt->satapkt_reason);
5372 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
5373 	}
5374 	return (TRAN_ACCEPT);
5375 }
5376 
5377 /*
5378  * Translate command: Synchronize Cache.
5379  * Translates into Flush Cache command.
5380  * (NO ATAPI implementation yet).
5381  *
5382  * NOTE: We should check if Flush Cache is supported by the device (ATAPI
5383  * devices)
5384  *
5385  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5386  * appropriate values in scsi_pkt fields.
5387  */
5388 static 	int
5389 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
5390 {
5391 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5392 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5393 	int cport = SATA_TXLT_CPORT(spx);
5394 	int rval;
5395 	int synch;
5396 
5397 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5398 
5399 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
5400 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5401 		return (rval);
5402 	}
5403 
5404 	scmd->satacmd_addr_type = 0;
5405 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
5406 	scmd->satacmd_device_reg = 0;
5407 	scmd->satacmd_sec_count_lsb = 0;
5408 	scmd->satacmd_lba_low_lsb = 0;
5409 	scmd->satacmd_lba_mid_lsb = 0;
5410 	scmd->satacmd_lba_high_lsb = 0;
5411 	scmd->satacmd_features_reg = 0;
5412 	scmd->satacmd_status_reg = 0;
5413 	scmd->satacmd_error_reg = 0;
5414 
5415 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5416 	    "sata_txlt_synchronize_cache\n", NULL);
5417 
5418 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5419 		/* Need to set-up a callback function */
5420 		spx->txlt_sata_pkt->satapkt_comp =
5421 		    sata_txlt_nodata_cmd_completion;
5422 		synch = FALSE;
5423 	} else
5424 		synch = TRUE;
5425 
5426 	/* Transfer command to HBA */
5427 	if (sata_hba_start(spx, &rval) != 0) {
5428 		/* Pkt not accepted for execution */
5429 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5430 		return (rval);
5431 	}
5432 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5433 
5434 	/*
5435 	 * If execution non-synchronous, it had to be completed
5436 	 * a callback function will handle potential errors, translate
5437 	 * the response and will do a callback to a target driver.
5438 	 * If it was synchronous, check status, using the same
5439 	 * framework callback.
5440 	 */
5441 	if (synch) {
5442 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5443 		    "synchronous execution status %x\n",
5444 		    spx->txlt_sata_pkt->satapkt_reason);
5445 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
5446 	}
5447 	return (TRAN_ACCEPT);
5448 }
5449 
5450 /*
5451  * Send pkt to SATA HBA driver
5452  *
5453  * This function may be called only if the operation is requested by scsi_pkt,
5454  * i.e. scsi_pkt is not NULL.
5455  *
5456  * This function has to be called with cport mutex held. It does release
5457  * the mutex when it calls HBA driver sata_tran_start function and
5458  * re-acquires it afterwards.
5459  *
5460  * If return value is 0, pkt was accepted, -1 otherwise
5461  * rval is set to appropriate sata_scsi_start return value.
5462  *
5463  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
5464  * have called the sata_pkt callback function for this packet.
5465  *
5466  * The scsi callback has to be performed by the caller of this routine.
5467  *
5468  * Note 2: No port multiplier support for now.
5469  */
5470 static int
5471 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
5472 {
5473 	int stat;
5474 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
5475 	sata_drive_info_t *sdinfo;
5476 	sata_device_t *sata_device;
5477 	uint8_t cmd;
5478 	struct sata_cmd_flags cmd_flags;
5479 
5480 	ASSERT(spx->txlt_sata_pkt != NULL);
5481 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(spx->txlt_sata_hba_inst,
5482 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport)));
5483 
5484 	sdinfo = sata_get_device_info(sata_hba_inst,
5485 	    &spx->txlt_sata_pkt->satapkt_device);
5486 	ASSERT(sdinfo != NULL);
5487 
5488 	/* Clear device reset state? */
5489 	if (sdinfo->satadrv_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
5490 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
5491 		    sata_clear_dev_reset = B_TRUE;
5492 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_CLEAR_DEVICE_RESET;
5493 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5494 		    "sata_hba_start: clearing device reset state\n", NULL);
5495 	}
5496 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
5497 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
5498 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
5499 
5500 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
5501 	    sdinfo->satadrv_addr.cport)));
5502 
5503 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5504 	    "Sata cmd 0x%2x\n", cmd);
5505 
5506 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
5507 	    spx->txlt_sata_pkt);
5508 
5509 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
5510 	    sdinfo->satadrv_addr.cport)));
5511 	/*
5512 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
5513 	 * with the sata callback, the sata_pkt could be already destroyed
5514 	 * by the time we check ther return status from the hba_start()
5515 	 * function, because sata_scsi_destroy_pkt() could have been already
5516 	 * called (perhaps in the interrupt context). So, in such case, there
5517 	 * should be no references to it. In other cases, sata_pkt still
5518 	 * exists.
5519 	 */
5520 	switch (stat) {
5521 	case SATA_TRAN_ACCEPTED:
5522 		/*
5523 		 * pkt accepted for execution.
5524 		 * If it was executed synchronously, it is already completed
5525 		 * and pkt completion_reason indicates completion status.
5526 		 */
5527 		*rval = TRAN_ACCEPT;
5528 		return (0);
5529 
5530 	case SATA_TRAN_QUEUE_FULL:
5531 		/*
5532 		 * Controller detected queue full condition.
5533 		 */
5534 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
5535 		    "sata_hba_start: queue full\n", NULL);
5536 
5537 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
5538 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
5539 
5540 		*rval = TRAN_BUSY;
5541 		break;
5542 
5543 	case SATA_TRAN_PORT_ERROR:
5544 		/*
5545 		 * Communication/link with device or general port error
5546 		 * detected before pkt execution begun.
5547 		 */
5548 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
5549 		    SATA_ADDR_CPORT ||
5550 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
5551 		    SATA_ADDR_DCPORT)
5552 			sata_log(sata_hba_inst, CE_CONT,
5553 			    "port %d error",
5554 			    sata_device->satadev_addr.cport);
5555 		else
5556 			sata_log(sata_hba_inst, CE_CONT,
5557 			    "port %d pmport %d error\n",
5558 			    sata_device->satadev_addr.cport,
5559 			    sata_device->satadev_addr.pmport);
5560 
5561 		/*
5562 		 * Update the port/device structure.
5563 		 * sata_pkt should be still valid. Since port error is
5564 		 * returned, sata_device content should reflect port
5565 		 * state - it means, that sata address have been changed,
5566 		 * because original packet's sata address refered to a device
5567 		 * attached to some port.
5568 		 */
5569 		sata_update_port_info(sata_hba_inst, sata_device);
5570 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
5571 		*rval = TRAN_FATAL_ERROR;
5572 		break;
5573 
5574 	case SATA_TRAN_CMD_UNSUPPORTED:
5575 		/*
5576 		 * Command rejected by HBA as unsupported. It was HBA driver
5577 		 * that rejected the command, command was not sent to
5578 		 * an attached device.
5579 		 */
5580 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
5581 		    sdinfo->satadrv_addr.cport)));
5582 		(void) sata_txlt_invalid_command(spx);
5583 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
5584 		    sdinfo->satadrv_addr.cport)));
5585 
5586 		if (sdinfo->satadrv_state & SATA_DSTATE_RESET)
5587 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5588 			    "sat_hba_start: cmd 0x%2x rejected "
5589 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
5590 
5591 		*rval = TRAN_ACCEPT;
5592 		break;
5593 
5594 	case SATA_TRAN_BUSY:
5595 		/*
5596 		 * Command rejected by HBA because other operation prevents
5597 		 * accepting the packet, or device is in RESET condition.
5598 		 */
5599 		if (sdinfo != NULL) {
5600 			sdinfo->satadrv_state =
5601 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
5602 
5603 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
5604 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5605 				    "sata_hba_start: cmd 0x%2x rejected "
5606 				    "because of device reset condition\n",
5607 				    cmd);
5608 			} else {
5609 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5610 				    "sata_hba_start: cmd 0x%2x rejected "
5611 				    "with SATA_TRAN_BUSY status\n",
5612 				    cmd);
5613 			}
5614 		}
5615 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
5616 		*rval = TRAN_BUSY;
5617 		break;
5618 
5619 	default:
5620 		/* Unrecognized HBA response */
5621 		SATA_LOG_D((sata_hba_inst, CE_WARN,
5622 		    "sata_hba_start: unrecognized HBA response "
5623 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
5624 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
5625 		*rval = TRAN_FATAL_ERROR;
5626 		break;
5627 	}
5628 
5629 	/*
5630 	 * If we got here, the packet was rejected.
5631 	 * Check if we need to remember reset state clearing request
5632 	 */
5633 	if (cmd_flags.sata_clear_dev_reset) {
5634 		/*
5635 		 * Check if device is still configured - it may have
5636 		 * disapeared from the configuration
5637 		 */
5638 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
5639 		if (sdinfo != NULL) {
5640 			/*
5641 			 * Restore the flag that requests clearing of
5642 			 * the device reset state,
5643 			 * so the next sata packet may carry it to HBA.
5644 			 */
5645 			sdinfo->satadrv_event_flags |=
5646 			    SATA_EVNT_CLEAR_DEVICE_RESET;
5647 		}
5648 	}
5649 	return (-1);
5650 }
5651 
5652 /*
5653  * Scsi response setup for invalid LBA
5654  *
5655  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
5656  */
5657 static int
5658 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
5659 {
5660 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5661 	struct scsi_extended_sense *sense;
5662 
5663 	scsipkt->pkt_reason = CMD_CMPLT;
5664 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5665 		STATE_SENT_CMD | STATE_GOT_STATUS;
5666 	*scsipkt->pkt_scbp = STATUS_CHECK;
5667 
5668 	*scsipkt->pkt_scbp = STATUS_CHECK;
5669 	sense = sata_arq_sense(spx);
5670 	sense->es_key = KEY_ILLEGAL_REQUEST;
5671 	sense->es_add_code = SD_SCSI_LBA_OUT_OF_RANGE;
5672 
5673 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5674 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5675 
5676 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5677 	    scsipkt->pkt_comp != NULL)
5678 		/* scsi callback required */
5679 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5680 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5681 		    TQ_SLEEP) == 0)
5682 			/* Scheduling the callback failed */
5683 			return (TRAN_BUSY);
5684 	return (TRAN_ACCEPT);
5685 }
5686 
5687 
5688 /*
5689  * Analyze device status and error registers and translate them into
5690  * appropriate scsi sense codes.
5691  * NOTE: non-packet commands only for now
5692  */
5693 static void
5694 sata_decode_device_error(sata_pkt_txlate_t *spx,
5695     struct scsi_extended_sense *sense)
5696 {
5697 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
5698 
5699 	ASSERT(sense != NULL);
5700 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
5701 	    SATA_STATUS_ERR);
5702 
5703 
5704 	if (err_reg & SATA_ERROR_ICRC) {
5705 		sense->es_key = KEY_ABORTED_COMMAND;
5706 		sense->es_add_code = 0x08; /* Communication failure */
5707 		return;
5708 	}
5709 
5710 	if (err_reg & SATA_ERROR_UNC) {
5711 		sense->es_key = KEY_MEDIUM_ERROR;
5712 		/* Information bytes (LBA) need to be set by a caller */
5713 		return;
5714 	}
5715 
5716 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
5717 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
5718 		sense->es_key = KEY_UNIT_ATTENTION;
5719 		sense->es_add_code = 0x3a; /* No media present */
5720 		return;
5721 	}
5722 
5723 	if (err_reg & SATA_ERROR_IDNF) {
5724 		if (err_reg & SATA_ERROR_ABORT) {
5725 			sense->es_key = KEY_ABORTED_COMMAND;
5726 		} else {
5727 			sense->es_key = KEY_ILLEGAL_REQUEST;
5728 			sense->es_add_code = 0x21; /* LBA out of range */
5729 		}
5730 		return;
5731 	}
5732 
5733 	if (err_reg & SATA_ERROR_ABORT) {
5734 		ASSERT(spx->txlt_sata_pkt != NULL);
5735 		sense->es_key = KEY_ABORTED_COMMAND;
5736 		return;
5737 	}
5738 }
5739 
5740 /*
5741  * Extract error LBA from sata_pkt.satapkt_cmd register fields
5742  */
5743 static void
5744 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
5745 {
5746 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
5747 
5748 	*lba = 0;
5749 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
5750 		*lba = sata_cmd->satacmd_lba_high_msb;
5751 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
5752 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
5753 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
5754 		*lba = sata_cmd->satacmd_device_reg & 0xf;
5755 	}
5756 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
5757 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
5758 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
5759 }
5760 
5761 /*
5762  * This is fixed sense format - if LBA exceeds the info field size,
5763  * no valid info will be returned (valid bit in extended sense will
5764  * be set to 0).
5765  */
5766 static struct scsi_extended_sense *
5767 sata_arq_sense(sata_pkt_txlate_t *spx)
5768 {
5769 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5770 	struct scsi_arq_status *arqs;
5771 	struct scsi_extended_sense *sense;
5772 
5773 	/* Fill ARQ sense data */
5774 	scsipkt->pkt_state |= STATE_ARQ_DONE;
5775 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
5776 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
5777 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
5778 	arqs->sts_rqpkt_reason = CMD_CMPLT;
5779 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5780 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
5781 	arqs->sts_rqpkt_resid = 0;
5782 	sense = &arqs->sts_sensedata;
5783 	bzero(sense, sizeof (struct scsi_extended_sense));
5784 	sense->es_valid = 1;		/* Valid sense */
5785 	sense->es_class = 7;		/* Response code 0x70 - current err */
5786 	sense->es_key = KEY_NO_SENSE;
5787 	sense->es_info_1 = 0;
5788 	sense->es_info_2 = 0;
5789 	sense->es_info_3 = 0;
5790 	sense->es_info_4 = 0;
5791 	sense->es_add_len = 6;		/* Additional length */
5792 	sense->es_cmd_info[0] = 0;
5793 	sense->es_cmd_info[1] = 0;
5794 	sense->es_cmd_info[2] = 0;
5795 	sense->es_cmd_info[3] = 0;
5796 	sense->es_add_code = 0;
5797 	sense->es_qual_code = 0;
5798 	return (sense);
5799 }
5800 
5801 
5802 /*
5803  * Translate completion status of SATA read/write commands into scsi response.
5804  * pkt completion_reason is checked to determine the completion status.
5805  * Do scsi callback if necessary.
5806  *
5807  * Note: this function may be called also for synchronously executed
5808  * commands.
5809  * This function may be used only if scsi_pkt is non-NULL.
5810  */
5811 static void
5812 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
5813 {
5814 	sata_pkt_txlate_t *spx =
5815 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
5816 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
5817 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5818 	struct scsi_extended_sense *sense;
5819 	uint64_t lba;
5820 	struct buf *bp;
5821 	int rval;
5822 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5823 		/* Normal completion */
5824 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5825 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
5826 		scsipkt->pkt_reason = CMD_CMPLT;
5827 		*scsipkt->pkt_scbp = STATUS_GOOD;
5828 		if (spx->txlt_tmp_buf != NULL) {
5829 			/* Temporary buffer was used */
5830 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5831 			if (bp->b_flags & B_READ) {
5832 				rval = ddi_dma_sync(
5833 				    spx->txlt_buf_dma_handle, 0, 0,
5834 				    DDI_DMA_SYNC_FORCPU);
5835 				ASSERT(rval == DDI_SUCCESS);
5836 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
5837 				    bp->b_bcount);
5838 			}
5839 		}
5840 	} else {
5841 		/*
5842 		 * Something went wrong - analyze return
5843 		 */
5844 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5845 		    STATE_SENT_CMD | STATE_GOT_STATUS;
5846 		scsipkt->pkt_reason = CMD_INCOMPLETE;
5847 		*scsipkt->pkt_scbp = STATUS_CHECK;
5848 		sense = sata_arq_sense(spx);
5849 		ASSERT(sense != NULL);
5850 
5851 		/*
5852 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
5853 		 * extract from device registers the failing LBA.
5854 		 */
5855 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
5856 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
5857 			    (scmd->satacmd_lba_mid_msb != 0 ||
5858 			    scmd->satacmd_lba_high_msb != 0)) {
5859 				/*
5860 				 * We have problem reporting this cmd LBA
5861 				 * in fixed sense data format, because of
5862 				 * the size of the scsi LBA fields.
5863 				 */
5864 				sense->es_valid = 0;
5865 			} else {
5866 				sata_extract_error_lba(spx, &lba);
5867 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
5868 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
5869 				sense->es_info_3 = (lba & 0xFF00) >> 8;
5870 				sense->es_info_4 = lba & 0xFF;
5871 			}
5872 		} else {
5873 			/* Invalid extended sense info */
5874 			sense->es_valid = 0;
5875 		}
5876 
5877 		switch (sata_pkt->satapkt_reason) {
5878 		case SATA_PKT_PORT_ERROR:
5879 			/* We may want to handle DEV GONE state as well */
5880 			/*
5881 			 * We have no device data. Assume no data transfered.
5882 			 */
5883 			sense->es_key = KEY_HARDWARE_ERROR;
5884 			break;
5885 
5886 		case SATA_PKT_DEV_ERROR:
5887 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
5888 			    SATA_STATUS_ERR) {
5889 				/*
5890 				 * determine dev error reason from error
5891 				 * reg content
5892 				 */
5893 				sata_decode_device_error(spx, sense);
5894 				if (sense->es_key == KEY_MEDIUM_ERROR) {
5895 					switch (scmd->satacmd_cmd_reg) {
5896 					case SATAC_READ_DMA:
5897 					case SATAC_READ_DMA_EXT:
5898 					case SATAC_READ_DMA_QUEUED:
5899 					case SATAC_READ_DMA_QUEUED_EXT:
5900 					case SATAC_READ_FPDMA_QUEUED:
5901 						/* Unrecovered read error */
5902 						sense->es_add_code =
5903 						    SD_SCSI_UNREC_READ_ERROR;
5904 						break;
5905 					case SATAC_WRITE_DMA:
5906 					case SATAC_WRITE_DMA_EXT:
5907 					case SATAC_WRITE_DMA_QUEUED:
5908 					case SATAC_WRITE_DMA_QUEUED_EXT:
5909 					case SATAC_WRITE_FPDMA_QUEUED:
5910 						/* Write error */
5911 						sense->es_add_code =
5912 						    SD_SCSI_WRITE_ERROR;
5913 						break;
5914 					default:
5915 						/* Internal error */
5916 						SATA_LOG_D((
5917 						    spx->txlt_sata_hba_inst,
5918 						    CE_WARN,
5919 						    "sata_txlt_rw_completion :"
5920 						    "internal error - invalid "
5921 						    "command 0x%2x",
5922 						    scmd->satacmd_cmd_reg));
5923 						break;
5924 					}
5925 				}
5926 				break;
5927 			}
5928 			/* No extended sense key - no info available */
5929 			scsipkt->pkt_reason = CMD_INCOMPLETE;
5930 			break;
5931 
5932 		case SATA_PKT_TIMEOUT:
5933 			/* scsipkt->pkt_reason = CMD_TIMEOUT; */
5934 			scsipkt->pkt_reason = CMD_INCOMPLETE;
5935 			/* No extended sense key ? */
5936 			break;
5937 
5938 		case SATA_PKT_ABORTED:
5939 			scsipkt->pkt_reason = CMD_ABORTED;
5940 			/* No extended sense key ? */
5941 			break;
5942 
5943 		case SATA_PKT_RESET:
5944 			scsipkt->pkt_reason = CMD_RESET;
5945 			break;
5946 
5947 		default:
5948 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
5949 			    "sata_txlt_rw_completion: "
5950 			    "invalid packet completion reason"));
5951 			scsipkt->pkt_reason = CMD_TRAN_ERR;
5952 			break;
5953 		}
5954 	}
5955 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5956 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5957 
5958 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5959 	    scsipkt->pkt_comp != NULL)
5960 		/* scsi callback required */
5961 		(*scsipkt->pkt_comp)(scsipkt);
5962 
5963 }
5964 
5965 /*
5966  * NON FUNCTIONAL IMPLEMENTATION. THIS IS A PLACE HOLDER.
5967  * ATAPI devices are not supported currently (are not be attached recognized
5968  * as valid devices).
5969  * Will be fixed in phase 2 of the development.
5970  */
5971 static void
5972 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
5973 {
5974 	sata_pkt_txlate_t *spx =
5975 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
5976 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5977 	struct scsi_arq_status *arqs;
5978 
5979 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5980 		/* Normal completion */
5981 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5982 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
5983 		scsipkt->pkt_reason = CMD_CMPLT;
5984 		*scsipkt->pkt_scbp = STATUS_GOOD;
5985 		scsipkt->pkt_resid = 0;
5986 	} else {
5987 		/*
5988 		 * Something went wrong - analyze return
5989 		 */
5990 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5991 		    STATE_SENT_CMD | STATE_GOT_STATUS | STATE_ARQ_DONE;
5992 		scsipkt->pkt_reason = CMD_CMPLT;
5993 
5994 		arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
5995 		*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
5996 		*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
5997 		arqs->sts_rqpkt_reason = CMD_CMPLT;
5998 		arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5999 		    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
6000 		arqs->sts_rqpkt_resid = 0;
6001 
6002 		bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense,
6003 		    &arqs->sts_sensedata, SATA_ATAPI_RQSENSE_LEN);
6004 	}
6005 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6006 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6007 
6008 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6009 	    scsipkt->pkt_comp != NULL) {
6010 		/* scsi callback required */
6011 		(*scsipkt->pkt_comp)(scsipkt);
6012 	}
6013 }
6014 
6015 
6016 /*
6017  * Translate completion status of non-data commands (i.e. commands returning
6018  * no data).
6019  * pkt completion_reason is checked to determine the completion status.
6020  * Do scsi callback if necessary (FLAG_NOINTR == 0)
6021  *
6022  * Note: this function may be called also for synchronously executed
6023  * commands.
6024  * This function may be used only if scsi_pkt is non-NULL.
6025  */
6026 
6027 static 	void
6028 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
6029 {
6030 	sata_pkt_txlate_t *spx =
6031 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6032 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6033 	struct scsi_extended_sense *sense;
6034 
6035 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6036 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6037 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6038 		/* Normal completion */
6039 		scsipkt->pkt_reason = CMD_CMPLT;
6040 		*scsipkt->pkt_scbp = STATUS_GOOD;
6041 	} else {
6042 		/* Something went wrong */
6043 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6044 		*scsipkt->pkt_scbp = STATUS_CHECK;
6045 		sense = sata_arq_sense(spx);
6046 		switch (sata_pkt->satapkt_reason) {
6047 		case SATA_PKT_PORT_ERROR:
6048 			/*
6049 			 * We have no device data. Assume no data transfered.
6050 			 */
6051 			sense->es_key = KEY_HARDWARE_ERROR;
6052 			break;
6053 
6054 		case SATA_PKT_DEV_ERROR:
6055 		    if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6056 			SATA_STATUS_ERR) {
6057 			/*
6058 			 * determine dev error reason from error
6059 			 * reg content
6060 			 */
6061 			sata_decode_device_error(spx, sense);
6062 			break;
6063 		    }
6064 		    /* No extended sense key - no info available */
6065 		    break;
6066 
6067 		case SATA_PKT_TIMEOUT:
6068 			/* scsipkt->pkt_reason = CMD_TIMEOUT; */
6069 			scsipkt->pkt_reason = CMD_INCOMPLETE;
6070 			/* No extended sense key ? */
6071 			break;
6072 
6073 		case SATA_PKT_ABORTED:
6074 			scsipkt->pkt_reason = CMD_ABORTED;
6075 			/* No extended sense key ? */
6076 			break;
6077 
6078 		case SATA_PKT_RESET:
6079 			/* pkt aborted by an explicit reset from a host */
6080 			scsipkt->pkt_reason = CMD_RESET;
6081 			break;
6082 
6083 		default:
6084 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6085 			    "sata_txlt_nodata_cmd_completion: "
6086 			    "invalid packet completion reason %d",
6087 			    sata_pkt->satapkt_reason));
6088 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6089 			break;
6090 		}
6091 
6092 	}
6093 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6094 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6095 
6096 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6097 	    scsipkt->pkt_comp != NULL)
6098 		/* scsi callback required */
6099 		(*scsipkt->pkt_comp)(scsipkt);
6100 }
6101 
6102 
6103 /*
6104  * Build Mode sense R/W recovery page
6105  * NOT IMPLEMENTED
6106  */
6107 
6108 static int
6109 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6110 {
6111 #ifndef __lock_lint
6112 	_NOTE(ARGUNUSED(sdinfo))
6113 	_NOTE(ARGUNUSED(pcntrl))
6114 	_NOTE(ARGUNUSED(buf))
6115 #endif
6116 	return (0);
6117 }
6118 
6119 /*
6120  * Build Mode sense caching page  -  scsi-3 implementation.
6121  * Page length distinguishes previous format from scsi-3 format.
6122  * buf must have space for 0x12 bytes.
6123  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
6124  *
6125  */
6126 static int
6127 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6128 {
6129 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
6130 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6131 
6132 	/*
6133 	 * Most of the fields are set to 0, being not supported and/or disabled
6134 	 */
6135 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
6136 
6137 	/* Saved paramters not supported */
6138 	if (pcntrl == 3)
6139 		return (0);
6140 	if (pcntrl == 0 || pcntrl == 2) {
6141 		/*
6142 		 * For now treat current and default parameters as same
6143 		 * That may have to change, if target driver will complain
6144 		 */
6145 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
6146 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
6147 
6148 		if ((sata_id->ai_cmdset82 & SATA_LOOK_AHEAD) &&
6149 		    !(sata_id->ai_features85 & SATA_LOOK_AHEAD)) {
6150 			page->dra = 1;		/* Read Ahead disabled */
6151 			page->rcd = 1;		/* Read Cache disabled */
6152 		}
6153 		if ((sata_id->ai_cmdset82 & SATA_WRITE_CACHE) &&
6154 		    (sata_id->ai_features85 & SATA_WRITE_CACHE))
6155 			page->wce = 1;		/* Write Cache enabled */
6156 	} else {
6157 		/* Changeable parameters */
6158 		page->mode_page.code = MODEPAGE_CACHING;
6159 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
6160 		if (sata_id->ai_cmdset82 & SATA_LOOK_AHEAD) {
6161 			page->dra = 1;
6162 			page->rcd = 1;
6163 		}
6164 		if (sata_id->ai_cmdset82 & SATA_WRITE_CACHE)
6165 			page->wce = 1;
6166 	}
6167 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
6168 		sizeof (struct mode_page));
6169 }
6170 
6171 /*
6172  * Build Mode sense exception cntrl page
6173  */
6174 static int
6175 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6176 {
6177 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
6178 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6179 
6180 	/*
6181 	 * Most of the fields are set to 0, being not supported and/or disabled
6182 	 */
6183 	bzero(buf, PAGELENGTH_INFO_EXCPT);
6184 
6185 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
6186 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
6187 
6188 	/* Indicate that this is page is saveable */
6189 	page->mode_page.ps = 1;
6190 
6191 	/*
6192 	 * We will return the same data for default, current and saved page.
6193 	 * The only changeable bit is dexcpt and that bit is required
6194 	 * by the ATA specification to be preserved across power cycles.
6195 	 */
6196 	if (pcntrl != 1) {
6197 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
6198 		page->mrie = MRIE_ONLY_ON_REQUEST;
6199 	}
6200 	else
6201 		page->dexcpt = 1;	/* Only changeable parameter */
6202 
6203 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_info_excpt_page));
6204 }
6205 
6206 
6207 /*
6208  * Build Mode sense power condition page
6209  * NOT IMPLEMENTED.
6210  */
6211 static int
6212 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6213 {
6214 #ifndef __lock_lint
6215 	_NOTE(ARGUNUSED(sdinfo))
6216 	_NOTE(ARGUNUSED(pcntrl))
6217 	_NOTE(ARGUNUSED(buf))
6218 #endif
6219 	return (0);
6220 }
6221 
6222 
6223 /*
6224  * Process mode select caching page 8 (scsi3 format only).
6225  * Read Ahead (same as read cache) and Write Cache may be turned on and off
6226  * if these features are supported by the device. If these features are not
6227  * supported, quietly ignore them.
6228  * This function fails only if the SET FEATURE command sent to
6229  * the device fails. The page format is not varified, assuming that the
6230  * target driver operates correctly - if parameters length is too short,
6231  * we just drop the page.
6232  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
6233  * setting have to be changed.
6234  * SET FEATURE command is executed synchronously, i.e. we wait here until
6235  * it is completed, regardless of the scsi pkt directives.
6236  *
6237  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
6238  * changing DRA will change RCD.
6239  *
6240  * More than one SATA command may be executed to perform operations specified
6241  * by mode select pages. The first error terminates further execution.
6242  * Operations performed successully are not backed-up in such case.
6243  *
6244  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
6245  * If operation resulted in changing device setup, dmod flag should be set to
6246  * one (1). If parameters were not changed, dmod flag should be set to 0.
6247  * Upon return, if operation required sending command to the device, the rval
6248  * should be set to the value returned by sata_hba_start. If operation
6249  * did not require device access, rval should be set to TRAN_ACCEPT.
6250  * The pagelen should be set to the length of the page.
6251  *
6252  * This function has to be called with a port mutex held.
6253  *
6254  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
6255  */
6256 int
6257 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
6258     int parmlen, int *pagelen, int *rval, int *dmod)
6259 {
6260 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6261 	sata_drive_info_t *sdinfo;
6262 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6263 	sata_id_t *sata_id;
6264 	struct scsi_extended_sense *sense;
6265 	int wce, dra;	/* Current settings */
6266 
6267 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6268 	    &spx->txlt_sata_pkt->satapkt_device);
6269 	sata_id = &sdinfo->satadrv_id;
6270 	*dmod = 0;
6271 
6272 	/* Verify parameters length. If too short, drop it */
6273 	if (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
6274 	    sizeof (struct mode_page) < parmlen) {
6275 		*scsipkt->pkt_scbp = STATUS_CHECK;
6276 		sense = sata_arq_sense(spx);
6277 		sense->es_key = KEY_ILLEGAL_REQUEST;
6278 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_PARAMETER_LIST;
6279 		*pagelen = parmlen;
6280 		*rval = TRAN_ACCEPT;
6281 		return (SATA_FAILURE);
6282 	}
6283 
6284 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
6285 
6286 	/*
6287 	 * We can manipulate only write cache and read ahead
6288 	 * (read cache) setting.
6289 	 */
6290 	if (!(sata_id->ai_cmdset82 & SATA_LOOK_AHEAD) &&
6291 	    !(sata_id->ai_cmdset82 & SATA_WRITE_CACHE)) {
6292 		/*
6293 		 * None of the features is supported - ignore
6294 		 */
6295 		*rval = TRAN_ACCEPT;
6296 		return (SATA_SUCCESS);
6297 	}
6298 
6299 	/* Current setting of Read Ahead (and Read Cache) */
6300 	if (sata_id->ai_features85 & SATA_LOOK_AHEAD)
6301 		dra = 0;	/* 0 == not disabled */
6302 	else
6303 		dra = 1;
6304 	/* Current setting of Write Cache */
6305 	if (sata_id->ai_features85 & SATA_WRITE_CACHE)
6306 		wce = 1;
6307 	else
6308 		wce = 0;
6309 
6310 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
6311 		/* nothing to do */
6312 		*rval = TRAN_ACCEPT;
6313 		return (SATA_SUCCESS);
6314 	}
6315 	/*
6316 	 * Need to flip some setting
6317 	 * Set-up Internal SET FEATURES command(s)
6318 	 */
6319 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6320 	scmd->satacmd_addr_type = 0;
6321 	scmd->satacmd_device_reg = 0;
6322 	scmd->satacmd_status_reg = 0;
6323 	scmd->satacmd_error_reg = 0;
6324 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
6325 	if (page->dra != dra || page->rcd != dra) {
6326 		/* Need to flip read ahead setting */
6327 		if (dra == 0)
6328 			/* Disable read ahead / read cache */
6329 			scmd->satacmd_features_reg =
6330 			    SATAC_SF_DISABLE_READ_AHEAD;
6331 		else
6332 			/* Enable read ahead  / read cache */
6333 			scmd->satacmd_features_reg =
6334 			    SATAC_SF_ENABLE_READ_AHEAD;
6335 
6336 		/* Transfer command to HBA */
6337 		if (sata_hba_start(spx, rval) != 0)
6338 			/*
6339 			 * Pkt not accepted for execution.
6340 			 */
6341 			return (SATA_FAILURE);
6342 
6343 		*dmod = 1;
6344 
6345 		/* Now process return */
6346 		if (spx->txlt_sata_pkt->satapkt_reason !=
6347 		    SATA_PKT_COMPLETED) {
6348 			goto failure;	/* Terminate */
6349 		}
6350 	}
6351 
6352 	/* Note that the packet is not removed, so it could be re-used */
6353 	if (page->wce != wce) {
6354 		/* Need to flip Write Cache setting */
6355 		if (page->wce == 1)
6356 			/* Enable write cache */
6357 			scmd->satacmd_features_reg =
6358 			    SATAC_SF_ENABLE_WRITE_CACHE;
6359 		else
6360 			/* Disable write cache */
6361 			scmd->satacmd_features_reg =
6362 			    SATAC_SF_DISABLE_WRITE_CACHE;
6363 
6364 		/* Transfer command to HBA */
6365 		if (sata_hba_start(spx, rval) != 0)
6366 			/*
6367 			 * Pkt not accepted for execution.
6368 			 */
6369 			return (SATA_FAILURE);
6370 
6371 		*dmod = 1;
6372 
6373 		/* Now process return */
6374 		if (spx->txlt_sata_pkt->satapkt_reason !=
6375 		    SATA_PKT_COMPLETED) {
6376 			goto failure;
6377 		}
6378 	}
6379 	return (SATA_SUCCESS);
6380 
6381 failure:
6382 	sata_xlate_errors(spx);
6383 
6384 	return (SATA_FAILURE);
6385 }
6386 
6387 /*
6388  * Process mode select informational exceptions control page 0x1c
6389  *
6390  * The only changeable bit is dexcpt (disable exceptions).
6391  * MRIE (method of reporting informational exceptions) must be
6392  * "only on request".
6393  *
6394  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
6395  * If operation resulted in changing device setup, dmod flag should be set to
6396  * one (1). If parameters were not changed, dmod flag should be set to 0.
6397  * Upon return, if operation required sending command to the device, the rval
6398  * should be set to the value returned by sata_hba_start. If operation
6399  * did not require device access, rval should be set to TRAN_ACCEPT.
6400  * The pagelen should be set to the length of the page.
6401  *
6402  * This function has to be called with a port mutex held.
6403  *
6404  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
6405  */
6406 static	int
6407 sata_mode_select_page_1c(
6408 	sata_pkt_txlate_t *spx,
6409 	struct mode_info_excpt_page *page,
6410 	int parmlen,
6411 	int *pagelen,
6412 	int *rval,
6413 	int *dmod)
6414 {
6415 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6416 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6417 	sata_drive_info_t *sdinfo;
6418 	sata_id_t *sata_id;
6419 	struct scsi_extended_sense *sense;
6420 
6421 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6422 	    &spx->txlt_sata_pkt->satapkt_device);
6423 	sata_id = &sdinfo->satadrv_id;
6424 
6425 	*dmod = 0;
6426 
6427 	/* Verify parameters length. If too short, drop it */
6428 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) < parmlen) ||
6429 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
6430 		*scsipkt->pkt_scbp = STATUS_CHECK;
6431 		sense = sata_arq_sense(spx);
6432 		sense->es_key = KEY_ILLEGAL_REQUEST;
6433 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_PARAMETER_LIST;
6434 		*pagelen = parmlen;
6435 		*rval = TRAN_ACCEPT;
6436 		return (SATA_FAILURE);
6437 	}
6438 
6439 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
6440 
6441 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
6442 		*scsipkt->pkt_scbp = STATUS_CHECK;
6443 		sense = sata_arq_sense(spx);
6444 		sense->es_key = KEY_ILLEGAL_REQUEST;
6445 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
6446 		*pagelen = parmlen;
6447 		*rval = TRAN_ACCEPT;
6448 		return (SATA_FAILURE);
6449 	}
6450 
6451 	/* If already in the state requested, we are done */
6452 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
6453 		/* nothing to do */
6454 		*rval = TRAN_ACCEPT;
6455 		return (SATA_SUCCESS);
6456 	}
6457 
6458 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6459 
6460 	/* Build SMART_ENABLE or SMART_DISABLE command */
6461 	scmd->satacmd_addr_type = 0;		/* N/A */
6462 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
6463 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
6464 	scmd->satacmd_features_reg = page->dexcpt ?
6465 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
6466 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
6467 	scmd->satacmd_cmd_reg = SATAC_SMART;
6468 
6469 	/* Transfer command to HBA */
6470 	if (sata_hba_start(spx, rval) != 0)
6471 		/*
6472 		 * Pkt not accepted for execution.
6473 		 */
6474 		return (SATA_FAILURE);
6475 
6476 	*dmod = 1;	/* At least may have been modified */
6477 
6478 	/* Now process return */
6479 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
6480 		return (SATA_SUCCESS);
6481 
6482 	/* Packet did not complete successfully */
6483 	sata_xlate_errors(spx);
6484 
6485 	return (SATA_FAILURE);
6486 }
6487 
6488 /*
6489  * sata_build_lsense_page0() is used to create the
6490  * SCSI LOG SENSE page 0 (supported log pages)
6491  *
6492  * Currently supported pages are 0, 0x10, 0x2f and 0x30
6493  * (supported log pages, self-test results, informational exceptions
6494  *  and Sun vendor specific ATA SMART data).
6495  *
6496  * Takes a sata_drive_info t * and the address of a buffer
6497  * in which to create the page information.
6498  *
6499  * Returns the number of bytes valid in the buffer.
6500  */
6501 static	int
6502 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
6503 {
6504 	struct log_parameter *lpp = (struct log_parameter *)buf;
6505 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
6506 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
6507 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6508 
6509 	lpp->param_code[0] = 0;
6510 	lpp->param_code[1] = 0;
6511 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
6512 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
6513 
6514 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
6515 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
6516 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
6517 			++num_pages_supported;
6518 		}
6519 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
6520 		++num_pages_supported;
6521 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
6522 		++num_pages_supported;
6523 	}
6524 
6525 	lpp->param_len = num_pages_supported;
6526 
6527 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
6528 	    num_pages_supported);
6529 }
6530 
6531 /*
6532  * sata_build_lsense_page_10() is used to create the
6533  * SCSI LOG SENSE page 0x10 (self-test results)
6534  *
6535  * Takes a sata_drive_info t * and the address of a buffer
6536  * in which to create the page information as well as a sata_hba_inst_t *.
6537  *
6538  * Returns the number of bytes valid in the buffer.
6539  */
6540 static	int
6541 sata_build_lsense_page_10(
6542 	sata_drive_info_t *sdinfo,
6543 	uint8_t *buf,
6544 	sata_hba_inst_t *sata_hba_inst)
6545 {
6546 	struct log_parameter *lpp = (struct log_parameter *)buf;
6547 	int rval;
6548 
6549 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
6550 		struct smart_ext_selftest_log *ext_selftest_log;
6551 
6552 		ext_selftest_log = kmem_zalloc(
6553 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
6554 
6555 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
6556 		    ext_selftest_log, 0);
6557 		if (rval == 0) {
6558 			int index, start_index;
6559 			struct smart_ext_selftest_log_entry *entry;
6560 			static const struct smart_ext_selftest_log_entry empty =
6561 			    {0};
6562 			uint16_t block_num;
6563 			int count;
6564 			boolean_t only_one_block = B_FALSE;
6565 
6566 			index = ext_selftest_log->
6567 			    smart_ext_selftest_log_index[0];
6568 			index |= ext_selftest_log->
6569 			    smart_ext_selftest_log_index[1] << 8;
6570 			if (index == 0)
6571 				goto out;
6572 
6573 			--index;	/* Correct for 0 origin */
6574 			start_index = index;	/* remember where we started */
6575 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6576 			if (block_num != 0) {
6577 				rval = sata_ext_smart_selftest_read_log(
6578 				    sata_hba_inst, sdinfo, ext_selftest_log,
6579 				    block_num);
6580 				if (rval != 0)
6581 					goto out;
6582 			}
6583 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6584 			entry =
6585 			    &ext_selftest_log->
6586 			    smart_ext_selftest_log_entries[index];
6587 
6588 			for (count = 1;
6589 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
6590 			    ++count) {
6591 				uint8_t status;
6592 				uint8_t code;
6593 				uint8_t sense_key;
6594 				uint8_t add_sense_code;
6595 				uint8_t add_sense_code_qual;
6596 
6597 				/* If this is an unused entry, we are done */
6598 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
6599 					/* Broken firmware on some disks */
6600 					if (index + 1 ==
6601 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
6602 						--entry;
6603 						--index;
6604 						if (bcmp(entry, &empty,
6605 						    sizeof (empty)) == 0)
6606 							goto out;
6607 					} else
6608 						goto out;
6609 				}
6610 
6611 				if (only_one_block &&
6612 				    start_index == index)
6613 					goto out;
6614 
6615 				lpp->param_code[0] = 0;
6616 				lpp->param_code[1] = count;
6617 				lpp->param_ctrl_flags =
6618 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
6619 				lpp->param_len =
6620 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
6621 
6622 				status = entry->smart_ext_selftest_log_status;
6623 				status >>= 4;
6624 				switch (status) {
6625 				case 0:
6626 				default:
6627 					sense_key = KEY_NO_SENSE;
6628 					add_sense_code = SD_SCSI_NO_ADD_SENSE;
6629 					add_sense_code_qual = 0;
6630 					break;
6631 				case 1:
6632 					sense_key = KEY_ABORTED_COMMAND;
6633 					add_sense_code =
6634 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6635 					add_sense_code_qual = SCSI_COMPONENT_81;
6636 					break;
6637 				case 2:
6638 					sense_key = KEY_ABORTED_COMMAND;
6639 					add_sense_code =
6640 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6641 					add_sense_code_qual = SCSI_COMPONENT_82;
6642 					break;
6643 				case 3:
6644 					sense_key = KEY_ABORTED_COMMAND;
6645 					add_sense_code =
6646 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6647 					add_sense_code_qual = SCSI_COMPONENT_83;
6648 					break;
6649 				case 4:
6650 					sense_key = KEY_HARDWARE_ERROR;
6651 					add_sense_code =
6652 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6653 					add_sense_code_qual = SCSI_COMPONENT_84;
6654 					break;
6655 				case 5:
6656 					sense_key = KEY_HARDWARE_ERROR;
6657 					add_sense_code =
6658 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6659 					add_sense_code_qual = SCSI_COMPONENT_85;
6660 					break;
6661 				case 6:
6662 					sense_key = KEY_HARDWARE_ERROR;
6663 					add_sense_code =
6664 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6665 					add_sense_code_qual = SCSI_COMPONENT_86;
6666 					break;
6667 				case 7:
6668 					sense_key = KEY_MEDIUM_ERROR;
6669 					add_sense_code =
6670 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6671 					add_sense_code_qual = SCSI_COMPONENT_87;
6672 					break;
6673 				case 8:
6674 					sense_key = KEY_HARDWARE_ERROR;
6675 					add_sense_code =
6676 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6677 					add_sense_code_qual = SCSI_COMPONENT_88;
6678 					break;
6679 				}
6680 				code = 0;	/* unspecified */
6681 				status |= (code << 4);
6682 				lpp->param_values[0] = status;
6683 				lpp->param_values[1] = 0; /* unspecified */
6684 				lpp->param_values[2] = entry->
6685 				    smart_ext_selftest_log_timestamp[1];
6686 				lpp->param_values[3] = entry->
6687 				    smart_ext_selftest_log_timestamp[0];
6688 				if (status != 0) {
6689 					lpp->param_values[4] = 0;
6690 					lpp->param_values[5] = 0;
6691 					lpp->param_values[6] = entry->
6692 					    smart_ext_selftest_log_failing_lba
6693 					    [5];
6694 					lpp->param_values[7] = entry->
6695 					    smart_ext_selftest_log_failing_lba
6696 					    [4];
6697 					lpp->param_values[8] = entry->
6698 					    smart_ext_selftest_log_failing_lba
6699 					    [3];
6700 					lpp->param_values[9] = entry->
6701 					    smart_ext_selftest_log_failing_lba
6702 					    [2];
6703 					lpp->param_values[10] = entry->
6704 					    smart_ext_selftest_log_failing_lba
6705 					    [1];
6706 					lpp->param_values[11] = entry->
6707 					    smart_ext_selftest_log_failing_lba
6708 					    [0];
6709 				} else {	/* No bad block address */
6710 					lpp->param_values[4] = 0xff;
6711 					lpp->param_values[5] = 0xff;
6712 					lpp->param_values[6] = 0xff;
6713 					lpp->param_values[7] = 0xff;
6714 					lpp->param_values[8] = 0xff;
6715 					lpp->param_values[9] = 0xff;
6716 					lpp->param_values[10] = 0xff;
6717 					lpp->param_values[11] = 0xff;
6718 				}
6719 
6720 				lpp->param_values[12] = sense_key;
6721 				lpp->param_values[13] = add_sense_code;
6722 				lpp->param_values[14] = add_sense_code_qual;
6723 				lpp->param_values[15] = 0; /* undefined */
6724 
6725 				lpp = (struct log_parameter *)
6726 				    (((uint8_t *)lpp) +
6727 				    SCSI_LOG_PARAM_HDR_LEN +
6728 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
6729 
6730 				--index;	/* Back up to previous entry */
6731 				if (index < 0) {
6732 					if (block_num > 0) {
6733 						--block_num;
6734 					} else {
6735 						struct read_log_ext_directory
6736 						    logdir;
6737 
6738 						rval =
6739 						    sata_read_log_ext_directory(
6740 						    sata_hba_inst, sdinfo,
6741 						    &logdir);
6742 						if (rval == -1)
6743 							goto out;
6744 						if ((logdir.read_log_ext_vers
6745 						    [0] == 0) &&
6746 						    (logdir.read_log_ext_vers
6747 						    [1] == 0))
6748 							goto out;
6749 						block_num =
6750 						    logdir.read_log_ext_nblks
6751 						    [EXT_SMART_SELFTEST_LOG_PAGE
6752 						    - 1][0];
6753 						block_num |= logdir.
6754 						    read_log_ext_nblks
6755 						    [EXT_SMART_SELFTEST_LOG_PAGE
6756 						    - 1][1] << 8;
6757 						--block_num;
6758 						only_one_block =
6759 						    (block_num == 0);
6760 					}
6761 					rval = sata_ext_smart_selftest_read_log(
6762 					    sata_hba_inst, sdinfo,
6763 					    ext_selftest_log, block_num);
6764 					if (rval != 0)
6765 						goto out;
6766 
6767 					index =
6768 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
6769 					    1;
6770 				}
6771 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6772 				entry = &ext_selftest_log->
6773 				    smart_ext_selftest_log_entries[index];
6774 			}
6775 		}
6776 out:
6777 		kmem_free(ext_selftest_log,
6778 		    sizeof (struct smart_ext_selftest_log));
6779 	} else {
6780 		struct smart_selftest_log *selftest_log;
6781 
6782 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
6783 		    KM_SLEEP);
6784 
6785 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
6786 		    selftest_log);
6787 
6788 		if (rval == 0) {
6789 			int index;
6790 			int count;
6791 			struct smart_selftest_log_entry *entry;
6792 			static const struct smart_selftest_log_entry empty =
6793 			    { 0 };
6794 
6795 			index = selftest_log->smart_selftest_log_index;
6796 			if (index == 0)
6797 				goto done;
6798 			--index;	/* Correct for 0 origin */
6799 			entry = &selftest_log->
6800 			    smart_selftest_log_entries[index];
6801 			for (count = 1;
6802 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
6803 			    ++count) {
6804 				uint8_t status;
6805 				uint8_t code;
6806 				uint8_t sense_key;
6807 				uint8_t add_sense_code;
6808 				uint8_t add_sense_code_qual;
6809 
6810 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
6811 					goto done;
6812 
6813 				lpp->param_code[0] = 0;
6814 				lpp->param_code[1] = count;
6815 				lpp->param_ctrl_flags =
6816 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
6817 				lpp->param_len =
6818 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
6819 
6820 				status = entry->smart_selftest_log_status;
6821 				status >>= 4;
6822 				switch (status) {
6823 				case 0:
6824 				default:
6825 					sense_key = KEY_NO_SENSE;
6826 					add_sense_code = SD_SCSI_NO_ADD_SENSE;
6827 					break;
6828 				case 1:
6829 					sense_key = KEY_ABORTED_COMMAND;
6830 					add_sense_code =
6831 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6832 					add_sense_code_qual = SCSI_COMPONENT_81;
6833 					break;
6834 				case 2:
6835 					sense_key = KEY_ABORTED_COMMAND;
6836 					add_sense_code =
6837 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6838 					add_sense_code_qual = SCSI_COMPONENT_82;
6839 					break;
6840 				case 3:
6841 					sense_key = KEY_ABORTED_COMMAND;
6842 					add_sense_code =
6843 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6844 					add_sense_code_qual = SCSI_COMPONENT_83;
6845 					break;
6846 				case 4:
6847 					sense_key = KEY_HARDWARE_ERROR;
6848 					add_sense_code =
6849 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6850 					add_sense_code_qual = SCSI_COMPONENT_84;
6851 					break;
6852 				case 5:
6853 					sense_key = KEY_HARDWARE_ERROR;
6854 					add_sense_code =
6855 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6856 					add_sense_code_qual = SCSI_COMPONENT_85;
6857 					break;
6858 				case 6:
6859 					sense_key = KEY_HARDWARE_ERROR;
6860 					add_sense_code =
6861 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6862 					add_sense_code_qual = SCSI_COMPONENT_86;
6863 					break;
6864 				case 7:
6865 					sense_key = KEY_MEDIUM_ERROR;
6866 					add_sense_code =
6867 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6868 					add_sense_code_qual = SCSI_COMPONENT_87;
6869 					break;
6870 				case 8:
6871 					sense_key = KEY_HARDWARE_ERROR;
6872 					add_sense_code =
6873 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6874 					add_sense_code_qual = SCSI_COMPONENT_88;
6875 					break;
6876 				}
6877 				code = 0;	/* unspecified */
6878 				status |= (code << 4);
6879 				lpp->param_values[0] = status;
6880 				lpp->param_values[1] = 0; /* unspecified */
6881 				lpp->param_values[2] = entry->
6882 				    smart_selftest_log_timestamp[1];
6883 				lpp->param_values[3] = entry->
6884 				    smart_selftest_log_timestamp[0];
6885 				if (status != 0) {
6886 					lpp->param_values[4] = 0;
6887 					lpp->param_values[5] = 0;
6888 					lpp->param_values[6] = 0;
6889 					lpp->param_values[7] = 0;
6890 					lpp->param_values[8] = entry->
6891 					    smart_selftest_log_failing_lba[3];
6892 					lpp->param_values[9] = entry->
6893 					    smart_selftest_log_failing_lba[2];
6894 					lpp->param_values[10] = entry->
6895 					    smart_selftest_log_failing_lba[1];
6896 					lpp->param_values[11] = entry->
6897 					    smart_selftest_log_failing_lba[0];
6898 				} else {	/* No block address */
6899 					lpp->param_values[4] = 0xff;
6900 					lpp->param_values[5] = 0xff;
6901 					lpp->param_values[6] = 0xff;
6902 					lpp->param_values[7] = 0xff;
6903 					lpp->param_values[8] = 0xff;
6904 					lpp->param_values[9] = 0xff;
6905 					lpp->param_values[10] = 0xff;
6906 					lpp->param_values[11] = 0xff;
6907 				}
6908 				lpp->param_values[12] = sense_key;
6909 				lpp->param_values[13] = add_sense_code;
6910 				lpp->param_values[14] = add_sense_code_qual;
6911 				lpp->param_values[15] = 0; /* undefined */
6912 
6913 				lpp = (struct log_parameter *)
6914 				    (((uint8_t *)lpp) +
6915 				    SCSI_LOG_PARAM_HDR_LEN +
6916 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
6917 				--index;	/* back up to previous entry */
6918 				if (index < 0) {
6919 					index =
6920 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
6921 				}
6922 				entry = &selftest_log->
6923 					smart_selftest_log_entries[index];
6924 			}
6925 		}
6926 done:
6927 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
6928 	}
6929 
6930 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
6931 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
6932 }
6933 
6934 /*
6935  * sata_build_lsense_page_2f() is used to create the
6936  * SCSI LOG SENSE page 0x10 (informational exceptions)
6937  *
6938  * Takes a sata_drive_info t * and the address of a buffer
6939  * in which to create the page information as well as a sata_hba_inst_t *.
6940  *
6941  * Returns the number of bytes valid in the buffer.
6942  */
6943 static	int
6944 sata_build_lsense_page_2f(
6945 	sata_drive_info_t *sdinfo,
6946 	uint8_t *buf,
6947 	sata_hba_inst_t *sata_hba_inst)
6948 {
6949 	struct log_parameter *lpp = (struct log_parameter *)buf;
6950 	int rval;
6951 	uint8_t *smart_data;
6952 	uint8_t temp;
6953 	sata_id_t *sata_id;
6954 #define	SMART_NO_TEMP	0xff
6955 
6956 	lpp->param_code[0] = 0;
6957 	lpp->param_code[1] = 0;
6958 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
6959 
6960 	/* Now get the SMART status w.r.t. threshold exceeded */
6961 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
6962 	switch (rval) {
6963 	case 1:
6964 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
6965 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
6966 		break;
6967 	case 0:
6968 	case -1:	/* failed to get data */
6969 		lpp->param_values[0] = 0;	/* No failure predicted */
6970 		lpp->param_values[1] = 0;
6971 		break;
6972 #if defined(SATA_DEBUG)
6973 	default:
6974 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
6975 		/* NOTREACHED */
6976 #endif
6977 	}
6978 
6979 	sata_id = &sdinfo->satadrv_id;
6980 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
6981 		temp = SMART_NO_TEMP;
6982 	else {
6983 		/* Now get the temperature */
6984 		smart_data = kmem_zalloc(512, KM_SLEEP);
6985 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
6986 		    SCT_STATUS_LOG_PAGE, 1);
6987 		if (rval == -1)
6988 			temp = SMART_NO_TEMP;
6989 		else {
6990 			temp = smart_data[200];
6991 			if (temp & 0x80) {
6992 				if (temp & 0x7f)
6993 					temp = 0;
6994 				else
6995 					temp = SMART_NO_TEMP;
6996 			}
6997 		}
6998 		kmem_free(smart_data, 512);
6999 	}
7000 
7001 	lpp->param_values[2] = temp;	/* most recent temperature */
7002 	lpp->param_values[3] = 0;	/* required vendor specific byte */
7003 
7004 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
7005 
7006 
7007 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
7008 }
7009 
7010 /*
7011  * sata_build_lsense_page_30() is used to create the
7012  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
7013  *
7014  * Takes a sata_drive_info t * and the address of a buffer
7015  * in which to create the page information as well as a sata_hba_inst_t *.
7016  *
7017  * Returns the number of bytes valid in the buffer.
7018  */
7019 static int
7020 sata_build_lsense_page_30(
7021 	sata_drive_info_t *sdinfo,
7022 	uint8_t *buf,
7023 	sata_hba_inst_t *sata_hba_inst)
7024 {
7025 	struct smart_data *smart_data = (struct smart_data *)buf;
7026 	int rval;
7027 
7028 	/* Now do the SMART READ DATA */
7029 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
7030 	if (rval == -1)
7031 		return (0);
7032 
7033 	return (sizeof (struct smart_data));
7034 }
7035 
7036 
7037 
7038 
7039 
7040 /* ************************** LOCAL FUNCTIONS ************************** */
7041 
7042 /*
7043  * Validate sata_tran info
7044  * SATA_FAILURE returns if structure is inconsistent or structure revision
7045  * does not match one used by the framework.
7046  *
7047  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
7048  * required function pointers.
7049  * Returns SATA_FAILURE otherwise.
7050  */
7051 static int
7052 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
7053 {
7054 	if (sata_tran->sata_tran_hba_rev != SATA_TRAN_HBA_REV) {
7055 		sata_log(NULL, CE_WARN,
7056 		    "sata: invalid sata_hba_tran version %d for driver %s",
7057 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
7058 		return (SATA_FAILURE);
7059 	}
7060 
7061 	if (dip != sata_tran->sata_tran_hba_dip) {
7062 		SATA_LOG_D((NULL, CE_WARN,
7063 		    "sata: inconsistent sata_tran_hba_dip "
7064 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
7065 		return (SATA_FAILURE);
7066 	}
7067 
7068 	if (sata_tran->sata_tran_probe_port == NULL ||
7069 	    sata_tran->sata_tran_start == NULL ||
7070 	    sata_tran->sata_tran_abort == NULL ||
7071 	    sata_tran->sata_tran_reset_dport == NULL) {
7072 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
7073 		    "required functions"));
7074 	}
7075 	return (SATA_SUCCESS);
7076 }
7077 
7078 /*
7079  * Remove HBA instance from sata_hba_list.
7080  */
7081 static void
7082 sata_remove_hba_instance(dev_info_t *dip)
7083 {
7084 	sata_hba_inst_t	*sata_hba_inst;
7085 
7086 	mutex_enter(&sata_mutex);
7087 	for (sata_hba_inst = sata_hba_list;
7088 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
7089 	    sata_hba_inst = sata_hba_inst->satahba_next) {
7090 		if (sata_hba_inst->satahba_dip == dip)
7091 			break;
7092 	}
7093 
7094 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
7095 #ifdef SATA_DEBUG
7096 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
7097 		    "unknown HBA instance\n");
7098 #endif
7099 		ASSERT(FALSE);
7100 	}
7101 	if (sata_hba_inst == sata_hba_list) {
7102 		sata_hba_list = sata_hba_inst->satahba_next;
7103 		if (sata_hba_list) {
7104 			sata_hba_list->satahba_prev =
7105 			    (struct sata_hba_inst *)NULL;
7106 		}
7107 		if (sata_hba_inst == sata_hba_list_tail) {
7108 			sata_hba_list_tail = NULL;
7109 		}
7110 	} else if (sata_hba_inst == sata_hba_list_tail) {
7111 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
7112 		if (sata_hba_list_tail) {
7113 			sata_hba_list_tail->satahba_next =
7114 			    (struct sata_hba_inst *)NULL;
7115 		}
7116 	} else {
7117 		sata_hba_inst->satahba_prev->satahba_next =
7118 		    sata_hba_inst->satahba_next;
7119 		sata_hba_inst->satahba_next->satahba_prev =
7120 		    sata_hba_inst->satahba_prev;
7121 	}
7122 	mutex_exit(&sata_mutex);
7123 }
7124 
7125 
7126 
7127 
7128 
7129 /*
7130  * Probe all SATA ports of the specified HBA instance.
7131  * The assumption is that there are no target and attachment point minor nodes
7132  * created by the boot subsystems, so we do not need to prune device tree.
7133  *
7134  * This function is called only from sata_hba_attach(). It does not have to
7135  * be protected by controller mutex, because the hba_attached flag is not set
7136  * yet and no one would be touching this HBA instance other then this thread.
7137  * Determines if port is active and what type of the device is attached
7138  * (if any). Allocates necessary structures for each port.
7139  *
7140  * An AP (Attachement Point) node is created for each SATA device port even
7141  * when there is no device attached.
7142  */
7143 
7144 static 	void
7145 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
7146 {
7147 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
7148 	int			ncport, npmport;
7149 	sata_cport_info_t 	*cportinfo;
7150 	sata_drive_info_t	*drive;
7151 	sata_pmult_info_t	*pminfo;
7152 	sata_pmport_info_t 	*pmportinfo;
7153 	sata_device_t		sata_device;
7154 	int			rval;
7155 	dev_t			minor_number;
7156 	char			name[16];
7157 	clock_t			start_time, cur_time;
7158 
7159 	/*
7160 	 * Probe controller ports first, to find port status and
7161 	 * any port multiplier attached.
7162 	 */
7163 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
7164 		/* allocate cport structure */
7165 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
7166 		ASSERT(cportinfo != NULL);
7167 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
7168 
7169 		mutex_enter(&cportinfo->cport_mutex);
7170 
7171 		cportinfo->cport_addr.cport = ncport;
7172 		cportinfo->cport_addr.pmport = 0;
7173 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
7174 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
7175 		cportinfo->cport_state |= SATA_STATE_PROBING;
7176 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
7177 
7178 		/*
7179 		 * Regardless if a port is usable or not, create
7180 		 * an attachment point
7181 		 */
7182 		mutex_exit(&cportinfo->cport_mutex);
7183 		minor_number =
7184 		    SATA_MAKE_AP_MINOR(ddi_get_instance(dip), ncport, 0, 0);
7185 		(void) sprintf(name, "%d", ncport);
7186 		if (ddi_create_minor_node(dip, name, S_IFCHR,
7187 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
7188 		    DDI_SUCCESS) {
7189 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
7190 			    "cannot create sata attachment point for port %d",
7191 			    ncport);
7192 		}
7193 
7194 		/* Probe port */
7195 		start_time = ddi_get_lbolt();
7196 	reprobe_cport:
7197 		sata_device.satadev_addr.cport = ncport;
7198 		sata_device.satadev_addr.pmport = 0;
7199 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
7200 		sata_device.satadev_rev = SATA_DEVICE_REV;
7201 
7202 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
7203 		    (dip, &sata_device);
7204 
7205 		mutex_enter(&cportinfo->cport_mutex);
7206 		sata_update_port_scr(&cportinfo->cport_scr, &sata_device);
7207 		if (rval != SATA_SUCCESS) {
7208 			/* Something went wrong? Fail the port */
7209 			cportinfo->cport_state = SATA_PSTATE_FAILED;
7210 			mutex_exit(&cportinfo->cport_mutex);
7211 			continue;
7212 		}
7213 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
7214 		cportinfo->cport_state |= SATA_STATE_PROBED;
7215 		cportinfo->cport_dev_type = sata_device.satadev_type;
7216 
7217 		cportinfo->cport_state |= SATA_STATE_READY;
7218 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
7219 			mutex_exit(&cportinfo->cport_mutex);
7220 			continue;
7221 		}
7222 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
7223 			/*
7224 			 * There is some device attached.
7225 			 * Allocate device info structure
7226 			 */
7227 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
7228 				mutex_exit(&cportinfo->cport_mutex);
7229 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
7230 				    kmem_zalloc(sizeof (sata_drive_info_t),
7231 				    KM_SLEEP);
7232 				mutex_enter(&cportinfo->cport_mutex);
7233 			}
7234 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
7235 			drive->satadrv_addr = cportinfo->cport_addr;
7236 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
7237 			drive->satadrv_type = cportinfo->cport_dev_type;
7238 			drive->satadrv_state = SATA_STATE_UNKNOWN;
7239 
7240 			mutex_exit(&cportinfo->cport_mutex);
7241 			if (sata_add_device(dip, sata_hba_inst, ncport, 0) !=
7242 			    SATA_SUCCESS) {
7243 				/*
7244 				 * Plugged device was not correctly identified.
7245 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
7246 				 */
7247 				cur_time = ddi_get_lbolt();
7248 				if ((cur_time - start_time) <
7249 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
7250 					/* sleep for a while */
7251 					delay(drv_usectohz(
7252 					    SATA_DEV_IDENTIFY_RETRY_DELAY));
7253 					goto reprobe_cport;
7254 				}
7255 			}
7256 		} else {
7257 			mutex_exit(&cportinfo->cport_mutex);
7258 			ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
7259 			pminfo = kmem_zalloc(sizeof (sata_pmult_info_t),
7260 			    KM_SLEEP);
7261 			mutex_enter(&cportinfo->cport_mutex);
7262 			ASSERT(pminfo != NULL);
7263 			SATA_CPORTINFO_PMULT_INFO(cportinfo) = pminfo;
7264 			pminfo->pmult_addr.cport = cportinfo->cport_addr.cport;
7265 			pminfo->pmult_addr.pmport = SATA_PMULT_HOSTPORT;
7266 			pminfo->pmult_addr.qual = SATA_ADDR_PMPORT;
7267 			pminfo->pmult_num_dev_ports =
7268 			    sata_device.satadev_add_info;
7269 			mutex_init(&pminfo->pmult_mutex, NULL, MUTEX_DRIVER,
7270 			    NULL);
7271 			pminfo->pmult_state = SATA_STATE_PROBING;
7272 			mutex_exit(&cportinfo->cport_mutex);
7273 
7274 			/* Probe Port Multiplier ports */
7275 			for (npmport = 0;
7276 			    npmport < pminfo->pmult_num_dev_ports;
7277 			    npmport++) {
7278 				pmportinfo = kmem_zalloc(
7279 				    sizeof (sata_pmport_info_t), KM_SLEEP);
7280 				mutex_enter(&cportinfo->cport_mutex);
7281 				ASSERT(pmportinfo != NULL);
7282 				pmportinfo->pmport_addr.cport = ncport;
7283 				pmportinfo->pmport_addr.pmport = npmport;
7284 				pmportinfo->pmport_addr.qual =
7285 				    SATA_ADDR_PMPORT;
7286 				pminfo->pmult_dev_port[npmport] = pmportinfo;
7287 
7288 				mutex_init(&pmportinfo->pmport_mutex, NULL,
7289 				    MUTEX_DRIVER, NULL);
7290 
7291 				mutex_exit(&cportinfo->cport_mutex);
7292 
7293 				/* Create an attachment point */
7294 				minor_number = SATA_MAKE_AP_MINOR(
7295 				    ddi_get_instance(dip), ncport, npmport, 1);
7296 				(void) sprintf(name, "%d.%d", ncport, npmport);
7297 				if (ddi_create_minor_node(dip, name, S_IFCHR,
7298 				    minor_number, DDI_NT_SATA_ATTACHMENT_POINT,
7299 				    0) != DDI_SUCCESS) {
7300 					sata_log(sata_hba_inst, CE_WARN,
7301 					    "sata_hba_attach: "
7302 					    "cannot create sata attachment "
7303 					    "point for port %d pmult port %d",
7304 					    ncport, npmport);
7305 				}
7306 
7307 				start_time = ddi_get_lbolt();
7308 			reprobe_pmport:
7309 				sata_device.satadev_addr.pmport = npmport;
7310 				sata_device.satadev_addr.qual =
7311 				    SATA_ADDR_PMPORT;
7312 
7313 				rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
7314 				    (dip, &sata_device);
7315 				mutex_enter(&cportinfo->cport_mutex);
7316 
7317 				/* sata_update_port_info() */
7318 				sata_update_port_scr(&pmportinfo->pmport_scr,
7319 				    &sata_device);
7320 
7321 				if (rval != SATA_SUCCESS) {
7322 					pmportinfo->pmport_state =
7323 					    SATA_PSTATE_FAILED;
7324 					mutex_exit(&cportinfo->cport_mutex);
7325 					continue;
7326 				}
7327 				pmportinfo->pmport_state &=
7328 				    ~SATA_STATE_PROBING;
7329 				pmportinfo->pmport_state |= SATA_STATE_PROBED;
7330 				pmportinfo->pmport_dev_type =
7331 				    sata_device.satadev_type;
7332 
7333 				pmportinfo->pmport_state |= SATA_STATE_READY;
7334 				if (pmportinfo->pmport_dev_type ==
7335 				    SATA_DTYPE_NONE) {
7336 					mutex_exit(&cportinfo->cport_mutex);
7337 					continue;
7338 				}
7339 				/* Port multipliers cannot be chained */
7340 				ASSERT(pmportinfo->pmport_dev_type !=
7341 				    SATA_DTYPE_PMULT);
7342 				/*
7343 				 * There is something attached to Port
7344 				 * Multiplier device port
7345 				 * Allocate device info structure
7346 				 */
7347 				if (pmportinfo->pmport_sata_drive == NULL) {
7348 					mutex_exit(&cportinfo->cport_mutex);
7349 					pmportinfo->pmport_sata_drive =
7350 					    kmem_zalloc(
7351 					    sizeof (sata_drive_info_t),
7352 					    KM_SLEEP);
7353 					mutex_enter(&cportinfo->cport_mutex);
7354 				}
7355 				drive = pmportinfo->pmport_sata_drive;
7356 				drive->satadrv_addr.cport =
7357 				    pmportinfo->pmport_addr.cport;
7358 				drive->satadrv_addr.pmport = npmport;
7359 				drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
7360 				drive->satadrv_type = pmportinfo->
7361 				    pmport_dev_type;
7362 				drive->satadrv_state = SATA_STATE_UNKNOWN;
7363 
7364 				mutex_exit(&cportinfo->cport_mutex);
7365 				if (sata_add_device(dip, sata_hba_inst, ncport,
7366 				    npmport) != SATA_SUCCESS) {
7367 					/*
7368 					 * Plugged device was not correctly
7369 					 * identified. Retry, within the
7370 					 * SATA_DEV_IDENTIFY_TIMEOUT
7371 					 */
7372 					cur_time = ddi_get_lbolt();
7373 					if ((cur_time - start_time) <
7374 					    drv_usectohz(
7375 					    SATA_DEV_IDENTIFY_TIMEOUT)) {
7376 						/* sleep for a while */
7377 						delay(drv_usectohz(
7378 						SATA_DEV_IDENTIFY_RETRY_DELAY));
7379 						goto reprobe_pmport;
7380 					}
7381 				}
7382 			}
7383 			pmportinfo->pmport_state =
7384 			    SATA_STATE_PROBED | SATA_STATE_READY;
7385 		}
7386 	}
7387 }
7388 
7389 /*
7390  * Add SATA device for specified HBA instance & port (SCSI target
7391  * device nodes).
7392  * This function is called (indirectly) only from sata_hba_attach().
7393  * A target node is created when there is a supported type device attached,
7394  * but may be removed if it cannot be put online.
7395  *
7396  * This function cannot be called from an interrupt context.
7397  *
7398  * ONLY DISK TARGET NODES ARE CREATED NOW
7399  *
7400  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
7401  * device identification failed - adding a device could be retried.
7402  *
7403  */
7404 static 	int
7405 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst, int cport,
7406     int pmport)
7407 {
7408 	sata_cport_info_t 	*cportinfo;
7409 	sata_pmult_info_t	*pminfo;
7410 	sata_pmport_info_t	*pmportinfo;
7411 	dev_info_t		*cdip;		/* child dip */
7412 	sata_device_t		sata_device;
7413 	int			rval;
7414 
7415 
7416 
7417 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
7418 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
7419 	mutex_enter(&cportinfo->cport_mutex);
7420 	/*
7421 	 * Some device is attached to a controller port.
7422 	 * We rely on controllers distinquishing between no-device,
7423 	 * attached port multiplier and other kind of attached device.
7424 	 * We need to get Identify Device data and determine
7425 	 * positively the dev type before trying to attach
7426 	 * the target driver.
7427 	 */
7428 	sata_device.satadev_rev = SATA_DEVICE_REV;
7429 	if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
7430 		/*
7431 		 * Not port multiplier.
7432 		 */
7433 		sata_device.satadev_addr = cportinfo->cport_addr;
7434 		sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
7435 		mutex_exit(&cportinfo->cport_mutex);
7436 
7437 		rval = sata_probe_device(sata_hba_inst, &sata_device);
7438 		if (rval != SATA_SUCCESS ||
7439 		    sata_device.satadev_type == SATA_DTYPE_UNKNOWN)
7440 			return (SATA_FAILURE);
7441 
7442 		mutex_enter(&cportinfo->cport_mutex);
7443 		if ((sata_device.satadev_type & SATA_VALID_DEV_TYPE) == 0) {
7444 			/*
7445 			 * Could not determine device type or
7446 			 * a device is not supported.
7447 			 * Degrade this device to unknown.
7448 			 */
7449 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
7450 			mutex_exit(&cportinfo->cport_mutex);
7451 			return (SATA_SUCCESS);
7452 		}
7453 		cportinfo->cport_dev_type = sata_device.satadev_type;
7454 		mutex_exit(&cportinfo->cport_mutex);
7455 
7456 		/*
7457 		 * Initialize device to the desired state. Even if it
7458 		 * fails, the device will still attach but syslog
7459 		 * will show the warning.
7460 		 */
7461 		if (sata_initialize_device(sata_hba_inst,
7462 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS)
7463 			/* Retry */
7464 			(void) sata_initialize_device(sata_hba_inst,
7465 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
7466 
7467 		mutex_enter(&cportinfo->cport_mutex);
7468 		sata_show_drive_info(sata_hba_inst,
7469 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
7470 		mutex_exit(&cportinfo->cport_mutex);
7471 		cdip = sata_create_target_node(pdip, sata_hba_inst,
7472 		    &sata_device.satadev_addr);
7473 		mutex_enter(&cportinfo->cport_mutex);
7474 		if (cdip == NULL) {
7475 			/*
7476 			 * Attaching target node failed.
7477 			 * We retain sata_drive_info structure...
7478 			 */
7479 			(SATA_CPORTINFO_DRV_INFO(cportinfo))->
7480 			    satadrv_type = SATA_DTYPE_UNKNOWN;
7481 			(SATA_CPORTINFO_DRV_INFO(cportinfo))->
7482 			    satadrv_state = SATA_STATE_UNKNOWN;
7483 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
7484 			mutex_exit(&cportinfo->cport_mutex);
7485 			return (SATA_SUCCESS);
7486 		}
7487 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
7488 		    satadrv_state = SATA_STATE_READY;
7489 	} else {
7490 		/* This must be Port Multiplier type */
7491 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
7492 			SATA_LOG_D((sata_hba_inst, CE_WARN,
7493 			    "sata_add_device: "
7494 			    "unrecognized dev type %x",
7495 			    cportinfo->cport_dev_type));
7496 			mutex_exit(&cportinfo->cport_mutex);
7497 			return (SATA_SUCCESS);
7498 		}
7499 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
7500 		pmportinfo = pminfo->pmult_dev_port[pmport];
7501 		sata_device.satadev_addr = pmportinfo->pmport_addr;
7502 		sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
7503 		mutex_exit(&cportinfo->cport_mutex);
7504 
7505 		rval = sata_probe_device(sata_hba_inst, &sata_device);
7506 		if (rval != SATA_SUCCESS ||
7507 		    sata_device.satadev_type == SATA_DTYPE_UNKNOWN) {
7508 			return (SATA_FAILURE);
7509 		}
7510 		mutex_enter(&cportinfo->cport_mutex);
7511 		if ((sata_device.satadev_type & SATA_VALID_DEV_TYPE) == 0) {
7512 			/*
7513 			 * Could not determine device type.
7514 			 * Degrade this device to unknown.
7515 			 */
7516 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
7517 			mutex_exit(&cportinfo->cport_mutex);
7518 			return (SATA_SUCCESS);
7519 		}
7520 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
7521 		mutex_exit(&cportinfo->cport_mutex);
7522 		/*
7523 		 * Initialize device to the desired state.
7524 		 * Even if it fails, the device will still
7525 		 * attach but syslog will show the warning.
7526 		 */
7527 		if (sata_initialize_device(sata_hba_inst,
7528 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS)
7529 			/* Retry */
7530 			(void) sata_initialize_device(sata_hba_inst,
7531 			    pmportinfo->pmport_sata_drive);
7532 
7533 		mutex_enter(&cportinfo->cport_mutex);
7534 		sata_show_drive_info(sata_hba_inst,
7535 		    pmportinfo->pmport_sata_drive);
7536 		mutex_exit(&cportinfo->cport_mutex);
7537 		cdip = sata_create_target_node(pdip, sata_hba_inst,
7538 		    &sata_device.satadev_addr);
7539 		mutex_enter(&cportinfo->cport_mutex);
7540 		if (cdip == NULL) {
7541 			/*
7542 			 * Attaching target node failed.
7543 			 * We retain sata_drive_info structure...
7544 			 */
7545 			pmportinfo->pmport_sata_drive->
7546 			    satadrv_type = SATA_DTYPE_UNKNOWN;
7547 			pmportinfo->pmport_sata_drive->
7548 			    satadrv_state = SATA_STATE_UNKNOWN;
7549 			pmportinfo->pmport_dev_type =
7550 			    SATA_DTYPE_UNKNOWN;
7551 			mutex_exit(&cportinfo->cport_mutex);
7552 			return (SATA_SUCCESS);
7553 		}
7554 		pmportinfo->pmport_sata_drive->satadrv_state |=
7555 		    SATA_STATE_READY;
7556 	}
7557 	mutex_exit(&cportinfo->cport_mutex);
7558 	return (SATA_SUCCESS);
7559 }
7560 
7561 
7562 /*
7563  * Create scsi target node for attached device, create node properties and
7564  * attach the node.
7565  * The node could be removed if the device onlining fails.
7566  *
7567  * A dev_info_t pointer is returned if operation is successful, NULL is
7568  * returned otherwise.
7569  */
7570 
7571 static dev_info_t *
7572 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
7573 			sata_address_t *sata_addr)
7574 {
7575 	dev_info_t *cdip = NULL;
7576 	int rval;
7577 	char *nname = NULL;
7578 	char **compatible = NULL;
7579 	int ncompatible;
7580 	struct scsi_inquiry inq;
7581 	sata_device_t sata_device;
7582 	sata_drive_info_t *sdinfo;
7583 	int target;
7584 	int i;
7585 
7586 	sata_device.satadev_rev = SATA_DEVICE_REV;
7587 	sata_device.satadev_addr = *sata_addr;
7588 
7589 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
7590 
7591 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
7592 
7593 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
7594 	    sata_addr->pmport, sata_addr->qual);
7595 
7596 	if (sdinfo == NULL) {
7597 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
7598 		    sata_addr->cport)));
7599 		SATA_LOG_D((sata_hba_inst, CE_WARN,
7600 		    "sata_create_target_node: no sdinfo for target %x",
7601 		    target));
7602 		return (NULL);
7603 	}
7604 
7605 	/*
7606 	 * create scsi inquiry data, expected by
7607 	 * scsi_hba_nodename_compatible_get()
7608 	 */
7609 	sata_identdev_to_inquiry(sata_hba_inst, sdinfo, (uint8_t *)&inq);
7610 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
7611 
7612 	/* determine the node name and compatible */
7613 	scsi_hba_nodename_compatible_get(&inq, NULL,
7614 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
7615 
7616 #ifdef SATA_DEBUG
7617 	if (sata_debug_flags & SATA_DBG_NODES) {
7618 		if (nname == NULL) {
7619 			cmn_err(CE_NOTE, "sata_create_target_node: "
7620 			    "cannot determine nodename for target %d\n",
7621 			    target);
7622 		} else {
7623 			cmn_err(CE_WARN, "sata_create_target_node: "
7624 			    "target %d nodename: %s\n", target, nname);
7625 		}
7626 		if (compatible == NULL) {
7627 			cmn_err(CE_WARN,
7628 			    "sata_create_target_node: no compatible name\n");
7629 		} else {
7630 			for (i = 0; i < ncompatible; i++) {
7631 				cmn_err(CE_WARN, "sata_create_target_node: "
7632 				    "compatible name: %s\n", compatible[i]);
7633 			}
7634 		}
7635 	}
7636 #endif
7637 
7638 	/* if nodename can't be determined, log error and exit */
7639 	if (nname == NULL) {
7640 		SATA_LOG_D((sata_hba_inst, CE_WARN,
7641 		    "sata_create_target_node: cannot determine nodename "
7642 		    "for target %d\n", target));
7643 		scsi_hba_nodename_compatible_free(nname, compatible);
7644 		return (NULL);
7645 	}
7646 	/*
7647 	 * Create scsi target node
7648 	 */
7649 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
7650 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
7651 	    "device-type", "scsi");
7652 
7653 	if (rval != DDI_PROP_SUCCESS) {
7654 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
7655 		    "updating device_type prop failed %d", rval));
7656 		goto fail;
7657 	}
7658 
7659 	/*
7660 	 * Create target node properties: target & lun
7661 	 */
7662 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
7663 	if (rval != DDI_PROP_SUCCESS) {
7664 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
7665 		    "updating target prop failed %d", rval));
7666 		goto fail;
7667 	}
7668 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
7669 	if (rval != DDI_PROP_SUCCESS) {
7670 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
7671 		    "updating target prop failed %d", rval));
7672 		goto fail;
7673 	}
7674 
7675 	/* decorate the node with compatible */
7676 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
7677 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
7678 		SATA_LOG_D((sata_hba_inst, CE_WARN,
7679 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
7680 		    (void *)cdip));
7681 		goto fail;
7682 	}
7683 
7684 	/*
7685 	 * Now, try to attach the driver. If probing of the device fails,
7686 	 * the target node may be removed
7687 	 */
7688 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
7689 
7690 	scsi_hba_nodename_compatible_free(nname, compatible);
7691 
7692 	if (rval == NDI_SUCCESS)
7693 		return (cdip);
7694 
7695 	/* target node was removed - are we sure? */
7696 	return (NULL);
7697 
7698 fail:
7699 	scsi_hba_nodename_compatible_free(nname, compatible);
7700 	ddi_prop_remove_all(cdip);
7701 	rval = ndi_devi_free(cdip);
7702 	if (rval != NDI_SUCCESS) {
7703 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
7704 		    "node removal failed %d", rval));
7705 	}
7706 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
7707 	    "cannot create target node for device at port %d",
7708 	    sata_addr->cport);
7709 	return (NULL);
7710 }
7711 
7712 
7713 
7714 /*
7715  * Re-probe sata port, check for a device and attach info
7716  * structures when necessary. Identify Device data is fetched, if possible.
7717  * Assumption: sata address is already validated.
7718  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
7719  * the presence of a device and its type.
7720  *
7721  * flag arg specifies that the function should try multiple times to identify
7722  * device type and to initialize it, or it should return immediately on failure.
7723  * SATA_DEV_IDENTIFY_RETRY - retry
7724  * SATA_DEV_IDENTIFY_NORETRY - no retry
7725  *
7726  * SATA_FAILURE is returned if one of the operations failed.
7727  *
7728  * This function cannot be called in interrupt context - it may sleep.
7729  */
7730 static int
7731 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
7732     int flag)
7733 {
7734 	sata_cport_info_t *cportinfo;
7735 	sata_drive_info_t *sdinfo;
7736 	boolean_t init_device = B_FALSE;
7737 	int prev_device_type = SATA_DTYPE_NONE;
7738 	int prev_device_settings = 0;
7739 	clock_t start_time;
7740 	int retry = B_FALSE;
7741 	int rval;
7742 
7743 	/* We only care about host sata cport for now */
7744 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
7745 	    sata_device->satadev_addr.cport);
7746 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
7747 	if (sdinfo != NULL) {
7748 		/*
7749 		 * We are re-probing port with a previously attached device.
7750 		 * Save previous device type and settings
7751 		 */
7752 		prev_device_type = cportinfo->cport_dev_type;
7753 		prev_device_settings = sdinfo->satadrv_settings;
7754 	}
7755 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
7756 		start_time = ddi_get_lbolt();
7757 		retry = B_TRUE;
7758 	}
7759 retry_probe:
7760 
7761 	/* probe port */
7762 	mutex_enter(&cportinfo->cport_mutex);
7763 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
7764 	cportinfo->cport_state |= SATA_STATE_PROBING;
7765 	mutex_exit(&cportinfo->cport_mutex);
7766 
7767 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
7768 	    (SATA_DIP(sata_hba_inst), sata_device);
7769 
7770 	mutex_enter(&cportinfo->cport_mutex);
7771 	if (rval != SATA_SUCCESS) {
7772 		cportinfo->cport_state = SATA_PSTATE_FAILED;
7773 		mutex_exit(&cportinfo->cport_mutex);
7774 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_hba_ioctl: "
7775 		    "connect: port probbing failed"));
7776 		return (SATA_FAILURE);
7777 	}
7778 
7779 	/*
7780 	 * update sata port state and set device type
7781 	 */
7782 	sata_update_port_info(sata_hba_inst, sata_device);
7783 	cportinfo->cport_state |= SATA_STATE_PROBED;
7784 
7785 	/*
7786 	 * Sanity check - Port is active? Is the link active?
7787 	 * Is there any device attached?
7788 	 */
7789 	if ((cportinfo->cport_state &
7790 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
7791 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
7792 	    SATA_PORT_DEVLINK_UP) {
7793 		/*
7794 		 * Port in non-usable state or no link active/no device.
7795 		 * Free info structure if necessary (direct attached drive
7796 		 * only, for now!
7797 		 */
7798 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
7799 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
7800 		/* Add here differentiation for device attached or not */
7801 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
7802 		mutex_exit(&cportinfo->cport_mutex);
7803 		if (sdinfo != NULL)
7804 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
7805 		return (SATA_SUCCESS);
7806 	}
7807 
7808 	cportinfo->cport_state |= SATA_STATE_READY;
7809 	cportinfo->cport_dev_type = sata_device->satadev_type;
7810 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
7811 
7812 	/*
7813 	 * If we are re-probing the port, there may be
7814 	 * sata_drive_info structure attached
7815 	 * (or sata_pm_info, if PMult is supported).
7816 	 */
7817 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
7818 		/*
7819 		 * There is no device, so remove device info structure,
7820 		 * if necessary. Direct attached drive only!
7821 		 */
7822 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
7823 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
7824 		if (sdinfo != NULL) {
7825 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
7826 			sata_log(sata_hba_inst, CE_WARN,
7827 			    "SATA device detached "
7828 			    "from port %d", cportinfo->cport_addr.cport);
7829 		}
7830 		mutex_exit(&cportinfo->cport_mutex);
7831 		return (SATA_SUCCESS);
7832 	}
7833 
7834 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
7835 		if (sdinfo == NULL) {
7836 			/*
7837 			 * There is some device attached, but there is
7838 			 * no sata_drive_info structure - allocate one
7839 			 */
7840 			mutex_exit(&cportinfo->cport_mutex);
7841 			sdinfo = kmem_zalloc(
7842 			    sizeof (sata_drive_info_t), KM_SLEEP);
7843 			mutex_enter(&cportinfo->cport_mutex);
7844 			/*
7845 			 * Recheck, that the port state did not change when we
7846 			 * released mutex.
7847 			 */
7848 			if (cportinfo->cport_state & SATA_STATE_READY) {
7849 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
7850 				sdinfo->satadrv_addr = cportinfo->cport_addr;
7851 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
7852 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
7853 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
7854 			} else {
7855 				/*
7856 				 * Port is not in ready state, we
7857 				 * cannot attach a device.
7858 				 */
7859 				mutex_exit(&cportinfo->cport_mutex);
7860 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
7861 				return (SATA_SUCCESS);
7862 			}
7863 			/*
7864 			 * Since we are adding device, presumably new one,
7865 			 * indicate that it  should be initalized,
7866 			 * as well as some internal framework states).
7867 			 */
7868 			init_device = B_TRUE;
7869 		}
7870 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
7871 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
7872 	} else {
7873 		/*
7874 		 * The device is a port multiplier - not handled now.
7875 		 */
7876 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
7877 		mutex_exit(&cportinfo->cport_mutex);
7878 		return (SATA_SUCCESS);
7879 	}
7880 	mutex_exit(&cportinfo->cport_mutex);
7881 	/*
7882 	 * Figure out what kind of device we are really
7883 	 * dealing with.
7884 	 */
7885 	rval = sata_probe_device(sata_hba_inst, sata_device);
7886 
7887 	if (rval == SATA_SUCCESS) {
7888 		/*
7889 		 * If we are dealing with the same type of a device as before,
7890 		 * restore its settings flags.
7891 		 */
7892 		if (sata_device->satadev_type == prev_device_type)
7893 			sdinfo->satadrv_settings = prev_device_settings;
7894 
7895 		/* Set initial device features, if necessary */
7896 		if (init_device == B_TRUE) {
7897 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
7898 		}
7899 		if (rval == SATA_SUCCESS)
7900 			return (rval);
7901 	}
7902 
7903 	if (retry) {
7904 		clock_t cur_time = ddi_get_lbolt();
7905 		/*
7906 		 * A device was not successfully identified or initialized.
7907 		 * Track retry time for device identification.
7908 		 */
7909 		if ((cur_time - start_time) <
7910 		    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
7911 			/* sleep for a while */
7912 			delay(drv_usectohz(SATA_DEV_IDENTIFY_RETRY_DELAY));
7913 			goto retry_probe;
7914 		}
7915 	}
7916 	return (rval);
7917 }
7918 
7919 /*
7920  * Initialize device
7921  * Specified device is initialized to a default state.
7922  * At this point only read cache and UDMA modes are set here.
7923  * Write cache mode should be set when a disk is configured.
7924  *
7925  * Only SATA disks are initialized for now.
7926  *
7927  * Returns SATA_SUCCESS if all device features are set successfully,
7928  * SATA_FAILURE otherwise
7929  */
7930 static int
7931 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
7932     sata_drive_info_t *sdinfo)
7933 {
7934 
7935 	sata_save_drive_settings(sdinfo);
7936 
7937 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
7938 
7939 	sata_init_write_cache_mode(sdinfo);
7940 
7941 	return (sata_set_drive_features(sata_hba_inst, sdinfo, 0));
7942 }
7943 
7944 
7945 /*
7946  * Initialize write cache mode.
7947  *
7948  * The default write cache setting is provided by sata_write_cache
7949  * static variable:
7950  * 1 - enable
7951  * 0 - disable
7952  * any other value - current drive setting
7953  *
7954  * In the future, it may be overridden by the
7955  * disk-write-cache-enable property setting, if it is defined.
7956  * Returns SATA_SUCCESS if all device features are set successfully,
7957  * SATA_FAILURE otherwise.
7958  */
7959 static void
7960 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
7961 {
7962 	if (sata_write_cache == 1)
7963 		sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
7964 	else if (sata_write_cache == 0)
7965 		sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
7966 	/*
7967 	 * When sata_write_cache value is not 0 or 1,
7968 	 * a current setting of the drive's write cache is used.
7969 	 */
7970 }
7971 
7972 
7973 /*
7974  * Validate sata address.
7975  * Specified cport, pmport and qualifier has to match
7976  * passed sata_scsi configuration info.
7977  * The presence of an attached device is not verified.
7978  *
7979  * Returns 0 when address is valid, -1 otherwise.
7980  */
7981 static int
7982 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
7983 	int pmport, int qual)
7984 {
7985 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
7986 		goto invalid_address;
7987 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
7988 		goto invalid_address;
7989 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
7990 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
7991 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
7992 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
7993 		goto invalid_address;
7994 
7995 	return (0);
7996 
7997 invalid_address:
7998 	return (-1);
7999 
8000 }
8001 
8002 /*
8003  * Validate scsi address
8004  * SCSI target address is translated into SATA cport/pmport and compared
8005  * with a controller port/device configuration. LUN has to be 0.
8006  * Returns 0 if a scsi target refers to an attached device,
8007  * returns 1 if address is valid but device is not attached,
8008  * returns -1 if bad address or device is of an unsupported type.
8009  * Upon return sata_device argument is set.
8010  */
8011 static int
8012 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
8013 	struct scsi_address *ap, sata_device_t *sata_device)
8014 {
8015 	int cport, pmport, qual, rval;
8016 
8017 	rval = -1;	/* Invalid address */
8018 	if (ap->a_lun != 0)
8019 		goto out;
8020 
8021 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
8022 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
8023 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
8024 
8025 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
8026 		goto out;
8027 
8028 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
8029 	    0) {
8030 
8031 		sata_cport_info_t *cportinfo;
8032 		sata_pmult_info_t *pmultinfo;
8033 		sata_drive_info_t *sdinfo = NULL;
8034 
8035 		rval = 1;	/* Valid sata address */
8036 
8037 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
8038 		if (qual == SATA_ADDR_DCPORT) {
8039 			if (cportinfo == NULL ||
8040 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
8041 				goto out;
8042 
8043 			if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT ||
8044 			    (cportinfo->cport_dev_type &
8045 			    SATA_VALID_DEV_TYPE) == 0) {
8046 				rval = -1;
8047 				goto out;
8048 			}
8049 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
8050 
8051 		} else if (qual == SATA_ADDR_DPMPORT) {
8052 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
8053 			if (pmultinfo == NULL) {
8054 				rval = -1;
8055 				goto out;
8056 			}
8057 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
8058 			    NULL ||
8059 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
8060 			    pmport) == SATA_DTYPE_NONE)
8061 				goto out;
8062 
8063 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
8064 			    pmport);
8065 		} else {
8066 			rval = -1;
8067 			goto out;
8068 		}
8069 		if ((sdinfo == NULL) ||
8070 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
8071 			goto out;
8072 
8073 		sata_device->satadev_type = sdinfo->satadrv_type;
8074 		sata_device->satadev_addr.qual = qual;
8075 		sata_device->satadev_addr.cport = cport;
8076 		sata_device->satadev_addr.pmport = pmport;
8077 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
8078 		return (0);
8079 	}
8080 out:
8081 	if (rval == 1) {
8082 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
8083 		    "sata_validate_scsi_address: no valid target %x lun %x",
8084 		    ap->a_target, ap->a_lun);
8085 	}
8086 	return (rval);
8087 }
8088 
8089 /*
8090  * Find dip corresponding to passed device number
8091  *
8092  * Returns NULL if invalid device number is passed or device cannot be found,
8093  * Returns dip is device is found.
8094  */
8095 static dev_info_t *
8096 sata_devt_to_devinfo(dev_t dev)
8097 {
8098 	dev_info_t *dip;
8099 #ifndef __lock_lint
8100 	struct devnames *dnp;
8101 	major_t major = getmajor(dev);
8102 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
8103 
8104 	if (major >= devcnt)
8105 		return (NULL);
8106 
8107 	dnp = &devnamesp[major];
8108 	LOCK_DEV_OPS(&(dnp->dn_lock));
8109 	dip = dnp->dn_head;
8110 	while (dip && (ddi_get_instance(dip) != instance)) {
8111 		dip = ddi_get_next(dip);
8112 	}
8113 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
8114 #endif
8115 
8116 	return (dip);
8117 }
8118 
8119 
8120 /*
8121  * Probe device.
8122  * This function issues Identify Device command and initializes local
8123  * sata_drive_info structure if the device can be identified.
8124  * The device type is determined by examining Identify Device
8125  * command response.
8126  * If the sata_hba_inst has linked drive info structure for this
8127  * device address, the Identify Device data is stored into sata_drive_info
8128  * structure linked to the port info structure.
8129  *
8130  * sata_device has to refer to the valid sata port(s) for HBA described
8131  * by sata_hba_inst structure.
8132  *
8133  * Returns: SATA_SUCCESS if device type was successfully probed and port-linked
8134  *	drive info structure was updated;
8135  * 	SATA_FAILURE if there is no device, or device was not probed
8136  *	successully.
8137  * If a device cannot be identified, sata_device's dev_state and dev_type
8138  * fields are set to unknown.
8139  * There are no retries in this function. Any retries should be managed by
8140  * the caller.
8141  */
8142 
8143 
8144 static int
8145 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
8146 {
8147 	sata_drive_info_t *sdinfo;
8148 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
8149 	int rval;
8150 
8151 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
8152 	    sata_device->satadev_addr.cport) &
8153 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
8154 
8155 	sata_device->satadev_type = SATA_DTYPE_NONE;
8156 
8157 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
8158 	    sata_device->satadev_addr.cport)));
8159 
8160 	/* Get pointer to port-linked sata device info structure */
8161 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
8162 	if (sdinfo != NULL) {
8163 		sdinfo->satadrv_state &=
8164 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
8165 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
8166 	} else {
8167 		/* No device to probe */
8168 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8169 		    sata_device->satadev_addr.cport)));
8170 		sata_device->satadev_type = SATA_DTYPE_NONE;
8171 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
8172 		return (SATA_FAILURE);
8173 	}
8174 	/*
8175 	 * Need to issue both types of identify device command and
8176 	 * determine device type by examining retreived data/status.
8177 	 * First, ATA Identify Device.
8178 	 */
8179 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
8180 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
8181 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8182 	    sata_device->satadev_addr.cport)));
8183 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
8184 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
8185 	if (rval == 1) {
8186 		/* We may try to check for ATAPI device */
8187 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
8188 			/*
8189 			 * HBA supports ATAPI - try to issue Identify Packet
8190 			 * Device command.
8191 			 */
8192 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPICD;
8193 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
8194 		}
8195 	}
8196 	if (rval == -1)
8197 		goto failure;
8198 	if (rval == 0) {
8199 		/*
8200 		 * Got something responding to ATA Identify Device or to
8201 		 * Identify Packet Device cmd.
8202 		 */
8203 		sata_device->satadev_type = new_sdinfo.satadrv_type;
8204 
8205 		/* save device info, if possible */
8206 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
8207 		    sata_device->satadev_addr.cport)));
8208 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
8209 		if (sdinfo == NULL) {
8210 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8211 			    sata_device->satadev_addr.cport)));
8212 			return (SATA_FAILURE);
8213 		}
8214 		/*
8215 		 * Copy drive info into the port-linked drive info structure.
8216 		 */
8217 		*sdinfo = new_sdinfo;
8218 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
8219 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
8220 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
8221 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
8222 			    sata_device->satadev_addr.cport) =
8223 			    sdinfo->satadrv_type;
8224 		else /* SATA_ADDR_DPMPORT */
8225 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
8226 			    sata_device->satadev_addr.cport,
8227 			    sata_device->satadev_addr.pmport) =
8228 			    sdinfo->satadrv_type;
8229 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8230 		    sata_device->satadev_addr.cport)));
8231 		return (SATA_SUCCESS);
8232 	}
8233 
8234 failure:
8235 	/*
8236 	 * Looks like we cannot determine the device type.
8237 	 */
8238 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
8239 	    sata_device->satadev_addr.cport)));
8240 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
8241 	if (sdinfo != NULL) {
8242 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
8243 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
8244 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
8245 		sdinfo->satadrv_state = SATA_STATE_PROBED;
8246 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
8247 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
8248 			    sata_device->satadev_addr.cport) =
8249 			    SATA_DTYPE_UNKNOWN;
8250 		else {
8251 			/* SATA_ADDR_DPMPORT */
8252 			if ((SATA_PMULT_INFO(sata_hba_inst,
8253 			    sata_device->satadev_addr.cport) != NULL) &&
8254 			    (SATA_PMPORT_INFO(sata_hba_inst,
8255 			    sata_device->satadev_addr.cport,
8256 			    sata_device->satadev_addr.pmport) != NULL))
8257 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
8258 				    sata_device->satadev_addr.cport,
8259 				    sata_device->satadev_addr.pmport) =
8260 				    SATA_DTYPE_UNKNOWN;
8261 		}
8262 	}
8263 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8264 	    sata_device->satadev_addr.cport)));
8265 	return (SATA_FAILURE);
8266 }
8267 
8268 
8269 /*
8270  * Get pointer to sata_drive_info structure.
8271  *
8272  * The sata_device has to contain address (cport, pmport and qualifier) for
8273  * specified sata_scsi structure.
8274  *
8275  * Returns NULL if device address is not valid for this HBA configuration.
8276  * Otherwise, returns a pointer to sata_drive_info structure.
8277  *
8278  * This function should be called with a port mutex held.
8279  */
8280 static sata_drive_info_t *
8281 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
8282     sata_device_t *sata_device)
8283 {
8284 	uint8_t cport = sata_device->satadev_addr.cport;
8285 	uint8_t pmport = sata_device->satadev_addr.pmport;
8286 	uint8_t qual = sata_device->satadev_addr.qual;
8287 
8288 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
8289 		return (NULL);
8290 
8291 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
8292 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
8293 		/* Port not probed yet */
8294 		return (NULL);
8295 
8296 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
8297 		return (NULL);
8298 
8299 	if (qual == SATA_ADDR_DCPORT) {
8300 		/* Request for a device on a controller port */
8301 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
8302 		    SATA_DTYPE_PMULT)
8303 			/* Port multiplier attached */
8304 			return (NULL);
8305 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
8306 	}
8307 	if (qual == SATA_ADDR_DPMPORT) {
8308 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
8309 		    SATA_DTYPE_PMULT)
8310 			return (NULL);
8311 
8312 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
8313 			return (NULL);
8314 
8315 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
8316 	}
8317 
8318 	/* we should not get here */
8319 	return (NULL);
8320 }
8321 
8322 
8323 /*
8324  * sata_identify_device.
8325  * Send Identify Device command to SATA HBA driver.
8326  * If command executes successfully, update sata_drive_info structure pointed
8327  * to by sdinfo argument, including Identify Device data.
8328  * If command fails, invalidate data in sata_drive_info.
8329  *
8330  * Cannot be called from interrupt level.
8331  *
8332  * Returns:
8333  * 0 if device was identified as a supported device,
8334  * 1 if device was not idenitfied but identify attempt could be retried,
8335  * -1if device was not idenitfied and identify attempt should not be retried.
8336  */
8337 static int
8338 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
8339     sata_drive_info_t *sdinfo)
8340 {
8341 	uint16_t cfg_word;
8342 	int rval;
8343 	int i;
8344 
8345 	/* fetch device identify data */
8346 	if ((rval = sata_fetch_device_identify_data(
8347 	    sata_hba_inst, sdinfo)) != 0)
8348 		goto fail_unknown;
8349 
8350 	cfg_word = sdinfo->satadrv_id.ai_config;
8351 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK &&
8352 	    (cfg_word & SATA_ATA_TYPE_MASK) != SATA_ATA_TYPE) {
8353 		/* Change device type to reflect Identify Device data */
8354 		if (((cfg_word & SATA_ATAPI_TYPE_MASK) ==
8355 		    SATA_ATAPI_TYPE) &&
8356 		    ((cfg_word & SATA_ATAPI_ID_DEV_TYPE) ==
8357 		    SATA_ATAPI_CDROM_DEV)) {
8358 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
8359 		} else {
8360 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
8361 		}
8362 	} else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD &&
8363 	    (((cfg_word & SATA_ATAPI_TYPE_MASK) != SATA_ATAPI_TYPE) ||
8364 	    ((cfg_word & SATA_ATAPI_ID_DEV_TYPE) != SATA_ATAPI_CDROM_DEV))) {
8365 		/* Change device type to reflect Identify Device data ! */
8366 		if ((sdinfo->satadrv_id.ai_config & SATA_ATA_TYPE_MASK) ==
8367 		    SATA_ATA_TYPE) {
8368 			sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
8369 		} else {
8370 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
8371 		}
8372 	}
8373 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
8374 		if (sdinfo->satadrv_capacity == 0) {
8375 			/* Non-LBA disk. Too bad... */
8376 			sata_log(sata_hba_inst, CE_WARN,
8377 			    "SATA disk device at port %d does not support LBA",
8378 			    sdinfo->satadrv_addr.cport);
8379 			rval = -1;
8380 			goto fail_unknown;
8381 		}
8382 	}
8383 	/* Check for Ultra DMA modes 6 through 0 being supported */
8384 	for (i = 6; i >= 0; --i) {
8385 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
8386 			break;
8387 	}
8388 	/*
8389 	 * At least UDMA 4 mode has to be supported. If mode 4 or
8390 	 * higher are not supported by the device, fail this
8391 	 * device.
8392 	 */
8393 	if (i < 4) {
8394 		/* No required Ultra DMA mode supported */
8395 		sata_log(sata_hba_inst, CE_WARN,
8396 		    "SATA disk device at port %d does not support UDMA "
8397 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
8398 		SATA_LOG_D((sata_hba_inst, CE_WARN,
8399 		    "mode 4 or higher required, %d supported", i));
8400 		rval = -1;
8401 		goto fail_unknown;
8402 	}
8403 
8404 	return (0);
8405 
8406 fail_unknown:
8407 	/* Invalidate sata_drive_info ? */
8408 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
8409 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
8410 	return (rval);
8411 }
8412 
8413 /*
8414  * Log/display device information
8415  */
8416 static void
8417 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
8418     sata_drive_info_t *sdinfo)
8419 {
8420 	int valid_version;
8421 	char msg_buf[MAXPATHLEN];
8422 
8423 	/* Show HBA path */
8424 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
8425 
8426 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
8427 
8428 	if (sdinfo->satadrv_type == SATA_DTYPE_UNKNOWN) {
8429 		(void) sprintf(msg_buf,
8430 		    "Unsupported SATA device type (cfg 0x%x) at ",
8431 		    sdinfo->satadrv_id.ai_config);
8432 	} else {
8433 		(void) sprintf(msg_buf, "SATA %s device at",
8434 		    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
8435 		    "disk":"CD/DVD (ATAPI)");
8436 	}
8437 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
8438 		cmn_err(CE_CONT, "?\t%s port %d\n",
8439 		    msg_buf, sdinfo->satadrv_addr.cport);
8440 	else
8441 		cmn_err(CE_CONT, "?\t%s port %d pmport %d\n",
8442 		    msg_buf, sdinfo->satadrv_addr.cport,
8443 		    sdinfo->satadrv_addr.pmport);
8444 
8445 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
8446 	    sizeof (sdinfo->satadrv_id.ai_model));
8447 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
8448 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
8449 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
8450 
8451 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
8452 	    sizeof (sdinfo->satadrv_id.ai_fw));
8453 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
8454 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
8455 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
8456 
8457 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
8458 	    sizeof (sdinfo->satadrv_id.ai_drvser));
8459 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
8460 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
8461 	cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
8462 
8463 #ifdef SATA_DEBUG
8464 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
8465 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
8466 		int i;
8467 		for (i = 14; i >= 2; i--) {
8468 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
8469 				valid_version = i;
8470 				break;
8471 			}
8472 		}
8473 		cmn_err(CE_CONT,
8474 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
8475 		    valid_version,
8476 		    sdinfo->satadrv_id.ai_majorversion,
8477 		    sdinfo->satadrv_id.ai_minorversion);
8478 	}
8479 #endif
8480 	/* Log some info */
8481 	cmn_err(CE_CONT, "?\tsupported features:\n");
8482 	msg_buf[0] = '\0';
8483 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
8484 		(void) strlcat(msg_buf, "48-bit LBA", MAXPATHLEN);
8485 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
8486 		(void) strlcat(msg_buf, "28-bit LBA", MAXPATHLEN);
8487 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
8488 		(void) strlcat(msg_buf, ", DMA", MAXPATHLEN);
8489 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
8490 		(void) strlcat(msg_buf, ", Native Command Queueing",
8491 		    MAXPATHLEN);
8492 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
8493 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
8494 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
8495 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
8496 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
8497 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
8498 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
8499 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
8500 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
8501 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
8502 		cmn_err(CE_CONT, "?\tSATA1 & SATA2 compatible\n");
8503 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
8504 		cmn_err(CE_CONT, "?\tSATA1 compatible\n");
8505 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ) {
8506 		cmn_err(CE_CONT, "?\tQueue depth %d\n",
8507 			sdinfo->satadrv_queue_depth);
8508 	}
8509 
8510 	if (sdinfo->satadrv_features_support &
8511 		(SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
8512 		(void) sprintf(msg_buf, "\tqueue depth %d\n",
8513 				sdinfo->satadrv_queue_depth);
8514 		cmn_err(CE_CONT, "?%s", msg_buf);
8515 	}
8516 
8517 #ifdef __i386
8518 	(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
8519 		sdinfo->satadrv_capacity);
8520 #else
8521 	(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
8522 		sdinfo->satadrv_capacity);
8523 #endif
8524 	cmn_err(CE_CONT, "?%s", msg_buf);
8525 }
8526 
8527 
8528 /*
8529  * sata_save_drive_settings extracts current setting of the device and stores
8530  * it for future reference, in case the device setup would need to be restored
8531  * after the device reset.
8532  *
8533  * At the moment only read ahead and write cache settings are saved, if the
8534  * device supports these features at all.
8535  */
8536 static void
8537 sata_save_drive_settings(sata_drive_info_t *sdinfo)
8538 {
8539 	if (!(sdinfo->satadrv_id.ai_cmdset82 & SATA_LOOK_AHEAD) &&
8540 	    !(sdinfo->satadrv_id.ai_cmdset82 & SATA_WRITE_CACHE)) {
8541 		/* None of the features is supported - do nothing */
8542 		return;
8543 	}
8544 
8545 	/* Current setting of Read Ahead (and Read Cache) */
8546 	if (sdinfo->satadrv_id.ai_features85 & SATA_LOOK_AHEAD)
8547 		sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
8548 	else
8549 		sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
8550 
8551 	/* Current setting of Write Cache */
8552 	if (sdinfo->satadrv_id.ai_features85 & SATA_WRITE_CACHE)
8553 		sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
8554 	else
8555 		sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
8556 }
8557 
8558 
8559 /*
8560  * sata_check_capacity function determines a disk capacity
8561  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
8562  *
8563  * NOTE: CHS mode is not supported! If a device does not support LBA,
8564  * this function is not called.
8565  *
8566  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
8567  */
8568 static uint64_t
8569 sata_check_capacity(sata_drive_info_t *sdinfo)
8570 {
8571 	uint64_t capacity = 0;
8572 	int i;
8573 
8574 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
8575 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
8576 		/* Capacity valid only for LBA-addressable disk devices */
8577 		return (0);
8578 
8579 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
8580 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
8581 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
8582 		/* LBA48 mode supported and enabled */
8583 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
8584 		    SATA_DEV_F_LBA28;
8585 		for (i = 3;  i >= 0;  --i) {
8586 			capacity <<= 16;
8587 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
8588 		}
8589 	} else {
8590 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
8591 		capacity <<= 16;
8592 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
8593 		if (capacity >= 0x1000000)
8594 			/* LBA28 mode */
8595 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
8596 	}
8597 	return (capacity);
8598 }
8599 
8600 
8601 /*
8602  * Allocate consistent buffer for DMA transfer
8603  *
8604  * Cannot be called from interrupt level or with mutex held - it may sleep.
8605  *
8606  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
8607  */
8608 static struct buf *
8609 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
8610 {
8611 	struct scsi_address ap;
8612 	struct buf *bp;
8613 	ddi_dma_attr_t	cur_dma_attr;
8614 
8615 	ASSERT(spx->txlt_sata_pkt != NULL);
8616 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
8617 	ap.a_target = SATA_TO_SCSI_TARGET(
8618 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
8619 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
8620 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
8621 	ap.a_lun = 0;
8622 
8623 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
8624 		B_READ, SLEEP_FUNC, NULL);
8625 
8626 	if (bp != NULL) {
8627 		/* Allocate DMA resources for this buffer */
8628 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
8629 		/*
8630 		 * We use a local version of the dma_attr, to account
8631 		 * for a device addressing limitations.
8632 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
8633 		 * will cause dma attributes to be adjusted to a lowest
8634 		 * acceptable level.
8635 		 */
8636 		sata_adjust_dma_attr(NULL,
8637 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
8638 
8639 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
8640 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
8641 			scsi_free_consistent_buf(bp);
8642 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
8643 			bp = NULL;
8644 		}
8645 	}
8646 	return (bp);
8647 }
8648 
8649 /*
8650  * Release local buffer (consistent buffer for DMA transfer) allocated
8651  * via sata_alloc_local_buffer().
8652  */
8653 static void
8654 sata_free_local_buffer(sata_pkt_txlate_t *spx)
8655 {
8656 	ASSERT(spx->txlt_sata_pkt != NULL);
8657 	ASSERT(spx->txlt_dma_cookie_list != NULL);
8658 	ASSERT(spx->txlt_dma_cookie_list_len != 0);
8659 	ASSERT(spx->txlt_buf_dma_handle != NULL);
8660 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
8661 
8662 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
8663 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
8664 
8665 	/* Free DMA resources */
8666 	(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
8667 	ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
8668 	spx->txlt_buf_dma_handle = 0;
8669 
8670 	kmem_free(spx->txlt_dma_cookie_list,
8671 	    spx->txlt_dma_cookie_list_len * sizeof (ddi_dma_cookie_t));
8672 	spx->txlt_dma_cookie_list = NULL;
8673 	spx->txlt_dma_cookie_list_len = 0;
8674 
8675 	/* Free buffer */
8676 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
8677 }
8678 
8679 
8680 
8681 
8682 /*
8683  * Allocate sata_pkt
8684  * Pkt structure version and embedded strcutures version are initialized.
8685  * sata_pkt and sata_pkt_txlate structures are cross-linked.
8686  *
8687  * Since this may be called in interrupt context by sata_scsi_init_pkt,
8688  * callback argument determines if it can sleep or not.
8689  * Hence, it should not be called from interrupt context.
8690  *
8691  * If successful, non-NULL pointer to a sata pkt is returned.
8692  * Upon failure, NULL pointer is returned.
8693  */
8694 static sata_pkt_t *
8695 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
8696 {
8697 	sata_pkt_t *spkt;
8698 	int kmsflag;
8699 
8700 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
8701 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
8702 	if (spkt == NULL) {
8703 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8704 		    "sata_pkt_alloc: failed"));
8705 		return (NULL);
8706 	}
8707 	spkt->satapkt_rev = SATA_PKT_REV;
8708 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
8709 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
8710 	spkt->satapkt_framework_private = spx;
8711 	spx->txlt_sata_pkt = spkt;
8712 	return (spkt);
8713 }
8714 
8715 /*
8716  * Free sata pkt allocated via sata_pkt_alloc()
8717  */
8718 static void
8719 sata_pkt_free(sata_pkt_txlate_t *spx)
8720 {
8721 	ASSERT(spx->txlt_sata_pkt != NULL);
8722 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
8723 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
8724 	spx->txlt_sata_pkt = NULL;
8725 }
8726 
8727 
8728 /*
8729  * Adjust DMA attributes.
8730  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
8731  * from 8 bits to 16 bits, depending on a command being used.
8732  * Limiting max block count arbitrarily to 256 for all read/write
8733  * commands may affects performance, so check both the device and
8734  * controller capability before adjusting dma attributes.
8735  * For ATAPI CD/DVD dma granularity has to be adjusted as well,
8736  * because these devices support block size of 2k rather
8737  * then 512 bytes.
8738  */
8739 void
8740 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
8741     ddi_dma_attr_t *adj_dma_attr)
8742 {
8743 	uint32_t count_max;
8744 
8745 	/* Copy original attributes */
8746 	*adj_dma_attr = *dma_attr;
8747 
8748 	/*
8749 	 * Things to consider: device addressing capability,
8750 	 * "excessive" controller DMA capabilities.
8751 	 * If a device is being probed/initialized, there are
8752 	 * no device info - use default limits then.
8753 	 */
8754 	if (sdinfo == NULL) {
8755 		count_max = dma_attr->dma_attr_granular * 0x100;
8756 		if (dma_attr->dma_attr_count_max > count_max)
8757 			adj_dma_attr->dma_attr_count_max = count_max;
8758 		if (dma_attr->dma_attr_maxxfer > count_max)
8759 			adj_dma_attr->dma_attr_maxxfer = count_max;
8760 		return;
8761 	}
8762 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
8763 		/* arbitrarily modify controller dma granularity */
8764 		adj_dma_attr->dma_attr_granular = SATA_ATAPI_SECTOR_SIZE;
8765 	}
8766 
8767 	if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
8768 		/*
8769 		 * 16-bit sector count may be used - we rely on
8770 		 * the assumption that only read and write cmds
8771 		 * will request more than 256 sectors worth of data
8772 		 */
8773 		count_max = adj_dma_attr->dma_attr_granular * 0x10000;
8774 	} else {
8775 		/*
8776 		 * 8-bit sector count will be used - default limits
8777 		 * for dma attributes
8778 		 */
8779 		count_max = adj_dma_attr->dma_attr_granular * 0x100;
8780 	}
8781 
8782 
8783 	/*
8784 	 * Adjust controler dma attributes, if necessary
8785 	 */
8786 	if (dma_attr->dma_attr_count_max > count_max)
8787 		adj_dma_attr->dma_attr_count_max = count_max;
8788 	if (dma_attr->dma_attr_maxxfer > count_max)
8789 		adj_dma_attr->dma_attr_maxxfer = count_max;
8790 }
8791 
8792 
8793 /*
8794  * Allocate DMA resources for the buffer
8795  * This function handles initial DMA resource allocation as well as
8796  * DMA window shift and may be called repeatedly for the same DMA window
8797  * until all DMA cookies in the DMA window are processed.
8798  *
8799  * Returns DDI_SUCCESS upon successful operation,
8800  * returns failure code returned by failing commands or DDI_FAILURE when
8801  * internal cleanup failed.
8802  */
8803 static int
8804 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
8805     int (*callback)(caddr_t), caddr_t arg,
8806     ddi_dma_attr_t *cur_dma_attr)
8807 {
8808 	int			rval;
8809 	ddi_dma_cookie_t	cookie;
8810 	off_t			offset;
8811 	size_t			size;
8812 	int			max_sg_len, req_sg_len, i;
8813 	uint_t			dma_flags;
8814 	struct buf		*bp;
8815 	uint64_t		max_txfer_len;
8816 	uint64_t		cur_txfer_len;
8817 
8818 
8819 	ASSERT(spx->txlt_sata_pkt != NULL);
8820 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8821 	ASSERT(bp != NULL);
8822 
8823 
8824 	if (spx->txlt_buf_dma_handle == NULL) {
8825 		/*
8826 		 * No DMA resources allocated so far - this is a first call
8827 		 * for this sata pkt.
8828 		 */
8829 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
8830 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
8831 
8832 		if (rval != DDI_SUCCESS) {
8833 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8834 			    "sata_dma_buf_setup: no buf DMA resources %x",
8835 			    rval));
8836 			return (rval);
8837 		}
8838 
8839 		if (bp->b_flags & B_READ)
8840 			dma_flags = DDI_DMA_READ;
8841 		else
8842 			dma_flags = DDI_DMA_WRITE;
8843 
8844 		if (flags & PKT_CONSISTENT)
8845 			dma_flags |= DDI_DMA_CONSISTENT;
8846 
8847 		if (flags & PKT_DMA_PARTIAL)
8848 			dma_flags |= DDI_DMA_PARTIAL;
8849 
8850 		/*
8851 		 * Check buffer alignment and size against dma attributes
8852 		 * Consider dma_attr_align only. There may be requests
8853 		 * with the size lower then device granularity, but they
8854 		 * will not read/write from/to the device, so no adjustment
8855 		 * is necessary. The dma_attr_minxfer theoretically should
8856 		 * be considered, but no HBA driver is checking it.
8857 		 */
8858 		if (IS_P2ALIGNED(bp->b_un.b_addr,
8859 		    cur_dma_attr->dma_attr_align)) {
8860 			rval = ddi_dma_buf_bind_handle(
8861 					spx->txlt_buf_dma_handle,
8862 					bp, dma_flags, callback, arg,
8863 					&cookie,
8864 					&spx->txlt_curwin_num_dma_cookies);
8865 		} else { /* Buffer is not aligned */
8866 
8867 			int	(*ddicallback)(caddr_t);
8868 			size_t	bufsz;
8869 
8870 			/* Check id sleeping is allowed */
8871 			ddicallback = (callback == NULL_FUNC) ?
8872 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
8873 
8874 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
8875 				"mis-aligned buffer: addr=0x%p, cnt=%lu",
8876 				(void *)bp->b_un.b_addr, bp->b_bcount);
8877 
8878 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
8879 				/*
8880 				 * CPU will need to access data in the buffer
8881 				 * (for copying) so map it.
8882 				 */
8883 				bp_mapin(bp);
8884 
8885 			ASSERT(spx->txlt_tmp_buf == NULL);
8886 
8887 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
8888 			rval = ddi_dma_mem_alloc(
8889 				spx->txlt_buf_dma_handle,
8890 				bp->b_bcount,
8891 				&sata_acc_attr,
8892 				DDI_DMA_STREAMING,
8893 				ddicallback, NULL,
8894 				&spx->txlt_tmp_buf,
8895 				&bufsz,
8896 				&spx->txlt_tmp_buf_handle);
8897 
8898 			if (rval != DDI_SUCCESS) {
8899 				/* DMA mapping failed */
8900 				(void) ddi_dma_free_handle(
8901 				    &spx->txlt_buf_dma_handle);
8902 				spx->txlt_buf_dma_handle = NULL;
8903 #ifdef SATA_DEBUG
8904 				mbuffail_count++;
8905 #endif
8906 				SATADBG1(SATA_DBG_DMA_SETUP,
8907 				    spx->txlt_sata_hba_inst,
8908 				    "sata_dma_buf_setup: "
8909 				    "buf dma mem alloc failed %x\n", rval);
8910 				return (rval);
8911 			}
8912 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
8913 			    cur_dma_attr->dma_attr_align));
8914 
8915 #ifdef SATA_DEBUG
8916 			mbuf_count++;
8917 
8918 			if (bp->b_bcount != bufsz)
8919 				/*
8920 				 * This will require special handling, because
8921 				 * DMA cookies will be based on the temporary
8922 				 * buffer size, not the original buffer
8923 				 * b_bcount, so the residue may have to
8924 				 * be counted differently.
8925 				 */
8926 				SATADBG2(SATA_DBG_DMA_SETUP,
8927 				    spx->txlt_sata_hba_inst,
8928 				    "sata_dma_buf_setup: bp size %x != "
8929 				    "bufsz %x\n", bp->b_bcount, bufsz);
8930 #endif
8931 			if (dma_flags & DDI_DMA_WRITE) {
8932 				/*
8933 				 * Write operation - copy data into
8934 				 * an aligned temporary buffer. Buffer will be
8935 				 * synced for device by ddi_dma_addr_bind_handle
8936 				 */
8937 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
8938 				    bp->b_bcount);
8939 			}
8940 
8941 			rval = ddi_dma_addr_bind_handle(
8942 				spx->txlt_buf_dma_handle,
8943 				NULL,
8944 				spx->txlt_tmp_buf,
8945 				bufsz, dma_flags, ddicallback, 0,
8946 				&cookie, &spx->txlt_curwin_num_dma_cookies);
8947 		}
8948 
8949 		switch (rval) {
8950 		case DDI_DMA_PARTIAL_MAP:
8951 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
8952 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
8953 			/*
8954 			 * Partial DMA mapping.
8955 			 * Retrieve number of DMA windows for this request.
8956 			 */
8957 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
8958 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
8959 				if (spx->txlt_tmp_buf != NULL) {
8960 					ddi_dma_mem_free(
8961 					    &spx->txlt_tmp_buf_handle);
8962 					spx->txlt_tmp_buf = NULL;
8963 				}
8964 				(void) ddi_dma_unbind_handle(
8965 				    spx->txlt_buf_dma_handle);
8966 				(void) ddi_dma_free_handle(
8967 				    &spx->txlt_buf_dma_handle);
8968 				spx->txlt_buf_dma_handle = NULL;
8969 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8970 				    "sata_dma_buf_setup: numwin failed\n"));
8971 				return (DDI_FAILURE);
8972 			}
8973 			spx->txlt_cur_dma_win = 0;
8974 			break;
8975 
8976 		case DDI_DMA_MAPPED:
8977 			/* DMA fully mapped */
8978 			spx->txlt_num_dma_win = 1;
8979 			spx->txlt_cur_dma_win = 0;
8980 			break;
8981 
8982 		default:
8983 			/* DMA mapping failed */
8984 			if (spx->txlt_tmp_buf != NULL) {
8985 				ddi_dma_mem_free(
8986 				    &spx->txlt_tmp_buf_handle);
8987 				spx->txlt_tmp_buf = NULL;
8988 			}
8989 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
8990 			spx->txlt_buf_dma_handle = NULL;
8991 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8992 			    "sata_dma_buf_setup: buf dma handle binding "
8993 			    "failed %x\n", rval));
8994 			return (rval);
8995 		}
8996 		spx->txlt_curwin_processed_dma_cookies = 0;
8997 		spx->txlt_dma_cookie_list = NULL;
8998 	} else {
8999 		/*
9000 		 * DMA setup is reused. Check if we need to process more
9001 		 * cookies in current window, or to get next window, if any.
9002 		 */
9003 
9004 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
9005 		    spx->txlt_curwin_num_dma_cookies);
9006 
9007 		if (spx->txlt_curwin_processed_dma_cookies ==
9008 		    spx->txlt_curwin_num_dma_cookies) {
9009 			/*
9010 			 * All cookies from current DMA window were processed.
9011 			 * Get next DMA window.
9012 			 */
9013 			spx->txlt_cur_dma_win++;
9014 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
9015 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
9016 				    spx->txlt_cur_dma_win, &offset, &size,
9017 				    &cookie,
9018 				    &spx->txlt_curwin_num_dma_cookies);
9019 				spx->txlt_curwin_processed_dma_cookies = 0;
9020 
9021 			} else {
9022 				/* No more windows! End of request! */
9023 				/* What to do? - panic for now */
9024 				ASSERT(spx->txlt_cur_dma_win >=
9025 				    spx->txlt_num_dma_win);
9026 
9027 				spx->txlt_curwin_num_dma_cookies = 0;
9028 				spx->txlt_curwin_processed_dma_cookies = 0;
9029 				spx->txlt_sata_pkt->
9030 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
9031 				return (DDI_SUCCESS);
9032 			}
9033 		}
9034 	}
9035 	/* There better be at least one DMA cookie */
9036 	ASSERT((spx->txlt_curwin_num_dma_cookies -
9037 	    spx->txlt_curwin_processed_dma_cookies) > 0);
9038 
9039 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
9040 		/*
9041 		 * Processing a new DMA window - set-up dma cookies list.
9042 		 * We may reuse previously allocated cookie array if it is
9043 		 * possible.
9044 		 */
9045 		if (spx->txlt_dma_cookie_list != NULL &&
9046 		    spx->txlt_dma_cookie_list_len <
9047 		    spx->txlt_curwin_num_dma_cookies) {
9048 			/*
9049 			 * New DMA window contains more cookies than
9050 			 * the previous one. We need larger cookie list - free
9051 			 * the old one.
9052 			 */
9053 			(void) kmem_free(spx->txlt_dma_cookie_list,
9054 			    spx->txlt_dma_cookie_list_len *
9055 			    sizeof (ddi_dma_cookie_t));
9056 			spx->txlt_dma_cookie_list = NULL;
9057 			spx->txlt_dma_cookie_list_len = 0;
9058 		}
9059 		if (spx->txlt_dma_cookie_list == NULL) {
9060 			/* Allocate new dma cookie array */
9061 			spx->txlt_dma_cookie_list = kmem_zalloc(
9062 			    sizeof (ddi_dma_cookie_t) *
9063 			    spx->txlt_curwin_num_dma_cookies,
9064 			    callback == NULL_FUNC ? KM_NOSLEEP : KM_SLEEP);
9065 			spx->txlt_dma_cookie_list_len =
9066 			    spx->txlt_curwin_num_dma_cookies;
9067 		}
9068 		/*
9069 		 * Copy all DMA cookies into local list, so we will know their
9070 		 * dma_size in advance of setting the sata_pkt.
9071 		 * One cookie was already fetched, so copy it.
9072 		 */
9073 		*(&spx->txlt_dma_cookie_list[0]) = cookie;
9074 		for (i = 1; i < spx->txlt_curwin_num_dma_cookies; i++) {
9075 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle, &cookie);
9076 			*(&spx->txlt_dma_cookie_list[i]) = cookie;
9077 		}
9078 	} else {
9079 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
9080 		    "sata_dma_buf_setup: sliding within DMA window, "
9081 		    "cur cookie %d, total cookies %d\n",
9082 		    spx->txlt_curwin_processed_dma_cookies,
9083 		    spx->txlt_curwin_num_dma_cookies);
9084 	}
9085 
9086 	/*
9087 	 * Set-up sata_pkt cookie list.
9088 	 * No single cookie transfer size would exceed max transfer size of
9089 	 * an ATA command used for addressed device (tha adjustment of the dma
9090 	 * attributes took care of this). But there may be more
9091 	 * then one cookie, so the cmd cookie list has to be
9092 	 * constrained by both a maximum scatter gather list length and
9093 	 * a maximum transfer size restriction of an ATA command.
9094 	 */
9095 
9096 	max_sg_len = cur_dma_attr->dma_attr_sgllen;
9097 	req_sg_len = MIN(max_sg_len,
9098 	    (spx->txlt_curwin_num_dma_cookies -
9099 	    spx->txlt_curwin_processed_dma_cookies));
9100 
9101 	ASSERT(req_sg_len > 0);
9102 
9103 	max_txfer_len = MAX((cur_dma_attr->dma_attr_granular * 0x100),
9104 	    cur_dma_attr->dma_attr_maxxfer);
9105 
9106 	/* One cookie should be always available */
9107 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
9108 	    &spx->txlt_dma_cookie_list[spx->txlt_curwin_processed_dma_cookies];
9109 
9110 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
9111 
9112 	cur_txfer_len =
9113 	    (uint64_t)spx->txlt_dma_cookie_list[
9114 	    spx->txlt_curwin_processed_dma_cookies].dmac_size;
9115 
9116 	spx->txlt_curwin_processed_dma_cookies++;
9117 
9118 	ASSERT(cur_txfer_len <= max_txfer_len);
9119 
9120 	/* Add more cookies to the scatter-gather list */
9121 	for (i = 1; i < req_sg_len; i++) {
9122 		if (cur_txfer_len < max_txfer_len) {
9123 			/*
9124 			 * Check if the next cookie could be used by
9125 			 * this sata_pkt.
9126 			 */
9127 			if ((cur_txfer_len +
9128 			    spx->txlt_dma_cookie_list[
9129 			    spx->txlt_curwin_processed_dma_cookies].
9130 			    dmac_size) <= max_txfer_len) {
9131 				/* Yes, transfer lenght is within bounds */
9132 				spx->txlt_sata_pkt->
9133 				    satapkt_cmd.satacmd_num_dma_cookies++;
9134 				cur_txfer_len +=
9135 				    spx->txlt_dma_cookie_list[
9136 				    spx->txlt_curwin_processed_dma_cookies].
9137 				    dmac_size;
9138 				spx->txlt_curwin_processed_dma_cookies++;
9139 			} else {
9140 				/* No, transfer would exceed max lenght. */
9141 				SATADBG3(SATA_DBG_DMA_SETUP,
9142 				    spx->txlt_sata_hba_inst,
9143 				    "ncookies %d, size 0x%lx, "
9144 				    "max_size 0x%lx\n",
9145 				    spx->txlt_sata_pkt->
9146 				    satapkt_cmd.satacmd_num_dma_cookies,
9147 				    cur_txfer_len, max_txfer_len);
9148 				break;
9149 			}
9150 		} else {
9151 			/* Cmd max transfer length reached */
9152 			SATADBG3(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
9153 			    "Max transfer length? "
9154 			    "ncookies %d, size 0x%lx, max_size 0x%lx\n",
9155 			    spx->txlt_sata_pkt->
9156 			    satapkt_cmd.satacmd_num_dma_cookies,
9157 			    cur_txfer_len, max_txfer_len);
9158 			break;
9159 		}
9160 	}
9161 
9162 	ASSERT(cur_txfer_len != 0);
9163 	if (cur_txfer_len <= bp->b_bcount)
9164 		spx->txlt_total_residue -= cur_txfer_len;
9165 	else
9166 		/*
9167 		 * Temporary DMA buffer has been padded by
9168 		 * ddi_dma_mem_alloc()!
9169 		 * This requires special handling, because DMA cookies are
9170 		 * based on the temporary buffer size, not the b_bcount,
9171 		 * and we have extra bytes to transfer - but the packet
9172 		 * residue has to stay correct because we will copy only
9173 		 * the requested number of bytes.
9174 		 */
9175 		spx->txlt_total_residue -= bp->b_bcount;
9176 
9177 	return (DDI_SUCCESS);
9178 }
9179 
9180 
9181 /*
9182  * Fetch Device Identify data.
9183  * Send DEVICE IDENTIFY command to a device and get the device identify data.
9184  * The device_info structure has to be set to device type (for selecting proper
9185  * device identify command).
9186  *
9187  * Returns:
9188  * 0 if cmd succeeded
9189  * 1 if cmd was rejected and could be retried,
9190  * -1if cmd failed and should not be retried (port error)
9191  *
9192  * Cannot be called in an interrupt context.
9193  */
9194 
9195 static int
9196 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
9197     sata_drive_info_t *sdinfo)
9198 {
9199 	struct buf *bp;
9200 	sata_pkt_t *spkt;
9201 	sata_cmd_t *scmd;
9202 	sata_pkt_txlate_t *spx;
9203 	int rval;
9204 
9205 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9206 	spx->txlt_sata_hba_inst = sata_hba_inst;
9207 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9208 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
9209 	if (spkt == NULL) {
9210 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9211 		return (1); /* may retry later */
9212 	}
9213 	/* address is needed now */
9214 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
9215 
9216 	/*
9217 	 * Allocate buffer for Identify Data return data
9218 	 */
9219 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
9220 	if (bp == NULL) {
9221 		sata_pkt_free(spx);
9222 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9223 		SATA_LOG_D((sata_hba_inst, CE_WARN,
9224 		    "sata_fetch_device_identify_data: "
9225 		    "cannot allocate buffer for ID"));
9226 		return (1); /* may retry later */
9227 	}
9228 
9229 	/* Fill sata_pkt */
9230 	sdinfo->satadrv_state = SATA_STATE_PROBING;
9231 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
9232 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9233 	/* Synchronous mode, no callback */
9234 	spkt->satapkt_comp = NULL;
9235 	/* Timeout 30s */
9236 	spkt->satapkt_time = sata_default_pkt_time;
9237 
9238 	scmd = &spkt->satapkt_cmd;
9239 	scmd->satacmd_bp = bp;
9240 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9241 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9242 
9243 	/* Build Identify Device cmd in the sata_pkt */
9244 	scmd->satacmd_addr_type = 0;		/* N/A */
9245 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
9246 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
9247 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
9248 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
9249 	scmd->satacmd_features_reg = 0;		/* N/A */
9250 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
9251 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
9252 		/* Identify Packet Device cmd */
9253 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
9254 	} else {
9255 		/* Identify Device cmd - mandatory for all other devices */
9256 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
9257 	}
9258 
9259 	/* Send pkt to SATA HBA driver */
9260 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
9261 	if (rval == SATA_TRAN_ACCEPTED &&
9262 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9263 		if ((sdinfo->satadrv_id.ai_config & 4) == 1) {
9264 			sata_log(sata_hba_inst, CE_WARN,
9265 			    "SATA disk device at port %d - "
9266 			    "partial Identify Data",
9267 			    sdinfo->satadrv_addr.cport);
9268 			rval = 1; /* may retry later */
9269 			goto fail;
9270 		}
9271 		/* Update sata_drive_info */
9272 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9273 			DDI_DMA_SYNC_FORKERNEL);
9274 		ASSERT(rval == DDI_SUCCESS);
9275 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
9276 		    sizeof (sata_id_t));
9277 
9278 		sdinfo->satadrv_features_support = 0;
9279 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9280 			/*
9281 			 * Retrieve capacity (disks only) and addressing mode
9282 			 */
9283 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
9284 		} else {
9285 			/*
9286 			 * For ATAPI devices one has to issue Get Capacity cmd
9287 			 * (not needed at the moment)
9288 			 */
9289 			sdinfo->satadrv_capacity = 0;
9290 		}
9291 		/* Setup supported features flags */
9292 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
9293 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
9294 
9295 		/* Check for NCQ support */
9296 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
9297 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
9298 			/* SATA compliance */
9299 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
9300 				sdinfo->satadrv_features_support |=
9301 				    SATA_DEV_F_NCQ;
9302 			if (sdinfo->satadrv_id.ai_satacap &
9303 			    (SATA_1_SPEED | SATA_2_SPEED)) {
9304 				if (sdinfo->satadrv_id.ai_satacap &
9305 				    SATA_2_SPEED)
9306 					sdinfo->satadrv_features_support |=
9307 					    SATA_DEV_F_SATA2;
9308 				if (sdinfo->satadrv_id.ai_satacap &
9309 				    SATA_1_SPEED)
9310 					sdinfo->satadrv_features_support |=
9311 					    SATA_DEV_F_SATA1;
9312 			} else {
9313 				sdinfo->satadrv_features_support |=
9314 				    SATA_DEV_F_SATA1;
9315 			}
9316 		}
9317 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
9318 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
9319 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
9320 
9321 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
9322 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
9323 			(sdinfo->satadrv_features_support & SATA_DEV_F_TCQ))
9324 			++sdinfo->satadrv_queue_depth;
9325 		rval = 0;
9326 	} else {
9327 		/*
9328 		 * Woops, no Identify Data.
9329 		 */
9330 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
9331 		    rval = 1; /* may retry later */
9332 		} else if (rval == SATA_TRAN_ACCEPTED) {
9333 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
9334 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
9335 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
9336 			    spkt->satapkt_reason == SATA_PKT_RESET)
9337 				rval = 1; /* may retry later */
9338 			else
9339 				rval = -1;
9340 		} else {
9341 			rval = -1;
9342 		}
9343 	}
9344 fail:
9345 	/* Free allocated resources */
9346 	sata_free_local_buffer(spx);
9347 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
9348 	sata_pkt_free(spx);
9349 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9350 
9351 	return (rval);
9352 }
9353 
9354 
9355 /*
9356  * SATA spec requires that the device supports at least UDMA 4 mode and
9357  * UDMA mode is selected.
9358  * Some devices (bridged devices) may not come-up with default UDMA mode
9359  * set correctly, so this function is setting it.
9360  *
9361  * Returns SATA_SUCCESS if proper UDMA mode is selected.
9362  * Returns SATA_FAILURE if proper UDMA mode could not be selected.
9363  */
9364 static int
9365 sata_set_udma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
9366 {
9367 	sata_pkt_t *spkt;
9368 	sata_cmd_t *scmd;
9369 	sata_pkt_txlate_t *spx;
9370 	int result = SATA_SUCCESS;
9371 	int i, mode;
9372 
9373 	ASSERT(sdinfo != NULL);
9374 	ASSERT(sata_hba_inst != NULL);
9375 
9376 	/* Find highest Ultra DMA mode supported */
9377 	for (mode = 6; mode >= 0; --mode) {
9378 		if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
9379 			break;
9380 	}
9381 	if (mode < 4)
9382 		return (SATA_FAILURE);
9383 
9384 	/* Find UDMA mode currently selected */
9385 	for (i = 6; i >= 0; --i) {
9386 		if (sdinfo->satadrv_id.ai_ultradma & (1 << (i + 8)))
9387 			break;
9388 	}
9389 
9390 	if (i < mode) {
9391 		/* Set UDMA mode via SET FEATURES COMMAND */
9392 		/* Prepare packet for SET FEATURES COMMAND */
9393 		spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9394 		spx->txlt_sata_hba_inst = sata_hba_inst;
9395 		spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
9396 		spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
9397 		if (spkt == NULL) {
9398 			result = SATA_FAILURE;
9399 			goto failure;
9400 		}
9401 		/* Fill sata_pkt */
9402 		spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
9403 		/* Timeout 30s */
9404 		spkt->satapkt_time = sata_default_pkt_time;
9405 		/* Synchronous mode, no callback, interrupts */
9406 		spkt->satapkt_op_mode =
9407 		    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9408 		spkt->satapkt_comp = NULL;
9409 		scmd = &spkt->satapkt_cmd;
9410 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
9411 		scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9412 		scmd->satacmd_addr_type = 0;
9413 		scmd->satacmd_device_reg = 0;
9414 		scmd->satacmd_status_reg = 0;
9415 		scmd->satacmd_error_reg = 0;
9416 		scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
9417 		scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
9418 		scmd->satacmd_sec_count_lsb =
9419 		    SATAC_TRANSFER_MODE_ULTRA_DMA | mode;
9420 
9421 		/* Transfer command to HBA */
9422 		if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
9423 		    spkt) != SATA_TRAN_ACCEPTED ||
9424 		    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
9425 			/* Pkt execution failed */
9426 			result = SATA_FAILURE;
9427 		}
9428 failure:
9429 		if (result == SATA_FAILURE)
9430 			SATA_LOG_D((sata_hba_inst, CE_WARN,
9431 			    "sata_set_udma_mode: could not set UDMA "
9432 			    "mode %", mode));
9433 
9434 		/* Free allocated resources */
9435 		if (spkt != NULL)
9436 			sata_pkt_free(spx);
9437 		(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
9438 	}
9439 	return (result);
9440 }
9441 
9442 
9443 /*
9444  * Set device caching mode.
9445  * One of the following operations should be specified:
9446  * SATAC_SF_ENABLE_READ_AHEAD
9447  * SATAC_SF_DISABLE_READ_AHEAD
9448  * SATAC_SF_ENABLE_WRITE_CACHE
9449  * SATAC_SF_DISABLE_WRITE_CACHE
9450  *
9451  * If operation fails, system log messgage is emitted.
9452  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
9453  */
9454 
9455 static int
9456 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
9457     int cache_op)
9458 {
9459 	sata_pkt_t *spkt;
9460 	sata_cmd_t *scmd;
9461 	sata_pkt_txlate_t *spx;
9462 	int rval = SATA_SUCCESS;
9463 	char *infop;
9464 
9465 	ASSERT(sdinfo != NULL);
9466 	ASSERT(sata_hba_inst != NULL);
9467 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
9468 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
9469 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
9470 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
9471 
9472 
9473 	/* Prepare packet for SET FEATURES COMMAND */
9474 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9475 	spx->txlt_sata_hba_inst = sata_hba_inst;
9476 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
9477 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
9478 	if (spkt == NULL) {
9479 		rval = SATA_FAILURE;
9480 		goto failure;
9481 	}
9482 	/* Fill sata_pkt */
9483 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
9484 	/* Timeout 30s */
9485 	spkt->satapkt_time = sata_default_pkt_time;
9486 	/* Synchronous mode, no callback, interrupts */
9487 	spkt->satapkt_op_mode =
9488 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9489 	spkt->satapkt_comp = NULL;
9490 	scmd = &spkt->satapkt_cmd;
9491 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
9492 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9493 	scmd->satacmd_addr_type = 0;
9494 	scmd->satacmd_device_reg = 0;
9495 	scmd->satacmd_status_reg = 0;
9496 	scmd->satacmd_error_reg = 0;
9497 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
9498 	scmd->satacmd_features_reg = cache_op;
9499 
9500 	/* Transfer command to HBA */
9501 	if (((*SATA_START_FUNC(sata_hba_inst))(
9502 	    SATA_DIP(sata_hba_inst), spkt) != 0) ||
9503 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
9504 		/* Pkt execution failed */
9505 		switch (cache_op) {
9506 		case SATAC_SF_ENABLE_READ_AHEAD:
9507 			infop = "enabling read ahead failed";
9508 			break;
9509 		case SATAC_SF_DISABLE_READ_AHEAD:
9510 			infop = "disabling read ahead failed";
9511 			break;
9512 		case SATAC_SF_ENABLE_WRITE_CACHE:
9513 			infop = "enabling write cache failed";
9514 			break;
9515 		case SATAC_SF_DISABLE_WRITE_CACHE:
9516 			infop = "disabling write cache failed";
9517 			break;
9518 		}
9519 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
9520 		rval = SATA_FAILURE;
9521 	}
9522 failure:
9523 	/* Free allocated resources */
9524 	if (spkt != NULL)
9525 		sata_pkt_free(spx);
9526 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
9527 	return (rval);
9528 }
9529 
9530 
9531 
9532 /*
9533  * Update port SCR block
9534  */
9535 static void
9536 sata_update_port_scr(sata_port_scr_t *port_scr, sata_device_t *device)
9537 {
9538 	port_scr->sstatus = device->satadev_scr.sstatus;
9539 	port_scr->serror = device->satadev_scr.serror;
9540 	port_scr->scontrol = device->satadev_scr.scontrol;
9541 	port_scr->sactive = device->satadev_scr.sactive;
9542 	port_scr->snotific = device->satadev_scr.snotific;
9543 }
9544 
9545 /*
9546  * Update state and copy port ss* values from passed sata_device structure.
9547  * sata_address is validated - if not valid, nothing is changed in sata_scsi
9548  * configuration struct.
9549  *
9550  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
9551  * regardless of the state in device argument.
9552  *
9553  * Port mutex should be held while calling this function.
9554  */
9555 static void
9556 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
9557 	sata_device_t *sata_device)
9558 {
9559 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst,
9560 	    sata_device->satadev_addr.cport)));
9561 
9562 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
9563 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
9564 
9565 		sata_cport_info_t *cportinfo;
9566 
9567 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
9568 		    sata_device->satadev_addr.cport)
9569 			return;
9570 
9571 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
9572 		    sata_device->satadev_addr.cport);
9573 		sata_update_port_scr(&cportinfo->cport_scr, sata_device);
9574 
9575 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
9576 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
9577 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
9578 		cportinfo->cport_state |=
9579 		    sata_device->satadev_state & SATA_PSTATE_VALID;
9580 	} else {
9581 		sata_pmport_info_t *pmportinfo;
9582 
9583 		if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT) ||
9584 		    (sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
9585 		    SATA_NUM_PMPORTS(sata_hba_inst,
9586 		    sata_device->satadev_addr.cport) <
9587 		    sata_device->satadev_addr.pmport)
9588 			return;
9589 
9590 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
9591 		    sata_device->satadev_addr.cport,
9592 		    sata_device->satadev_addr.pmport);
9593 		sata_update_port_scr(&pmportinfo->pmport_scr, sata_device);
9594 
9595 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
9596 		pmportinfo->pmport_state &=
9597 		    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF |
9598 		    SATA_PSTATE_FAILED);
9599 		pmportinfo->pmport_state |=
9600 		    sata_device->satadev_state & SATA_PSTATE_VALID;
9601 	}
9602 }
9603 
9604 
9605 
9606 /*
9607  * Extract SATA port specification from an IOCTL argument.
9608  *
9609  * This function return the port the user land send us as is, unless it
9610  * cannot retrieve port spec, then -1 is returned.
9611  *
9612  * Note: Only cport  - no port multiplier port.
9613  */
9614 static int32_t
9615 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
9616 {
9617 	int32_t port;
9618 
9619 	/* Extract port number from nvpair in dca structure  */
9620 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
9621 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
9622 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
9623 		    port));
9624 		port = -1;
9625 	}
9626 
9627 	return (port);
9628 }
9629 
9630 /*
9631  * Get dev_info_t pointer to the device node pointed to by port argument.
9632  * NOTE: target argument is a value used in ioctls to identify
9633  * the AP - it is not a sata_address.
9634  * It is a combination of cport, pmport and address qualifier, encodded same
9635  * way as a scsi target number.
9636  * At this moment it carries only cport number.
9637  *
9638  * No PMult hotplug support.
9639  *
9640  * Returns dev_info_t pointer if target device was found, NULL otherwise.
9641  */
9642 
9643 static dev_info_t *
9644 sata_get_target_dip(dev_info_t *dip, int32_t port)
9645 {
9646 	dev_info_t	*cdip = NULL;
9647 	int		target, tgt;
9648 	int		ncport;
9649 	int 		circ;
9650 
9651 	ncport = port & SATA_CFGA_CPORT_MASK;
9652 	target = SATA_TO_SCSI_TARGET(ncport, 0, SATA_ADDR_DCPORT);
9653 
9654 	ndi_devi_enter(dip, &circ);
9655 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
9656 		dev_info_t *next = ddi_get_next_sibling(cdip);
9657 
9658 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
9659 		    DDI_PROP_DONTPASS, "target", -1);
9660 		if (tgt == -1) {
9661 			/*
9662 			 * This is actually an error condition, but not
9663 			 * a fatal one. Just continue the search.
9664 			 */
9665 			cdip = next;
9666 			continue;
9667 		}
9668 
9669 		if (tgt == target)
9670 			break;
9671 
9672 		cdip = next;
9673 	}
9674 	ndi_devi_exit(dip, circ);
9675 
9676 	return (cdip);
9677 }
9678 
9679 
9680 /*
9681  * sata_cfgadm_state:
9682  * Use the sata port state and state of the target node to figure out
9683  * the cfgadm_state.
9684  *
9685  * The port argument is a value with encoded cport,
9686  * pmport and address qualifier, in the same manner as a scsi target number.
9687  * SCSI_TO_SATA_CPORT macro extracts cport number,
9688  * SCSI_TO_SATA_PMPORT extracts pmport number and
9689  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
9690  *
9691  * For now, support is for cports only - no pmultiplier ports.
9692  */
9693 
9694 static void
9695 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
9696     devctl_ap_state_t *ap_state)
9697 {
9698 	uint16_t	cport;
9699 	int		port_state;
9700 
9701 	/* Cport only */
9702 	cport = SCSI_TO_SATA_CPORT(port);
9703 
9704 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
9705 	if (port_state & SATA_PSTATE_SHUTDOWN ||
9706 	    port_state & SATA_PSTATE_FAILED) {
9707 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
9708 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
9709 		if (port_state & SATA_PSTATE_FAILED)
9710 			ap_state->ap_condition = AP_COND_FAILED;
9711 		else
9712 			ap_state->ap_condition = AP_COND_UNKNOWN;
9713 
9714 		return;
9715 	}
9716 
9717 	/* Need to check pmult device port here as well, when supported */
9718 
9719 	/* Port is enabled and ready */
9720 
9721 	switch (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport)) {
9722 	case SATA_DTYPE_NONE:
9723 	{
9724 		/* No device attached */
9725 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
9726 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
9727 		ap_state->ap_condition = AP_COND_OK;
9728 		break;
9729 	}
9730 	case SATA_DTYPE_UNKNOWN:
9731 	case SATA_DTYPE_ATAPINONCD:
9732 	case SATA_DTYPE_PMULT:	/* Until PMult is supported */
9733 	{
9734 		/* Unknown device attached */
9735 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
9736 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
9737 		ap_state->ap_condition = AP_COND_UNKNOWN;
9738 		break;
9739 	}
9740 	case SATA_DTYPE_ATADISK:
9741 	case SATA_DTYPE_ATAPICD:
9742 	{
9743 		dev_info_t *tdip = NULL;
9744 		dev_info_t *dip = NULL;
9745 		int circ;
9746 
9747 		dip = SATA_DIP(sata_hba_inst);
9748 		tdip = sata_get_target_dip(dip, port);
9749 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
9750 		if (tdip != NULL) {
9751 			ndi_devi_enter(dip, &circ);
9752 			mutex_enter(&(DEVI(tdip)->devi_lock));
9753 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
9754 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
9755 				ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
9756 			} else {
9757 				ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
9758 			}
9759 			ap_state->ap_condition = AP_COND_OK;
9760 			mutex_exit(&(DEVI(tdip)->devi_lock));
9761 			ndi_devi_exit(dip, circ);
9762 		} else {
9763 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
9764 			ap_state->ap_condition = AP_COND_UNKNOWN;
9765 		}
9766 		break;
9767 	}
9768 	default:
9769 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
9770 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
9771 		ap_state->ap_condition = AP_COND_UNKNOWN;
9772 		/*
9773 		 * This is actually internal error condition (non fatal),
9774 		 * beacuse we already checked all defined device types.
9775 		 */
9776 		SATA_LOG_D((sata_hba_inst, CE_WARN,
9777 		    "sata_cfgadm_state: Internal error: "
9778 		    "unknown device type"));
9779 		break;
9780 	}
9781 }
9782 
9783 /*
9784  * Start or terminate the thread, depending on flag arg and current state
9785  */
9786 static void
9787 sata_event_thread_control(int startstop)
9788 {
9789 	static 	int sata_event_thread_terminating = 0;
9790 	static 	int sata_event_thread_starting = 0;
9791 	int i;
9792 
9793 	mutex_enter(&sata_event_mutex);
9794 
9795 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
9796 	    sata_event_thread_terminating == 1)) {
9797 		mutex_exit(&sata_event_mutex);
9798 		return;
9799 	}
9800 	if (startstop == 1 && sata_event_thread_starting == 1) {
9801 		mutex_exit(&sata_event_mutex);
9802 		return;
9803 	}
9804 	if (startstop == 1 && sata_event_thread_terminating == 1) {
9805 		sata_event_thread_starting = 1;
9806 		/* wait til terminate operation completes */
9807 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
9808 		while (sata_event_thread_terminating == 1) {
9809 			if (i-- <= 0) {
9810 				sata_event_thread_starting = 0;
9811 				mutex_exit(&sata_event_mutex);
9812 #ifdef SATA_DEBUG
9813 				cmn_err(CE_WARN, "sata_event_thread_control: "
9814 				    "timeout waiting for thread to terminate");
9815 #endif
9816 				return;
9817 			}
9818 			mutex_exit(&sata_event_mutex);
9819 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
9820 			mutex_enter(&sata_event_mutex);
9821 		}
9822 	}
9823 	if (startstop == 1) {
9824 		if (sata_event_thread == NULL) {
9825 			sata_event_thread = thread_create(NULL, 0,
9826 			    (void (*)())sata_event_daemon,
9827 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
9828 		}
9829 		sata_event_thread_starting = 0;
9830 		mutex_exit(&sata_event_mutex);
9831 		return;
9832 	}
9833 
9834 	/*
9835 	 * If we got here, thread may need to be terminated
9836 	 */
9837 	if (sata_event_thread != NULL) {
9838 		int i;
9839 		/* Signal event thread to go away */
9840 		sata_event_thread_terminating = 1;
9841 		sata_event_thread_terminate = 1;
9842 		cv_signal(&sata_event_cv);
9843 		/*
9844 		 * Wait til daemon terminates.
9845 		 */
9846 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
9847 		while (sata_event_thread_terminate == 1) {
9848 			mutex_exit(&sata_event_mutex);
9849 			if (i-- <= 0) {
9850 				/* Daemon did not go away !!! */
9851 #ifdef SATA_DEBUG
9852 				cmn_err(CE_WARN, "sata_event_thread_control: "
9853 				    "cannot terminate event daemon thread");
9854 #endif
9855 				mutex_enter(&sata_event_mutex);
9856 				break;
9857 			}
9858 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
9859 			mutex_enter(&sata_event_mutex);
9860 		}
9861 		sata_event_thread_terminating = 0;
9862 	}
9863 	ASSERT(sata_event_thread_terminating == 0);
9864 	ASSERT(sata_event_thread_starting == 0);
9865 	mutex_exit(&sata_event_mutex);
9866 }
9867 
9868 
9869 /*
9870  * Log sata message
9871  * dev pathname msg line preceeds the logged message.
9872  */
9873 
9874 static	void
9875 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
9876 {
9877 	char pathname[128];
9878 	dev_info_t *dip;
9879 	va_list ap;
9880 
9881 	mutex_enter(&sata_log_mutex);
9882 
9883 	va_start(ap, fmt);
9884 	(void) vsprintf(sata_log_buf, fmt, ap);
9885 	va_end(ap);
9886 
9887 	if (sata_hba_inst != NULL) {
9888 		dip = SATA_DIP(sata_hba_inst);
9889 		(void) ddi_pathname(dip, pathname);
9890 	} else {
9891 		pathname[0] = 0;
9892 	}
9893 	if (level == CE_CONT) {
9894 		if (sata_debug_flags == 0)
9895 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
9896 		else
9897 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
9898 	} else
9899 		cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
9900 
9901 	mutex_exit(&sata_log_mutex);
9902 }
9903 
9904 
9905 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
9906 
9907 /*
9908  * SATA HBA event notification function.
9909  * Events reported by SATA HBA drivers per HBA instance relate to a change in
9910  * a port and/or device state or a controller itself.
9911  * Events for different addresses/addr types cannot be combined.
9912  * A warning message is generated for each event type.
9913  * Events are not processed by this function, so only the
9914  * event flag(s)is set for an affected entity and the event thread is
9915  * waken up. Event daemon thread processes all events.
9916  *
9917  * NOTE: Since more than one event may be reported at the same time, one
9918  * cannot determine a sequence of events when opposite event are reported, eg.
9919  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
9920  * is taking precedence over reported events, i.e. may cause ignoring some
9921  * events.
9922  */
9923 #define	SATA_EVENT_MAX_MSG_LENGTH	79
9924 
9925 void
9926 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
9927 {
9928 	sata_hba_inst_t *sata_hba_inst = NULL;
9929 	sata_address_t *saddr;
9930 	sata_drive_info_t *sdinfo;
9931 	sata_port_stats_t *pstats;
9932 	int cport, pmport;
9933 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
9934 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
9935 	char *lcp;
9936 	static char *err_msg_evnt_1 =
9937 	    "sata_hba_event_notify: invalid port event 0x%x ";
9938 	static char *err_msg_evnt_2 =
9939 	    "sata_hba_event_notify: invalid device event 0x%x ";
9940 	int linkevent;
9941 
9942 	/*
9943 	 * There is a possibility that an event will be generated on HBA
9944 	 * that has not completed attachment or is detaching.
9945 	 * HBA driver should prevent this, but just in case it does not,
9946 	 * we need to ignore events for such HBA.
9947 	 */
9948 	mutex_enter(&sata_mutex);
9949 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
9950 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9951 		if (SATA_DIP(sata_hba_inst) == dip)
9952 			if (sata_hba_inst->satahba_attached == 1)
9953 				break;
9954 	}
9955 	mutex_exit(&sata_mutex);
9956 	if (sata_hba_inst == NULL)
9957 		/* HBA not attached */
9958 		return;
9959 
9960 	ASSERT(sata_device != NULL);
9961 
9962 	/*
9963 	 * Validate address before - do not proceed with invalid address.
9964 	 */
9965 	saddr = &sata_device->satadev_addr;
9966 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
9967 		return;
9968 	if (saddr->qual == SATA_ADDR_PMPORT ||
9969 	    saddr->qual == SATA_ADDR_DPMPORT)
9970 		/* Port Multiplier not supported yet */
9971 		return;
9972 
9973 	cport = saddr->cport;
9974 	pmport = saddr->pmport;
9975 
9976 	buf1[0] = buf2[0] = '\0';
9977 
9978 	/*
9979 	 * Events refer to devices, ports and controllers - each has
9980 	 * unique address. Events for different addresses cannot be combined.
9981 	 */
9982 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
9983 
9984 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
9985 
9986 		/* qualify this event(s) */
9987 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
9988 			/* Invalid event for the device port */
9989 			(void) sprintf(buf2, err_msg_evnt_1,
9990 			    event & SATA_EVNT_PORT_EVENTS);
9991 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
9992 			goto event_info;
9993 		}
9994 		if (saddr->qual == SATA_ADDR_CPORT) {
9995 			/* Controller's device port event */
9996 
9997 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
9998 			    cport_event_flags |=
9999 			    event & SATA_EVNT_PORT_EVENTS;
10000 			pstats =
10001 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
10002 			    cport_stats;
10003 		} else {
10004 			/* Port multiplier's device port event */
10005 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
10006 			    pmport_event_flags |=
10007 			    event & SATA_EVNT_PORT_EVENTS;
10008 			pstats =
10009 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
10010 			    pmport_stats;
10011 		}
10012 
10013 		/*
10014 		 * Add to statistics and log the message. We have to do it
10015 		 * here rather than in the event daemon, because there may be
10016 		 * multiple events occuring before they are processed.
10017 		 */
10018 		linkevent = event &
10019 			(SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
10020 		if (linkevent) {
10021 			if (linkevent == (SATA_EVNT_LINK_LOST |
10022 			    SATA_EVNT_LINK_ESTABLISHED)) {
10023 				/* This is likely event combination */
10024 				(void) strlcat(buf1, "link lost/established, ",
10025 				    SATA_EVENT_MAX_MSG_LENGTH);
10026 
10027 				if (pstats->link_lost < 0xffffffffffffffffULL)
10028 					pstats->link_lost++;
10029 				if (pstats->link_established <
10030 				    0xffffffffffffffffULL)
10031 					pstats->link_established++;
10032 				linkevent = 0;
10033 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
10034 				(void) strlcat(buf1, "link lost, ",
10035 				    SATA_EVENT_MAX_MSG_LENGTH);
10036 
10037 				if (pstats->link_lost < 0xffffffffffffffffULL)
10038 					pstats->link_lost++;
10039 			} else {
10040 				(void) strlcat(buf1, "link established, ",
10041 				    SATA_EVENT_MAX_MSG_LENGTH);
10042 				if (pstats->link_established <
10043 				    0xffffffffffffffffULL)
10044 					pstats->link_established++;
10045 			}
10046 		}
10047 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
10048 			(void) strlcat(buf1, "device attached, ",
10049 			    SATA_EVENT_MAX_MSG_LENGTH);
10050 			if (pstats->device_attached < 0xffffffffffffffffULL)
10051 				pstats->device_attached++;
10052 		}
10053 		if (event & SATA_EVNT_DEVICE_DETACHED) {
10054 			(void) strlcat(buf1, "device detached, ",
10055 			    SATA_EVENT_MAX_MSG_LENGTH);
10056 			if (pstats->device_detached < 0xffffffffffffffffULL)
10057 				pstats->device_detached++;
10058 		}
10059 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
10060 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
10061 			    "port %d power level changed", cport);
10062 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
10063 				pstats->port_pwr_changed++;
10064 		}
10065 
10066 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
10067 			/* There should be no other events for this address */
10068 			(void) sprintf(buf2, err_msg_evnt_1,
10069 			    event & ~SATA_EVNT_PORT_EVENTS);
10070 		}
10071 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
10072 
10073 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
10074 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
10075 
10076 		/* qualify this event */
10077 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
10078 			/* Invalid event for a device */
10079 			(void) sprintf(buf2, err_msg_evnt_2,
10080 			    event & SATA_EVNT_DEVICE_RESET);
10081 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
10082 			goto event_info;
10083 		}
10084 		/* drive event */
10085 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
10086 		if (sdinfo != NULL) {
10087 			if (event & SATA_EVNT_DEVICE_RESET) {
10088 				(void) strlcat(buf1, "device reset, ",
10089 				    SATA_EVENT_MAX_MSG_LENGTH);
10090 				if (sdinfo->satadrv_stats.drive_reset <
10091 				    0xffffffffffffffffULL)
10092 					sdinfo->satadrv_stats.drive_reset++;
10093 				sdinfo->satadrv_event_flags |=
10094 				    SATA_EVNT_DEVICE_RESET;
10095 			}
10096 		}
10097 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
10098 			/* Invalid event for a device */
10099 			(void) sprintf(buf2, err_msg_evnt_2,
10100 			    event & ~SATA_EVNT_DRIVE_EVENTS);
10101 		}
10102 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
10103 	} else {
10104 		if (saddr->qual != SATA_ADDR_NULL) {
10105 			/* Wrong address qualifier */
10106 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10107 			    "sata_hba_event_notify: invalid address 0x%x",
10108 			    *(uint32_t *)saddr));
10109 			return;
10110 		}
10111 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
10112 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
10113 			/* Invalid event for the controller */
10114 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10115 			    "sata_hba_event_notify: invalid event 0x%x for "
10116 			    "controller",
10117 			    event & SATA_EVNT_CONTROLLER_EVENTS));
10118 			return;
10119 		}
10120 		buf1[0] = '\0';
10121 		/* This may be a frequent and not interesting event */
10122 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
10123 		    "controller power level changed\n", NULL);
10124 
10125 		mutex_enter(&sata_hba_inst->satahba_mutex);
10126 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
10127 		    0xffffffffffffffffULL)
10128 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
10129 
10130 		sata_hba_inst->satahba_event_flags |=
10131 		    SATA_EVNT_PWR_LEVEL_CHANGED;
10132 		mutex_exit(&sata_hba_inst->satahba_mutex);
10133 	}
10134 	/*
10135 	 * If we got here, there is something to do with this HBA
10136 	 * instance.
10137 	 */
10138 	mutex_enter(&sata_hba_inst->satahba_mutex);
10139 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
10140 	mutex_exit(&sata_hba_inst->satahba_mutex);
10141 	mutex_enter(&sata_mutex);
10142 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
10143 	mutex_exit(&sata_mutex);
10144 
10145 	/* Tickle event thread */
10146 	mutex_enter(&sata_event_mutex);
10147 	if (sata_event_thread_active == 0)
10148 		cv_signal(&sata_event_cv);
10149 	mutex_exit(&sata_event_mutex);
10150 
10151 event_info:
10152 	if (buf1[0] != '\0') {
10153 		lcp = strrchr(buf1, ',');
10154 		if (lcp != NULL)
10155 			*lcp = '\0';
10156 	}
10157 	if (saddr->qual == SATA_ADDR_CPORT ||
10158 	    saddr->qual == SATA_ADDR_DCPORT) {
10159 		if (buf1[0] != '\0') {
10160 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
10161 			    cport, buf1);
10162 		}
10163 		if (buf2[0] != '\0') {
10164 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
10165 			    cport, buf2);
10166 		}
10167 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
10168 	    saddr->qual == SATA_ADDR_DPMPORT) {
10169 		if (buf1[0] != '\0') {
10170 			sata_log(sata_hba_inst, CE_NOTE,
10171 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
10172 		}
10173 		if (buf2[0] != '\0') {
10174 			sata_log(sata_hba_inst, CE_NOTE,
10175 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
10176 		}
10177 	}
10178 }
10179 
10180 
10181 /*
10182  * Event processing thread.
10183  * Arg is a pointer to the sata_hba_list pointer.
10184  * It is not really needed, because sata_hba_list is global and static
10185  */
10186 static void
10187 sata_event_daemon(void *arg)
10188 {
10189 #ifndef __lock_lint
10190 	_NOTE(ARGUNUSED(arg))
10191 #endif
10192 	sata_hba_inst_t *sata_hba_inst;
10193 	clock_t lbolt;
10194 
10195 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
10196 	    "SATA event daemon started\n", NULL);
10197 loop:
10198 	/*
10199 	 * Process events here. Walk through all registered HBAs
10200 	 */
10201 	mutex_enter(&sata_mutex);
10202 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
10203 	    sata_hba_inst = sata_hba_inst->satahba_next) {
10204 		ASSERT(sata_hba_inst != NULL);
10205 		mutex_enter(&sata_hba_inst->satahba_mutex);
10206 		if (sata_hba_inst->satahba_attached != 1 ||
10207 		    (sata_hba_inst->satahba_event_flags &
10208 		    SATA_EVNT_SKIP) != 0) {
10209 			mutex_exit(&sata_hba_inst->satahba_mutex);
10210 			continue;
10211 		}
10212 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
10213 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
10214 			mutex_exit(&sata_hba_inst->satahba_mutex);
10215 			mutex_exit(&sata_mutex);
10216 			/* Got the controller with pending event */
10217 			sata_process_controller_events(sata_hba_inst);
10218 			/*
10219 			 * Since global mutex was released, there is a
10220 			 * possibility that HBA list has changed, so start
10221 			 * over from the top. Just processed controller
10222 			 * will be passed-over because of the SKIP flag.
10223 			 */
10224 			goto loop;
10225 		}
10226 		mutex_exit(&sata_hba_inst->satahba_mutex);
10227 	}
10228 	/* Clear SKIP flag in all controllers */
10229 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
10230 	    sata_hba_inst = sata_hba_inst->satahba_next) {
10231 		mutex_enter(&sata_hba_inst->satahba_mutex);
10232 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
10233 		mutex_exit(&sata_hba_inst->satahba_mutex);
10234 	}
10235 	mutex_exit(&sata_mutex);
10236 
10237 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
10238 	    "SATA EVENT DAEMON suspending itself", NULL);
10239 
10240 #ifdef SATA_DEBUG
10241 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
10242 		sata_log(sata_hba_inst, CE_WARN,
10243 		    "SATA EVENTS PROCESSING DISABLED\n");
10244 		thread_exit(); /* Daemon will not run again */
10245 	}
10246 #endif
10247 	mutex_enter(&sata_event_mutex);
10248 	sata_event_thread_active = 0;
10249 	mutex_exit(&sata_event_mutex);
10250 	/*
10251 	 * Go to sleep/suspend itself and wake up either because new event or
10252 	 * wait timeout. Exit if there is a termination request (driver
10253 	 * unload).
10254 	 */
10255 	do {
10256 		lbolt = ddi_get_lbolt();
10257 		lbolt += drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
10258 		mutex_enter(&sata_event_mutex);
10259 		(void) cv_timedwait(&sata_event_cv, &sata_event_mutex, lbolt);
10260 
10261 		if (sata_event_thread_active != 0) {
10262 			mutex_exit(&sata_event_mutex);
10263 			continue;
10264 		}
10265 
10266 		/* Check if it is time to go away */
10267 		if (sata_event_thread_terminate == 1) {
10268 			/*
10269 			 * It is up to the thread setting above flag to make
10270 			 * sure that this thread is not killed prematurely.
10271 			 */
10272 			sata_event_thread_terminate = 0;
10273 			sata_event_thread = NULL;
10274 			mutex_exit(&sata_event_mutex);
10275 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
10276 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
10277 			thread_exit();  { _NOTE(NOT_REACHED) }
10278 		}
10279 		mutex_exit(&sata_event_mutex);
10280 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
10281 
10282 	mutex_enter(&sata_event_mutex);
10283 	sata_event_thread_active = 1;
10284 	mutex_exit(&sata_event_mutex);
10285 
10286 	mutex_enter(&sata_mutex);
10287 	sata_event_pending &= ~SATA_EVNT_MAIN;
10288 	mutex_exit(&sata_mutex);
10289 
10290 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
10291 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
10292 
10293 	goto loop;
10294 }
10295 
10296 /*
10297  * Specific HBA instance event processing.
10298  *
10299  * NOTE: At the moment, device event processing is limited to hard disks
10300  * only.
10301  * cports only are supported - no pmports.
10302  */
10303 static void
10304 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
10305 {
10306 	int ncport;
10307 	uint32_t event_flags;
10308 	sata_address_t *saddr;
10309 
10310 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
10311 	    "Processing controller %d event(s)",
10312 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
10313 
10314 	mutex_enter(&sata_hba_inst->satahba_mutex);
10315 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
10316 	event_flags = sata_hba_inst->satahba_event_flags;
10317 	mutex_exit(&sata_hba_inst->satahba_mutex);
10318 	/*
10319 	 * Process controller power change first
10320 	 * HERE
10321 	 */
10322 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
10323 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
10324 
10325 	/*
10326 	 * Search through ports/devices to identify affected port/device.
10327 	 * We may have to process events for more than one port/device.
10328 	 */
10329 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
10330 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
10331 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
10332 		    cport_event_flags;
10333 		/* Check if port was locked by IOCTL processing */
10334 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
10335 			/*
10336 			 * We ignore port events because port is busy
10337 			 * with AP control processing. Set again
10338 			 * controller and main event flag, so that
10339 			 * events may be processed by the next daemon
10340 			 * run.
10341 			 */
10342 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
10343 			mutex_enter(&sata_hba_inst->satahba_mutex);
10344 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
10345 			mutex_exit(&sata_hba_inst->satahba_mutex);
10346 			mutex_enter(&sata_mutex);
10347 			sata_event_pending |= SATA_EVNT_MAIN;
10348 			mutex_exit(&sata_mutex);
10349 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
10350 			    "Event processing postponed until "
10351 			    "AP control processing completes",
10352 			    NULL);
10353 			/* Check other ports */
10354 			continue;
10355 		} else {
10356 			/*
10357 			 * Set BSY flag so that AP control would not
10358 			 * interfere with events processing for
10359 			 * this port.
10360 			 */
10361 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
10362 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
10363 		}
10364 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
10365 
10366 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
10367 
10368 		if ((event_flags &
10369 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
10370 			/*
10371 			 * Got port event.
10372 			 * We need some hierarchy of event processing as they
10373 			 * are affecting each other:
10374 			 * 1. port failed
10375 			 * 2. device detached/attached
10376 			 * 3. link events - link events may trigger device
10377 			 *    detached or device attached events in some
10378 			 *    circumstances.
10379 			 * 4. port power level changed
10380 			 */
10381 			if (event_flags & SATA_EVNT_PORT_FAILED) {
10382 				sata_process_port_failed_event(sata_hba_inst,
10383 				    saddr);
10384 			}
10385 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
10386 				sata_process_device_detached(sata_hba_inst,
10387 				    saddr);
10388 			}
10389 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
10390 				sata_process_device_attached(sata_hba_inst,
10391 				    saddr);
10392 			}
10393 			if (event_flags &
10394 			    (SATA_EVNT_LINK_ESTABLISHED |
10395 			    SATA_EVNT_LINK_LOST)) {
10396 				sata_process_port_link_events(sata_hba_inst,
10397 				    saddr);
10398 			}
10399 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
10400 				sata_process_port_pwr_change(sata_hba_inst,
10401 				    saddr);
10402 			}
10403 		}
10404 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
10405 		    SATA_DTYPE_NONE) {
10406 			/* May have device event */
10407 			sata_process_device_reset(sata_hba_inst, saddr);
10408 		}
10409 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
10410 		/* Release PORT_BUSY flag */
10411 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
10412 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
10413 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
10414 
10415 	} /* End of loop through the controller SATA ports */
10416 }
10417 
10418 /*
10419  * Process HBA power level change reported by HBA driver.
10420  * Not implemented at this time - event is ignored.
10421  */
10422 static void
10423 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
10424 {
10425 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10426 	    "Processing controller power level change", NULL);
10427 
10428 	/* Ignoring it for now */
10429 	mutex_enter(&sata_hba_inst->satahba_mutex);
10430 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
10431 	mutex_exit(&sata_hba_inst->satahba_mutex);
10432 }
10433 
10434 /*
10435  * Process port power level change reported by HBA driver.
10436  * Not implemented at this time - event is ignored.
10437  */
10438 static void
10439 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
10440     sata_address_t *saddr)
10441 {
10442 	sata_cport_info_t *cportinfo;
10443 
10444 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10445 	    "Processing port power level change", NULL);
10446 
10447 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
10448 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10449 	/* Reset event flag */
10450 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
10451 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10452 }
10453 
10454 /*
10455  * Process port failure reported by HBA driver.
10456  * cports support only - no pmports.
10457  */
10458 static void
10459 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
10460     sata_address_t *saddr)
10461 {
10462 	sata_cport_info_t *cportinfo;
10463 
10464 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
10465 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10466 	/* Reset event flag first */
10467 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
10468 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
10469 	if ((cportinfo->cport_state &
10470 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
10471 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10472 		    cport_mutex);
10473 		return;
10474 	}
10475 	/* Fail the port */
10476 	cportinfo->cport_state = SATA_PSTATE_FAILED;
10477 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10478 	sata_log(sata_hba_inst, CE_WARN, "port %d failed", saddr->cport);
10479 }
10480 
10481 /*
10482  * Device Reset Event processing.
10483  * The seqeunce is managed by 3 stage flags:
10484  * - reset event reported,
10485  * - reset event being processed,
10486  * - request to clear device reset state.
10487  */
10488 static void
10489 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
10490     sata_address_t *saddr)
10491 {
10492 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
10493 	sata_drive_info_t *sdinfo;
10494 	sata_cport_info_t *cportinfo;
10495 	sata_device_t sata_device;
10496 	int rval;
10497 
10498 	/* We only care about host sata cport for now */
10499 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
10500 
10501 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10502 
10503 	/* If the port is in SHUTDOWN or FAILED state, ignore reset event. */
10504 	if ((cportinfo->cport_state &
10505 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
10506 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10507 		    cport_mutex);
10508 		return;
10509 	}
10510 
10511 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
10512 	    SATA_VALID_DEV_TYPE) == 0) {
10513 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10514 		    cport_mutex);
10515 		return;
10516 	}
10517 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
10518 	if (sdinfo == NULL) {
10519 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10520 		    cport_mutex);
10521 		return;
10522 	}
10523 
10524 	if ((sdinfo->satadrv_event_flags & SATA_EVNT_DEVICE_RESET) == 0) {
10525 		/* Nothing to do */
10526 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10527 		    cport_mutex);
10528 		return;
10529 	}
10530 
10531 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10532 	    "Processing port %d device reset", saddr->cport);
10533 
10534 	if (sdinfo->satadrv_event_flags & SATA_EVNT_INPROC_DEVICE_RESET) {
10535 		/* Something is weird - new device reset event */
10536 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10537 		    "Overlapping device reset events!", NULL);
10538 		/* Just leave */
10539 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10540 		    cport_mutex);
10541 		return;
10542 	}
10543 
10544 	/* Clear event flag */
10545 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
10546 
10547 	/* It seems that we always need to check the port state first */
10548 	sata_device.satadev_rev = SATA_DEVICE_REV;
10549 	sata_device.satadev_addr = *saddr;
10550 	/*
10551 	 * We have to exit mutex, because the HBA probe port function may
10552 	 * block on its own mutex.
10553 	 */
10554 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10555 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10556 	    (SATA_DIP(sata_hba_inst), &sata_device);
10557 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10558 	sata_update_port_info(sata_hba_inst, &sata_device);
10559 	if (rval != SATA_SUCCESS) {
10560 		/* Something went wrong? Fail the port */
10561 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10562 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10563 		    cport_mutex);
10564 		SATA_LOG_D((sata_hba_inst, CE_WARN, "Port %d probing failed",
10565 		    saddr->cport));
10566 		return;
10567 	}
10568 	if ((sata_device.satadev_scr.sstatus  &
10569 	    SATA_PORT_DEVLINK_UP_MASK) !=
10570 	    SATA_PORT_DEVLINK_UP ||
10571 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
10572 		/*
10573 		 * No device to process, anymore. Some other event processing
10574 		 * would or have already performed port info cleanup.
10575 		 * To be safe (HBA may need it), request clearing device
10576 		 * reset condition.
10577 		 */
10578 		sdinfo->satadrv_event_flags = 0;
10579 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
10580 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10581 		    cport_mutex);
10582 		return;
10583 	}
10584 
10585 	/* Mark device reset processing as active */
10586 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
10587 
10588 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
10589 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10590 
10591 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
10592 	    SATA_FAILURE) {
10593 		/*
10594 		 * Restoring drive setting failed.
10595 		 * Probe the port first, to check if the port state has changed
10596 		 */
10597 		sata_device.satadev_rev = SATA_DEVICE_REV;
10598 		sata_device.satadev_addr = *saddr;
10599 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
10600 		/* probe port */
10601 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10602 		    (SATA_DIP(sata_hba_inst), &sata_device);
10603 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10604 		    cport_mutex);
10605 		if (rval == SATA_SUCCESS &&
10606 		    (sata_device.satadev_state &
10607 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
10608 		    (sata_device.satadev_scr.sstatus  &
10609 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
10610 		    (sata_device.satadev_type & SATA_DTYPE_ATADISK) != 0) {
10611 			/*
10612 			 * We may retry this a bit later - reinstate reset
10613 			 * condition
10614 			 */
10615 			if ((cportinfo->cport_dev_type &
10616 			    SATA_VALID_DEV_TYPE) != 0 &&
10617 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10618 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10619 				sdinfo->satadrv_event_flags |=
10620 				    SATA_EVNT_DEVICE_RESET;
10621 				sdinfo->satadrv_event_flags &=
10622 				    ~SATA_EVNT_INPROC_DEVICE_RESET;
10623 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
10624 				    saddr->cport)->cport_mutex);
10625 				mutex_enter(&sata_hba_inst->satahba_mutex);
10626 				sata_hba_inst->satahba_event_flags |=
10627 				    SATA_EVNT_MAIN;
10628 				mutex_exit(&sata_hba_inst->satahba_mutex);
10629 				mutex_enter(&sata_mutex);
10630 				sata_event_pending |= SATA_EVNT_MAIN;
10631 				mutex_exit(&sata_mutex);
10632 				return;
10633 			}
10634 		} else {
10635 			/*
10636 			 * No point of retrying - some other event processing
10637 			 * would or already did port info cleanup.
10638 			 * To be safe (HBA may need it),
10639 			 * request clearing device reset condition.
10640 			 */
10641 			sdinfo->satadrv_event_flags = 0;
10642 			sdinfo->satadrv_event_flags |=
10643 			    SATA_EVNT_CLEAR_DEVICE_RESET;
10644 		}
10645 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10646 		    cport_mutex);
10647 		return;
10648 	}
10649 
10650 	/*
10651 	 * Raise the flag indicating that the next sata command could
10652 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
10653 	 * reset is reported.
10654 	 */
10655 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10656 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0 &&
10657 	    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10658 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10659 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
10660 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
10661 	}
10662 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10663 }
10664 
10665 
10666 /*
10667  * Port Link Events processing.
10668  * Every link established event may involve device reset (due to
10669  * COMRESET signal, equivalent of the hard reset) so arbitrarily
10670  * set device reset event for an attached device (if any).
10671  * If the port is in SHUTDOWN or FAILED state, ignore link events.
10672  *
10673  * The link established event processing varies, depending on the state
10674  * of the target node, HBA hotplugging capabilities, state of the port.
10675  * If the link is not active, the link established event is ignored.
10676  * If HBA cannot detect device attachment and there is no target node,
10677  * the link established event triggers device attach event processing.
10678  * Else, link established event triggers device reset event processing.
10679  *
10680  * The link lost event processing varies, depending on a HBA hotplugging
10681  * capability and the state of the port (link active or not active).
10682  * If the link is active, the lost link event is ignored.
10683  * If HBA cannot detect device removal, the lost link event triggers
10684  * device detached event processing after link lost timeout.
10685  * Else, the event is ignored.
10686  *
10687  * NOTE: Only cports are processed for now, i.e. no port multiplier ports
10688  */
10689 static void
10690 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
10691     sata_address_t *saddr)
10692 {
10693 	sata_device_t sata_device;
10694 	sata_cport_info_t *cportinfo;
10695 	sata_drive_info_t *sdinfo;
10696 	uint32_t event_flags;
10697 	int rval;
10698 
10699 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10700 	    "Processing port %d link event(s)", saddr->cport);
10701 
10702 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
10703 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10704 	event_flags = cportinfo->cport_event_flags;
10705 
10706 	/* Reset event flags first */
10707 	cportinfo->cport_event_flags &=
10708 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
10709 
10710 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
10711 	if ((cportinfo->cport_state &
10712 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
10713 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10714 		    cport_mutex);
10715 		return;
10716 	}
10717 
10718 	/*
10719 	 * For the sanity sake get current port state.
10720 	 * Set device address only. Other sata_device fields should be
10721 	 * set by HBA driver.
10722 	 */
10723 	sata_device.satadev_rev = SATA_DEVICE_REV;
10724 	sata_device.satadev_addr = *saddr;
10725 	/*
10726 	 * We have to exit mutex, because the HBA probe port function may
10727 	 * block on its own mutex.
10728 	 */
10729 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10730 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10731 	    (SATA_DIP(sata_hba_inst), &sata_device);
10732 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10733 	sata_update_port_info(sata_hba_inst, &sata_device);
10734 	if (rval != SATA_SUCCESS) {
10735 		/* Something went wrong? Fail the port */
10736 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10737 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10738 		    cport_mutex);
10739 		SATA_LOG_D((sata_hba_inst, CE_WARN, "Port %d probing failed",
10740 		    saddr->cport));
10741 		/*
10742 		 * We may want to release device info structure, but
10743 		 * it is not necessary.
10744 		 */
10745 		return;
10746 	} else {
10747 		/* port probed successfully */
10748 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
10749 	}
10750 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
10751 
10752 		if ((sata_device.satadev_scr.sstatus &
10753 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
10754 			/* Ignore event */
10755 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10756 			    "Ignoring port %d link established event - "
10757 			    "link down",
10758 			    saddr->cport);
10759 			goto linklost;
10760 		}
10761 
10762 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10763 		    "Processing port %d link established event",
10764 		    saddr->cport);
10765 
10766 		/*
10767 		 * For the sanity sake check if a device is attached - check
10768 		 * return state of a port probing.
10769 		 */
10770 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
10771 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
10772 			/*
10773 			 * HBA port probe indicated that there is a device
10774 			 * attached. Check if the framework had device info
10775 			 * structure attached for this device.
10776 			 */
10777 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
10778 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
10779 				    NULL);
10780 
10781 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10782 				if ((sdinfo->satadrv_type &
10783 				    SATA_VALID_DEV_TYPE) != 0) {
10784 					/*
10785 					 * Dev info structure is present.
10786 					 * If dev_type is set to known type in
10787 					 * the framework's drive info struct
10788 					 * then the device existed before and
10789 					 * the link was probably lost
10790 					 * momentarily - in such case
10791 					 * we may want to check device
10792 					 * identity.
10793 					 * Identity check is not supported now.
10794 					 *
10795 					 * Link established event
10796 					 * triggers device reset event.
10797 					 */
10798 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
10799 					    satadrv_event_flags |=
10800 					    SATA_EVNT_DEVICE_RESET;
10801 				}
10802 			} else if (cportinfo->cport_dev_type ==
10803 			    SATA_DTYPE_NONE) {
10804 				/*
10805 				 * We got new device attached! If HBA does not
10806 				 * generate device attached events, trigger it
10807 				 * here.
10808 				 */
10809 				if (!(SATA_FEATURES(sata_hba_inst) &
10810 				    SATA_CTLF_HOTPLUG)) {
10811 					cportinfo->cport_event_flags |=
10812 					    SATA_EVNT_DEVICE_ATTACHED;
10813 				}
10814 			}
10815 			/* Reset link lost timeout */
10816 			cportinfo->cport_link_lost_time = 0;
10817 		}
10818 	}
10819 linklost:
10820 	if (event_flags & SATA_EVNT_LINK_LOST) {
10821 		if ((sata_device.satadev_scr.sstatus &
10822 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
10823 			/* Ignore event */
10824 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10825 			    "Ignoring port %d link lost event - link is up",
10826 			    saddr->cport);
10827 			goto done;
10828 		}
10829 #ifdef SATA_DEBUG
10830 		if (cportinfo->cport_link_lost_time == 0) {
10831 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10832 			    "Processing port %d link lost event",
10833 			    saddr->cport);
10834 		}
10835 #endif
10836 		/*
10837 		 * When HBA cannot generate device attached/detached events,
10838 		 * we need to track link lost time and eventually generate
10839 		 * device detach event.
10840 		 */
10841 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
10842 			/* We are tracking link lost time */
10843 			if (cportinfo->cport_link_lost_time == 0) {
10844 				/* save current time (lbolt value) */
10845 				cportinfo->cport_link_lost_time =
10846 				    ddi_get_lbolt();
10847 				/* just keep link lost event */
10848 				cportinfo->cport_event_flags |=
10849 				    SATA_EVNT_LINK_LOST;
10850 			} else {
10851 				clock_t cur_time = ddi_get_lbolt();
10852 				if ((cur_time -
10853 				    cportinfo->cport_link_lost_time) >=
10854 				    drv_usectohz(
10855 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
10856 					/* trigger device detach event */
10857 					cportinfo->cport_event_flags |=
10858 					    SATA_EVNT_DEVICE_DETACHED;
10859 					cportinfo->cport_link_lost_time = 0;
10860 					SATADBG1(SATA_DBG_EVENTS,
10861 					    sata_hba_inst,
10862 					    "Triggering port %d "
10863 					    "device detached event",
10864 					    saddr->cport);
10865 				} else {
10866 					/* keep link lost event */
10867 					cportinfo->cport_event_flags |=
10868 					    SATA_EVNT_LINK_LOST;
10869 				}
10870 			}
10871 		}
10872 		/*
10873 		 * We could change port state to disable/delay access to
10874 		 * the attached device until the link is recovered.
10875 		 */
10876 	}
10877 done:
10878 	event_flags = cportinfo->cport_event_flags;
10879 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10880 	if (event_flags != 0) {
10881 		mutex_enter(&sata_hba_inst->satahba_mutex);
10882 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
10883 		mutex_exit(&sata_hba_inst->satahba_mutex);
10884 		mutex_enter(&sata_mutex);
10885 		sata_event_pending |= SATA_EVNT_MAIN;
10886 		mutex_exit(&sata_mutex);
10887 	}
10888 }
10889 
10890 /*
10891  * Device Detached Event processing.
10892  * Port is probed to find if a device is really gone. If so,
10893  * the device info structure is detached from the SATA port info structure
10894  * and released.
10895  * Port status is updated.
10896  *
10897  * NOTE: Process cports event only, no port multiplier ports.
10898  */
10899 static void
10900 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
10901     sata_address_t *saddr)
10902 {
10903 	sata_cport_info_t *cportinfo;
10904 	sata_drive_info_t *sdevinfo;
10905 	sata_device_t sata_device;
10906 	dev_info_t *tdip;
10907 	int rval;
10908 
10909 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10910 	    "Processing port %d device detached", saddr->cport);
10911 
10912 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
10913 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10914 	/* Clear event flag */
10915 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
10916 
10917 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
10918 	if ((cportinfo->cport_state &
10919 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
10920 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10921 		    cport_mutex);
10922 		return;
10923 	}
10924 	/* For sanity, re-probe the port */
10925 	sata_device.satadev_rev = SATA_DEVICE_REV;
10926 	sata_device.satadev_addr = *saddr;
10927 
10928 	/*
10929 	 * We have to exit mutex, because the HBA probe port function may
10930 	 * block on its own mutex.
10931 	 */
10932 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10933 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10934 	    (SATA_DIP(sata_hba_inst), &sata_device);
10935 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10936 	sata_update_port_info(sata_hba_inst, &sata_device);
10937 	if (rval != SATA_SUCCESS) {
10938 		/* Something went wrong? Fail the port */
10939 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10940 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10941 		    cport_mutex);
10942 		SATA_LOG_D((sata_hba_inst, CE_WARN, "Port %d probing failed",
10943 		    saddr->cport));
10944 		/*
10945 		 * We may want to release device info structure, but
10946 		 * it is not necessary.
10947 		 */
10948 		return;
10949 	} else {
10950 		/* port probed successfully */
10951 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
10952 	}
10953 	/*
10954 	 * Check if a device is still attached. For sanity, check also
10955 	 * link status - if no link, there is no device.
10956 	 */
10957 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
10958 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
10959 	    SATA_DTYPE_NONE) {
10960 		/*
10961 		 * Device is still attached - ignore detach event.
10962 		 */
10963 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10964 		    cport_mutex);
10965 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10966 		    "Ignoring detach - device still attached to port %d",
10967 		    sata_device.satadev_addr.cport);
10968 		return;
10969 	}
10970 	/*
10971 	 * We need to detach and release device info structure here
10972 	 */
10973 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10974 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10975 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10976 		(void) kmem_free((void *)sdevinfo,
10977 		    sizeof (sata_drive_info_t));
10978 	}
10979 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10980 	/*
10981 	 * Device cannot be reached anymore, even if the target node may be
10982 	 * still present.
10983 	 */
10984 
10985 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10986 	sata_log(sata_hba_inst, CE_WARN, "SATA device detached at port %d",
10987 	    sata_device.satadev_addr.cport);
10988 
10989 	/*
10990 	 * Try to offline a device and remove target node if it still exists
10991 	 */
10992 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport);
10993 	if (tdip != NULL) {
10994 		/*
10995 		 * target node exist - unconfigure device first, then remove
10996 		 * the node
10997 		 */
10998 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
10999 			/*
11000 			 * PROBLEM - no device, but target node remained
11001 			 * This happens when the file was open or node was
11002 			 * waiting for resources.
11003 			 */
11004 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11005 			    "sata_process_device_detached: "
11006 			    "Failed to unconfigure removed device."));
11007 		}
11008 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11009 			/*
11010 			 * PROBLEM - no device, but target node remained
11011 			 * This happens when the file was open or node was
11012 			 * waiting for resources.
11013 			 */
11014 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11015 			    "sata_process_device_detached: "
11016 			    "Failed to remove target node for "
11017 			    "removed device."));
11018 		}
11019 	}
11020 	/*
11021 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11022 	 * with the hint: SE_HINT_REMOVE
11023 	 */
11024 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
11025 }
11026 
11027 
11028 /*
11029  * Device Attached Event processing.
11030  * Port state is checked to verify that a device is really attached. If so,
11031  * the device info structure is created and attached to the SATA port info
11032  * structure.
11033  *
11034  * If attached device cannot be identified or set-up, the retry for the
11035  * attach processing is set-up. Subsequent daemon run would try again to
11036  * identify the device, until the time limit is reached
11037  * (SATA_DEV_IDENTIFY_TIMEOUT).
11038  *
11039  * This function cannot be called in interrupt context (it may sleep).
11040  *
11041  * NOTE: Process cports event only, no port multiplier ports.
11042  */
11043 static void
11044 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
11045     sata_address_t *saddr)
11046 {
11047 	sata_cport_info_t *cportinfo;
11048 	sata_drive_info_t *sdevinfo;
11049 	sata_device_t sata_device;
11050 	dev_info_t *tdip;
11051 	uint32_t event_flags;
11052 	int rval;
11053 
11054 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
11055 	    "Processing port %d device attached", saddr->cport);
11056 
11057 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
11058 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
11059 
11060 	/* Clear event flag first */
11061 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
11062 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
11063 	if ((cportinfo->cport_state &
11064 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
11065 		cportinfo->cport_dev_attach_time = 0;
11066 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
11067 		    cport_mutex);
11068 		return;
11069 	}
11070 
11071 	/*
11072 	 * If the sata_drive_info structure is found attached to the port info,
11073 	 * something went wrong in the event reporting and processing sequence.
11074 	 * To recover, arbitrarily release device info structure and issue
11075 	 * a warning.
11076 	 */
11077 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
11078 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11079 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11080 		(void) kmem_free((void *)sdevinfo,
11081 		    sizeof (sata_drive_info_t));
11082 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
11083 		    "Arbitrarily detaching old device info.", NULL);
11084 	}
11085 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11086 
11087 	/* For sanity, re-probe the port */
11088 	sata_device.satadev_rev = SATA_DEVICE_REV;
11089 	sata_device.satadev_addr = *saddr;
11090 
11091 	/*
11092 	 * We have to exit mutex, because the HBA probe port function may
11093 	 * block on its own mutex.
11094 	 */
11095 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
11096 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11097 	    (SATA_DIP(sata_hba_inst), &sata_device);
11098 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
11099 	sata_update_port_info(sata_hba_inst, &sata_device);
11100 	if (rval != SATA_SUCCESS) {
11101 		/* Something went wrong? Fail the port */
11102 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11103 		cportinfo->cport_dev_attach_time = 0;
11104 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
11105 		    cport_mutex);
11106 		SATA_LOG_D((sata_hba_inst, CE_WARN, "Port %d probing failed",
11107 		    saddr->cport));
11108 		return;
11109 	} else {
11110 		/* port probed successfully */
11111 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
11112 	}
11113 	/*
11114 	 * Check if a device is still attached. For sanity, check also
11115 	 * link status - if no link, there is no device.
11116 	 */
11117 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11118 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
11119 	    SATA_DTYPE_NONE) {
11120 		/*
11121 		 * No device - ignore attach event.
11122 		 */
11123 		cportinfo->cport_dev_attach_time = 0;
11124 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
11125 		    cport_mutex);
11126 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
11127 		    "Ignoring attach - no device connected to port %d",
11128 		    sata_device.satadev_addr.cport);
11129 		return;
11130 	}
11131 
11132 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
11133 	/*
11134 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11135 	 * with the hint: SE_HINT_INSERT
11136 	 */
11137 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
11138 
11139 	/*
11140 	 * Make sure that there is no target node for that device.
11141 	 * If so, release it. It should not happen, unless we had problem
11142 	 * removing the node when device was detached.
11143 	 */
11144 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport);
11145 	if (tdip != NULL) {
11146 
11147 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11148 		    "sata_process_device_attached: "
11149 		    "old device target node exists!!!"));
11150 		/*
11151 		 * target node exist - unconfigure device first, then remove
11152 		 * the node
11153 		 */
11154 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
11155 			/*
11156 			 * PROBLEM - no device, but target node remained
11157 			 * This happens when the file was open or node was
11158 			 * waiting for resources.
11159 			 */
11160 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11161 			    "sata_process_device_attached: "
11162 			    "Failed to unconfigure old target node!"));
11163 		}
11164 		/* Following call will retry node offlining and removing it */
11165 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11166 			/* PROBLEM - no device, but target node remained */
11167 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11168 			    "sata_process_device_attached: "
11169 			    "Failed to remove old target node!"));
11170 			/*
11171 			 * It is not clear, what should be done here.
11172 			 * For now, we will not attach a new device
11173 			 */
11174 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11175 			    saddr->cport)->cport_mutex);
11176 			cportinfo->cport_dev_attach_time = 0;
11177 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
11178 			    saddr->cport)->cport_mutex);
11179 			return;
11180 		}
11181 	}
11182 
11183 	/*
11184 	 * Port reprobing will take care of the creation of the device info
11185 	 * structure and determination of the device type.
11186 	 */
11187 	sata_device.satadev_addr = *saddr;
11188 	rval = sata_reprobe_port(sata_hba_inst, &sata_device,
11189 	    SATA_DEV_IDENTIFY_NORETRY);
11190 
11191 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
11192 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
11193 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
11194 		/* Some device is attached to the port */
11195 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
11196 			/*
11197 			 * A device was not successfully attached.
11198 			 * Track retry time for device identification.
11199 			 */
11200 			if (cportinfo->cport_dev_attach_time != 0) {
11201 				clock_t cur_time = ddi_get_lbolt();
11202 				/*
11203 				 * If the retry time limit was not exceeded,
11204 				 * reinstate attach event.
11205 				 */
11206 				if ((cur_time -
11207 				    cportinfo->cport_dev_attach_time) <
11208 				    drv_usectohz(
11209 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
11210 					/* OK, restore attach event */
11211 					cportinfo->cport_event_flags |=
11212 					    SATA_EVNT_DEVICE_ATTACHED;
11213 				} else {
11214 					/* Timeout - cannot identify device */
11215 					cportinfo->cport_dev_attach_time = 0;
11216 				}
11217 			} else {
11218 				/*
11219 				 * Start tracking time for dev identification.
11220 				 * save current time (lbolt value).
11221 				 */
11222 				cportinfo->cport_dev_attach_time =
11223 				    ddi_get_lbolt();
11224 				/* Restore attach event */
11225 				cportinfo->cport_event_flags |=
11226 				    SATA_EVNT_DEVICE_ATTACHED;
11227 			}
11228 		} else {
11229 			/*
11230 			 * If device was successfully attached, an explicit
11231 			 * 'configure' command will be needed to configure it.
11232 			 */
11233 			cportinfo->cport_dev_attach_time = 0;
11234 			sata_log(sata_hba_inst, CE_WARN,
11235 			    "SATA device attached at port %d", saddr->cport);
11236 
11237 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
11238 				sata_drive_info_t new_sdinfo;
11239 
11240 				/* Log device info data */
11241 				new_sdinfo =
11242 				    *(SATA_CPORTINFO_DRV_INFO(cportinfo));
11243 				sata_show_drive_info(sata_hba_inst,
11244 				    &new_sdinfo);
11245 			}
11246 		}
11247 	} else {
11248 		cportinfo->cport_dev_attach_time = 0;
11249 	}
11250 	event_flags = cportinfo->cport_event_flags;
11251 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
11252 	if (event_flags != 0) {
11253 		mutex_enter(&sata_hba_inst->satahba_mutex);
11254 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
11255 		mutex_exit(&sata_hba_inst->satahba_mutex);
11256 		mutex_enter(&sata_mutex);
11257 		sata_event_pending |= SATA_EVNT_MAIN;
11258 		mutex_exit(&sata_mutex);
11259 	}
11260 }
11261 
11262 
11263 /*
11264  * sata_set_drive_features function compares current device features setting
11265  * with the saved device features settings and, if there is a difference,
11266  * it restores device features setting to the previously saved state.
11267  * Device Identify data has to be current.
11268  * At the moment only read ahead and write cache settings are considered.
11269  *
11270  * This function cannot be called in the interrupt context (it may sleep).
11271  *
11272  * The input argument sdinfo should point to the drive info structure
11273  * to be updated after features are set.
11274  *
11275  * Returns TRUE if successful or there was nothing to do.
11276  * Returns FALSE if device features could not be set .
11277  *
11278  * Note: This function may fail the port, making it inaccessible.
11279  * Explicit port disconnect/connect or physical device
11280  * detach/attach is required to re-evaluate it's state afterwards
11281  */
11282 
11283 static int
11284 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
11285     sata_drive_info_t *sdinfo, int restore)
11286 {
11287 	int rval = SATA_SUCCESS;
11288 	sata_drive_info_t new_sdinfo;
11289 	char *finfo = "sata_set_drive_features: cannot";
11290 	char *finfox;
11291 	int cache_op;
11292 
11293 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
11294 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
11295 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
11296 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
11297 		/*
11298 		 * Cannot get device identification - retry later
11299 		 */
11300 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11301 		    "%s fetch device identify data\n", finfo));
11302 		return (SATA_FAILURE);
11303 	}
11304 	/* Arbitrarily set UDMA mode */
11305 	if (sata_set_udma_mode(sata_hba_inst, &new_sdinfo) != SATA_SUCCESS) {
11306 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11307 		    "%s set UDMA mode\n", finfo));
11308 		return (SATA_FAILURE);
11309 	}
11310 
11311 	if (!(new_sdinfo.satadrv_id.ai_cmdset82 & SATA_LOOK_AHEAD) &&
11312 	    !(new_sdinfo.satadrv_id.ai_cmdset82 & SATA_WRITE_CACHE)) {
11313 		/* None of the features is supported - do nothing */
11314 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
11315 		    "settable features not supported\n", NULL);
11316 		return (SATA_SUCCESS);
11317 	}
11318 
11319 	if (((new_sdinfo.satadrv_id.ai_features85 & SATA_LOOK_AHEAD) &&
11320 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
11321 	    ((new_sdinfo.satadrv_id.ai_features85 & SATA_WRITE_CACHE) &&
11322 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
11323 		/* Nothing to do */
11324 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
11325 		    "no device features to set\n", NULL);
11326 		return (SATA_SUCCESS);
11327 	}
11328 
11329 	finfox = (restore != 0) ? " restore device features" :
11330 	    " initialize device features\n";
11331 
11332 	if (!((new_sdinfo.satadrv_id.ai_features85 & SATA_LOOK_AHEAD) &&
11333 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD))) {
11334 		if (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) {
11335 			/* Enable read ahead / read cache */
11336 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
11337 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
11338 			    "enabling read cache\n", NULL);
11339 		} else {
11340 			/* Disable read ahead  / read cache */
11341 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
11342 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
11343 			    "disabling read cache\n", NULL);
11344 		}
11345 
11346 		/* Try to set read cache mode */
11347 		if (sata_set_cache_mode(sata_hba_inst, &new_sdinfo,
11348 		    cache_op) != SATA_SUCCESS) {
11349 			/* Pkt execution failed */
11350 			rval = SATA_FAILURE;
11351 		}
11352 	}
11353 
11354 	if (!((new_sdinfo.satadrv_id.ai_features85 & SATA_WRITE_CACHE) &&
11355 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
11356 		if (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) {
11357 			/* Enable write cache */
11358 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
11359 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
11360 			    "enabling write cache\n", NULL);
11361 		} else {
11362 			/* Disable write cache */
11363 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
11364 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
11365 			    "disabling write cache\n", NULL);
11366 		}
11367 		/* Try to set write cache mode */
11368 		if (sata_set_cache_mode(sata_hba_inst, &new_sdinfo,
11369 		    cache_op) != SATA_SUCCESS) {
11370 			/* Pkt execution failed */
11371 			rval = SATA_FAILURE;
11372 		}
11373 	}
11374 
11375 	if (rval == SATA_FAILURE)
11376 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11377 		    "%s %s", finfo, finfox));
11378 
11379 	/*
11380 	 * We need to fetch Device Identify data again
11381 	 */
11382 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
11383 		/*
11384 		 * Cannot get device identification - retry later
11385 		 */
11386 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11387 		    "%s cannot re-fetch device identify data\n"));
11388 		rval = SATA_FAILURE;
11389 	}
11390 	/* Copy device sata info. */
11391 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
11392 
11393 	return (rval);
11394 }
11395 
11396 
11397 /*
11398  *
11399  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
11400  * unable to determine.
11401  *
11402  * Cannot be called in an interrupt context.
11403  *
11404  * Called by sata_build_lsense_page_2f()
11405  */
11406 
11407 static int
11408 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
11409     sata_drive_info_t *sdinfo)
11410 {
11411 	sata_pkt_t *spkt;
11412 	sata_cmd_t *scmd;
11413 	sata_pkt_txlate_t *spx;
11414 	int rval;
11415 
11416 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
11417 	spx->txlt_sata_hba_inst = sata_hba_inst;
11418 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
11419 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
11420 	if (spkt == NULL) {
11421 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11422 		return (-1);
11423 	}
11424 	/* address is needed now */
11425 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11426 
11427 
11428 	/* Fill sata_pkt */
11429 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11430 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
11431 	/* Synchronous mode, no callback */
11432 	spkt->satapkt_comp = NULL;
11433 	/* Timeout 30s */
11434 	spkt->satapkt_time = sata_default_pkt_time;
11435 
11436 	scmd = &spkt->satapkt_cmd;
11437 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
11438 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
11439 
11440 	/* Set up which registers need to be returned */
11441 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
11442 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
11443 
11444 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
11445 	scmd->satacmd_addr_type = 0;		/* N/A */
11446 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
11447 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
11448 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
11449 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
11450 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
11451 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
11452 	scmd->satacmd_cmd_reg = SATAC_SMART;
11453 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11454 	    sdinfo->satadrv_addr.cport)));
11455 
11456 
11457 	/* Send pkt to SATA HBA driver */
11458 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
11459 	    SATA_TRAN_ACCEPTED ||
11460 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
11461 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11462 		    sdinfo->satadrv_addr.cport)));
11463 		/*
11464 		 * Whoops, no SMART RETURN STATUS
11465 		 */
11466 		rval = -1;
11467 	} else {
11468 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11469 		    sdinfo->satadrv_addr.cport)));
11470 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
11471 			rval = -1;
11472 			goto fail;
11473 		}
11474 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
11475 			rval = -1;
11476 			goto fail;
11477 		}
11478 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
11479 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
11480 			rval = 0;
11481 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
11482 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
11483 			rval = 1;
11484 		else {
11485 			rval = -1;
11486 			goto fail;
11487 		}
11488 	}
11489 fail:
11490 	/* Free allocated resources */
11491 	sata_pkt_free(spx);
11492 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
11493 
11494 	return (rval);
11495 }
11496 
11497 /*
11498  *
11499  * Returns 0 if succeeded, -1 otherwise
11500  *
11501  * Cannot be called in an interrupt context.
11502  *
11503  */
11504 static int
11505 sata_fetch_smart_data(
11506 	sata_hba_inst_t *sata_hba_inst,
11507 	sata_drive_info_t *sdinfo,
11508 	struct smart_data *smart_data)
11509 {
11510 	sata_pkt_t *spkt;
11511 	sata_cmd_t *scmd;
11512 	sata_pkt_txlate_t *spx;
11513 	int rval;
11514 
11515 #if ! defined(lint)
11516 	ASSERT(sizeof (struct smart_data) == 512);
11517 #endif
11518 
11519 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
11520 	spx->txlt_sata_hba_inst = sata_hba_inst;
11521 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
11522 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
11523 	if (spkt == NULL) {
11524 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11525 		return (-1);
11526 	}
11527 	/* address is needed now */
11528 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11529 
11530 
11531 	/* Fill sata_pkt */
11532 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11533 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
11534 	/* Synchronous mode, no callback */
11535 	spkt->satapkt_comp = NULL;
11536 	/* Timeout 30s */
11537 	spkt->satapkt_time = sata_default_pkt_time;
11538 
11539 	scmd = &spkt->satapkt_cmd;
11540 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
11541 
11542 	/*
11543 	 * Allocate buffer for SMART data
11544 	 */
11545 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
11546 	    sizeof (struct smart_data));
11547 	if (scmd->satacmd_bp == NULL) {
11548 		sata_pkt_free(spx);
11549 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11550 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11551 		    "sata_fetch_smart_data: "
11552 		    "cannot allocate buffer"));
11553 		return (-1);
11554 	}
11555 
11556 
11557 	/* Build SMART_READ_DATA cmd in the sata_pkt */
11558 	scmd->satacmd_addr_type = 0;		/* N/A */
11559 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
11560 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
11561 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
11562 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
11563 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
11564 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
11565 	scmd->satacmd_cmd_reg = SATAC_SMART;
11566 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11567 	    sdinfo->satadrv_addr.cport)));
11568 
11569 	/* Send pkt to SATA HBA driver */
11570 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
11571 	    SATA_TRAN_ACCEPTED ||
11572 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
11573 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11574 		    sdinfo->satadrv_addr.cport)));
11575 		/*
11576 		 * Whoops, no SMART DATA available
11577 		 */
11578 		rval = -1;
11579 		goto fail;
11580 	} else {
11581 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11582 		    sdinfo->satadrv_addr.cport)));
11583 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
11584 			DDI_DMA_SYNC_FORKERNEL);
11585 		ASSERT(rval == DDI_SUCCESS);
11586 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
11587 		    sizeof (struct smart_data));
11588 	}
11589 
11590 fail:
11591 	/* Free allocated resources */
11592 	sata_free_local_buffer(spx);
11593 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
11594 	sata_pkt_free(spx);
11595 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
11596 
11597 	return (rval);
11598 }
11599 
11600 /*
11601  * Used by LOG SENSE page 0x10
11602  *
11603  * return 0 for success, -1 otherwise
11604  *
11605  */
11606 static int
11607 sata_ext_smart_selftest_read_log(
11608 	sata_hba_inst_t *sata_hba_inst,
11609 	sata_drive_info_t *sdinfo,
11610 	struct smart_ext_selftest_log *ext_selftest_log,
11611 	uint16_t block_num)
11612 {
11613 	sata_pkt_txlate_t *spx;
11614 	sata_pkt_t *spkt;
11615 	sata_cmd_t *scmd;
11616 	int rval;
11617 
11618 #if ! defined(lint)
11619 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
11620 #endif
11621 
11622 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
11623 	spx->txlt_sata_hba_inst = sata_hba_inst;
11624 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
11625 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
11626 	if (spkt == NULL) {
11627 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11628 		return (-1);
11629 	}
11630 	/* address is needed now */
11631 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11632 
11633 
11634 	/* Fill sata_pkt */
11635 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11636 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
11637 	/* Synchronous mode, no callback */
11638 	spkt->satapkt_comp = NULL;
11639 	/* Timeout 30s */
11640 	spkt->satapkt_time = sata_default_pkt_time;
11641 
11642 	scmd = &spkt->satapkt_cmd;
11643 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
11644 
11645 	/*
11646 	 * Allocate buffer for SMART extended self-test log
11647 	 */
11648 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
11649 	    sizeof (struct smart_ext_selftest_log));
11650 	if (scmd->satacmd_bp == NULL) {
11651 		sata_pkt_free(spx);
11652 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11653 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11654 		    "sata_ext_smart_selftest_log: "
11655 		    "cannot allocate buffer"));
11656 		return (-1);
11657 	}
11658 
11659 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
11660 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
11661 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
11662 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
11663 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
11664 	scmd->satacmd_lba_low_msb = 0;
11665 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
11666 	scmd->satacmd_lba_mid_msb = block_num >> 8;
11667 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
11668 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
11669 
11670 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11671 	    sdinfo->satadrv_addr.cport)));
11672 
11673 	/* Send pkt to SATA HBA driver */
11674 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
11675 	    SATA_TRAN_ACCEPTED ||
11676 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
11677 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11678 		    sdinfo->satadrv_addr.cport)));
11679 
11680 		/*
11681 		 * Whoops, no SMART selftest log info available
11682 		 */
11683 		rval = -1;
11684 		goto fail;
11685 	} else {
11686 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11687 		    sdinfo->satadrv_addr.cport)));
11688 
11689 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
11690 			DDI_DMA_SYNC_FORKERNEL);
11691 		ASSERT(rval == DDI_SUCCESS);
11692 		bcopy(scmd->satacmd_bp->b_un.b_addr,
11693 		    (uint8_t *)ext_selftest_log,
11694 		    sizeof (struct smart_ext_selftest_log));
11695 		rval = 0;
11696 	}
11697 
11698 fail:
11699 	/* Free allocated resources */
11700 	sata_free_local_buffer(spx);
11701 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
11702 	sata_pkt_free(spx);
11703 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
11704 
11705 	return (rval);
11706 }
11707 
11708 /*
11709  * Returns 0 for success, -1 otherwise
11710  *
11711  * SMART self-test log data is returned in buffer pointed to by selftest_log
11712  */
11713 static int
11714 sata_smart_selftest_log(
11715 	sata_hba_inst_t *sata_hba_inst,
11716 	sata_drive_info_t *sdinfo,
11717 	struct smart_selftest_log *selftest_log)
11718 {
11719 	sata_pkt_t *spkt;
11720 	sata_cmd_t *scmd;
11721 	sata_pkt_txlate_t *spx;
11722 	int rval;
11723 
11724 #if ! defined(lint)
11725 	ASSERT(sizeof (struct smart_selftest_log) == 512);
11726 #endif
11727 
11728 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
11729 	spx->txlt_sata_hba_inst = sata_hba_inst;
11730 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
11731 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
11732 	if (spkt == NULL) {
11733 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11734 		return (-1);
11735 	}
11736 	/* address is needed now */
11737 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11738 
11739 
11740 	/* Fill sata_pkt */
11741 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11742 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
11743 	/* Synchronous mode, no callback */
11744 	spkt->satapkt_comp = NULL;
11745 	/* Timeout 30s */
11746 	spkt->satapkt_time = sata_default_pkt_time;
11747 
11748 	scmd = &spkt->satapkt_cmd;
11749 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
11750 
11751 	/*
11752 	 * Allocate buffer for SMART SELFTEST LOG
11753 	 */
11754 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
11755 	    sizeof (struct smart_selftest_log));
11756 	if (scmd->satacmd_bp == NULL) {
11757 		sata_pkt_free(spx);
11758 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11759 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11760 		    "sata_smart_selftest_log: "
11761 		    "cannot allocate buffer"));
11762 		return (-1);
11763 	}
11764 
11765 	/* Build SMART_READ_LOG cmd in the sata_pkt */
11766 	scmd->satacmd_addr_type = 0;		/* N/A */
11767 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
11768 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
11769 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
11770 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
11771 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
11772 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
11773 	scmd->satacmd_cmd_reg = SATAC_SMART;
11774 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11775 	    sdinfo->satadrv_addr.cport)));
11776 
11777 	/* Send pkt to SATA HBA driver */
11778 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
11779 	    SATA_TRAN_ACCEPTED ||
11780 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
11781 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11782 		    sdinfo->satadrv_addr.cport)));
11783 		/*
11784 		 * Whoops, no SMART DATA available
11785 		 */
11786 		rval = -1;
11787 		goto fail;
11788 	} else {
11789 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11790 		    sdinfo->satadrv_addr.cport)));
11791 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
11792 			DDI_DMA_SYNC_FORKERNEL);
11793 		ASSERT(rval == DDI_SUCCESS);
11794 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
11795 		    sizeof (struct smart_selftest_log));
11796 		rval = 0;
11797 	}
11798 
11799 fail:
11800 	/* Free allocated resources */
11801 	sata_free_local_buffer(spx);
11802 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
11803 	sata_pkt_free(spx);
11804 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
11805 
11806 	return (rval);
11807 }
11808 
11809 
11810 /*
11811  * Returns 0 for success, -1 otherwise
11812  *
11813  * SMART READ LOG data is returned in buffer pointed to by smart_log
11814  */
11815 static int
11816 sata_smart_read_log(
11817 	sata_hba_inst_t *sata_hba_inst,
11818 	sata_drive_info_t *sdinfo,
11819 	uint8_t *smart_log,		/* where the data should be returned */
11820 	uint8_t which_log,		/* which log should be returned */
11821 	uint8_t log_size)		/* # of 512 bytes in log */
11822 {
11823 	sata_pkt_t *spkt;
11824 	sata_cmd_t *scmd;
11825 	sata_pkt_txlate_t *spx;
11826 	int rval;
11827 
11828 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
11829 	spx->txlt_sata_hba_inst = sata_hba_inst;
11830 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
11831 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
11832 	if (spkt == NULL) {
11833 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11834 		return (-1);
11835 	}
11836 	/* address is needed now */
11837 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11838 
11839 
11840 	/* Fill sata_pkt */
11841 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11842 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
11843 	/* Synchronous mode, no callback */
11844 	spkt->satapkt_comp = NULL;
11845 	/* Timeout 30s */
11846 	spkt->satapkt_time = sata_default_pkt_time;
11847 
11848 	scmd = &spkt->satapkt_cmd;
11849 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
11850 
11851 	/*
11852 	 * Allocate buffer for SMART READ LOG
11853 	 */
11854 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
11855 	if (scmd->satacmd_bp == NULL) {
11856 		sata_pkt_free(spx);
11857 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11858 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11859 		    "sata_smart_read_log: " "cannot allocate buffer"));
11860 		return (-1);
11861 	}
11862 
11863 	/* Build SMART_READ_LOG cmd in the sata_pkt */
11864 	scmd->satacmd_addr_type = 0;		/* N/A */
11865 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
11866 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
11867 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
11868 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
11869 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
11870 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
11871 	scmd->satacmd_cmd_reg = SATAC_SMART;
11872 
11873 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11874 	    sdinfo->satadrv_addr.cport)));
11875 
11876 	/* Send pkt to SATA HBA driver */
11877 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
11878 	    SATA_TRAN_ACCEPTED ||
11879 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
11880 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11881 		    sdinfo->satadrv_addr.cport)));
11882 
11883 		/*
11884 		 * Whoops, no SMART DATA available
11885 		 */
11886 		rval = -1;
11887 		goto fail;
11888 	} else {
11889 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11890 		    sdinfo->satadrv_addr.cport)));
11891 
11892 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
11893 			DDI_DMA_SYNC_FORKERNEL);
11894 		ASSERT(rval == DDI_SUCCESS);
11895 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
11896 		rval = 0;
11897 	}
11898 
11899 fail:
11900 	/* Free allocated resources */
11901 	sata_free_local_buffer(spx);
11902 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
11903 	sata_pkt_free(spx);
11904 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
11905 
11906 	return (rval);
11907 }
11908 
11909 /*
11910  * Used by LOG SENSE page 0x10
11911  *
11912  * return 0 for success, -1 otherwise
11913  *
11914  */
11915 static int
11916 sata_read_log_ext_directory(
11917 	sata_hba_inst_t *sata_hba_inst,
11918 	sata_drive_info_t *sdinfo,
11919 	struct read_log_ext_directory *logdir)
11920 {
11921 	sata_pkt_txlate_t *spx;
11922 	sata_pkt_t *spkt;
11923 	sata_cmd_t *scmd;
11924 	int rval;
11925 
11926 #if ! defined(lint)
11927 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
11928 #endif
11929 
11930 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
11931 	spx->txlt_sata_hba_inst = sata_hba_inst;
11932 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
11933 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
11934 	if (spkt == NULL) {
11935 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11936 		return (-1);
11937 	}
11938 
11939 	/* Fill sata_pkt */
11940 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11941 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
11942 	/* Synchronous mode, no callback */
11943 	spkt->satapkt_comp = NULL;
11944 	/* Timeout 30s */
11945 	spkt->satapkt_time = sata_default_pkt_time;
11946 
11947 	scmd = &spkt->satapkt_cmd;
11948 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
11949 
11950 	/*
11951 	 * Allocate buffer for SMART READ LOG EXTENDED command
11952 	 */
11953 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
11954 	    sizeof (struct read_log_ext_directory));
11955 	if (scmd->satacmd_bp == NULL) {
11956 		sata_pkt_free(spx);
11957 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11958 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11959 		    "sata_read_log_ext_directory: "
11960 		    "cannot allocate buffer"));
11961 		return (-1);
11962 	}
11963 
11964 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
11965 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
11966 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
11967 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
11968 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
11969 	scmd->satacmd_lba_low_msb = 0;
11970 	scmd->satacmd_lba_mid_lsb = 0;
11971 	scmd->satacmd_lba_mid_msb = 0;
11972 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
11973 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
11974 
11975 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11976 	    sdinfo->satadrv_addr.cport)));
11977 
11978 	/* Send pkt to SATA HBA driver */
11979 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
11980 	    SATA_TRAN_ACCEPTED ||
11981 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
11982 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11983 		    sdinfo->satadrv_addr.cport)));
11984 		/*
11985 		 * Whoops, no SMART selftest log info available
11986 		 */
11987 		rval = -1;
11988 		goto fail;
11989 	} else {
11990 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11991 		    sdinfo->satadrv_addr.cport)));
11992 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
11993 			DDI_DMA_SYNC_FORKERNEL);
11994 		ASSERT(rval == DDI_SUCCESS);
11995 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
11996 		    sizeof (struct read_log_ext_directory));
11997 		rval = 0;
11998 	}
11999 
12000 fail:
12001 	/* Free allocated resources */
12002 	sata_free_local_buffer(spx);
12003 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12004 	sata_pkt_free(spx);
12005 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
12006 
12007 	return (rval);
12008 }
12009 
12010 static void
12011 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
12012     int hint)
12013 {
12014 	char ap[MAXPATHLEN];
12015 	nvlist_t *ev_attr_list = NULL;
12016 	int err;
12017 
12018 	/* Allocate and build sysevent attribute list */
12019 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
12020 	if (err != 0) {
12021 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12022 		    "sata_gen_sysevent: "
12023 		    "cannot allocate memory for sysevent attributes\n"));
12024 		return;
12025 	}
12026 	/* Add hint attribute */
12027 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
12028 	if (err != 0) {
12029 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12030 		    "sata_gen_sysevent: "
12031 		    "failed to add DR_HINT attr for sysevent"));
12032 		nvlist_free(ev_attr_list);
12033 		return;
12034 	}
12035 	/*
12036 	 * Add AP attribute.
12037 	 * Get controller pathname and convert it into AP pathname by adding
12038 	 * a target number.
12039 	 */
12040 	(void) snprintf(ap, MAXPATHLEN, "/devices");
12041 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
12042 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
12043 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
12044 
12045 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
12046 	if (err != 0) {
12047 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12048 		    "sata_gen_sysevent: "
12049 		    "failed to add DR_AP_ID attr for sysevent"));
12050 		nvlist_free(ev_attr_list);
12051 		return;
12052 	}
12053 
12054 	/* Generate/log sysevent */
12055 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
12056 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
12057 	if (err != DDI_SUCCESS) {
12058 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12059 		    "sata_gen_sysevent: "
12060 		    "cannot log sysevent, err code %x\n", err));
12061 	}
12062 
12063 	nvlist_free(ev_attr_list);
12064 }
12065 
12066 /*
12067  * sata_xlate_errors() is used to translate (S)ATA error
12068  * information to SCSI information returned in the SCSI
12069  * packet.
12070  */
12071 static void
12072 sata_xlate_errors(sata_pkt_txlate_t *spx)
12073 {
12074 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
12075 	struct scsi_extended_sense *sense;
12076 
12077 	scsipkt->pkt_reason = CMD_INCOMPLETE;
12078 	*scsipkt->pkt_scbp = STATUS_CHECK;
12079 	sense = sata_arq_sense(spx);
12080 
12081 	switch (spx->txlt_sata_pkt->satapkt_reason) {
12082 	case SATA_PKT_PORT_ERROR:
12083 		/*
12084 		 * We have no device data. Assume no data transfered.
12085 		 */
12086 		sense->es_key = KEY_HARDWARE_ERROR;
12087 		break;
12088 
12089 	case SATA_PKT_DEV_ERROR:
12090 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
12091 		    SATA_STATUS_ERR) {
12092 			/*
12093 			 * determine dev error reason from error
12094 			 * reg content
12095 			 */
12096 			sata_decode_device_error(spx, sense);
12097 			break;
12098 		}
12099 		/* No extended sense key - no info available */
12100 		break;
12101 
12102 	case SATA_PKT_TIMEOUT:
12103 		/*
12104 		 * scsipkt->pkt_reason = CMD_TIMEOUT; This causes problems.
12105 		 */
12106 		scsipkt->pkt_reason = CMD_INCOMPLETE;
12107 		/* No extended sense key */
12108 		break;
12109 
12110 	case SATA_PKT_ABORTED:
12111 		scsipkt->pkt_reason = CMD_ABORTED;
12112 		/* No extended sense key */
12113 		break;
12114 
12115 	case SATA_PKT_RESET:
12116 		/*
12117 		 * pkt aborted either by an explicit reset request from
12118 		 * a host, or due to error recovery
12119 		 */
12120 		scsipkt->pkt_reason = CMD_RESET;
12121 		break;
12122 
12123 	default:
12124 		scsipkt->pkt_reason = CMD_TRAN_ERR;
12125 		break;
12126 	}
12127 }
12128