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