xref: /titanic_41/usr/src/uts/common/io/sata/impl/sata.c (revision 774ef820abb3ffe8f38adcc17dee852d45d871a0)
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 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2659 		sata_pkt_free(spx);
2660 		/*
2661 		 * If a DMA allocation request fails with
2662 		 * DDI_DMA_NOMAPPING, indicate the error by calling
2663 		 * bioerror(9F) with bp and an error code of EFAULT.
2664 		 * If a DMA allocation request fails with
2665 		 * DDI_DMA_TOOBIG, indicate the error by calling
2666 		 * bioerror(9F) with bp and an error code of EINVAL.
2667 		 */
2668 		switch (rval) {
2669 		case DDI_DMA_NORESOURCES:
2670 			bioerror(bp, 0);
2671 			break;
2672 		case DDI_DMA_NOMAPPING:
2673 		case DDI_DMA_BADATTR:
2674 			bioerror(bp, EFAULT);
2675 			break;
2676 		case DDI_DMA_TOOBIG:
2677 		default:
2678 			bioerror(bp, EINVAL);
2679 			break;
2680 		}
2681 		if (new_pkt == TRUE) {
2682 			sata_pkt_free(spx);
2683 			scsi_hba_pkt_free(ap, pkt);
2684 		}
2685 		return (NULL);
2686 	}
2687 	/* Set number of bytes that are not yet accounted for */
2688 	pkt->pkt_resid = spx->txlt_total_residue;
2689 	ASSERT(pkt->pkt_resid >= 0);
2690 
2691 	return (pkt);
2692 }
2693 
2694 /*
2695  * Implementation of scsi tran_start.
2696  * Translate scsi cmd into sata operation and return status.
2697  * Supported scsi commands:
2698  * SCMD_INQUIRY
2699  * SCMD_TEST_UNIT_READY
2700  * SCMD_START_STOP
2701  * SCMD_READ_CAPACITY
2702  * SCMD_REQUEST_SENSE
2703  * SCMD_LOG_SENSE_G1
2704  * SCMD_LOG_SELECT_G1
2705  * SCMD_MODE_SENSE	(specific pages)
2706  * SCMD_MODE_SENSE_G1	(specific pages)
2707  * SCMD_MODE_SELECT	(specific pages)
2708  * SCMD_MODE_SELECT_G1	(specific pages)
2709  * SCMD_SYNCHRONIZE_CACHE
2710  * SCMD_SYNCHRONIZE_CACHE_G1
2711  * SCMD_READ
2712  * SCMD_READ_G1
2713  * SCMD_READ_G4
2714  * SCMD_READ_G5
2715  * SCMD_WRITE
2716  * SCMD_WRITE_G1
2717  * SCMD_WRITE_G4
2718  * SCMD_WRITE_G5
2719  * SCMD_SEEK		(noop)
2720  * SCMD_SDIAG
2721  *
2722  * All other commands are rejected as unsupported.
2723  *
2724  * Returns:
2725  * TRAN_ACCEPT if command was executed successfully or accepted by HBA driver
2726  * for execution.
2727  * TRAN_BADPKT if cmd was directed to invalid address.
2728  * TRAN_FATAL_ERROR is command was rejected due to hardware error, including
2729  * unexpected removal of a device or some other unspecified error.
2730  * TRAN_BUSY if command could not be executed becasue HBA driver or SATA
2731  * framework was busy performing some other operation(s).
2732  *
2733  */
2734 static int
2735 sata_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
2736 {
2737 	sata_hba_inst_t *sata_hba_inst =
2738 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2739 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2740 	sata_drive_info_t *sdinfo;
2741 	struct buf *bp;
2742 	int cport;
2743 	int rval;
2744 
2745 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2746 	    "sata_scsi_start: cmd 0x%02x\n", pkt->pkt_cdbp[0]);
2747 
2748 	ASSERT(spx != NULL &&
2749 	    spx->txlt_scsi_pkt == pkt && spx->txlt_sata_pkt != NULL);
2750 
2751 	/*
2752 	 * Mutex-protected section below is just to identify device type
2753 	 * and switch to ATAPI processing, if necessary
2754 	 */
2755 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
2756 
2757 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2758 
2759 	sdinfo = sata_get_device_info(sata_hba_inst,
2760 	    &spx->txlt_sata_pkt->satapkt_device);
2761 	if (sdinfo == NULL) {
2762 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2763 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
2764 		return (TRAN_FATAL_ERROR);
2765 	}
2766 
2767 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
2768 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2769 		rval = sata_txlt_atapi(spx);
2770 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2771 		    "sata_scsi_start atapi: rval %d\n", rval);
2772 		return (rval);
2773 	}
2774 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2775 
2776 	/* ATA Disk commands processing starts here */
2777 
2778 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2779 
2780 	switch (pkt->pkt_cdbp[0]) {
2781 
2782 	case SCMD_INQUIRY:
2783 		/* Mapped to identify device */
2784 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2785 			bp_mapin(bp);
2786 		rval = sata_txlt_inquiry(spx);
2787 		break;
2788 
2789 	case SCMD_TEST_UNIT_READY:
2790 		/*
2791 		 * SAT "SATA to ATA Translation" doc specifies translation
2792 		 * to ATA CHECK POWER MODE.
2793 		 */
2794 		rval = sata_txlt_test_unit_ready(spx);
2795 		break;
2796 
2797 	case SCMD_START_STOP:
2798 		/* Mapping depends on the command */
2799 		rval = sata_txlt_start_stop_unit(spx);
2800 		break;
2801 
2802 	case SCMD_READ_CAPACITY:
2803 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2804 			bp_mapin(bp);
2805 		rval = sata_txlt_read_capacity(spx);
2806 		break;
2807 
2808 	case SCMD_REQUEST_SENSE:
2809 		/*
2810 		 * Always No Sense, since we force ARQ
2811 		 */
2812 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2813 			bp_mapin(bp);
2814 		rval = sata_txlt_request_sense(spx);
2815 		break;
2816 
2817 	case SCMD_LOG_SENSE_G1:
2818 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2819 			bp_mapin(bp);
2820 		rval = sata_txlt_log_sense(spx);
2821 		break;
2822 
2823 	case SCMD_LOG_SELECT_G1:
2824 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2825 			bp_mapin(bp);
2826 		rval = sata_txlt_log_select(spx);
2827 		break;
2828 
2829 	case SCMD_MODE_SENSE:
2830 	case SCMD_MODE_SENSE_G1:
2831 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2832 			bp_mapin(bp);
2833 		rval = sata_txlt_mode_sense(spx);
2834 		break;
2835 
2836 
2837 	case SCMD_MODE_SELECT:
2838 	case SCMD_MODE_SELECT_G1:
2839 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2840 			bp_mapin(bp);
2841 		rval = sata_txlt_mode_select(spx);
2842 		break;
2843 
2844 	case SCMD_SYNCHRONIZE_CACHE:
2845 	case SCMD_SYNCHRONIZE_CACHE_G1:
2846 		rval = sata_txlt_synchronize_cache(spx);
2847 		break;
2848 
2849 	case SCMD_READ:
2850 	case SCMD_READ_G1:
2851 	case SCMD_READ_G4:
2852 	case SCMD_READ_G5:
2853 		rval = sata_txlt_read(spx);
2854 		break;
2855 
2856 	case SCMD_WRITE:
2857 	case SCMD_WRITE_G1:
2858 	case SCMD_WRITE_G4:
2859 	case SCMD_WRITE_G5:
2860 		rval = sata_txlt_write(spx);
2861 		break;
2862 
2863 	case SCMD_SEEK:
2864 		rval = sata_txlt_nodata_cmd_immediate(spx);
2865 		break;
2866 
2867 		/* Other cases will be filed later */
2868 		/* postponed until phase 2 of the development */
2869 	default:
2870 		rval = sata_txlt_invalid_command(spx);
2871 		break;
2872 	}
2873 
2874 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2875 	    "sata_scsi_start: rval %d\n", rval);
2876 
2877 	return (rval);
2878 }
2879 
2880 /*
2881  * Implementation of scsi tran_abort.
2882  * Abort specific pkt or all packets.
2883  *
2884  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2885  *
2886  * May be called from an interrupt level.
2887  */
2888 static int
2889 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2890 {
2891 	sata_hba_inst_t *sata_hba_inst =
2892 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2893 	sata_device_t	sata_device;
2894 	sata_pkt_t	*sata_pkt;
2895 
2896 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2897 	    "sata_scsi_abort: %s at target: 0x%x\n",
2898 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2899 
2900 	/* Validate address */
2901 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2902 		/* Invalid address */
2903 		return (0);
2904 
2905 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2906 	    sata_device.satadev_addr.cport)));
2907 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2908 		/* invalid address */
2909 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2910 		    sata_device.satadev_addr.cport)));
2911 		return (0);
2912 	}
2913 	if (scsi_pkt == NULL) {
2914 		/*
2915 		 * Abort all packets.
2916 		 * Although we do not have specific packet, we still need
2917 		 * dummy packet structure to pass device address to HBA.
2918 		 * Allocate one, without sleeping. Fail if pkt cannot be
2919 		 * allocated.
2920 		 */
2921 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2922 		if (sata_pkt == NULL) {
2923 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2924 			    sata_device.satadev_addr.cport)));
2925 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2926 			    "could not allocate sata_pkt"));
2927 			return (0);
2928 		}
2929 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2930 		sata_pkt->satapkt_device = sata_device;
2931 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2932 	} else {
2933 		if (scsi_pkt->pkt_ha_private == NULL) {
2934 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2935 			    sata_device.satadev_addr.cport)));
2936 			return (0); /* Bad scsi pkt */
2937 		}
2938 		/* extract pointer to sata pkt */
2939 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2940 		    txlt_sata_pkt;
2941 	}
2942 
2943 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2944 	    sata_device.satadev_addr.cport)));
2945 	/* Send abort request to HBA */
2946 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2947 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2948 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2949 	    SATA_SUCCESS) {
2950 		if (scsi_pkt == NULL)
2951 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2952 		/* Success */
2953 		return (1);
2954 	}
2955 	/* Else, something did not go right */
2956 	if (scsi_pkt == NULL)
2957 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
2958 	/* Failure */
2959 	return (0);
2960 }
2961 
2962 
2963 /*
2964  * Implementation os scsi tran_reset.
2965  * RESET_ALL request is translated into port reset.
2966  * RESET_TARGET requests is translated into a device reset,
2967  * RESET_LUN request is accepted only for LUN 0 and translated into
2968  * device reset.
2969  * The target reset should cause all HBA active and queued packets to
2970  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
2971  * the return. HBA should report reset event for the device.
2972  *
2973  * Returns 1 upon success, 0 upon failure.
2974  */
2975 static int
2976 sata_scsi_reset(struct scsi_address *ap, int level)
2977 {
2978 	sata_hba_inst_t	*sata_hba_inst =
2979 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2980 	sata_device_t	sata_device;
2981 	int		val;
2982 
2983 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2984 	    "sata_scsi_reset: level %d target: 0x%x\n",
2985 	    level, ap->a_target);
2986 
2987 	/* Validate address */
2988 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
2989 	if (val == -1)
2990 		/* Invalid address */
2991 		return (0);
2992 
2993 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2994 	    sata_device.satadev_addr.cport)));
2995 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2996 		/* invalid address */
2997 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2998 		    sata_device.satadev_addr.cport)));
2999 		return (0);
3000 	}
3001 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
3002 	    sata_device.satadev_addr.cport)));
3003 	if (level == RESET_ALL) {
3004 		/* port reset - cport only */
3005 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
3006 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
3007 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
3008 			return (1);
3009 		else
3010 			return (0);
3011 
3012 	} else if (val == 0 &&
3013 	    (level == RESET_TARGET || level == RESET_LUN)) {
3014 		/* reset device (device attached) */
3015 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
3016 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
3017 			return (1);
3018 		else
3019 			return (0);
3020 	}
3021 	return (0);
3022 }
3023 
3024 
3025 /*
3026  * Implementation of scsi tran_getcap (get transport/device capabilities).
3027  * Supported capabilities:
3028  * auto-rqsense		(always supported)
3029  * tagged-qing		(supported if HBA supports it)
3030  * dma_max
3031  * interconnect-type	(INTERCONNECT_SATA)
3032  *
3033  * Request for other capabilities is rejected as unsupported.
3034  *
3035  * Returns supported capability value, or -1 if capability is unsuppported or
3036  * the address is invalid (no device).
3037  */
3038 
3039 static int
3040 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
3041 {
3042 
3043 	sata_hba_inst_t 	*sata_hba_inst =
3044 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
3045 	sata_device_t		sata_device;
3046 	sata_drive_info_t	*sdinfo;
3047 	ddi_dma_attr_t		adj_dma_attr;
3048 	int 			rval;
3049 
3050 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
3051 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
3052 	    ap->a_target, cap);
3053 
3054 	/*
3055 	 * We want to process the capabilities on per port granularity.
3056 	 * So, we are specifically restricting ourselves to whom != 0
3057 	 * to exclude the controller wide handling.
3058 	 */
3059 	if (cap == NULL || whom == 0)
3060 		return (-1);
3061 
3062 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
3063 		/* Invalid address */
3064 		return (-1);
3065 	}
3066 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
3067 	    sata_device.satadev_addr.cport)));
3068 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
3069 	    NULL) {
3070 		/* invalid address */
3071 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
3072 		    sata_device.satadev_addr.cport)));
3073 		return (0);
3074 	}
3075 
3076 	switch (scsi_hba_lookup_capstr(cap)) {
3077 	case SCSI_CAP_ARQ:
3078 		rval = 1;		/* ARQ supported, turned on */
3079 		break;
3080 
3081 	case SCSI_CAP_SECTOR_SIZE:
3082 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
3083 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
3084 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
3085 			rval = SATA_ATAPI_SECTOR_SIZE;
3086 		else rval = -1;
3087 		break;
3088 
3089 	case SCSI_CAP_TAGGED_QING:
3090 		/*
3091 		 * It is enough if the controller supports queuing, regardless
3092 		 * of the device. NCQ support is an internal implementation
3093 		 * feature used between HBA and the device.
3094 		 */
3095 		if (SATA_QDEPTH(sata_hba_inst) > 1)
3096 			rval = 1;	/* Queuing supported */
3097 		else
3098 			rval = -1;	/* Queuing not supported */
3099 		break;
3100 
3101 	case SCSI_CAP_DMA_MAX:
3102 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
3103 		    &adj_dma_attr);
3104 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
3105 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
3106 		break;
3107 
3108 	case SCSI_CAP_INTERCONNECT_TYPE:
3109 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
3110 		break;
3111 
3112 	default:
3113 		rval = -1;
3114 		break;
3115 	}
3116 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
3117 	    sata_device.satadev_addr.cport)));
3118 	return (rval);
3119 }
3120 
3121 /*
3122  * Implementation of scsi tran_setcap
3123  *
3124  * All supported capabilities are fixed/unchangeable.
3125  * Returns 0 for all supported capabilities and valid device, -1 otherwise.
3126  */
3127 static int
3128 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
3129 {
3130 #ifndef __lock_lint
3131 	_NOTE(ARGUNUSED(value))
3132 #endif
3133 	sata_hba_inst_t	*sata_hba_inst =
3134 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
3135 	sata_device_t	sata_device;
3136 	int		rval;
3137 
3138 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
3139 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
3140 
3141 	/*
3142 	 * We want to process the capabilities on per port granularity.
3143 	 * So, we are specifically restricting ourselves to whom != 0
3144 	 * to exclude the controller wide handling.
3145 	 */
3146 	if (cap == NULL || whom == 0) {
3147 		return (-1);
3148 	}
3149 
3150 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
3151 		/* Invalid address */
3152 		return (-1);
3153 	}
3154 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
3155 	    sata_device.satadev_addr.cport)));
3156 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
3157 		/* invalid address */
3158 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
3159 		    sata_device.satadev_addr.cport)));
3160 		return (0);
3161 	}
3162 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
3163 	    sata_device.satadev_addr.cport)));
3164 
3165 	switch (scsi_hba_lookup_capstr(cap)) {
3166 	case SCSI_CAP_ARQ:
3167 	case SCSI_CAP_SECTOR_SIZE:
3168 	case SCSI_CAP_TAGGED_QING:
3169 	case SCSI_CAP_DMA_MAX:
3170 	case SCSI_CAP_INTERCONNECT_TYPE:
3171 		rval = 0;		/* Capability cannot be changed */
3172 		break;
3173 
3174 	default:
3175 		rval = -1;
3176 		break;
3177 	}
3178 	return (rval);
3179 }
3180 
3181 /*
3182  * Implementations of scsi tran_destroy_pkt.
3183  * Free resources allocated by sata_scsi_init_pkt()
3184  */
3185 static void
3186 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3187 {
3188 	sata_pkt_txlate_t *spx;
3189 
3190 	ASSERT(pkt != NULL);
3191 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3192 
3193 	if (spx->txlt_buf_dma_handle != NULL) {
3194 		/*
3195 		 * Free DMA resources - cookies and handles
3196 		 */
3197 		ASSERT(spx->txlt_dma_cookie_list != NULL);
3198 		(void) kmem_free(spx->txlt_dma_cookie_list,
3199 		    spx->txlt_dma_cookie_list_len * sizeof (ddi_dma_cookie_t));
3200 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
3201 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
3202 	}
3203 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
3204 	sata_pkt_free(spx);
3205 
3206 	scsi_hba_pkt_free(ap, pkt);
3207 }
3208 
3209 /*
3210  * Implementation of scsi tran_dmafree.
3211  * Free DMA resources allocated by sata_scsi_init_pkt()
3212  */
3213 
3214 static void
3215 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
3216 {
3217 #ifndef __lock_lint
3218 	_NOTE(ARGUNUSED(ap))
3219 #endif
3220 	sata_pkt_txlate_t *spx;
3221 
3222 	ASSERT(pkt != NULL);
3223 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3224 
3225 	if (spx->txlt_buf_dma_handle != NULL) {
3226 		/*
3227 		 * Free DMA resources - cookies and handles
3228 		 */
3229 		ASSERT(spx->txlt_dma_cookie_list != NULL);
3230 		(void) kmem_free(spx->txlt_dma_cookie_list,
3231 		    spx->txlt_dma_cookie_list_len * sizeof (ddi_dma_cookie_t));
3232 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
3233 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
3234 	}
3235 }
3236 
3237 /*
3238  * Implementation of scsi tran_sync_pkt.
3239  *
3240  * The assumption below is that pkt is unique - there is no need to check ap
3241  */
3242 static void
3243 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3244 {
3245 #ifndef __lock_lint
3246 	_NOTE(ARGUNUSED(ap))
3247 #endif
3248 	int rval;
3249 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3250 
3251 	if (spx->txlt_buf_dma_handle != NULL) {
3252 		if (spx->txlt_sata_pkt != NULL &&
3253 		    spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3254 		    sata_data_direction != SATA_DIR_NODATA_XFER) {
3255 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
3256 			    (spx->txlt_sata_pkt->satapkt_cmd.
3257 			    satacmd_flags.sata_data_direction &
3258 			    SATA_DIR_WRITE) ?
3259 			    DDI_DMA_SYNC_FORDEV : DDI_DMA_SYNC_FORCPU);
3260 			if (rval == DDI_SUCCESS) {
3261 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
3262 				    "sata_scsi_sync_pkt: sync pkt failed"));
3263 			}
3264 		}
3265 	}
3266 }
3267 
3268 
3269 
3270 /* *******************  SATA - SCSI Translation functions **************** */
3271 /*
3272  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
3273  * translation.
3274  */
3275 
3276 /*
3277  * Checks if a device exists and can be access and translates common
3278  * scsi_pkt data to sata_pkt data.
3279  *
3280  * Returns TRAN_ACCEPT if device exists and sata_pkt was set-up.
3281  * Returns other TRAN_XXXXX values when error occured.
3282  *
3283  * This function should be called with port mutex held.
3284  */
3285 static int
3286 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx)
3287 {
3288 	sata_drive_info_t *sdinfo;
3289 	sata_device_t sata_device;
3290 	const struct sata_cmd_flags sata_initial_cmd_flags = {
3291 		SATA_DIR_NODATA_XFER,
3292 		/* all other values to 0/FALSE */
3293 	};
3294 
3295 	/* Validate address */
3296 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
3297 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
3298 
3299 	case -1:
3300 		/* Invalid address or invalid device type */
3301 		return (TRAN_BADPKT);
3302 	case 1:
3303 		/* valid address but no device - it has disappeared ? */
3304 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
3305 		return (TRAN_FATAL_ERROR);
3306 	default:
3307 		/* all OK */
3308 		break;
3309 	}
3310 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3311 	    &spx->txlt_sata_pkt->satapkt_device);
3312 
3313 	/*
3314 	 * If device is in reset condition, reject the packet with
3315 	 * TRAN_BUSY
3316 	 */
3317 	if (sdinfo->satadrv_event_flags &
3318 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
3319 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3320 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3321 		    "sata_scsi_start: rejecting command because "
3322 		    "of device reset state\n", NULL);
3323 		return (TRAN_BUSY);
3324 	}
3325 
3326 	/*
3327 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
3328 	 * sata_scsi_pkt_init() because pkt init had to work also with
3329 	 * non-existing devices.
3330 	 * Now we know that the packet was set-up for a real device, so its
3331 	 * type is known.
3332 	 */
3333 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
3334 
3335 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
3336 
3337 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3338 
3339 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3340 		/* Synchronous execution */
3341 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
3342 		    SATA_OPMODE_POLLING;
3343 	} else {
3344 		/* Asynchronous execution */
3345 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
3346 		    SATA_OPMODE_INTERRUPTS;
3347 	}
3348 	/* Convert queuing information */
3349 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
3350 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
3351 		    B_TRUE;
3352 	else if (spx->txlt_scsi_pkt->pkt_flags &
3353 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
3354 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
3355 		    B_TRUE;
3356 
3357 	/* Always limit pkt time */
3358 	if (spx->txlt_scsi_pkt->pkt_time == 0)
3359 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
3360 	else
3361 		/* Pass on scsi_pkt time */
3362 		spx->txlt_sata_pkt->satapkt_time =
3363 		    spx->txlt_scsi_pkt->pkt_time;
3364 
3365 	return (TRAN_ACCEPT);
3366 }
3367 
3368 
3369 /*
3370  * Translate ATA(ATAPI) Identify (Packet) Device data to SCSI Inquiry data.
3371  * SATA Identify Device data has to be valid in sata_rive_info.
3372  * Buffer has to accomodate the inquiry length (36 bytes).
3373  *
3374  * This function should be called with a port mutex held.
3375  */
3376 static	void
3377 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
3378     sata_drive_info_t *sdinfo, uint8_t *buf)
3379 {
3380 
3381 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
3382 	struct sata_id *sid = &sdinfo->satadrv_id;
3383 
3384 	/* Start with a nice clean slate */
3385 	bzero((void *)inq, sizeof (struct scsi_inquiry));
3386 
3387 	/* Rely on the dev_type for setting paripheral qualifier */
3388 	/* Does DTYPE_RODIRECT apply to CD/DVD R/W devices ? */
3389 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3390 	    DTYPE_DIRECT : DTYPE_RODIRECT;
3391 
3392 	inq->inq_rmb = sid->ai_config & SATA_REM_MEDIA ? 1 : 0;
3393 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
3394 	inq->inq_iso = 0;	/* ISO version */
3395 	inq->inq_ecma = 0;	/* ECMA version */
3396 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
3397 	inq->inq_aenc = 0;	/* Async event notification cap. */
3398 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg ??? */
3399 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
3400 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
3401 	inq->inq_len = 31;	/* Additional length */
3402 	inq->inq_dualp = 0;	/* dual port device - NO */
3403 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
3404 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
3405 	inq->inq_linked = 0;	/* Supports linked commands - NO */
3406 				/*
3407 				 * Queuing support - controller has to
3408 				 * support some sort of command queuing.
3409 				 */
3410 	if (SATA_QDEPTH(sata_hba_inst) > 1)
3411 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
3412 	else
3413 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
3414 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
3415 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
3416 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
3417 
3418 #ifdef _LITTLE_ENDIAN
3419 	/* Swap text fields to match SCSI format */
3420 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3421 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3422 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3423 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
3424 	else
3425 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
3426 #else
3427 	bcopy(sid->ai_model, inq->inq_vid, 8);		/* Vendor ID */
3428 	bcopy(&sid->ai_model[8], inq->inq_pid, 16);	/* Product ID */
3429 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3430 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
3431 	else
3432 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
3433 #endif
3434 }
3435 
3436 
3437 /*
3438  * Scsi response set up for invalid command (command not supported)
3439  *
3440  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3441  */
3442 static int
3443 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
3444 {
3445 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3446 	struct scsi_extended_sense *sense;
3447 
3448 	scsipkt->pkt_reason = CMD_CMPLT;
3449 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3450 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3451 
3452 	*scsipkt->pkt_scbp = STATUS_CHECK;
3453 
3454 	sense = sata_arq_sense(spx);
3455 	sense->es_key = KEY_ILLEGAL_REQUEST;
3456 	sense->es_add_code = SD_SCSI_INVALID_COMMAND_CODE;
3457 
3458 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3459 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3460 
3461 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3462 	    scsipkt->pkt_comp != NULL)
3463 		/* scsi callback required */
3464 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3465 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3466 		    (void *)spx->txlt_scsi_pkt,
3467 		    TQ_SLEEP) == 0)
3468 			/* Scheduling the callback failed */
3469 			return (TRAN_BUSY);
3470 	return (TRAN_ACCEPT);
3471 }
3472 
3473 /*
3474  * Scsi response setup for
3475  * emulated non-data command that requires no action/return data
3476  *
3477  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3478  */
3479 static 	int
3480 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3481 {
3482 	int rval;
3483 
3484 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3485 
3486 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
3487 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3488 		return (rval);
3489 	}
3490 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3491 
3492 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3493 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3494 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3495 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3496 
3497 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3498 	    "Scsi_pkt completion reason %x\n",
3499 	    spx->txlt_scsi_pkt->pkt_reason);
3500 
3501 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3502 	    spx->txlt_scsi_pkt->pkt_comp != NULL)
3503 		/* scsi callback required */
3504 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3505 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3506 		    (void *)spx->txlt_scsi_pkt,
3507 		    TQ_SLEEP) == 0)
3508 			/* Scheduling the callback failed */
3509 			return (TRAN_BUSY);
3510 	return (TRAN_ACCEPT);
3511 }
3512 
3513 
3514 /*
3515  * SATA translate command: Inquiry / Identify Device
3516  * Use cached Identify Device data for now, rather then issuing actual
3517  * Device Identify cmd request. If device is detached and re-attached,
3518  * asynchromous event processing should fetch and refresh Identify Device
3519  * data.
3520  * Two VPD pages are supported now:
3521  * Vital Product Data page
3522  * Unit Serial Number page
3523  *
3524  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3525  */
3526 
3527 #define	EVPD			1	/* Extended Vital Product Data flag */
3528 #define	CMDDT			2	/* Command Support Data - Obsolete */
3529 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VDP Pages Page COde */
3530 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3531 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3532 
3533 static int
3534 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3535 {
3536 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3537 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3538 	sata_drive_info_t *sdinfo;
3539 	struct scsi_extended_sense *sense;
3540 	int count;
3541 	uint8_t *p;
3542 	int i, j;
3543 	uint8_t page_buf[0xff]; /* Max length */
3544 	int rval;
3545 
3546 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3547 
3548 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
3549 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3550 		return (rval);
3551 	}
3552 
3553 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3554 	    &spx->txlt_sata_pkt->satapkt_device);
3555 
3556 	ASSERT(sdinfo != NULL);
3557 
3558 	scsipkt->pkt_reason = CMD_CMPLT;
3559 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3560 		STATE_SENT_CMD | STATE_GOT_STATUS;
3561 
3562 	/* Reject not supported request */
3563 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3564 		*scsipkt->pkt_scbp = STATUS_CHECK;
3565 		sense = sata_arq_sense(spx);
3566 		sense->es_key = KEY_ILLEGAL_REQUEST;
3567 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
3568 		goto done;
3569 	}
3570 
3571 	/* Valid Inquiry request */
3572 	*scsipkt->pkt_scbp = STATUS_GOOD;
3573 
3574 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3575 
3576 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3577 		/* Standard Inquiry Data request */
3578 			struct scsi_inquiry inq;
3579 			unsigned int bufsize;
3580 
3581 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3582 			    sdinfo, (uint8_t *)&inq);
3583 			/* Copy no more than requested */
3584 			count = MIN(bp->b_bcount,
3585 			    sizeof (struct scsi_inquiry));
3586 			bufsize = scsipkt->pkt_cdbp[4];
3587 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3588 			count = MIN(count, bufsize);
3589 			bcopy(&inq, bp->b_un.b_addr, count);
3590 
3591 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3592 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3593 			    bufsize - count : 0;
3594 		} else {
3595 			/*
3596 			 * peripheral_qualifier = 0;
3597 			 *
3598 			 * We are dealing only with HD and will be
3599 			 * dealing with CD/DVD devices soon
3600 			 */
3601 			uint8_t peripheral_device_type =
3602 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3603 				DTYPE_DIRECT : DTYPE_RODIRECT;
3604 
3605 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3606 			case INQUIRY_SUP_VPD_PAGE:
3607 				/*
3608 				 * Request for suported Vital Product Data
3609 				 * pages - assuming only 2 page codes
3610 				 * supported
3611 				 */
3612 				page_buf[0] = peripheral_device_type;
3613 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3614 				page_buf[2] = 0;
3615 				page_buf[3] = 2; /* page length */
3616 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3617 				page_buf[5] = INQUIRY_USN_PAGE;
3618 				/* Copy no more than requested */
3619 				count = MIN(bp->b_bcount, 6);
3620 				bcopy(page_buf, bp->b_un.b_addr, count);
3621 				break;
3622 			case INQUIRY_USN_PAGE:
3623 				/*
3624 				 * Request for Unit Serial Number page
3625 				 */
3626 				page_buf[0] = peripheral_device_type;
3627 				page_buf[1] = INQUIRY_USN_PAGE;
3628 				page_buf[2] = 0;
3629 				page_buf[3] = 20; /* remaining page length */
3630 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3631 #ifdef	_LITTLE_ENDIAN
3632 				swab(p, &page_buf[4], 20);
3633 #else
3634 				bcopy(p, &page_buf[4], 20);
3635 #endif
3636 				for (i = 0; i < 20; i++) {
3637 					if (page_buf[4 + i] == '\0' ||
3638 					    page_buf[4 + i] == '\040') {
3639 						break;
3640 					}
3641 				}
3642 				/*
3643 				 * 'i' contains string length.
3644 				 *
3645 				 * Least significant character of the serial
3646 				 * number shall appear as the last byte,
3647 				 * according to SBC-3 spec.
3648 				 */
3649 				p = &page_buf[20 + 4 - 1];
3650 				for (j = i; j > 0; j--, p--) {
3651 					*p = *(p - 20 + i);
3652 				}
3653 				p = &page_buf[4];
3654 				for (j = 20 - i; j > 0; j--) {
3655 					*p++ = '\040';
3656 				}
3657 				count = MIN(bp->b_bcount, 24);
3658 				bcopy(page_buf, bp->b_un.b_addr, count);
3659 				break;
3660 
3661 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3662 				/*
3663 				 * We may want to implement this page, when
3664 				 * identifiers are common for SATA devices
3665 				 * But not now.
3666 				 */
3667 				/*FALLTHRU*/
3668 
3669 			default:
3670 				/* Request for unsupported VPD page */
3671 				*scsipkt->pkt_scbp = STATUS_CHECK;
3672 				sense = sata_arq_sense(spx);
3673 				sense->es_key = KEY_ILLEGAL_REQUEST;
3674 				sense->es_add_code =
3675 				    SD_SCSI_INVALID_FIELD_IN_CDB;
3676 				goto done;
3677 			}
3678 		}
3679 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3680 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3681 		    scsipkt->pkt_cdbp[4] - count : 0;
3682 	}
3683 done:
3684 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3685 
3686 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3687 	    "Scsi_pkt completion reason %x\n",
3688 	    scsipkt->pkt_reason);
3689 
3690 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3691 	    scsipkt->pkt_comp != NULL) {
3692 		/* scsi callback required */
3693 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3694 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3695 		    TQ_SLEEP) == 0)
3696 			/* Scheduling the callback failed */
3697 			return (TRAN_BUSY);
3698 	}
3699 	return (TRAN_ACCEPT);
3700 }
3701 
3702 /*
3703  * SATA translate command: Request Sense
3704  * emulated command (ATA version so far, no ATAPI)
3705  * Always NO SENSE, because any sense data should be reported by ARQ sense.
3706  *
3707  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3708  */
3709 static int
3710 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3711 {
3712 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3713 	struct scsi_extended_sense sense;
3714 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3715 	int rval;
3716 
3717 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3718 
3719 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
3720 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3721 		return (rval);
3722 	}
3723 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3724 
3725 
3726 	scsipkt->pkt_reason = CMD_CMPLT;
3727 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3728 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3729 	*scsipkt->pkt_scbp = STATUS_GOOD;
3730 
3731 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3732 		int count = MIN(bp->b_bcount,
3733 		    sizeof (struct scsi_extended_sense));
3734 		bzero(&sense, sizeof (struct scsi_extended_sense));
3735 		sense.es_valid = 0;	/* Valid LBA */
3736 		sense.es_class = 7;	/* Response code 0x70 - current err */
3737 		sense.es_key = KEY_NO_SENSE;
3738 		sense.es_add_len = 6;	/* Additional length */
3739 		/* Copy no more than requested */
3740 		bcopy(&sense, bp->b_un.b_addr, count);
3741 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3742 		scsipkt->pkt_resid = 0;
3743 	}
3744 
3745 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3746 	    "Scsi_pkt completion reason %x\n",
3747 	    scsipkt->pkt_reason);
3748 
3749 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3750 	    scsipkt->pkt_comp != NULL)
3751 		/* scsi callback required */
3752 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3753 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3754 		    TQ_SLEEP) == 0)
3755 			/* Scheduling the callback failed */
3756 			return (TRAN_BUSY);
3757 	return (TRAN_ACCEPT);
3758 }
3759 
3760 /*
3761  * SATA translate command: Test Unit Ready
3762  * At the moment this is an emulated command (ATA version so far, no ATAPI).
3763  * May be translated into Check Power Mode command in the future
3764  *
3765  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3766  */
3767 static int
3768 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3769 {
3770 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3771 	struct scsi_extended_sense *sense;
3772 	int power_state;
3773 	int rval;
3774 
3775 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3776 
3777 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
3778 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3779 		return (rval);
3780 	}
3781 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3782 
3783 	/* At this moment, emulate it rather than execute anything */
3784 	power_state = SATA_PWRMODE_ACTIVE;
3785 
3786 	scsipkt->pkt_reason = CMD_CMPLT;
3787 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3788 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3789 
3790 	switch (power_state) {
3791 	case SATA_PWRMODE_ACTIVE:
3792 	case SATA_PWRMODE_IDLE:
3793 		*scsipkt->pkt_scbp = STATUS_GOOD;
3794 		break;
3795 	default:
3796 		/* PWR mode standby */
3797 		*scsipkt->pkt_scbp = STATUS_CHECK;
3798 		sense = sata_arq_sense(spx);
3799 		sense->es_key = KEY_NOT_READY;
3800 		sense->es_add_code = SD_SCSI_LU_NOT_READY;
3801 		break;
3802 	}
3803 
3804 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3805 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3806 
3807 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3808 	    scsipkt->pkt_comp != NULL)
3809 		/* scsi callback required */
3810 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3811 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3812 		    TQ_SLEEP) == 0)
3813 			/* Scheduling the callback failed */
3814 			return (TRAN_BUSY);
3815 
3816 	return (TRAN_ACCEPT);
3817 }
3818 
3819 
3820 /*
3821  * SATA translate command: Start Stop Unit
3822  * Translation depends on a command:
3823  *	Start Unit translated into Idle Immediate
3824  *	Stop Unit translated into Standby Immediate
3825  *	Unload Media / NOT SUPPORTED YET
3826  *	Load Media / NOT SUPPROTED YET
3827  * Power condition bits are ignored, so is Immediate bit
3828  * Requesting synchronous execution.
3829  *
3830  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
3831  * appropriate values in scsi_pkt fields.
3832  */
3833 static int
3834 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
3835 {
3836 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3837 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3838 	struct scsi_extended_sense *sense;
3839 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3840 	int cport = SATA_TXLT_CPORT(spx);
3841 	int rval;
3842 	int synch;
3843 
3844 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3845 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
3846 
3847 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3848 
3849 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
3850 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3851 		return (rval);
3852 	}
3853 
3854 	if (scsipkt->pkt_cdbp[4] & 2) {
3855 		/* Load/Unload Media - invalid request */
3856 		*scsipkt->pkt_scbp = STATUS_CHECK;
3857 		sense = sata_arq_sense(spx);
3858 		sense->es_key = KEY_ILLEGAL_REQUEST;
3859 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
3860 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3861 
3862 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3863 		    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3864 
3865 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3866 		    scsipkt->pkt_comp != NULL)
3867 			/* scsi callback required */
3868 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3869 			    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3870 			    TQ_SLEEP) == 0)
3871 				/* Scheduling the callback failed */
3872 				return (TRAN_BUSY);
3873 
3874 		return (TRAN_ACCEPT);
3875 	}
3876 	scmd->satacmd_addr_type = 0;
3877 	scmd->satacmd_sec_count_lsb = 0;
3878 	scmd->satacmd_lba_low_lsb = 0;
3879 	scmd->satacmd_lba_mid_lsb = 0;
3880 	scmd->satacmd_lba_high_lsb = 0;
3881 	scmd->satacmd_features_reg = 0;
3882 	scmd->satacmd_device_reg = 0;
3883 	scmd->satacmd_status_reg = 0;
3884 	if (scsipkt->pkt_cdbp[4] & 1) {
3885 		/* Start Unit */
3886 		scmd->satacmd_cmd_reg = SATAC_IDLE_IM;
3887 	} else {
3888 		/* Stop Unit */
3889 		scmd->satacmd_cmd_reg = SATAC_STANDBY_IM;
3890 	}
3891 
3892 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
3893 		/* Need to set-up a callback function */
3894 		spx->txlt_sata_pkt->satapkt_comp =
3895 		    sata_txlt_nodata_cmd_completion;
3896 		synch = FALSE;
3897 	} else {
3898 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
3899 		synch = TRUE;
3900 	}
3901 
3902 	/* Transfer command to HBA */
3903 	if (sata_hba_start(spx, &rval) != 0) {
3904 		/* Pkt not accepted for execution */
3905 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3906 		return (rval);
3907 	}
3908 
3909 	/*
3910 	 * If execution is non-synchronous,
3911 	 * a callback function will handle potential errors, translate
3912 	 * the response and will do a callback to a target driver.
3913 	 * If it was synchronous, check execution status using the same
3914 	 * framework callback.
3915 	 */
3916 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3917 	if (synch) {
3918 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3919 		    "synchronous execution status %x\n",
3920 		    spx->txlt_sata_pkt->satapkt_reason);
3921 
3922 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
3923 	}
3924 	return (TRAN_ACCEPT);
3925 
3926 }
3927 
3928 
3929 /*
3930  * SATA translate command:  Read Capacity.
3931  * Emulated command for SATA disks.
3932  * Capacity is retrieved from cached Idenifty Device data.
3933  * Identify Device data shows effective disk capacity, not the native
3934  * capacity, which may be limitted by Set Max Address command.
3935  * This is ATA version (non-ATAPI).
3936  *
3937  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3938  */
3939 static int
3940 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
3941 {
3942 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3943 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3944 	sata_drive_info_t *sdinfo;
3945 	uint64_t val;
3946 	uchar_t *rbuf;
3947 	int rval;
3948 
3949 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3950 	    "sata_txlt_read_capacity: ", NULL);
3951 
3952 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3953 
3954 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
3955 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3956 		return (rval);
3957 	}
3958 
3959 	scsipkt->pkt_reason = CMD_CMPLT;
3960 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3961 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3962 	*scsipkt->pkt_scbp = STATUS_GOOD;
3963 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3964 		sdinfo = sata_get_device_info(
3965 		    spx->txlt_sata_hba_inst,
3966 		    &spx->txlt_sata_pkt->satapkt_device);
3967 		/* Last logical block address */
3968 		val = sdinfo->satadrv_capacity - 1;
3969 		rbuf = (uchar_t *)bp->b_un.b_addr;
3970 		/* Need to swap endians to match scsi format */
3971 		rbuf[0] = (val >> 24) & 0xff;
3972 		rbuf[1] = (val >> 16) & 0xff;
3973 		rbuf[2] = (val >> 8) & 0xff;
3974 		rbuf[3] = val & 0xff;
3975 		/* block size - always 512 bytes, for now */
3976 		rbuf[4] = 0;
3977 		rbuf[5] = 0;
3978 		rbuf[6] = 0x02;
3979 		rbuf[7] = 0;
3980 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3981 		scsipkt->pkt_resid = 0;
3982 
3983 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
3984 		    sdinfo->satadrv_capacity -1);
3985 	}
3986 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3987 	/*
3988 	 * If a callback was requested, do it now.
3989 	 */
3990 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3991 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3992 
3993 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3994 	    scsipkt->pkt_comp != NULL)
3995 		/* scsi callback required */
3996 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3997 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3998 		    TQ_SLEEP) == 0)
3999 			/* Scheduling the callback failed */
4000 			return (TRAN_BUSY);
4001 
4002 	return (TRAN_ACCEPT);
4003 }
4004 
4005 /*
4006  * SATA translate command: Mode Sense.
4007  * Translated into appropriate SATA command or emulated.
4008  * Saved Values Page Control (03) are not supported.
4009  *
4010  * NOTE: only caching mode sense page is currently implemented.
4011  *
4012  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4013  */
4014 
4015 static int
4016 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4017 {
4018 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4019 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4020 	sata_drive_info_t *sdinfo;
4021 	sata_id_t *sata_id;
4022 	struct scsi_extended_sense *sense;
4023 	int 		len, bdlen, count, alc_len;
4024 	int		pc;	/* Page Control code */
4025 	uint8_t		*buf;	/* mode sense buffer */
4026 	int		rval;
4027 
4028 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4029 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
4030 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4031 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4032 
4033 	buf = kmem_zalloc(1024, KM_SLEEP);
4034 
4035 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4036 
4037 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
4038 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4039 		kmem_free(buf, 1024);
4040 		return (rval);
4041 	}
4042 
4043 	scsipkt->pkt_reason = CMD_CMPLT;
4044 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4045 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4046 
4047 	pc = scsipkt->pkt_cdbp[2] >> 6;
4048 
4049 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4050 		len = 0;
4051 		bdlen = 0;
4052 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
4053 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
4054 			    (scsipkt->pkt_cdbp[0] & 0x10))
4055 				bdlen = 16;
4056 			else
4057 				bdlen = 8;
4058 		}
4059 		/* Build mode parameter header */
4060 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4061 			/* 4-byte mode parameter header */
4062 			buf[len++] = 0;   	/* mode data length */
4063 			buf[len++] = 0;		/* medium type */
4064 			buf[len++] = 0;		/* dev-specific param */
4065 			buf[len++] = bdlen;	/* Block Descriptor length */
4066 		} else {
4067 			/* 8-byte mode parameter header */
4068 			buf[len++] = 0;		/* mode data length */
4069 			buf[len++] = 0;
4070 			buf[len++] = 0;		/* medium type */
4071 			buf[len++] = 0;		/* dev-specific param */
4072 			if (bdlen == 16)
4073 				buf[len++] = 1;	/* long lba descriptor */
4074 			else
4075 				buf[len++] = 0;
4076 			buf[len++] = 0;
4077 			buf[len++] = 0;		/* Block Descriptor length */
4078 			buf[len++] = bdlen;
4079 		}
4080 
4081 		sdinfo = sata_get_device_info(
4082 		    spx->txlt_sata_hba_inst,
4083 		    &spx->txlt_sata_pkt->satapkt_device);
4084 
4085 		/* Build block descriptor only if not disabled (DBD) */
4086 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
4087 			/* Block descriptor - direct-access device format */
4088 			if (bdlen == 8) {
4089 				/* build regular block descriptor */
4090 				buf[len++] =
4091 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4092 				buf[len++] =
4093 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4094 				buf[len++] =
4095 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4096 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4097 				buf[len++] = 0; /* density code */
4098 				buf[len++] = 0;
4099 				if (sdinfo->satadrv_type ==
4100 				    SATA_DTYPE_ATADISK)
4101 					buf[len++] = 2;
4102 				else
4103 					/* ATAPI */
4104 					buf[len++] = 8;
4105 				buf[len++] = 0;
4106 			} else if (bdlen == 16) {
4107 				/* Long LBA Accepted */
4108 				/* build long lba block descriptor */
4109 #ifndef __lock_lint
4110 				buf[len++] =
4111 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
4112 				buf[len++] =
4113 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
4114 				buf[len++] =
4115 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
4116 				buf[len++] =
4117 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
4118 #endif
4119 				buf[len++] =
4120 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4121 				buf[len++] =
4122 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4123 				buf[len++] =
4124 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4125 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4126 				buf[len++] = 0;
4127 				buf[len++] = 0; /* density code */
4128 				buf[len++] = 0;
4129 				buf[len++] = 0;
4130 				if (sdinfo->satadrv_type ==
4131 				    SATA_DTYPE_ATADISK)
4132 					buf[len++] = 2;
4133 				else
4134 					/* ATAPI */
4135 					buf[len++] = 8;
4136 				buf[len++] = 0;
4137 			}
4138 		}
4139 
4140 		sata_id = &sdinfo->satadrv_id;
4141 
4142 		/*
4143 		 * Add requested pages.
4144 		 * Page 3 and 4 are obsolete and we are not supporting them.
4145 		 * We deal now with:
4146 		 * caching (read/write cache control).
4147 		 * We should eventually deal with following mode pages:
4148 		 * error recovery  (0x01),
4149 		 * power condition (0x1a),
4150 		 * exception control page (enables SMART) (0x1c),
4151 		 * enclosure management (ses),
4152 		 * protocol-specific port mode (port control).
4153 		 */
4154 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
4155 		case MODEPAGE_RW_ERRRECOV:
4156 			/* DAD_MODE_ERR_RECOV */
4157 			/* R/W recovery */
4158 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4159 			break;
4160 		case MODEPAGE_CACHING:
4161 			/* DAD_MODE_CACHE */
4162 			/* Reject not supported request for saved parameters */
4163 			if (pc == 3) {
4164 				*scsipkt->pkt_scbp = STATUS_CHECK;
4165 				sense = sata_arq_sense(spx);
4166 				sense->es_key = KEY_ILLEGAL_REQUEST;
4167 				sense->es_add_code =
4168 				    SD_SCSI_SAVING_PARAMS_NOT_SUP;
4169 				goto done;
4170 			}
4171 
4172 			/* caching */
4173 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4174 			break;
4175 		case MODEPAGE_INFO_EXCPT:
4176 			/* exception cntrl */
4177 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4178 				len += sata_build_msense_page_1c(sdinfo, pc,
4179 				    buf+len);
4180 			}
4181 			else
4182 				goto err;
4183 			break;
4184 		case MODEPAGE_POWER_COND:
4185 			/* DAD_MODE_POWER_COND */
4186 			/* power condition */
4187 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4188 			break;
4189 		case MODEPAGE_ALLPAGES:
4190 			/* all pages */
4191 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4192 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4193 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4194 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4195 				len += sata_build_msense_page_1c(sdinfo, pc,
4196 				    buf+len);
4197 			}
4198 			break;
4199 		default:
4200 		err:
4201 			/* Invalid request */
4202 			*scsipkt->pkt_scbp = STATUS_CHECK;
4203 			sense = sata_arq_sense(spx);
4204 			sense->es_key = KEY_ILLEGAL_REQUEST;
4205 			sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
4206 			goto done;
4207 		}
4208 
4209 		/* fix total mode data length */
4210 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4211 			/* 4-byte mode parameter header */
4212 			buf[0] = len - 1;   	/* mode data length */
4213 		} else {
4214 			buf[0] = (len -2) >> 8;
4215 			buf[1] = (len -2) & 0xff;
4216 		}
4217 
4218 
4219 		/* Check allocation length */
4220 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4221 			alc_len = scsipkt->pkt_cdbp[4];
4222 		} else {
4223 			alc_len = scsipkt->pkt_cdbp[7];
4224 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4225 		}
4226 		/*
4227 		 * We do not check for possible parameters truncation
4228 		 * (alc_len < len) assuming that the target driver works
4229 		 * correctly. Just avoiding overrun.
4230 		 * Copy no more than requested and possible, buffer-wise.
4231 		 */
4232 		count = MIN(alc_len, len);
4233 		count = MIN(bp->b_bcount, count);
4234 		bcopy(buf, bp->b_un.b_addr, count);
4235 
4236 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4237 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4238 	}
4239 	*scsipkt->pkt_scbp = STATUS_GOOD;
4240 done:
4241 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4242 	(void) kmem_free(buf, 1024);
4243 
4244 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4245 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4246 
4247 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4248 	    scsipkt->pkt_comp != NULL)
4249 		/* scsi callback required */
4250 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4251 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4252 		    TQ_SLEEP) == 0)
4253 			/* Scheduling the callback failed */
4254 			return (TRAN_BUSY);
4255 
4256 	return (TRAN_ACCEPT);
4257 }
4258 
4259 
4260 /*
4261  * SATA translate command: Mode Select.
4262  * Translated into appropriate SATA command or emulated.
4263  * Saving parameters is not supported.
4264  * Changing device capacity is not supported (although theoretically
4265  * possible by executing SET FEATURES/SET MAX ADDRESS)
4266  *
4267  * Assumption is that the target driver is working correctly.
4268  *
4269  * More than one SATA command may be executed to perform operations specified
4270  * by mode select pages. The first error terminates further execution.
4271  * Operations performed successully are not backed-up in such case.
4272  *
4273  * NOTE: only caching mode select page is implemented.
4274  * Caching setup is remembered so it could be re-stored in case of
4275  * an unexpected device reset.
4276  *
4277  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4278  */
4279 
4280 static int
4281 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
4282 {
4283 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4284 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4285 	struct scsi_extended_sense *sense;
4286 	int len, pagelen, count, pllen;
4287 	uint8_t *buf;	/* mode select buffer */
4288 	int rval, stat;
4289 	uint_t nointr_flag;
4290 	int dmod = 0;
4291 
4292 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4293 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
4294 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4295 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4296 
4297 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4298 
4299 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
4300 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4301 		return (rval);
4302 	}
4303 
4304 	rval = TRAN_ACCEPT;
4305 
4306 	scsipkt->pkt_reason = CMD_CMPLT;
4307 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4308 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4309 
4310 	/* Reject not supported request */
4311 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
4312 		*scsipkt->pkt_scbp = STATUS_CHECK;
4313 		sense = sata_arq_sense(spx);
4314 		sense->es_key = KEY_ILLEGAL_REQUEST;
4315 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
4316 		goto done;
4317 	}
4318 
4319 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4320 		pllen = scsipkt->pkt_cdbp[4];
4321 	} else {
4322 		pllen = scsipkt->pkt_cdbp[7];
4323 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
4324 	}
4325 
4326 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
4327 
4328 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
4329 		buf = (uint8_t *)bp->b_un.b_addr;
4330 		count = MIN(bp->b_bcount, pllen);
4331 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4332 		scsipkt->pkt_resid = 0;
4333 		pllen = count;
4334 
4335 		/*
4336 		 * Check the header to skip the block descriptor(s) - we
4337 		 * do not support setting device capacity.
4338 		 * Existing macros do not recognize long LBA dscriptor,
4339 		 * hence manual calculation.
4340 		 */
4341 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4342 			/* 6-bytes CMD, 4 bytes header */
4343 			if (count <= 4)
4344 				goto done;		/* header only */
4345 			len = buf[3] + 4;
4346 		} else {
4347 			/* 10-bytes CMD, 8 bytes header */
4348 			if (count <= 8)
4349 				goto done;		/* header only */
4350 			len = buf[6];
4351 			len = (len << 8) + buf[7] + 8;
4352 		}
4353 		if (len >= count)
4354 			goto done;	/* header + descriptor(s) only */
4355 
4356 		pllen -= len;		/* remaining data length */
4357 
4358 		/*
4359 		 * We may be executing SATA command and want to execute it
4360 		 * in SYNCH mode, regardless of scsi_pkt setting.
4361 		 * Save scsi_pkt setting and indicate SYNCH mode
4362 		 */
4363 		nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
4364 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4365 		    scsipkt->pkt_comp != NULL) {
4366 			scsipkt->pkt_flags |= FLAG_NOINTR;
4367 		}
4368 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
4369 
4370 		/*
4371 		 * len is now the offset to a first mode select page
4372 		 * Process all pages
4373 		 */
4374 		while (pllen > 0) {
4375 			switch ((int)buf[len]) {
4376 			case MODEPAGE_CACHING:
4377 				/* No support for SP (saving) */
4378 				if (scsipkt->pkt_cdbp[1] & 0x01) {
4379 					*scsipkt->pkt_scbp = STATUS_CHECK;
4380 					sense = sata_arq_sense(spx);
4381 					sense->es_key = KEY_ILLEGAL_REQUEST;
4382 					sense->es_add_code =
4383 					    SD_SCSI_INVALID_FIELD_IN_CDB;
4384 					goto done;
4385 				}
4386 				stat = sata_mode_select_page_8(spx,
4387 				    (struct mode_cache_scsi3 *)&buf[len],
4388 				    pllen, &pagelen, &rval, &dmod);
4389 				/*
4390 				 * The pagelen value indicates the number of
4391 				 * parameter bytes already processed.
4392 				 * The rval is the return value from
4393 				 * sata_tran_start().
4394 				 * The stat indicates the overall status of
4395 				 * the operation(s).
4396 				 */
4397 				if (stat != SATA_SUCCESS)
4398 					/*
4399 					 * Page processing did not succeed -
4400 					 * all error info is already set-up,
4401 					 * just return
4402 					 */
4403 					pllen = 0; /* this breaks the loop */
4404 				else {
4405 					len += pagelen;
4406 					pllen -= pagelen;
4407 				}
4408 				break;
4409 
4410 			case MODEPAGE_INFO_EXCPT:
4411 				stat = sata_mode_select_page_1c(spx,
4412 				    (struct mode_info_excpt_page *)&buf[len],
4413 				    pllen, &pagelen, &rval, &dmod);
4414 				/*
4415 				 * The pagelen value indicates the number of
4416 				 * parameter bytes already processed.
4417 				 * The rval is the return value from
4418 				 * sata_tran_start().
4419 				 * The stat indicates the overall status of
4420 				 * the operation(s).
4421 				 */
4422 				if (stat != SATA_SUCCESS)
4423 					/*
4424 					 * Page processing did not succeed -
4425 					 * all error info is already set-up,
4426 					 * just return
4427 					 */
4428 					pllen = 0; /* this breaks the loop */
4429 				else {
4430 					len += pagelen;
4431 					pllen -= pagelen;
4432 				}
4433 				break;
4434 
4435 			default:
4436 				*scsipkt->pkt_scbp = STATUS_CHECK;
4437 				sense = sata_arq_sense(spx);
4438 				sense->es_key = KEY_ILLEGAL_REQUEST;
4439 				sense->es_add_code =
4440 				    SD_SCSI_INVALID_FIELD_IN_PARAMETER_LIST;
4441 				goto done;
4442 			}
4443 		}
4444 	}
4445 done:
4446 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4447 	/*
4448 	 * If device parameters were modified, fetch and store the new
4449 	 * Identify Device data. Since port mutex could have been released
4450 	 * for accessing HBA driver, we need to re-check device existence.
4451 	 */
4452 	if (dmod != 0) {
4453 		sata_drive_info_t new_sdinfo, *sdinfo;
4454 		int rv;
4455 
4456 		new_sdinfo.satadrv_addr =
4457 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
4458 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
4459 		    &new_sdinfo);
4460 
4461 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4462 		/*
4463 		 * Since port mutex could have been released when
4464 		 * accessing HBA driver, we need to re-check that the
4465 		 * framework still holds the device info structure.
4466 		 */
4467 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4468 		    &spx->txlt_sata_pkt->satapkt_device);
4469 		if (sdinfo != NULL) {
4470 			/*
4471 			 * Device still has info structure in the
4472 			 * sata framework. Copy newly fetched info
4473 			 */
4474 			if (rv == 0) {
4475 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
4476 				sata_save_drive_settings(sdinfo);
4477 			} else {
4478 				/*
4479 				 * Could not fetch new data - invalidate
4480 				 * sata_drive_info. That makes device
4481 				 * unusable.
4482 				 */
4483 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
4484 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
4485 			}
4486 		}
4487 		if (rv != 0 || sdinfo == NULL) {
4488 			/*
4489 			 * This changes the overall mode select completion
4490 			 * reason to a failed one !!!!!
4491 			 */
4492 			*scsipkt->pkt_scbp = STATUS_CHECK;
4493 			sense = sata_arq_sense(spx);
4494 			scsipkt->pkt_reason = CMD_INCOMPLETE;
4495 			rval = TRAN_ACCEPT;
4496 		}
4497 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4498 	}
4499 	/* Restore the scsi pkt flags */
4500 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
4501 	scsipkt->pkt_flags |= nointr_flag;
4502 
4503 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4504 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4505 
4506 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4507 	    scsipkt->pkt_comp != NULL)
4508 		/* scsi callback required */
4509 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4510 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4511 		    TQ_SLEEP) == 0)
4512 			/* Scheduling the callback failed */
4513 			return (TRAN_BUSY);
4514 
4515 	return (rval);
4516 }
4517 
4518 
4519 
4520 /*
4521  * Translate command: Log Sense
4522  */
4523 static 	int
4524 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
4525 {
4526 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4527 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4528 	sata_drive_info_t *sdinfo;
4529 	struct scsi_extended_sense *sense;
4530 	int 		len, count, alc_len;
4531 	int		pc;	/* Page Control code */
4532 	int		page_code;	/* Page code */
4533 	uint8_t		*buf;	/* log sense buffer */
4534 	int		rval;
4535 #define	MAX_LOG_SENSE_PAGE_SIZE	512
4536 
4537 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4538 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
4539 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4540 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4541 
4542 	buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
4543 
4544 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4545 
4546 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
4547 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4548 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4549 		return (rval);
4550 	}
4551 
4552 	scsipkt->pkt_reason = CMD_CMPLT;
4553 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4554 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4555 
4556 	pc = scsipkt->pkt_cdbp[2] >> 6;
4557 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
4558 
4559 	/* Reject not supported request for all but cummulative values */
4560 	switch (pc) {
4561 	case PC_CUMMULATIVE_VALUES:
4562 		break;
4563 	default:
4564 		*scsipkt->pkt_scbp = STATUS_CHECK;
4565 		sense = sata_arq_sense(spx);
4566 		sense->es_key = KEY_ILLEGAL_REQUEST;
4567 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
4568 		goto done;
4569 	}
4570 
4571 	switch (page_code) {
4572 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
4573 	case PAGE_CODE_SELF_TEST_RESULTS:
4574 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
4575 	case PAGE_CODE_SMART_READ_DATA:
4576 		break;
4577 	default:
4578 		*scsipkt->pkt_scbp = STATUS_CHECK;
4579 		sense = sata_arq_sense(spx);
4580 		sense->es_key = KEY_ILLEGAL_REQUEST;
4581 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
4582 		goto done;
4583 	}
4584 
4585 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4586 		sata_id_t *sata_id;
4587 		len = 0;
4588 
4589 		/* Build log parameter header */
4590 		buf[len++] = page_code;	/* page code as in the CDB */
4591 		buf[len++] = 0;		/* reserved */
4592 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
4593 		buf[len++] = 0;		/* (LSB) */
4594 
4595 		sdinfo = sata_get_device_info(
4596 		    spx->txlt_sata_hba_inst,
4597 		    &spx->txlt_sata_pkt->satapkt_device);
4598 
4599 
4600 		/*
4601 		 * Add requested pages.
4602 		 */
4603 		switch (page_code) {
4604 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
4605 			len = sata_build_lsense_page_0(sdinfo, buf + len);
4606 			break;
4607 		case PAGE_CODE_SELF_TEST_RESULTS:
4608 			sata_id = &sdinfo->satadrv_id;
4609 			if ((! (sata_id->ai_cmdset84 &
4610 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
4611 			    (! (sata_id->ai_features87 &
4612 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
4613 				*scsipkt->pkt_scbp = STATUS_CHECK;
4614 				sense = sata_arq_sense(spx);
4615 				sense->es_key = KEY_ILLEGAL_REQUEST;
4616 				sense->es_add_code =
4617 				    SD_SCSI_INVALID_FIELD_IN_CDB;
4618 
4619 				goto done;
4620 			}
4621 			len = sata_build_lsense_page_10(sdinfo, buf + len,
4622 			    spx->txlt_sata_hba_inst);
4623 			break;
4624 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
4625 			sata_id = &sdinfo->satadrv_id;
4626 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
4627 				*scsipkt->pkt_scbp = STATUS_CHECK;
4628 				sense = sata_arq_sense(spx);
4629 				sense->es_key = KEY_ILLEGAL_REQUEST;
4630 				sense->es_add_code =
4631 				    SD_SCSI_INVALID_FIELD_IN_CDB;
4632 
4633 				goto done;
4634 			}
4635 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
4636 				*scsipkt->pkt_scbp = STATUS_CHECK;
4637 				sense = sata_arq_sense(spx);
4638 				sense->es_key = KEY_ABORTED_COMMAND;
4639 				sense->es_add_code =
4640 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
4641 				sense->es_qual_code =
4642 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
4643 
4644 				goto done;
4645 			}
4646 
4647 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
4648 			    spx->txlt_sata_hba_inst);
4649 			break;
4650 		case PAGE_CODE_SMART_READ_DATA:
4651 			sata_id = &sdinfo->satadrv_id;
4652 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
4653 				*scsipkt->pkt_scbp = STATUS_CHECK;
4654 				sense = sata_arq_sense(spx);
4655 				sense->es_key = KEY_ILLEGAL_REQUEST;
4656 				sense->es_add_code =
4657 				    SD_SCSI_INVALID_FIELD_IN_CDB;
4658 
4659 				goto done;
4660 			}
4661 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
4662 				*scsipkt->pkt_scbp = STATUS_CHECK;
4663 				sense = sata_arq_sense(spx);
4664 				sense->es_key = KEY_ABORTED_COMMAND;
4665 				sense->es_add_code =
4666 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
4667 				sense->es_qual_code =
4668 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
4669 
4670 				goto done;
4671 			}
4672 
4673 			/* This page doesn't include a page header */
4674 			len = sata_build_lsense_page_30(sdinfo, buf,
4675 			    spx->txlt_sata_hba_inst);
4676 			goto no_header;
4677 		default:
4678 			/* Invalid request */
4679 			*scsipkt->pkt_scbp = STATUS_CHECK;
4680 			sense = sata_arq_sense(spx);
4681 			sense->es_key = KEY_ILLEGAL_REQUEST;
4682 			sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
4683 			goto done;
4684 		}
4685 
4686 		/* set parameter log sense data length */
4687 		buf[2] = len >> 8;	/* log sense length (MSB) */
4688 		buf[3] = len & 0xff;	/* log sense length (LSB) */
4689 
4690 		len += SCSI_LOG_PAGE_HDR_LEN;
4691 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
4692 
4693 no_header:
4694 		/* Check allocation length */
4695 		alc_len = scsipkt->pkt_cdbp[7];
4696 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4697 
4698 		/*
4699 		 * We do not check for possible parameters truncation
4700 		 * (alc_len < len) assuming that the target driver works
4701 		 * correctly. Just avoiding overrun.
4702 		 * Copy no more than requested and possible, buffer-wise.
4703 		 */
4704 		count = MIN(alc_len, len);
4705 		count = MIN(bp->b_bcount, count);
4706 		bcopy(buf, bp->b_un.b_addr, count);
4707 
4708 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4709 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4710 	}
4711 	*scsipkt->pkt_scbp = STATUS_GOOD;
4712 done:
4713 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4714 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4715 
4716 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4717 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4718 
4719 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4720 	    scsipkt->pkt_comp != NULL)
4721 		/* scsi callback required */
4722 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4723 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4724 		    TQ_SLEEP) == 0)
4725 			/* Scheduling the callback failed */
4726 			return (TRAN_BUSY);
4727 
4728 	return (TRAN_ACCEPT);
4729 }
4730 
4731 /*
4732  * Translate command: Log Select
4733  * Not implemented at this time - returns invalid command response.
4734  */
4735 static 	int
4736 sata_txlt_log_select(sata_pkt_txlate_t *spx)
4737 {
4738 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4739 	    "sata_txlt_log_select\n", NULL);
4740 
4741 	return (sata_txlt_invalid_command(spx));
4742 }
4743 
4744 
4745 /*
4746  * Translate command: Read (various types).
4747  * Translated into appropriate type of ATA READ command
4748  * (NO ATAPI implementation yet).
4749  * Both the device capabilities and requested operation mode are
4750  * considered.
4751  *
4752  * Following scsi cdb fields are ignored:
4753  * rdprotect, dpo, fua, fua_nv, group_number.
4754  *
4755  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
4756  * enable variable sata_func_enable), the capability of the controller and
4757  * capability of a device are checked and if both support queueing, read
4758  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
4759  * command rather than plain READ_XXX command.
4760  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
4761  * both the controller and device suport such functionality, the read
4762  * request will be translated to READ_FPDMA_QUEUED command.
4763  *
4764  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4765  * appropriate values in scsi_pkt fields.
4766  */
4767 static int
4768 sata_txlt_read(sata_pkt_txlate_t *spx)
4769 {
4770 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4771 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4772 	sata_drive_info_t *sdinfo;
4773 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
4774 	int cport = SATA_TXLT_CPORT(spx);
4775 	uint16_t sec_count;
4776 	uint64_t lba;
4777 	int rval;
4778 	int synch;
4779 
4780 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4781 
4782 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
4783 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4784 		return (rval);
4785 	}
4786 
4787 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4788 	    &spx->txlt_sata_pkt->satapkt_device);
4789 
4790 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
4791 	/*
4792 	 * Build cmd block depending on the device capability and
4793 	 * requested operation mode.
4794 	 * Do not bother with non-dma mode.
4795 	 */
4796 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
4797 	case SCMD_READ:
4798 		/* 6-byte scsi read cmd : 0x08 */
4799 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
4800 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
4801 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4802 		sec_count = scsipkt->pkt_cdbp[4];
4803 		/* sec_count 0 will be interpreted as 256 by a device */
4804 		break;
4805 	case SCMD_READ_G1:
4806 		/* 10-bytes scsi read command : 0x28 */
4807 		lba = scsipkt->pkt_cdbp[2];
4808 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4809 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4810 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4811 		sec_count = scsipkt->pkt_cdbp[7];
4812 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4813 		break;
4814 	case SCMD_READ_G5:
4815 		/* 12-bytes scsi read command : 0xA8 */
4816 		lba = scsipkt->pkt_cdbp[2];
4817 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4818 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4819 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4820 		sec_count = scsipkt->pkt_cdbp[6];
4821 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
4822 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4823 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
4824 		break;
4825 	case SCMD_READ_G4:
4826 		/* 16-bytes scsi read command : 0x88 */
4827 		lba = scsipkt->pkt_cdbp[2];
4828 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4829 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4830 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4831 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
4832 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
4833 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
4834 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
4835 		sec_count = scsipkt->pkt_cdbp[10];
4836 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
4837 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
4838 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
4839 		break;
4840 	default:
4841 		/* Unsupported command */
4842 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4843 		return (sata_txlt_invalid_command(spx));
4844 	}
4845 
4846 	/*
4847 	 * Check if specified address exceeds device capacity
4848 	 */
4849 	if ((lba >= sdinfo->satadrv_capacity) ||
4850 	    ((lba + sec_count) >= sdinfo->satadrv_capacity)) {
4851 		/* LBA out of range */
4852 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4853 		return (sata_txlt_lba_out_of_range(spx));
4854 	}
4855 
4856 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
4857 	scmd->satacmd_device_reg = SATA_ADH_LBA;
4858 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
4859 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
4860 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
4861 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
4862 		scmd->satacmd_sec_count_msb = sec_count >> 8;
4863 #ifndef __lock_lint
4864 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
4865 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
4866 		scmd->satacmd_lba_high_msb = lba >> 40;
4867 #endif
4868 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
4869 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
4870 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
4871 	}
4872 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
4873 	scmd->satacmd_lba_low_lsb = lba & 0xff;
4874 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
4875 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
4876 	scmd->satacmd_features_reg = 0;
4877 	scmd->satacmd_status_reg = 0;
4878 	scmd->satacmd_error_reg = 0;
4879 
4880 	/*
4881 	 * Check if queueing commands should be used and switch
4882 	 * to appropriate command if possible
4883 	 */
4884 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
4885 		boolean_t using_queuing;
4886 
4887 		/* Queuing supported by controller and device? */
4888 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
4889 		    (sdinfo->satadrv_features_support &
4890 		    SATA_DEV_F_NCQ) &&
4891 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4892 		    SATA_CTLF_NCQ)) {
4893 			using_queuing = B_TRUE;
4894 
4895 			/* NCQ supported - use FPDMA READ */
4896 			scmd->satacmd_cmd_reg =
4897 			    SATAC_READ_FPDMA_QUEUED;
4898 			scmd->satacmd_features_reg_ext =
4899 			    scmd->satacmd_sec_count_msb;
4900 			scmd->satacmd_sec_count_msb = 0;
4901 			scmd->satacmd_rle_sata_cmd = NULL;
4902 		} else if ((sdinfo->satadrv_features_support &
4903 		    SATA_DEV_F_TCQ) &&
4904 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4905 		    SATA_CTLF_QCMD)) {
4906 			using_queuing = B_TRUE;
4907 
4908 			/* Legacy queueing */
4909 			if (sdinfo->satadrv_features_support &
4910 			    SATA_DEV_F_LBA48) {
4911 				scmd->satacmd_cmd_reg =
4912 				    SATAC_READ_DMA_QUEUED_EXT;
4913 				scmd->satacmd_features_reg_ext =
4914 				    scmd->satacmd_sec_count_msb;
4915 				scmd->satacmd_sec_count_msb = 0;
4916 			} else {
4917 				scmd->satacmd_cmd_reg =
4918 				    SATAC_READ_DMA_QUEUED;
4919 			}
4920 		} else	/* Queuing not supported */
4921 			using_queuing = B_FALSE;
4922 
4923 		/*
4924 		 * If queuing, the sector count goes in the features register
4925 		 * and the secount count will contain the tag.
4926 		 */
4927 		if (using_queuing) {
4928 			scmd->satacmd_features_reg =
4929 			    scmd->satacmd_sec_count_lsb;
4930 			scmd->satacmd_sec_count_lsb = 0;
4931 			scmd->satacmd_flags.sata_queued = B_TRUE;
4932 		}
4933 	}
4934 
4935 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
4936 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
4937 	    scmd->satacmd_cmd_reg, lba, sec_count);
4938 
4939 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
4940 		/* Need callback function */
4941 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
4942 		synch = FALSE;
4943 	} else
4944 		synch = TRUE;
4945 
4946 	/* Transfer command to HBA */
4947 	if (sata_hba_start(spx, &rval) != 0) {
4948 		/* Pkt not accepted for execution */
4949 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4950 		return (rval);
4951 	}
4952 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4953 	/*
4954 	 * If execution is non-synchronous,
4955 	 * a callback function will handle potential errors, translate
4956 	 * the response and will do a callback to a target driver.
4957 	 * If it was synchronous, check execution status using the same
4958 	 * framework callback.
4959 	 */
4960 	if (synch) {
4961 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4962 		    "synchronous execution status %x\n",
4963 		    spx->txlt_sata_pkt->satapkt_reason);
4964 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
4965 	}
4966 	return (TRAN_ACCEPT);
4967 }
4968 
4969 
4970 /*
4971  * SATA translate command: Write (various types)
4972  * Translated into appropriate type of ATA WRITE command
4973  * (NO ATAPI implementation yet).
4974  * Both the device capabilities and requested operation mode are
4975  * considered.
4976  *
4977  * Following scsi cdb fields are ignored:
4978  * rwprotect, dpo, fua, fua_nv, group_number.
4979  *
4980  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4981  * appropriate values in scsi_pkt fields.
4982  */
4983 static int
4984 sata_txlt_write(sata_pkt_txlate_t *spx)
4985 {
4986 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4987 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4988 	sata_drive_info_t *sdinfo;
4989 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
4990 	int cport = SATA_TXLT_CPORT(spx);
4991 	uint16_t sec_count;
4992 	uint64_t lba;
4993 	int rval;
4994 	int synch;
4995 
4996 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4997 
4998 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
4999 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5000 		return (rval);
5001 	}
5002 
5003 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5004 	    &spx->txlt_sata_pkt->satapkt_device);
5005 
5006 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5007 	/*
5008 	 * Build cmd block depending on the device capability and
5009 	 * requested operation mode.
5010 	 * Do not bother with non-dma mode.
5011 	 */
5012 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5013 	case SCMD_WRITE:
5014 		/* 6-byte scsi read cmd : 0x0A */
5015 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5016 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5017 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5018 		sec_count = scsipkt->pkt_cdbp[4];
5019 		/* sec_count 0 will be interpreted as 256 by a device */
5020 		break;
5021 	case SCMD_WRITE_G1:
5022 		/* 10-bytes scsi write command : 0x2A */
5023 		lba = scsipkt->pkt_cdbp[2];
5024 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5025 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5026 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5027 		sec_count = scsipkt->pkt_cdbp[7];
5028 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5029 		break;
5030 	case SCMD_WRITE_G5:
5031 		/* 12-bytes scsi read command : 0xAA */
5032 		lba = scsipkt->pkt_cdbp[2];
5033 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5034 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5035 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5036 		sec_count = scsipkt->pkt_cdbp[6];
5037 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5038 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5039 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5040 		break;
5041 	case SCMD_WRITE_G4:
5042 		/* 16-bytes scsi write command : 0x8A */
5043 		lba = scsipkt->pkt_cdbp[2];
5044 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5045 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5046 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5047 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5048 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5049 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5050 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5051 		sec_count = scsipkt->pkt_cdbp[10];
5052 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5053 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5054 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5055 		break;
5056 	default:
5057 		/* Unsupported command */
5058 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5059 		return (sata_txlt_invalid_command(spx));
5060 	}
5061 
5062 	/*
5063 	 * Check if specified address and length exceeds device capacity
5064 	 */
5065 	if ((lba >= sdinfo->satadrv_capacity) ||
5066 	    ((lba + sec_count) >= sdinfo->satadrv_capacity)) {
5067 		/* LBA out of range */
5068 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5069 		return (sata_txlt_lba_out_of_range(spx));
5070 	}
5071 
5072 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5073 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5074 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
5075 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5076 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5077 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
5078 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5079 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5080 #ifndef __lock_lint
5081 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5082 		scmd->satacmd_lba_high_msb = lba >> 40;
5083 #endif
5084 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5085 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5086 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5087 	}
5088 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5089 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5090 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5091 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5092 	scmd->satacmd_features_reg = 0;
5093 	scmd->satacmd_status_reg = 0;
5094 	scmd->satacmd_error_reg = 0;
5095 
5096 	/*
5097 	 * Check if queueing commands should be used and switch
5098 	 * to appropriate command if possible
5099 	 */
5100 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5101 		boolean_t using_queuing;
5102 
5103 		/* Queuing supported by controller and device? */
5104 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5105 		    (sdinfo->satadrv_features_support &
5106 		    SATA_DEV_F_NCQ) &&
5107 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5108 		    SATA_CTLF_NCQ)) {
5109 			using_queuing = B_TRUE;
5110 
5111 			/* NCQ supported - use FPDMA WRITE */
5112 			scmd->satacmd_cmd_reg =
5113 			    SATAC_WRITE_FPDMA_QUEUED;
5114 			scmd->satacmd_features_reg_ext =
5115 			    scmd->satacmd_sec_count_msb;
5116 			scmd->satacmd_sec_count_msb = 0;
5117 			scmd->satacmd_rle_sata_cmd = NULL;
5118 		} else if ((sdinfo->satadrv_features_support &
5119 		    SATA_DEV_F_TCQ) &&
5120 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5121 		    SATA_CTLF_QCMD)) {
5122 			using_queuing = B_TRUE;
5123 
5124 			/* Legacy queueing */
5125 			if (sdinfo->satadrv_features_support &
5126 			    SATA_DEV_F_LBA48) {
5127 				scmd->satacmd_cmd_reg =
5128 				    SATAC_WRITE_DMA_QUEUED_EXT;
5129 				scmd->satacmd_features_reg_ext =
5130 				    scmd->satacmd_sec_count_msb;
5131 				scmd->satacmd_sec_count_msb = 0;
5132 			} else {
5133 				scmd->satacmd_cmd_reg =
5134 				    SATAC_WRITE_DMA_QUEUED;
5135 			}
5136 		} else	/* Queuing not supported */
5137 			using_queuing = B_FALSE;
5138 
5139 		if (using_queuing) {
5140 			scmd->satacmd_features_reg =
5141 			    scmd->satacmd_sec_count_lsb;
5142 			scmd->satacmd_sec_count_lsb = 0;
5143 			scmd->satacmd_flags.sata_queued = B_TRUE;
5144 		}
5145 	}
5146 
5147 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5148 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
5149 	    scmd->satacmd_cmd_reg, lba, sec_count);
5150 
5151 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5152 		/* Need callback function */
5153 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5154 		synch = FALSE;
5155 	} else
5156 		synch = TRUE;
5157 
5158 	/* Transfer command to HBA */
5159 	if (sata_hba_start(spx, &rval) != 0) {
5160 		/* Pkt not accepted for execution */
5161 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5162 		return (rval);
5163 	}
5164 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5165 
5166 	/*
5167 	 * If execution is non-synchronous,
5168 	 * a callback function will handle potential errors, translate
5169 	 * the response and will do a callback to a target driver.
5170 	 * If it was synchronous, check execution status using the same
5171 	 * framework callback.
5172 	 */
5173 	if (synch) {
5174 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5175 		    "synchronous execution status %x\n",
5176 		    spx->txlt_sata_pkt->satapkt_reason);
5177 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5178 	}
5179 	return (TRAN_ACCEPT);
5180 }
5181 
5182 
5183 /*
5184  * NOTE: NOT FUNCTIONAL IMPLEMENTATION. THIS IS A PLACEHOLDER for the function
5185  * that will be fixed in phase 2 of the development.
5186  * Currently ATAPI is not supported. ATAPI devices are threated as not-valid
5187  * devices.
5188  * This function is not called, since scsi_sata_start() will bail-out prior
5189  * to calling it.
5190  */
5191 static int
5192 sata_txlt_atapi(sata_pkt_txlate_t *spx)
5193 {
5194 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5195 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5196 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5197 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5198 	int cport = SATA_TXLT_CPORT(spx);
5199 	int rval;
5200 	int synch;
5201 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
5202 
5203 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5204 
5205 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
5206 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5207 		return (rval);
5208 	}
5209 
5210 	/*
5211 	 * scmd->satacmd_flags.sata_data_direction default -
5212 	 * SATA_DIR_NODATA_XFER - is set by
5213 	 * sata_txlt_generic_pkt_info().
5214 	 */
5215 	if (scmd->satacmd_bp) {
5216 		if (scmd->satacmd_bp->b_flags & B_READ) {
5217 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5218 		} else {
5219 			scmd->satacmd_flags.sata_data_direction =
5220 			    SATA_DIR_WRITE;
5221 		}
5222 	}
5223 
5224 	scmd->satacmd_acdb_len = scsi_cdb_size[GETGROUP(cdbp)];
5225 	scmd->satacmd_cmd_reg = SATAC_PACKET;
5226 	bcopy(cdbp, scmd->satacmd_acdb,  16);
5227 
5228 	/*
5229 	 * For non-read/write commands we need to
5230 	 * map buffer
5231 	 */
5232 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5233 	case SCMD_READ:
5234 	case SCMD_READ_G1:
5235 	case SCMD_READ_G5:
5236 	case SCMD_READ_G4:
5237 	case SCMD_WRITE:
5238 	case SCMD_WRITE_G1:
5239 	case SCMD_WRITE_G5:
5240 	case SCMD_WRITE_G4:
5241 		break;
5242 	default:
5243 		if (bp->b_flags & (B_PHYS | B_PAGEIO))
5244 			bp_mapin(bp);
5245 		break;
5246 	}
5247 
5248 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5249 		/* Need callback function */
5250 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
5251 		synch = FALSE;
5252 	} else
5253 		synch = TRUE;
5254 
5255 	/* Transfer command to HBA */
5256 	if (sata_hba_start(spx, &rval) != 0) {
5257 		/* Pkt not accepted for execution */
5258 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5259 		return (rval);
5260 	}
5261 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5262 	/*
5263 	 * If execution is non-synchronous,
5264 	 * a callback function will handle potential errors, translate
5265 	 * the response and will do a callback to a target driver.
5266 	 * If it was synchronous, check execution status using the same
5267 	 * framework callback.
5268 	 */
5269 	if (synch) {
5270 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5271 		    "synchronous execution status %x\n",
5272 		    spx->txlt_sata_pkt->satapkt_reason);
5273 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
5274 	}
5275 	return (TRAN_ACCEPT);
5276 }
5277 
5278 /*
5279  * Translate command: Synchronize Cache.
5280  * Translates into Flush Cache command.
5281  * (NO ATAPI implementation yet).
5282  *
5283  * NOTE: We should check if Flush Cache is supported by the device (ATAPI
5284  * devices)
5285  *
5286  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5287  * appropriate values in scsi_pkt fields.
5288  */
5289 static 	int
5290 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
5291 {
5292 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5293 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5294 	int cport = SATA_TXLT_CPORT(spx);
5295 	int rval;
5296 	int synch;
5297 
5298 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5299 
5300 	if ((rval = sata_txlt_generic_pkt_info(spx)) != TRAN_ACCEPT) {
5301 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5302 		return (rval);
5303 	}
5304 
5305 	scmd->satacmd_addr_type = 0;
5306 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
5307 	scmd->satacmd_device_reg = 0;
5308 	scmd->satacmd_sec_count_lsb = 0;
5309 	scmd->satacmd_lba_low_lsb = 0;
5310 	scmd->satacmd_lba_mid_lsb = 0;
5311 	scmd->satacmd_lba_high_lsb = 0;
5312 	scmd->satacmd_features_reg = 0;
5313 	scmd->satacmd_status_reg = 0;
5314 	scmd->satacmd_error_reg = 0;
5315 
5316 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5317 	    "sata_txlt_synchronize_cache\n", NULL);
5318 
5319 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5320 		/* Need to set-up a callback function */
5321 		spx->txlt_sata_pkt->satapkt_comp =
5322 		    sata_txlt_nodata_cmd_completion;
5323 		synch = FALSE;
5324 	} else
5325 		synch = TRUE;
5326 
5327 	/* Transfer command to HBA */
5328 	if (sata_hba_start(spx, &rval) != 0) {
5329 		/* Pkt not accepted for execution */
5330 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5331 		return (rval);
5332 	}
5333 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5334 
5335 	/*
5336 	 * If execution non-synchronous, it had to be completed
5337 	 * a callback function will handle potential errors, translate
5338 	 * the response and will do a callback to a target driver.
5339 	 * If it was synchronous, check status, using the same
5340 	 * framework callback.
5341 	 */
5342 	if (synch) {
5343 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5344 		    "synchronous execution status %x\n",
5345 		    spx->txlt_sata_pkt->satapkt_reason);
5346 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
5347 	}
5348 	return (TRAN_ACCEPT);
5349 }
5350 
5351 /*
5352  * Send pkt to SATA HBA driver
5353  *
5354  * This function may be called only if the operation is requested by scsi_pkt,
5355  * i.e. scsi_pkt is not NULL.
5356  *
5357  * This function has to be called with cport mutex held. It does release
5358  * the mutex when it calls HBA driver sata_tran_start function and
5359  * re-acquires it afterwards.
5360  *
5361  * If return value is 0, pkt was accepted, -1 otherwise
5362  * rval is set to appropriate sata_scsi_start return value.
5363  *
5364  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
5365  * have called the sata_pkt callback function for this packet.
5366  *
5367  * The scsi callback has to be performed by the caller of this routine.
5368  *
5369  * Note 2: No port multiplier support for now.
5370  */
5371 static int
5372 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
5373 {
5374 	int stat;
5375 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
5376 	sata_drive_info_t *sdinfo;
5377 	sata_device_t sata_device;
5378 	uint8_t cmd;
5379 	struct sata_cmd_flags cmd_flags;
5380 
5381 	ASSERT(spx->txlt_sata_pkt != NULL);
5382 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(spx->txlt_sata_hba_inst,
5383 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport)));
5384 
5385 	sdinfo = sata_get_device_info(sata_hba_inst,
5386 	    &spx->txlt_sata_pkt->satapkt_device);
5387 	ASSERT(sdinfo != NULL);
5388 
5389 	/* Clear device reset state? */
5390 	if (sdinfo->satadrv_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
5391 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
5392 		    sata_clear_dev_reset = B_TRUE;
5393 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_CLEAR_DEVICE_RESET;
5394 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5395 		    "sata_hba_start: clearing device reset state\n", NULL);
5396 	}
5397 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
5398 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
5399 	sata_device = spx->txlt_sata_pkt->satapkt_device; /* local copy */
5400 
5401 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
5402 	    sdinfo->satadrv_addr.cport)));
5403 
5404 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5405 	    "Sata cmd 0x%2x\n", cmd);
5406 
5407 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
5408 	    spx->txlt_sata_pkt);
5409 
5410 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
5411 	    sdinfo->satadrv_addr.cport)));
5412 	/*
5413 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
5414 	 * with the sata callback, the sata_pkt could be already destroyed
5415 	 * by the time we check ther return status from the hba_start()
5416 	 * function, because sata_scsi_destroy_pkt() could have been already
5417 	 * called (perhaps in the interrupt context). So, in such case, there
5418 	 * should be no references to it. In other cases, sata_pkt still
5419 	 * exists.
5420 	 */
5421 	switch (stat) {
5422 	case SATA_TRAN_ACCEPTED:
5423 		/*
5424 		 * pkt accepted for execution.
5425 		 * If it was executed synchronously, it is already completed
5426 		 * and pkt completion_reason indicates completion status.
5427 		 */
5428 		*rval = TRAN_ACCEPT;
5429 		return (0);
5430 
5431 	case SATA_TRAN_QUEUE_FULL:
5432 		/*
5433 		 * Controller detected queue full condition.
5434 		 */
5435 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
5436 		    "sata_hba_start: queue full\n", NULL);
5437 
5438 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
5439 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
5440 
5441 		*rval = TRAN_BUSY;
5442 		break;
5443 
5444 	case SATA_TRAN_PORT_ERROR:
5445 		/*
5446 		 * Communication/link with device or general port error
5447 		 * detected before pkt execution begun.
5448 		 */
5449 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
5450 		    SATA_ADDR_CPORT)
5451 			sata_log(sata_hba_inst, CE_CONT,
5452 			    "port %d error",
5453 			    sata_device.satadev_addr.cport);
5454 		else
5455 			sata_log(sata_hba_inst, CE_CONT,
5456 			    "port %d pmport %d error\n",
5457 			    sata_device.satadev_addr.cport,
5458 			    sata_device.satadev_addr.pmport);
5459 
5460 		/*
5461 		 * Update the port/device structure.
5462 		 * sata_pkt should be still valid. Since port error is
5463 		 * returned, sata_device content should reflect port
5464 		 * state - it means, that sata address have been changed,
5465 		 * because original packet's sata address refered to a device
5466 		 * attached to some port.
5467 		 */
5468 		sata_update_port_info(sata_hba_inst, &sata_device);
5469 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
5470 		*rval = TRAN_FATAL_ERROR;
5471 		break;
5472 
5473 	case SATA_TRAN_CMD_UNSUPPORTED:
5474 		/*
5475 		 * Command rejected by HBA as unsupported. It was HBA driver
5476 		 * that rejected the command, command was not sent to
5477 		 * an attached device.
5478 		 */
5479 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
5480 		    sdinfo->satadrv_addr.cport)));
5481 		(void) sata_txlt_invalid_command(spx);
5482 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
5483 		    sdinfo->satadrv_addr.cport)));
5484 
5485 		if (sdinfo->satadrv_state & SATA_DSTATE_RESET)
5486 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5487 			    "sat_hba_start: cmd 0x%2x rejected "
5488 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
5489 
5490 		*rval = TRAN_ACCEPT;
5491 		break;
5492 
5493 	case SATA_TRAN_BUSY:
5494 		/*
5495 		 * Command rejected by HBA because other operation prevents
5496 		 * accepting the packet, or device is in RESET condition.
5497 		 */
5498 		if (sdinfo != NULL) {
5499 			sdinfo->satadrv_state =
5500 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
5501 
5502 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
5503 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5504 				    "sata_hba_start: cmd 0x%2x rejected "
5505 				    "because of device reset condition\n",
5506 				    cmd);
5507 			} else {
5508 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5509 				    "sata_hba_start: cmd 0x%2x rejected "
5510 				    "with SATA_TRAN_BUSY status\n",
5511 				    cmd);
5512 			}
5513 		}
5514 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
5515 		*rval = TRAN_BUSY;
5516 		break;
5517 
5518 	default:
5519 		/* Unrecognized HBA response */
5520 		SATA_LOG_D((sata_hba_inst, CE_WARN,
5521 		    "sata_hba_start: unrecognized HBA response "
5522 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
5523 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
5524 		*rval = TRAN_FATAL_ERROR;
5525 		break;
5526 	}
5527 
5528 	/*
5529 	 * If we got here, the packet was rejected.
5530 	 * Check if we need to remember reset state clearing request
5531 	 */
5532 	if (cmd_flags.sata_clear_dev_reset) {
5533 		/*
5534 		 * Check if device is still configured - it may have
5535 		 * disapeared from the configuration
5536 		 */
5537 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
5538 		if (sdinfo != NULL) {
5539 			/*
5540 			 * Restore the flag that requests clearing of
5541 			 * the device reset state,
5542 			 * so the next sata packet may carry it to HBA.
5543 			 */
5544 			sdinfo->satadrv_event_flags |=
5545 			    SATA_EVNT_CLEAR_DEVICE_RESET;
5546 		}
5547 	}
5548 	return (-1);
5549 }
5550 
5551 /*
5552  * Scsi response setup for invalid LBA
5553  *
5554  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
5555  */
5556 static int
5557 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
5558 {
5559 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5560 	struct scsi_extended_sense *sense;
5561 
5562 	scsipkt->pkt_reason = CMD_CMPLT;
5563 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5564 		STATE_SENT_CMD | STATE_GOT_STATUS;
5565 	*scsipkt->pkt_scbp = STATUS_CHECK;
5566 
5567 	*scsipkt->pkt_scbp = STATUS_CHECK;
5568 	sense = sata_arq_sense(spx);
5569 	sense->es_key = KEY_ILLEGAL_REQUEST;
5570 	sense->es_add_code = SD_SCSI_LBA_OUT_OF_RANGE;
5571 
5572 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5573 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5574 
5575 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5576 	    scsipkt->pkt_comp != NULL)
5577 		/* scsi callback required */
5578 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5579 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5580 		    TQ_SLEEP) == 0)
5581 			/* Scheduling the callback failed */
5582 			return (TRAN_BUSY);
5583 	return (TRAN_ACCEPT);
5584 }
5585 
5586 
5587 /*
5588  * Analyze device status and error registers and translate them into
5589  * appropriate scsi sense codes.
5590  * NOTE: non-packet commands only for now
5591  */
5592 static void
5593 sata_decode_device_error(sata_pkt_txlate_t *spx,
5594     struct scsi_extended_sense *sense)
5595 {
5596 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
5597 
5598 	ASSERT(sense != NULL);
5599 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
5600 	    SATA_STATUS_ERR);
5601 
5602 
5603 	if (err_reg & SATA_ERROR_ICRC) {
5604 		sense->es_key = KEY_ABORTED_COMMAND;
5605 		sense->es_add_code = 0x08; /* Communication failure */
5606 		return;
5607 	}
5608 
5609 	if (err_reg & SATA_ERROR_UNC) {
5610 		sense->es_key = KEY_MEDIUM_ERROR;
5611 		/* Information bytes (LBA) need to be set by a caller */
5612 		return;
5613 	}
5614 
5615 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
5616 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
5617 		sense->es_key = KEY_UNIT_ATTENTION;
5618 		sense->es_add_code = 0x3a; /* No media present */
5619 		return;
5620 	}
5621 
5622 	if (err_reg & SATA_ERROR_IDNF) {
5623 		if (err_reg & SATA_ERROR_ABORT) {
5624 			sense->es_key = KEY_ABORTED_COMMAND;
5625 		} else {
5626 			sense->es_key = KEY_ILLEGAL_REQUEST;
5627 			sense->es_add_code = 0x21; /* LBA out of range */
5628 		}
5629 		return;
5630 	}
5631 
5632 	if (err_reg & SATA_ERROR_ABORT) {
5633 		ASSERT(spx->txlt_sata_pkt != NULL);
5634 		sense->es_key = KEY_ABORTED_COMMAND;
5635 		return;
5636 	}
5637 }
5638 
5639 /*
5640  * Extract error LBA from sata_pkt.satapkt_cmd register fields
5641  */
5642 static void
5643 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
5644 {
5645 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
5646 
5647 	*lba = 0;
5648 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
5649 		*lba = sata_cmd->satacmd_lba_high_msb;
5650 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
5651 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
5652 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
5653 		*lba = sata_cmd->satacmd_device_reg & 0xf;
5654 	}
5655 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
5656 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
5657 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
5658 }
5659 
5660 /*
5661  * This is fixed sense format - if LBA exceeds the info field size,
5662  * no valid info will be returned (valid bit in extended sense will
5663  * be set to 0).
5664  */
5665 static struct scsi_extended_sense *
5666 sata_arq_sense(sata_pkt_txlate_t *spx)
5667 {
5668 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5669 	struct scsi_arq_status *arqs;
5670 	struct scsi_extended_sense *sense;
5671 
5672 	/* Fill ARQ sense data */
5673 	scsipkt->pkt_state |= STATE_ARQ_DONE;
5674 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
5675 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
5676 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
5677 	arqs->sts_rqpkt_reason = CMD_CMPLT;
5678 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5679 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
5680 	arqs->sts_rqpkt_resid = 0;
5681 	sense = &arqs->sts_sensedata;
5682 	bzero(sense, sizeof (struct scsi_extended_sense));
5683 	sense->es_valid = 1;		/* Valid sense */
5684 	sense->es_class = 7;		/* Response code 0x70 - current err */
5685 	sense->es_key = KEY_NO_SENSE;
5686 	sense->es_info_1 = 0;
5687 	sense->es_info_2 = 0;
5688 	sense->es_info_3 = 0;
5689 	sense->es_info_4 = 0;
5690 	sense->es_add_len = 6;		/* Additional length */
5691 	sense->es_cmd_info[0] = 0;
5692 	sense->es_cmd_info[1] = 0;
5693 	sense->es_cmd_info[2] = 0;
5694 	sense->es_cmd_info[3] = 0;
5695 	sense->es_add_code = 0;
5696 	sense->es_qual_code = 0;
5697 	return (sense);
5698 }
5699 
5700 
5701 /*
5702  * Translate completion status of SATA read/write commands into scsi response.
5703  * pkt completion_reason is checked to determine the completion status.
5704  * Do scsi callback if necessary.
5705  *
5706  * Note: this function may be called also for synchronously executed
5707  * commands.
5708  * This function may be used only if scsi_pkt is non-NULL.
5709  */
5710 static void
5711 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
5712 {
5713 	sata_pkt_txlate_t *spx =
5714 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
5715 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
5716 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5717 	struct scsi_extended_sense *sense;
5718 	uint64_t lba;
5719 
5720 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5721 		/* Normal completion */
5722 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5723 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
5724 		scsipkt->pkt_reason = CMD_CMPLT;
5725 		*scsipkt->pkt_scbp = STATUS_GOOD;
5726 	} else {
5727 		/*
5728 		 * Something went wrong - analyze return
5729 		 */
5730 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5731 		    STATE_SENT_CMD | STATE_GOT_STATUS;
5732 		scsipkt->pkt_reason = CMD_INCOMPLETE;
5733 		*scsipkt->pkt_scbp = STATUS_CHECK;
5734 		sense = sata_arq_sense(spx);
5735 		ASSERT(sense != NULL);
5736 
5737 		/*
5738 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
5739 		 * extract from device registers the failing LBA.
5740 		 */
5741 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
5742 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
5743 			    (scmd->satacmd_lba_mid_msb != 0 ||
5744 			    scmd->satacmd_lba_high_msb != 0)) {
5745 				/*
5746 				 * We have problem reporting this cmd LBA
5747 				 * in fixed sense data format, because of
5748 				 * the size of the scsi LBA fields.
5749 				 */
5750 				sense->es_valid = 0;
5751 			} else {
5752 				sata_extract_error_lba(spx, &lba);
5753 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
5754 				sense->es_info_1 = (lba & 0xFF0000) >> 16;
5755 				sense->es_info_1 = (lba & 0xFF00) >> 8;
5756 				sense->es_info_1 = lba & 0xFF;
5757 			}
5758 		} else {
5759 			/* Invalid extended sense info */
5760 			sense->es_valid = 0;
5761 		}
5762 
5763 		switch (sata_pkt->satapkt_reason) {
5764 		case SATA_PKT_PORT_ERROR:
5765 			/* We may want to handle DEV GONE state as well */
5766 			/*
5767 			 * We have no device data. Assume no data transfered.
5768 			 */
5769 			sense->es_key = KEY_HARDWARE_ERROR;
5770 			break;
5771 
5772 		case SATA_PKT_DEV_ERROR:
5773 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
5774 			    SATA_STATUS_ERR) {
5775 				/*
5776 				 * determine dev error reason from error
5777 				 * reg content
5778 				 */
5779 				sata_decode_device_error(spx, sense);
5780 				if (sense->es_key == KEY_MEDIUM_ERROR) {
5781 					switch (scmd->satacmd_cmd_reg) {
5782 					case SATAC_READ_DMA:
5783 					case SATAC_READ_DMA_EXT:
5784 					case SATAC_READ_DMA_QUEUED:
5785 					case SATAC_READ_DMA_QUEUED_EXT:
5786 					case SATAC_READ_FPDMA_QUEUED:
5787 						/* Unrecovered read error */
5788 						sense->es_add_code =
5789 						    SD_SCSI_UNREC_READ_ERROR;
5790 						break;
5791 					case SATAC_WRITE_DMA:
5792 					case SATAC_WRITE_DMA_EXT:
5793 					case SATAC_WRITE_DMA_QUEUED:
5794 					case SATAC_WRITE_DMA_QUEUED_EXT:
5795 					case SATAC_WRITE_FPDMA_QUEUED:
5796 						/* Write error */
5797 						sense->es_add_code =
5798 						    SD_SCSI_WRITE_ERROR;
5799 						break;
5800 					default:
5801 						/* Internal error */
5802 						SATA_LOG_D((
5803 						    spx->txlt_sata_hba_inst,
5804 						    CE_WARN,
5805 						    "sata_txlt_rw_completion :"
5806 						    "internal error - invalid "
5807 						    "command 0x%2x",
5808 						    scmd->satacmd_cmd_reg));
5809 						break;
5810 					}
5811 				}
5812 				break;
5813 			}
5814 			/* No extended sense key - no info available */
5815 			scsipkt->pkt_reason = CMD_INCOMPLETE;
5816 			break;
5817 
5818 		case SATA_PKT_TIMEOUT:
5819 			/* scsipkt->pkt_reason = CMD_TIMEOUT; */
5820 			scsipkt->pkt_reason = CMD_INCOMPLETE;
5821 			/* No extended sense key ? */
5822 			break;
5823 
5824 		case SATA_PKT_ABORTED:
5825 			scsipkt->pkt_reason = CMD_ABORTED;
5826 			/* No extended sense key ? */
5827 			break;
5828 
5829 		case SATA_PKT_RESET:
5830 			scsipkt->pkt_reason = CMD_RESET;
5831 			break;
5832 
5833 		default:
5834 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
5835 			    "sata_txlt_rw_completion: "
5836 			    "invalid packet completion reason"));
5837 			scsipkt->pkt_reason = CMD_TRAN_ERR;
5838 			break;
5839 		}
5840 	}
5841 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5842 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5843 
5844 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5845 	    scsipkt->pkt_comp != NULL)
5846 		/* scsi callback required */
5847 		(*scsipkt->pkt_comp)(scsipkt);
5848 
5849 }
5850 
5851 /*
5852  * NON FUNCTIONAL IMPLEMENTATION. THIS IS A PLACE HOLDER.
5853  * ATAPI devices are not supported currently (are not be attached recognized
5854  * as valid devices).
5855  * Will be fixed in phase 2 of the development.
5856  */
5857 static void
5858 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
5859 {
5860 	sata_pkt_txlate_t *spx =
5861 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
5862 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5863 	struct scsi_arq_status *arqs;
5864 
5865 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5866 		/* Normal completion */
5867 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5868 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
5869 		scsipkt->pkt_reason = CMD_CMPLT;
5870 		*scsipkt->pkt_scbp = STATUS_GOOD;
5871 		scsipkt->pkt_resid = 0;
5872 	} else {
5873 		/*
5874 		 * Something went wrong - analyze return
5875 		 */
5876 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5877 		    STATE_SENT_CMD | STATE_GOT_STATUS | STATE_ARQ_DONE;
5878 		scsipkt->pkt_reason = CMD_CMPLT;
5879 
5880 		arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
5881 		*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
5882 		*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
5883 		arqs->sts_rqpkt_reason = CMD_CMPLT;
5884 		arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5885 		    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
5886 		arqs->sts_rqpkt_resid = 0;
5887 
5888 		bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense,
5889 		    &arqs->sts_sensedata, SATA_ATAPI_RQSENSE_LEN);
5890 	}
5891 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5892 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5893 
5894 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5895 	    scsipkt->pkt_comp != NULL) {
5896 		/* scsi callback required */
5897 		(*scsipkt->pkt_comp)(scsipkt);
5898 	}
5899 }
5900 
5901 
5902 /*
5903  * Translate completion status of non-data commands (i.e. commands returning
5904  * no data).
5905  * pkt completion_reason is checked to determine the completion status.
5906  * Do scsi callback if necessary (FLAG_NOINTR == 0)
5907  *
5908  * Note: this function may be called also for synchronously executed
5909  * commands.
5910  * This function may be used only if scsi_pkt is non-NULL.
5911  */
5912 
5913 static 	void
5914 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
5915 {
5916 	sata_pkt_txlate_t *spx =
5917 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
5918 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5919 	struct scsi_extended_sense *sense;
5920 
5921 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5922 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5923 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5924 		/* Normal completion */
5925 		scsipkt->pkt_reason = CMD_CMPLT;
5926 		*scsipkt->pkt_scbp = STATUS_GOOD;
5927 	} else {
5928 		/* Something went wrong */
5929 		scsipkt->pkt_reason = CMD_INCOMPLETE;
5930 		*scsipkt->pkt_scbp = STATUS_CHECK;
5931 		sense = sata_arq_sense(spx);
5932 		switch (sata_pkt->satapkt_reason) {
5933 		case SATA_PKT_PORT_ERROR:
5934 			/*
5935 			 * We have no device data. Assume no data transfered.
5936 			 */
5937 			sense->es_key = KEY_HARDWARE_ERROR;
5938 			break;
5939 
5940 		case SATA_PKT_DEV_ERROR:
5941 		    if (sata_pkt->satapkt_cmd.satacmd_status_reg &
5942 			SATA_STATUS_ERR) {
5943 			/*
5944 			 * determine dev error reason from error
5945 			 * reg content
5946 			 */
5947 			sata_decode_device_error(spx, sense);
5948 			break;
5949 		    }
5950 		    /* No extended sense key - no info available */
5951 		    break;
5952 
5953 		case SATA_PKT_TIMEOUT:
5954 			/* scsipkt->pkt_reason = CMD_TIMEOUT; */
5955 			scsipkt->pkt_reason = CMD_INCOMPLETE;
5956 			/* No extended sense key ? */
5957 			break;
5958 
5959 		case SATA_PKT_ABORTED:
5960 			scsipkt->pkt_reason = CMD_ABORTED;
5961 			/* No extended sense key ? */
5962 			break;
5963 
5964 		case SATA_PKT_RESET:
5965 			/* pkt aborted by an explicit reset from a host */
5966 			scsipkt->pkt_reason = CMD_RESET;
5967 			break;
5968 
5969 		default:
5970 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
5971 			    "sata_txlt_nodata_cmd_completion: "
5972 			    "invalid packet completion reason %d",
5973 			    sata_pkt->satapkt_reason));
5974 			scsipkt->pkt_reason = CMD_TRAN_ERR;
5975 			break;
5976 		}
5977 
5978 	}
5979 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5980 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5981 
5982 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5983 	    scsipkt->pkt_comp != NULL)
5984 		/* scsi callback required */
5985 		(*scsipkt->pkt_comp)(scsipkt);
5986 }
5987 
5988 
5989 /*
5990  * Build Mode sense R/W recovery page
5991  * NOT IMPLEMENTED
5992  */
5993 
5994 static int
5995 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
5996 {
5997 #ifndef __lock_lint
5998 	_NOTE(ARGUNUSED(sdinfo))
5999 	_NOTE(ARGUNUSED(pcntrl))
6000 	_NOTE(ARGUNUSED(buf))
6001 #endif
6002 	return (0);
6003 }
6004 
6005 /*
6006  * Build Mode sense caching page  -  scsi-3 implementation.
6007  * Page length distinguishes previous format from scsi-3 format.
6008  * buf must have space for 0x12 bytes.
6009  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
6010  *
6011  */
6012 static int
6013 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6014 {
6015 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
6016 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6017 
6018 	/*
6019 	 * Most of the fields are set to 0, being not supported and/or disabled
6020 	 */
6021 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
6022 
6023 	/* Saved paramters not supported */
6024 	if (pcntrl == 3)
6025 		return (0);
6026 	if (pcntrl == 0 || pcntrl == 2) {
6027 		/*
6028 		 * For now treat current and default parameters as same
6029 		 * That may have to change, if target driver will complain
6030 		 */
6031 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
6032 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
6033 
6034 		if ((sata_id->ai_cmdset82 & SATA_LOOK_AHEAD) &&
6035 		    !(sata_id->ai_features85 & SATA_LOOK_AHEAD)) {
6036 			page->dra = 1;		/* Read Ahead disabled */
6037 			page->rcd = 1;		/* Read Cache disabled */
6038 		}
6039 		if ((sata_id->ai_cmdset82 & SATA_WRITE_CACHE) &&
6040 		    (sata_id->ai_features85 & SATA_WRITE_CACHE))
6041 			page->wce = 1;		/* Write Cache enabled */
6042 	} else {
6043 		/* Changeable parameters */
6044 		page->mode_page.code = MODEPAGE_CACHING;
6045 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
6046 		if (sata_id->ai_cmdset82 & SATA_LOOK_AHEAD) {
6047 			page->dra = 1;
6048 			page->rcd = 1;
6049 		}
6050 		if (sata_id->ai_cmdset82 & SATA_WRITE_CACHE)
6051 			page->wce = 1;
6052 	}
6053 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
6054 		sizeof (struct mode_page));
6055 }
6056 
6057 /*
6058  * Build Mode sense exception cntrl page
6059  */
6060 static int
6061 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6062 {
6063 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
6064 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6065 
6066 	/*
6067 	 * Most of the fields are set to 0, being not supported and/or disabled
6068 	 */
6069 	bzero(buf, PAGELENGTH_INFO_EXCPT);
6070 
6071 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
6072 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
6073 
6074 	/* Indicate that this is page is saveable */
6075 	page->mode_page.ps = 1;
6076 
6077 	/*
6078 	 * We will return the same data for default, current and saved page.
6079 	 * The only changeable bit is dexcpt and that bit is required
6080 	 * by the ATA specification to be preserved across power cycles.
6081 	 */
6082 	if (pcntrl != 1) {
6083 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
6084 		page->mrie = MRIE_ONLY_ON_REQUEST;
6085 	}
6086 	else
6087 		page->dexcpt = 1;	/* Only changeable parameter */
6088 
6089 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_info_excpt_page));
6090 }
6091 
6092 
6093 /*
6094  * Build Mode sense power condition page
6095  * NOT IMPLEMENTED.
6096  */
6097 static int
6098 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6099 {
6100 #ifndef __lock_lint
6101 	_NOTE(ARGUNUSED(sdinfo))
6102 	_NOTE(ARGUNUSED(pcntrl))
6103 	_NOTE(ARGUNUSED(buf))
6104 #endif
6105 	return (0);
6106 }
6107 
6108 
6109 /*
6110  * Process mode select caching page 8 (scsi3 format only).
6111  * Read Ahead (same as read cache) and Write Cache may be turned on and off
6112  * if these features are supported by the device. If these features are not
6113  * supported, quietly ignore them.
6114  * This function fails only if the SET FEATURE command sent to
6115  * the device fails. The page format is not varified, assuming that the
6116  * target driver operates correctly - if parameters length is too short,
6117  * we just drop the page.
6118  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
6119  * setting have to be changed.
6120  * SET FEATURE command is executed synchronously, i.e. we wait here until
6121  * it is completed, regardless of the scsi pkt directives.
6122  *
6123  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
6124  * changing DRA will change RCD.
6125  *
6126  * More than one SATA command may be executed to perform operations specified
6127  * by mode select pages. The first error terminates further execution.
6128  * Operations performed successully are not backed-up in such case.
6129  *
6130  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
6131  * If operation resulted in changing device setup, dmod flag should be set to
6132  * one (1). If parameters were not changed, dmod flag should be set to 0.
6133  * Upon return, if operation required sending command to the device, the rval
6134  * should be set to the value returned by sata_hba_start. If operation
6135  * did not require device access, rval should be set to TRAN_ACCEPT.
6136  * The pagelen should be set to the length of the page.
6137  *
6138  * This function has to be called with a port mutex held.
6139  *
6140  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
6141  */
6142 int
6143 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
6144     int parmlen, int *pagelen, int *rval, int *dmod)
6145 {
6146 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6147 	sata_drive_info_t *sdinfo;
6148 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6149 	sata_id_t *sata_id;
6150 	struct scsi_extended_sense *sense;
6151 	int wce, dra;	/* Current settings */
6152 
6153 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6154 	    &spx->txlt_sata_pkt->satapkt_device);
6155 	sata_id = &sdinfo->satadrv_id;
6156 	*dmod = 0;
6157 
6158 	/* Verify parameters length. If too short, drop it */
6159 	if (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
6160 	    sizeof (struct mode_page) < parmlen) {
6161 		*scsipkt->pkt_scbp = STATUS_CHECK;
6162 		sense = sata_arq_sense(spx);
6163 		sense->es_key = KEY_ILLEGAL_REQUEST;
6164 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_PARAMETER_LIST;
6165 		*pagelen = parmlen;
6166 		*rval = TRAN_ACCEPT;
6167 		return (SATA_FAILURE);
6168 	}
6169 
6170 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
6171 
6172 	/*
6173 	 * We can manipulate only write cache and read ahead
6174 	 * (read cache) setting.
6175 	 */
6176 	if (!(sata_id->ai_cmdset82 & SATA_LOOK_AHEAD) &&
6177 	    !(sata_id->ai_cmdset82 & SATA_WRITE_CACHE)) {
6178 		/*
6179 		 * None of the features is supported - ignore
6180 		 */
6181 		*rval = TRAN_ACCEPT;
6182 		return (SATA_SUCCESS);
6183 	}
6184 
6185 	/* Current setting of Read Ahead (and Read Cache) */
6186 	if (sata_id->ai_features85 & SATA_LOOK_AHEAD)
6187 		dra = 0;	/* 0 == not disabled */
6188 	else
6189 		dra = 1;
6190 	/* Current setting of Write Cache */
6191 	if (sata_id->ai_features85 & SATA_WRITE_CACHE)
6192 		wce = 1;
6193 	else
6194 		wce = 0;
6195 
6196 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
6197 		/* nothing to do */
6198 		*rval = TRAN_ACCEPT;
6199 		return (SATA_SUCCESS);
6200 	}
6201 	/*
6202 	 * Need to flip some setting
6203 	 * Set-up Internal SET FEATURES command(s)
6204 	 */
6205 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6206 	scmd->satacmd_addr_type = 0;
6207 	scmd->satacmd_device_reg = 0;
6208 	scmd->satacmd_status_reg = 0;
6209 	scmd->satacmd_error_reg = 0;
6210 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
6211 	if (page->dra != dra || page->rcd != dra) {
6212 		/* Need to flip read ahead setting */
6213 		if (dra == 0)
6214 			/* Disable read ahead / read cache */
6215 			scmd->satacmd_features_reg =
6216 			    SATAC_SF_DISABLE_READ_AHEAD;
6217 		else
6218 			/* Enable read ahead  / read cache */
6219 			scmd->satacmd_features_reg =
6220 			    SATAC_SF_ENABLE_READ_AHEAD;
6221 
6222 		/* Transfer command to HBA */
6223 		if (sata_hba_start(spx, rval) != 0)
6224 			/*
6225 			 * Pkt not accepted for execution.
6226 			 */
6227 			return (SATA_FAILURE);
6228 
6229 		*dmod = 1;
6230 
6231 		/* Now process return */
6232 		if (spx->txlt_sata_pkt->satapkt_reason !=
6233 		    SATA_PKT_COMPLETED) {
6234 			goto failure;	/* Terminate */
6235 		}
6236 	}
6237 
6238 	/* Note that the packet is not removed, so it could be re-used */
6239 	if (page->wce != wce) {
6240 		/* Need to flip Write Cache setting */
6241 		if (page->wce == 1)
6242 			/* Enable write cache */
6243 			scmd->satacmd_features_reg =
6244 			    SATAC_SF_ENABLE_WRITE_CACHE;
6245 		else
6246 			/* Disable write cache */
6247 			scmd->satacmd_features_reg =
6248 			    SATAC_SF_DISABLE_WRITE_CACHE;
6249 
6250 		/* Transfer command to HBA */
6251 		if (sata_hba_start(spx, rval) != 0)
6252 			/*
6253 			 * Pkt not accepted for execution.
6254 			 */
6255 			return (SATA_FAILURE);
6256 
6257 		*dmod = 1;
6258 
6259 		/* Now process return */
6260 		if (spx->txlt_sata_pkt->satapkt_reason !=
6261 		    SATA_PKT_COMPLETED) {
6262 			goto failure;
6263 		}
6264 	}
6265 	return (SATA_SUCCESS);
6266 
6267 failure:
6268 	sata_xlate_errors(spx);
6269 
6270 	return (SATA_FAILURE);
6271 }
6272 
6273 /*
6274  * Process mode select informational exceptions control page 0x1c
6275  *
6276  * The only changeable bit is dexcpt (disable exceptions).
6277  * MRIE (method of reporting informational exceptions) must be
6278  * "only on request".
6279  *
6280  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
6281  * If operation resulted in changing device setup, dmod flag should be set to
6282  * one (1). If parameters were not changed, dmod flag should be set to 0.
6283  * Upon return, if operation required sending command to the device, the rval
6284  * should be set to the value returned by sata_hba_start. If operation
6285  * did not require device access, rval should be set to TRAN_ACCEPT.
6286  * The pagelen should be set to the length of the page.
6287  *
6288  * This function has to be called with a port mutex held.
6289  *
6290  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
6291  */
6292 static	int
6293 sata_mode_select_page_1c(
6294 	sata_pkt_txlate_t *spx,
6295 	struct mode_info_excpt_page *page,
6296 	int parmlen,
6297 	int *pagelen,
6298 	int *rval,
6299 	int *dmod)
6300 {
6301 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6302 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6303 	sata_drive_info_t *sdinfo;
6304 	sata_id_t *sata_id;
6305 	struct scsi_extended_sense *sense;
6306 
6307 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6308 	    &spx->txlt_sata_pkt->satapkt_device);
6309 	sata_id = &sdinfo->satadrv_id;
6310 
6311 	*dmod = 0;
6312 
6313 	/* Verify parameters length. If too short, drop it */
6314 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) < parmlen) ||
6315 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
6316 		*scsipkt->pkt_scbp = STATUS_CHECK;
6317 		sense = sata_arq_sense(spx);
6318 		sense->es_key = KEY_ILLEGAL_REQUEST;
6319 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_PARAMETER_LIST;
6320 		*pagelen = parmlen;
6321 		*rval = TRAN_ACCEPT;
6322 		return (SATA_FAILURE);
6323 	}
6324 
6325 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
6326 
6327 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
6328 		*scsipkt->pkt_scbp = STATUS_CHECK;
6329 		sense = sata_arq_sense(spx);
6330 		sense->es_key = KEY_ILLEGAL_REQUEST;
6331 		sense->es_add_code = SD_SCSI_INVALID_FIELD_IN_CDB;
6332 		*pagelen = parmlen;
6333 		*rval = TRAN_ACCEPT;
6334 		return (SATA_FAILURE);
6335 	}
6336 
6337 	/* If already in the state requested, we are done */
6338 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
6339 		/* nothing to do */
6340 		*rval = TRAN_ACCEPT;
6341 		return (SATA_SUCCESS);
6342 	}
6343 
6344 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6345 
6346 	/* Build SMART_ENABLE or SMART_DISABLE command */
6347 	scmd->satacmd_addr_type = 0;		/* N/A */
6348 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
6349 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
6350 	scmd->satacmd_features_reg = page->dexcpt ?
6351 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
6352 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
6353 	scmd->satacmd_cmd_reg = SATAC_SMART;
6354 
6355 	/* Transfer command to HBA */
6356 	if (sata_hba_start(spx, rval) != 0)
6357 		/*
6358 		 * Pkt not accepted for execution.
6359 		 */
6360 		return (SATA_FAILURE);
6361 
6362 	*dmod = 1;	/* At least may have been modified */
6363 
6364 	/* Now process return */
6365 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
6366 		return (SATA_SUCCESS);
6367 
6368 	/* Packet did not complete successfully */
6369 	sata_xlate_errors(spx);
6370 
6371 	return (SATA_FAILURE);
6372 }
6373 
6374 /*
6375  * sata_build_lsense_page0() is used to create the
6376  * SCSI LOG SENSE page 0 (supported log pages)
6377  *
6378  * Currently supported pages are 0, 0x10, 0x2f and 0x30
6379  * (supported log pages, self-test results, informational exceptions
6380  *  and Sun vendor specific ATA SMART data).
6381  *
6382  * Takes a sata_drive_info t * and the address of a buffer
6383  * in which to create the page information.
6384  *
6385  * Returns the number of bytes valid in the buffer.
6386  */
6387 static	int
6388 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
6389 {
6390 	struct log_parameter *lpp = (struct log_parameter *)buf;
6391 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
6392 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
6393 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6394 
6395 	lpp->param_code[0] = 0;
6396 	lpp->param_code[1] = 0;
6397 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
6398 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
6399 
6400 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
6401 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
6402 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
6403 			++num_pages_supported;
6404 		}
6405 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
6406 		++num_pages_supported;
6407 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
6408 		++num_pages_supported;
6409 	}
6410 
6411 	lpp->param_len = num_pages_supported;
6412 
6413 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
6414 	    num_pages_supported);
6415 }
6416 
6417 /*
6418  * sata_build_lsense_page_10() is used to create the
6419  * SCSI LOG SENSE page 0x10 (self-test results)
6420  *
6421  * Takes a sata_drive_info t * and the address of a buffer
6422  * in which to create the page information as well as a sata_hba_inst_t *.
6423  *
6424  * Returns the number of bytes valid in the buffer.
6425  */
6426 static	int
6427 sata_build_lsense_page_10(
6428 	sata_drive_info_t *sdinfo,
6429 	uint8_t *buf,
6430 	sata_hba_inst_t *sata_hba_inst)
6431 {
6432 	struct log_parameter *lpp = (struct log_parameter *)buf;
6433 	int rval;
6434 
6435 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
6436 		struct smart_ext_selftest_log *ext_selftest_log;
6437 
6438 		ext_selftest_log = kmem_zalloc(
6439 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
6440 
6441 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
6442 		    ext_selftest_log, 0);
6443 		if (rval == 0) {
6444 			int index, start_index;
6445 			struct smart_ext_selftest_log_entry *entry;
6446 			static const struct smart_ext_selftest_log_entry empty =
6447 			    {0};
6448 			uint16_t block_num;
6449 			int count;
6450 			boolean_t only_one_block = B_FALSE;
6451 
6452 			index = ext_selftest_log->
6453 			    smart_ext_selftest_log_index[0];
6454 			index |= ext_selftest_log->
6455 			    smart_ext_selftest_log_index[1] << 8;
6456 			if (index == 0)
6457 				goto out;
6458 
6459 			--index;	/* Correct for 0 origin */
6460 			start_index = index;	/* remember where we started */
6461 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6462 			if (block_num != 0) {
6463 				rval = sata_ext_smart_selftest_read_log(
6464 				    sata_hba_inst, sdinfo, ext_selftest_log,
6465 				    block_num);
6466 				if (rval != 0)
6467 					goto out;
6468 			}
6469 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6470 			entry =
6471 			    &ext_selftest_log->
6472 			    smart_ext_selftest_log_entries[index];
6473 
6474 			for (count = 1;
6475 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
6476 			    ++count) {
6477 				uint8_t status;
6478 				uint8_t code;
6479 				uint8_t sense_key;
6480 				uint8_t add_sense_code;
6481 				uint8_t add_sense_code_qual;
6482 
6483 				/* If this is an unused entry, we are done */
6484 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
6485 					/* Broken firmware on some disks */
6486 					if (index + 1 ==
6487 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
6488 						--entry;
6489 						--index;
6490 						if (bcmp(entry, &empty,
6491 						    sizeof (empty)) == 0)
6492 							goto out;
6493 					} else
6494 						goto out;
6495 				}
6496 
6497 				if (only_one_block &&
6498 				    start_index == index)
6499 					goto out;
6500 
6501 				lpp->param_code[0] = 0;
6502 				lpp->param_code[1] = count;
6503 				lpp->param_ctrl_flags =
6504 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
6505 				lpp->param_len =
6506 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
6507 
6508 				status = entry->smart_ext_selftest_log_status;
6509 				status >>= 4;
6510 				switch (status) {
6511 				case 0:
6512 				default:
6513 					sense_key = KEY_NO_SENSE;
6514 					add_sense_code = SD_SCSI_NO_ADD_SENSE;
6515 					add_sense_code_qual = 0;
6516 					break;
6517 				case 1:
6518 					sense_key = KEY_ABORTED_COMMAND;
6519 					add_sense_code =
6520 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6521 					add_sense_code_qual = SCSI_COMPONENT_81;
6522 					break;
6523 				case 2:
6524 					sense_key = KEY_ABORTED_COMMAND;
6525 					add_sense_code =
6526 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6527 					add_sense_code_qual = SCSI_COMPONENT_82;
6528 					break;
6529 				case 3:
6530 					sense_key = KEY_ABORTED_COMMAND;
6531 					add_sense_code =
6532 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6533 					add_sense_code_qual = SCSI_COMPONENT_83;
6534 					break;
6535 				case 4:
6536 					sense_key = KEY_HARDWARE_ERROR;
6537 					add_sense_code =
6538 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6539 					add_sense_code_qual = SCSI_COMPONENT_84;
6540 					break;
6541 				case 5:
6542 					sense_key = KEY_HARDWARE_ERROR;
6543 					add_sense_code =
6544 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6545 					add_sense_code_qual = SCSI_COMPONENT_85;
6546 					break;
6547 				case 6:
6548 					sense_key = KEY_HARDWARE_ERROR;
6549 					add_sense_code =
6550 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6551 					add_sense_code_qual = SCSI_COMPONENT_86;
6552 					break;
6553 				case 7:
6554 					sense_key = KEY_MEDIUM_ERROR;
6555 					add_sense_code =
6556 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6557 					add_sense_code_qual = SCSI_COMPONENT_87;
6558 					break;
6559 				case 8:
6560 					sense_key = KEY_HARDWARE_ERROR;
6561 					add_sense_code =
6562 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6563 					add_sense_code_qual = SCSI_COMPONENT_88;
6564 					break;
6565 				}
6566 				code = 0;	/* unspecified */
6567 				status |= (code << 4);
6568 				lpp->param_values[0] = status;
6569 				lpp->param_values[1] = 0; /* unspecified */
6570 				lpp->param_values[2] = entry->
6571 				    smart_ext_selftest_log_timestamp[1];
6572 				lpp->param_values[3] = entry->
6573 				    smart_ext_selftest_log_timestamp[0];
6574 				if (status != 0) {
6575 					lpp->param_values[4] = 0;
6576 					lpp->param_values[5] = 0;
6577 					lpp->param_values[6] = entry->
6578 					    smart_ext_selftest_log_failing_lba
6579 					    [5];
6580 					lpp->param_values[7] = entry->
6581 					    smart_ext_selftest_log_failing_lba
6582 					    [4];
6583 					lpp->param_values[8] = entry->
6584 					    smart_ext_selftest_log_failing_lba
6585 					    [3];
6586 					lpp->param_values[9] = entry->
6587 					    smart_ext_selftest_log_failing_lba
6588 					    [2];
6589 					lpp->param_values[10] = entry->
6590 					    smart_ext_selftest_log_failing_lba
6591 					    [1];
6592 					lpp->param_values[11] = entry->
6593 					    smart_ext_selftest_log_failing_lba
6594 					    [0];
6595 				} else {	/* No bad block address */
6596 					lpp->param_values[4] = 0xff;
6597 					lpp->param_values[5] = 0xff;
6598 					lpp->param_values[6] = 0xff;
6599 					lpp->param_values[7] = 0xff;
6600 					lpp->param_values[8] = 0xff;
6601 					lpp->param_values[9] = 0xff;
6602 					lpp->param_values[10] = 0xff;
6603 					lpp->param_values[11] = 0xff;
6604 				}
6605 
6606 				lpp->param_values[12] = sense_key;
6607 				lpp->param_values[13] = add_sense_code;
6608 				lpp->param_values[14] = add_sense_code_qual;
6609 				lpp->param_values[15] = 0; /* undefined */
6610 
6611 				lpp = (struct log_parameter *)
6612 				    (((uint8_t *)lpp) +
6613 				    SCSI_LOG_PARAM_HDR_LEN +
6614 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
6615 
6616 				--index;	/* Back up to previous entry */
6617 				if (index < 0) {
6618 					if (block_num > 0) {
6619 						--block_num;
6620 					} else {
6621 						struct read_log_ext_directory
6622 						    logdir;
6623 
6624 						rval =
6625 						    sata_read_log_ext_directory(
6626 						    sata_hba_inst, sdinfo,
6627 						    &logdir);
6628 						if (rval == -1)
6629 							goto out;
6630 						if ((logdir.read_log_ext_vers
6631 						    [0] == 0) &&
6632 						    (logdir.read_log_ext_vers
6633 						    [1] == 0))
6634 							goto out;
6635 						block_num =
6636 						    logdir.read_log_ext_nblks
6637 						    [EXT_SMART_SELFTEST_LOG_PAGE
6638 						    - 1][0];
6639 						block_num |= logdir.
6640 						    read_log_ext_nblks
6641 						    [EXT_SMART_SELFTEST_LOG_PAGE
6642 						    - 1][1] << 8;
6643 						--block_num;
6644 						only_one_block =
6645 						    (block_num == 0);
6646 					}
6647 					rval = sata_ext_smart_selftest_read_log(
6648 					    sata_hba_inst, sdinfo,
6649 					    ext_selftest_log, block_num);
6650 					if (rval != 0)
6651 						goto out;
6652 
6653 					index =
6654 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
6655 					    1;
6656 				}
6657 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6658 				entry = &ext_selftest_log->
6659 				    smart_ext_selftest_log_entries[index];
6660 			}
6661 		}
6662 out:
6663 		kmem_free(ext_selftest_log,
6664 		    sizeof (struct smart_ext_selftest_log));
6665 	} else {
6666 		struct smart_selftest_log *selftest_log;
6667 
6668 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
6669 		    KM_SLEEP);
6670 
6671 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
6672 		    selftest_log);
6673 
6674 		if (rval == 0) {
6675 			int index;
6676 			int count;
6677 			struct smart_selftest_log_entry *entry;
6678 			static const struct smart_selftest_log_entry empty =
6679 			    { 0 };
6680 
6681 			index = selftest_log->smart_selftest_log_index;
6682 			if (index == 0)
6683 				goto done;
6684 			--index;	/* Correct for 0 origin */
6685 			entry = &selftest_log->
6686 			    smart_selftest_log_entries[index];
6687 			for (count = 1;
6688 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
6689 			    ++count) {
6690 				uint8_t status;
6691 				uint8_t code;
6692 				uint8_t sense_key;
6693 				uint8_t add_sense_code;
6694 				uint8_t add_sense_code_qual;
6695 
6696 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
6697 					goto done;
6698 
6699 				lpp->param_code[0] = 0;
6700 				lpp->param_code[1] = count;
6701 				lpp->param_ctrl_flags =
6702 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
6703 				lpp->param_len =
6704 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
6705 
6706 				status = entry->smart_selftest_log_status;
6707 				status >>= 4;
6708 				switch (status) {
6709 				case 0:
6710 				default:
6711 					sense_key = KEY_NO_SENSE;
6712 					add_sense_code = SD_SCSI_NO_ADD_SENSE;
6713 					break;
6714 				case 1:
6715 					sense_key = KEY_ABORTED_COMMAND;
6716 					add_sense_code =
6717 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6718 					add_sense_code_qual = SCSI_COMPONENT_81;
6719 					break;
6720 				case 2:
6721 					sense_key = KEY_ABORTED_COMMAND;
6722 					add_sense_code =
6723 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6724 					add_sense_code_qual = SCSI_COMPONENT_82;
6725 					break;
6726 				case 3:
6727 					sense_key = KEY_ABORTED_COMMAND;
6728 					add_sense_code =
6729 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6730 					add_sense_code_qual = SCSI_COMPONENT_83;
6731 					break;
6732 				case 4:
6733 					sense_key = KEY_HARDWARE_ERROR;
6734 					add_sense_code =
6735 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6736 					add_sense_code_qual = SCSI_COMPONENT_84;
6737 					break;
6738 				case 5:
6739 					sense_key = KEY_HARDWARE_ERROR;
6740 					add_sense_code =
6741 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6742 					add_sense_code_qual = SCSI_COMPONENT_85;
6743 					break;
6744 				case 6:
6745 					sense_key = KEY_HARDWARE_ERROR;
6746 					add_sense_code =
6747 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6748 					add_sense_code_qual = SCSI_COMPONENT_86;
6749 					break;
6750 				case 7:
6751 					sense_key = KEY_MEDIUM_ERROR;
6752 					add_sense_code =
6753 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6754 					add_sense_code_qual = SCSI_COMPONENT_87;
6755 					break;
6756 				case 8:
6757 					sense_key = KEY_HARDWARE_ERROR;
6758 					add_sense_code =
6759 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6760 					add_sense_code_qual = SCSI_COMPONENT_88;
6761 					break;
6762 				}
6763 				code = 0;	/* unspecified */
6764 				status |= (code << 4);
6765 				lpp->param_values[0] = status;
6766 				lpp->param_values[1] = 0; /* unspecified */
6767 				lpp->param_values[2] = entry->
6768 				    smart_selftest_log_timestamp[1];
6769 				lpp->param_values[3] = entry->
6770 				    smart_selftest_log_timestamp[0];
6771 				if (status != 0) {
6772 					lpp->param_values[4] = 0;
6773 					lpp->param_values[5] = 0;
6774 					lpp->param_values[6] = 0;
6775 					lpp->param_values[7] = 0;
6776 					lpp->param_values[8] = entry->
6777 					    smart_selftest_log_failing_lba[3];
6778 					lpp->param_values[9] = entry->
6779 					    smart_selftest_log_failing_lba[2];
6780 					lpp->param_values[10] = entry->
6781 					    smart_selftest_log_failing_lba[1];
6782 					lpp->param_values[11] = entry->
6783 					    smart_selftest_log_failing_lba[0];
6784 				} else {	/* No block address */
6785 					lpp->param_values[4] = 0xff;
6786 					lpp->param_values[5] = 0xff;
6787 					lpp->param_values[6] = 0xff;
6788 					lpp->param_values[7] = 0xff;
6789 					lpp->param_values[8] = 0xff;
6790 					lpp->param_values[9] = 0xff;
6791 					lpp->param_values[10] = 0xff;
6792 					lpp->param_values[11] = 0xff;
6793 				}
6794 				lpp->param_values[12] = sense_key;
6795 				lpp->param_values[13] = add_sense_code;
6796 				lpp->param_values[14] = add_sense_code_qual;
6797 				lpp->param_values[15] = 0; /* undefined */
6798 
6799 				lpp = (struct log_parameter *)
6800 				    (((uint8_t *)lpp) +
6801 				    SCSI_LOG_PARAM_HDR_LEN +
6802 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
6803 				--index;	/* back up to previous entry */
6804 				if (index < 0) {
6805 					index =
6806 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
6807 				}
6808 				entry = &selftest_log->
6809 					smart_selftest_log_entries[index];
6810 			}
6811 		}
6812 done:
6813 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
6814 	}
6815 
6816 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
6817 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
6818 }
6819 
6820 /*
6821  * sata_build_lsense_page_2f() is used to create the
6822  * SCSI LOG SENSE page 0x10 (informational exceptions)
6823  *
6824  * Takes a sata_drive_info t * and the address of a buffer
6825  * in which to create the page information as well as a sata_hba_inst_t *.
6826  *
6827  * Returns the number of bytes valid in the buffer.
6828  */
6829 static	int
6830 sata_build_lsense_page_2f(
6831 	sata_drive_info_t *sdinfo,
6832 	uint8_t *buf,
6833 	sata_hba_inst_t *sata_hba_inst)
6834 {
6835 	struct log_parameter *lpp = (struct log_parameter *)buf;
6836 	int rval;
6837 	uint8_t *smart_data;
6838 	uint8_t temp;
6839 	sata_id_t *sata_id;
6840 #define	SMART_NO_TEMP	0xff
6841 
6842 	lpp->param_code[0] = 0;
6843 	lpp->param_code[1] = 0;
6844 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
6845 
6846 	/* Now get the SMART status w.r.t. threshold exceeded */
6847 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
6848 	switch (rval) {
6849 	case 1:
6850 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
6851 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
6852 		break;
6853 	case 0:
6854 	case -1:	/* failed to get data */
6855 		lpp->param_values[0] = 0;	/* No failure predicted */
6856 		lpp->param_values[1] = 0;
6857 		break;
6858 #if defined(SATA_DEBUG)
6859 	default:
6860 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
6861 		/* NOTREACHED */
6862 #endif
6863 	}
6864 
6865 	sata_id = &sdinfo->satadrv_id;
6866 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
6867 		temp = SMART_NO_TEMP;
6868 	else {
6869 		/* Now get the temperature */
6870 		smart_data = kmem_zalloc(512, KM_SLEEP);
6871 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
6872 		    SCT_STATUS_LOG_PAGE, 1);
6873 		if (rval == -1)
6874 			temp = SMART_NO_TEMP;
6875 		else {
6876 			temp = smart_data[200];
6877 			if (temp & 0x80) {
6878 				if (temp & 0x7f)
6879 					temp = 0;
6880 				else
6881 					temp = SMART_NO_TEMP;
6882 			}
6883 		}
6884 		kmem_free(smart_data, 512);
6885 	}
6886 
6887 	lpp->param_values[2] = temp;	/* most recent temperature */
6888 	lpp->param_values[3] = 0;	/* required vendor specific byte */
6889 
6890 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
6891 
6892 
6893 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
6894 }
6895 
6896 /*
6897  * sata_build_lsense_page_30() is used to create the
6898  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
6899  *
6900  * Takes a sata_drive_info t * and the address of a buffer
6901  * in which to create the page information as well as a sata_hba_inst_t *.
6902  *
6903  * Returns the number of bytes valid in the buffer.
6904  */
6905 static int
6906 sata_build_lsense_page_30(
6907 	sata_drive_info_t *sdinfo,
6908 	uint8_t *buf,
6909 	sata_hba_inst_t *sata_hba_inst)
6910 {
6911 	struct smart_data *smart_data = (struct smart_data *)buf;
6912 	int rval;
6913 
6914 	/* Now do the SMART READ DATA */
6915 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
6916 	if (rval == -1)
6917 		return (0);
6918 
6919 	return (sizeof (struct smart_data));
6920 }
6921 
6922 
6923 
6924 
6925 
6926 /* ************************** LOCAL FUNCTIONS ************************** */
6927 
6928 /*
6929  * Validate sata_tran info
6930  * SATA_FAILURE returns if structure is inconsistent or structure revision
6931  * does not match one used by the framework.
6932  *
6933  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
6934  * required function pointers.
6935  * Returns SATA_FAILURE otherwise.
6936  */
6937 static int
6938 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
6939 {
6940 	if (sata_tran->sata_tran_hba_rev != SATA_TRAN_HBA_REV) {
6941 		sata_log(NULL, CE_WARN,
6942 		    "sata: invalid sata_hba_tran version %d for driver %s",
6943 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
6944 		return (SATA_FAILURE);
6945 	}
6946 
6947 	if (dip != sata_tran->sata_tran_hba_dip) {
6948 		SATA_LOG_D((NULL, CE_WARN,
6949 		    "sata: inconsistent sata_tran_hba_dip "
6950 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
6951 		return (SATA_FAILURE);
6952 	}
6953 
6954 	if (sata_tran->sata_tran_probe_port == NULL ||
6955 	    sata_tran->sata_tran_start == NULL ||
6956 	    sata_tran->sata_tran_abort == NULL ||
6957 	    sata_tran->sata_tran_reset_dport == NULL) {
6958 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
6959 		    "required functions"));
6960 	}
6961 	return (SATA_SUCCESS);
6962 }
6963 
6964 /*
6965  * Remove HBA instance from sata_hba_list.
6966  */
6967 static void
6968 sata_remove_hba_instance(dev_info_t *dip)
6969 {
6970 	sata_hba_inst_t	*sata_hba_inst;
6971 
6972 	mutex_enter(&sata_mutex);
6973 	for (sata_hba_inst = sata_hba_list;
6974 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
6975 	    sata_hba_inst = sata_hba_inst->satahba_next) {
6976 		if (sata_hba_inst->satahba_dip == dip)
6977 			break;
6978 	}
6979 
6980 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
6981 #ifdef SATA_DEBUG
6982 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
6983 		    "unknown HBA instance\n");
6984 #endif
6985 		ASSERT(FALSE);
6986 	}
6987 	if (sata_hba_inst == sata_hba_list) {
6988 		sata_hba_list = sata_hba_inst->satahba_next;
6989 		if (sata_hba_list) {
6990 			sata_hba_list->satahba_prev =
6991 			    (struct sata_hba_inst *)NULL;
6992 		}
6993 		if (sata_hba_inst == sata_hba_list_tail) {
6994 			sata_hba_list_tail = NULL;
6995 		}
6996 	} else if (sata_hba_inst == sata_hba_list_tail) {
6997 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
6998 		if (sata_hba_list_tail) {
6999 			sata_hba_list_tail->satahba_next =
7000 			    (struct sata_hba_inst *)NULL;
7001 		}
7002 	} else {
7003 		sata_hba_inst->satahba_prev->satahba_next =
7004 		    sata_hba_inst->satahba_next;
7005 		sata_hba_inst->satahba_next->satahba_prev =
7006 		    sata_hba_inst->satahba_prev;
7007 	}
7008 	mutex_exit(&sata_mutex);
7009 }
7010 
7011 
7012 
7013 
7014 
7015 /*
7016  * Probe all SATA ports of the specified HBA instance.
7017  * This function is called only from sata_hba_attach(). It does not have to
7018  * be protected by controller mutex, because the hba_attached flag is not set
7019  * yet and no one would be touching this HBA instance other then this thread.
7020  * Determines if port is active and what type of the device is attached
7021  * (if any). Allocates necessary structures for each port.
7022  * Creates attachment point minor node for each non-failed port.
7023  */
7024 
7025 static 	void
7026 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
7027 {
7028 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
7029 	int			ncport, npmport;
7030 	sata_cport_info_t 	*cportinfo;
7031 	sata_drive_info_t	*drive;
7032 	sata_pmult_info_t	*pminfo;
7033 	sata_pmport_info_t 	*pmportinfo;
7034 	sata_device_t		sata_device;
7035 	int			rval;
7036 	dev_t			minor_number;
7037 	char			name[16];
7038 
7039 	/*
7040 	 * Probe controller ports first, to find port status and
7041 	 * any port multiplier attached.
7042 	 */
7043 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
7044 		/* allocate cport structure */
7045 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
7046 		ASSERT(cportinfo != NULL);
7047 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
7048 
7049 		mutex_enter(&cportinfo->cport_mutex);
7050 
7051 		cportinfo->cport_addr.cport = ncport;
7052 		cportinfo->cport_addr.pmport = 0;
7053 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
7054 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
7055 		cportinfo->cport_state |= SATA_STATE_PROBING;
7056 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
7057 
7058 		/*
7059 		 * Regardless if a port is usable or not, create
7060 		 * an attachment point
7061 		 */
7062 		mutex_exit(&cportinfo->cport_mutex);
7063 		minor_number =
7064 		    SATA_MAKE_AP_MINOR(ddi_get_instance(dip), ncport, 0, 0);
7065 		(void) sprintf(name, "%d", ncport);
7066 		if (ddi_create_minor_node(dip, name, S_IFCHR,
7067 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
7068 		    DDI_SUCCESS) {
7069 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
7070 			    "cannot create sata attachment point for port %d",
7071 			    ncport);
7072 		}
7073 
7074 		/* Probe port */
7075 		sata_device.satadev_addr.cport = ncport;
7076 		sata_device.satadev_addr.pmport = 0;
7077 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
7078 		sata_device.satadev_rev = SATA_DEVICE_REV;
7079 
7080 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
7081 		    (dip, &sata_device);
7082 
7083 		mutex_enter(&cportinfo->cport_mutex);
7084 		sata_update_port_scr(&cportinfo->cport_scr, &sata_device);
7085 		if (rval != SATA_SUCCESS) {
7086 			/* Something went wrong? Fail the port */
7087 			cportinfo->cport_state = SATA_PSTATE_FAILED;
7088 			mutex_exit(&cportinfo->cport_mutex);
7089 			continue;
7090 		}
7091 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
7092 		cportinfo->cport_state |= SATA_STATE_PROBED;
7093 		cportinfo->cport_dev_type = sata_device.satadev_type;
7094 
7095 		cportinfo->cport_state |= SATA_STATE_READY;
7096 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
7097 			mutex_exit(&cportinfo->cport_mutex);
7098 			continue;
7099 		}
7100 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
7101 			/*
7102 			 * There is some device attached.
7103 			 * Allocate device info structure
7104 			 */
7105 			mutex_exit(&cportinfo->cport_mutex);
7106 			drive = kmem_zalloc(sizeof (sata_drive_info_t),
7107 			    KM_SLEEP);
7108 			mutex_enter(&cportinfo->cport_mutex);
7109 			SATA_CPORTINFO_DRV_INFO(cportinfo) = drive;
7110 			drive->satadrv_addr = cportinfo->cport_addr;
7111 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
7112 			drive->satadrv_type = cportinfo->cport_dev_type;
7113 			drive->satadrv_state = SATA_STATE_UNKNOWN;
7114 		} else {
7115 			ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
7116 			mutex_exit(&cportinfo->cport_mutex);
7117 			pminfo = kmem_zalloc(sizeof (sata_pmult_info_t),
7118 			    KM_SLEEP);
7119 			mutex_enter(&cportinfo->cport_mutex);
7120 			ASSERT(pminfo != NULL);
7121 			SATA_CPORTINFO_PMULT_INFO(cportinfo) = pminfo;
7122 			pminfo->pmult_addr.cport = cportinfo->cport_addr.cport;
7123 			pminfo->pmult_addr.pmport = SATA_PMULT_HOSTPORT;
7124 			pminfo->pmult_addr.qual = SATA_ADDR_PMPORT;
7125 			pminfo->pmult_num_dev_ports =
7126 			    sata_device.satadev_add_info;
7127 			mutex_init(&pminfo->pmult_mutex, NULL, MUTEX_DRIVER,
7128 			    NULL);
7129 			pminfo->pmult_state = SATA_STATE_PROBING;
7130 
7131 			/* Probe Port Multiplier ports */
7132 			for (npmport = 0;
7133 			    npmport < pminfo->pmult_num_dev_ports;
7134 			    npmport++) {
7135 				mutex_exit(&cportinfo->cport_mutex);
7136 				pmportinfo = kmem_zalloc(
7137 				    sizeof (sata_pmport_info_t), KM_SLEEP);
7138 				mutex_enter(&cportinfo->cport_mutex);
7139 				ASSERT(pmportinfo != NULL);
7140 				pmportinfo->pmport_addr.cport = ncport;
7141 				pmportinfo->pmport_addr.pmport = npmport;
7142 				pmportinfo->pmport_addr.qual =
7143 				    SATA_ADDR_PMPORT;
7144 				pminfo->pmult_dev_port[npmport] = pmportinfo;
7145 				mutex_init(&pmportinfo->pmport_mutex, NULL,
7146 				    MUTEX_DRIVER, NULL);
7147 
7148 				sata_device.satadev_addr.pmport = npmport;
7149 				sata_device.satadev_addr.qual =
7150 				    SATA_ADDR_PMPORT;
7151 
7152 				mutex_exit(&cportinfo->cport_mutex);
7153 				/* Create an attachment point */
7154 				minor_number = SATA_MAKE_AP_MINOR(
7155 				    ddi_get_instance(dip), ncport, npmport, 1);
7156 				(void) sprintf(name, "%d.%d", ncport, npmport);
7157 				if (ddi_create_minor_node(dip, name, S_IFCHR,
7158 				    minor_number, DDI_NT_SATA_ATTACHMENT_POINT,
7159 				    0) != DDI_SUCCESS) {
7160 					sata_log(sata_hba_inst, CE_WARN,
7161 					    "sata_hba_attach: "
7162 					    "cannot create sata attachment "
7163 					    "point for port %d pmult port %d",
7164 					    ncport, npmport);
7165 				}
7166 				rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
7167 				    (dip, &sata_device);
7168 				mutex_enter(&cportinfo->cport_mutex);
7169 
7170 				/* sata_update_port_info() */
7171 				sata_update_port_scr(&pmportinfo->pmport_scr,
7172 				    &sata_device);
7173 
7174 				if (rval != SATA_SUCCESS) {
7175 					pmportinfo->pmport_state =
7176 					    SATA_PSTATE_FAILED;
7177 					continue;
7178 				}
7179 				pmportinfo->pmport_state &=
7180 				    ~SATA_STATE_PROBING;
7181 				pmportinfo->pmport_state |= SATA_STATE_PROBED;
7182 				pmportinfo->pmport_dev_type =
7183 				    sata_device.satadev_type;
7184 
7185 				pmportinfo->pmport_state |= SATA_STATE_READY;
7186 				if (pmportinfo->pmport_dev_type ==
7187 				    SATA_DTYPE_NONE)
7188 					continue;
7189 
7190 				/* Port multipliers cannot be chained */
7191 				ASSERT(pmportinfo->pmport_dev_type !=
7192 				    SATA_DTYPE_PMULT);
7193 				/*
7194 				 * There is something attached to Port
7195 				 * Multiplier device port
7196 				 * Allocate device info structure
7197 				 */
7198 				mutex_exit(&cportinfo->cport_mutex);
7199 				drive = kmem_zalloc(
7200 				    sizeof (sata_drive_info_t), KM_SLEEP);
7201 				rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
7202 				    (dip, &sata_device);
7203 				mutex_enter(&cportinfo->cport_mutex);
7204 
7205 				/* sata_update_port_info() */
7206 				sata_update_port_scr(&pmportinfo->pmport_scr,
7207 				    &sata_device);
7208 
7209 				pmportinfo->pmport_sata_drive = drive;
7210 				drive->satadrv_addr.cport =
7211 				    pmportinfo->pmport_addr.cport;
7212 				drive->satadrv_addr.pmport = npmport;
7213 				drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
7214 				drive->satadrv_type = pmportinfo->
7215 				    pmport_dev_type;
7216 				drive->satadrv_state = SATA_STATE_UNKNOWN;
7217 			}
7218 			pmportinfo->pmport_state =
7219 			    SATA_STATE_PROBED | SATA_STATE_READY;
7220 		}
7221 		mutex_exit(&cportinfo->cport_mutex);
7222 	}
7223 }
7224 
7225 
7226 
7227 /*
7228  * Create SATA device nodes for specified HBA instance (SCSI target
7229  * device nodes).
7230  * This function is called only from sata_hba_attach(). The hba_attached flag
7231  * is not set yet, so no ports or device data structures would be touched
7232  * by anyone other then this thread, therefore per-port mutex protection is
7233  * not needed.
7234  * The assumption is that there are no target and attachment point minor nodes
7235  * created by the boot subsystems, so we do not need to prune device tree.
7236  * An AP (Attachement Point) node is created for each SATA device port even
7237  * when there is no device attached.
7238  * A target node is created when there is a supported type of device attached,
7239  * but may be removed if it cannot be put online.
7240  *
7241  * This function cannot be called from an interrupt context.
7242  *
7243  * ONLY DISK TARGET NODES ARE CREATED NOW
7244  */
7245 static 	void
7246 sata_make_device_nodes(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst)
7247 {
7248 	int			ncport, npmport;
7249 	sata_cport_info_t 	*cportinfo;
7250 	sata_pmult_info_t	*pminfo;
7251 	sata_pmport_info_t	*pmportinfo;
7252 	dev_info_t		*cdip;		/* child dip */
7253 	sata_device_t		sata_device;
7254 	int			rval;
7255 
7256 	/*
7257 	 * Walk through pre-probed sata ports info in sata_hba_inst structure
7258 	 */
7259 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
7260 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
7261 		mutex_enter(&cportinfo->cport_mutex);
7262 		if (!(cportinfo->cport_state & SATA_STATE_PROBED)) {
7263 			mutex_exit(&cportinfo->cport_mutex);
7264 			continue;
7265 		}
7266 		if (cportinfo->cport_state == SATA_PSTATE_FAILED) {
7267 			mutex_exit(&cportinfo->cport_mutex);
7268 			continue;
7269 		}
7270 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
7271 			/* No device attached to the controller port */
7272 			mutex_exit(&cportinfo->cport_mutex);
7273 			continue;
7274 		}
7275 		/*
7276 		 * Some device is attached to a controller port.
7277 		 * We rely on controllers distinquishing between no-device,
7278 		 * attached port multiplier and other kind of attached device.
7279 		 * We need to get Identify Device data and determine
7280 		 * positively the dev type before trying to attach
7281 		 * the target driver.
7282 		 */
7283 		sata_device.satadev_rev = SATA_DEVICE_REV;
7284 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
7285 			/*
7286 			 * Not port multiplier.
7287 			 */
7288 			sata_device.satadev_addr = cportinfo->cport_addr;
7289 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
7290 			mutex_exit(&cportinfo->cport_mutex);
7291 			rval = sata_probe_device(sata_hba_inst, &sata_device);
7292 			if (rval != SATA_SUCCESS ||
7293 			    sata_device.satadev_type == SATA_DTYPE_UNKNOWN)
7294 				continue;
7295 
7296 			mutex_enter(&cportinfo->cport_mutex);
7297 			if ((sata_device.satadev_type &
7298 			    SATA_VALID_DEV_TYPE) == 0) {
7299 				/*
7300 				 * Could not determine device type or
7301 				 * a device is not supported.
7302 				 * Degrade this device to unknown.
7303 				 */
7304 				cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
7305 				mutex_exit(&cportinfo->cport_mutex);
7306 				continue;
7307 			}
7308 			cportinfo->cport_dev_type = sata_device.satadev_type;
7309 			mutex_exit(&cportinfo->cport_mutex);
7310 
7311 			if (sata_initialize_device(sata_hba_inst,
7312 			    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS)
7313 				/* Retry */
7314 				(void) sata_initialize_device(sata_hba_inst,
7315 				    SATA_CPORTINFO_DRV_INFO(cportinfo));
7316 
7317 			mutex_enter(&cportinfo->cport_mutex);
7318 			sata_show_drive_info(sata_hba_inst,
7319 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
7320 			mutex_exit(&cportinfo->cport_mutex);
7321 			cdip = sata_create_target_node(pdip, sata_hba_inst,
7322 			    &sata_device.satadev_addr);
7323 			mutex_enter(&cportinfo->cport_mutex);
7324 			if (cdip == NULL) {
7325 				/*
7326 				 * Attaching target node failed.
7327 				 * We retain sata_drive_info structure...
7328 				 */
7329 				(SATA_CPORTINFO_DRV_INFO(cportinfo))->
7330 				    satadrv_type = SATA_DTYPE_UNKNOWN;
7331 				(SATA_CPORTINFO_DRV_INFO(cportinfo))->
7332 				    satadrv_state = SATA_STATE_UNKNOWN;
7333 				cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
7334 				mutex_exit(&cportinfo->cport_mutex);
7335 				continue;
7336 			}
7337 			(SATA_CPORTINFO_DRV_INFO(cportinfo))->
7338 			    satadrv_state = SATA_STATE_READY;
7339 		} else {
7340 			/* This must be Port Multiplier type */
7341 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
7342 				SATA_LOG_D((sata_hba_inst, CE_WARN,
7343 				    "sata_make_device_nodes: "
7344 				    "unknown dev type %x",
7345 				    cportinfo->cport_dev_type));
7346 				mutex_exit(&cportinfo->cport_mutex);
7347 				continue;
7348 			}
7349 			pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
7350 			for (npmport = 0;
7351 			    npmport < pminfo->pmult_num_dev_ports;
7352 			    npmport++) {
7353 				pmportinfo = pminfo->pmult_dev_port[npmport];
7354 				if (pmportinfo->pmport_state &
7355 				    SATA_PSTATE_FAILED) {
7356 					continue;
7357 				}
7358 				if (pmportinfo->pmport_dev_type &
7359 				    SATA_DTYPE_NONE)
7360 					/* No device attached */
7361 					continue;
7362 
7363 				sata_device.satadev_addr =
7364 				    pmportinfo->pmport_addr;
7365 				sata_device.satadev_addr.qual =
7366 				    SATA_ADDR_DPMPORT;
7367 				mutex_exit(&cportinfo->cport_mutex);
7368 				rval = sata_probe_device(sata_hba_inst,
7369 				    &sata_device);
7370 				if (rval != SATA_SUCCESS ||
7371 				    sata_device.satadev_type ==
7372 				    SATA_DTYPE_UNKNOWN) {
7373 					mutex_enter(&cportinfo->cport_mutex);
7374 					continue;
7375 				}
7376 				mutex_enter(&cportinfo->cport_mutex);
7377 				if ((sata_device.satadev_type &
7378 				    SATA_VALID_DEV_TYPE) == 0) {
7379 					/*
7380 					 * Could not determine device type.
7381 					 * Degrade this device to unknown.
7382 					 */
7383 					pmportinfo->pmport_dev_type =
7384 					    SATA_DTYPE_UNKNOWN;
7385 					continue;
7386 				}
7387 				pmportinfo->pmport_dev_type =
7388 				    sata_device.satadev_type;
7389 				mutex_exit(&cportinfo->cport_mutex);
7390 				if (sata_initialize_device(sata_hba_inst,
7391 				    pmportinfo->pmport_sata_drive) !=
7392 				    SATA_SUCCESS)
7393 					/* Retry */
7394 					(void) sata_initialize_device(
7395 					    sata_hba_inst,
7396 					    pmportinfo->pmport_sata_drive);
7397 
7398 				mutex_enter(&cportinfo->cport_mutex);
7399 				sata_show_drive_info(sata_hba_inst,
7400 				    pmportinfo->pmport_sata_drive);
7401 				mutex_exit(&cportinfo->cport_mutex);
7402 				cdip = sata_create_target_node(pdip,
7403 				    sata_hba_inst, &sata_device.satadev_addr);
7404 				mutex_enter(&cportinfo->cport_mutex);
7405 				if (cdip == NULL) {
7406 					/*
7407 					 * Attaching target node failed.
7408 					 * We retain sata_drive_info
7409 					 * structure...
7410 					 */
7411 					pmportinfo->pmport_sata_drive->
7412 					    satadrv_type = SATA_DTYPE_UNKNOWN;
7413 					pmportinfo->pmport_sata_drive->
7414 					    satadrv_state = SATA_STATE_UNKNOWN;
7415 					pmportinfo->pmport_dev_type =
7416 					    SATA_DTYPE_UNKNOWN;
7417 					continue;
7418 				}
7419 				pmportinfo->pmport_sata_drive->
7420 				    satadrv_state |= SATA_STATE_READY;
7421 			}
7422 		}
7423 		mutex_exit(&cportinfo->cport_mutex);
7424 	}
7425 }
7426 
7427 
7428 
7429 /*
7430  * Create scsi target node for attached device, create node properties and
7431  * attach the node.
7432  * The node could be removed if the device onlining fails.
7433  *
7434  * A dev_info_t pointer is returned if operation is successful, NULL is
7435  * returned otherwise.
7436  */
7437 
7438 static dev_info_t *
7439 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
7440 			sata_address_t *sata_addr)
7441 {
7442 	dev_info_t *cdip = NULL;
7443 	int rval;
7444 	char *nname = NULL;
7445 	char **compatible = NULL;
7446 	int ncompatible;
7447 	struct scsi_inquiry inq;
7448 	sata_device_t sata_device;
7449 	sata_drive_info_t *sdinfo;
7450 	int target;
7451 	int i;
7452 
7453 	sata_device.satadev_rev = SATA_DEVICE_REV;
7454 	sata_device.satadev_addr = *sata_addr;
7455 
7456 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
7457 
7458 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
7459 
7460 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
7461 	    sata_addr->pmport, sata_addr->qual);
7462 
7463 	if (sdinfo == NULL) {
7464 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
7465 		    sata_addr->cport)));
7466 		SATA_LOG_D((sata_hba_inst, CE_WARN,
7467 		    "sata_create_target_node: no sdinfo for target %x",
7468 		    target));
7469 		return (NULL);
7470 	}
7471 
7472 	/*
7473 	 * create scsi inquiry data, expected by
7474 	 * scsi_hba_nodename_compatible_get()
7475 	 */
7476 	sata_identdev_to_inquiry(sata_hba_inst, sdinfo, (uint8_t *)&inq);
7477 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
7478 
7479 	/* determine the node name and compatible */
7480 	scsi_hba_nodename_compatible_get(&inq, NULL,
7481 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
7482 
7483 #ifdef SATA_DEBUG
7484 	if (sata_debug_flags & SATA_DBG_NODES) {
7485 		if (nname == NULL) {
7486 			cmn_err(CE_NOTE, "sata_create_target_node: "
7487 			    "cannot determine nodename for target %d\n",
7488 			    target);
7489 		} else {
7490 			cmn_err(CE_WARN, "sata_create_target_node: "
7491 			    "target %d nodename: %s\n", target, nname);
7492 		}
7493 		if (compatible == NULL) {
7494 			cmn_err(CE_WARN,
7495 			    "sata_create_target_node: no compatible name\n");
7496 		} else {
7497 			for (i = 0; i < ncompatible; i++) {
7498 				cmn_err(CE_WARN, "sata_create_target_node: "
7499 				    "compatible name: %s\n", compatible[i]);
7500 			}
7501 		}
7502 	}
7503 #endif
7504 
7505 	/* if nodename can't be determined, log error and exit */
7506 	if (nname == NULL) {
7507 		SATA_LOG_D((sata_hba_inst, CE_WARN,
7508 		    "sata_create_target_node: cannot determine nodename "
7509 		    "for target %d\n", target));
7510 		scsi_hba_nodename_compatible_free(nname, compatible);
7511 		return (NULL);
7512 	}
7513 	/*
7514 	 * Create scsi target node
7515 	 */
7516 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
7517 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
7518 	    "device-type", "scsi");
7519 
7520 	if (rval != DDI_PROP_SUCCESS) {
7521 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
7522 		    "updating device_type prop failed %d", rval));
7523 		goto fail;
7524 	}
7525 
7526 	/*
7527 	 * Create target node properties: target & lun
7528 	 */
7529 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
7530 	if (rval != DDI_PROP_SUCCESS) {
7531 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
7532 		    "updating target prop failed %d", rval));
7533 		goto fail;
7534 	}
7535 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
7536 	if (rval != DDI_PROP_SUCCESS) {
7537 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
7538 		    "updating target prop failed %d", rval));
7539 		goto fail;
7540 	}
7541 
7542 	/* decorate the node with compatible */
7543 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
7544 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
7545 		SATA_LOG_D((sata_hba_inst, CE_WARN,
7546 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
7547 		    (void *)cdip));
7548 		goto fail;
7549 	}
7550 
7551 	/*
7552 	 * Set default write cache mode
7553 	 */
7554 	rval = sata_init_write_cache_mode(sata_hba_inst, sdinfo);
7555 	if (rval != SATA_SUCCESS) {
7556 		sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
7557 		    "cannot set deafult write cache mode for "
7558 		    "device at port %d", sata_addr->cport);
7559 	}
7560 
7561 	/*
7562 	 * Now, try to attach the driver. If probing of the device fails,
7563 	 * the target node may be removed
7564 	 */
7565 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
7566 
7567 	scsi_hba_nodename_compatible_free(nname, compatible);
7568 
7569 	if (rval == NDI_SUCCESS)
7570 		return (cdip);
7571 
7572 	/* target node was removed - are we sure? */
7573 	return (NULL);
7574 
7575 fail:
7576 	scsi_hba_nodename_compatible_free(nname, compatible);
7577 	ddi_prop_remove_all(cdip);
7578 	rval = ndi_devi_free(cdip);
7579 	if (rval != NDI_SUCCESS) {
7580 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
7581 		    "node removal failed %d", rval));
7582 	}
7583 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
7584 	    "cannot create target node for device at port %d",
7585 	    sata_addr->cport);
7586 	return (NULL);
7587 }
7588 
7589 
7590 
7591 /*
7592  * Re-probe sata port, check for a device and attach necessary info
7593  * structures when necessary. Identify Device data is fetched, if possible.
7594  * Assumption: sata address is already validated.
7595  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
7596  * the presence of a device and its type.
7597  * SATA_FAILURE is returned if one of the operations failed.
7598  */
7599 static int
7600 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
7601 {
7602 	sata_cport_info_t *cportinfo;
7603 	sata_drive_info_t *sdinfo;
7604 	boolean_t init_device = B_FALSE;
7605 	int rval;
7606 
7607 	/* We only care about host sata cport for now */
7608 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
7609 	    sata_device->satadev_addr.cport);
7610 	/* probe port */
7611 	mutex_enter(&cportinfo->cport_mutex);
7612 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
7613 	cportinfo->cport_state |= SATA_STATE_PROBING;
7614 	mutex_exit(&cportinfo->cport_mutex);
7615 
7616 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
7617 	    (SATA_DIP(sata_hba_inst), sata_device);
7618 
7619 	mutex_enter(&cportinfo->cport_mutex);
7620 	if (rval != SATA_SUCCESS) {
7621 		cportinfo->cport_state = SATA_PSTATE_FAILED;
7622 		mutex_exit(&cportinfo->cport_mutex);
7623 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_hba_ioctl: "
7624 		    "connect: port probbing failed"));
7625 		return (SATA_FAILURE);
7626 	}
7627 
7628 	/*
7629 	 * update sata port state and set device type
7630 	 */
7631 	sata_update_port_info(sata_hba_inst, sata_device);
7632 	cportinfo->cport_state |= SATA_STATE_PROBED;
7633 
7634 	/*
7635 	 * Sanity check - Port is active? Is the link active?
7636 	 * Is there any device attached?
7637 	 */
7638 	if ((cportinfo->cport_state &
7639 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
7640 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
7641 	    SATA_PORT_DEVLINK_UP) {
7642 		/*
7643 		 * Port in non-usable state or no link active/no device.
7644 		 * Free info structure if necessary (direct attached drive
7645 		 * only, for now!
7646 		 */
7647 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
7648 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
7649 		/* Add here differentiation for device attached or not */
7650 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
7651 		mutex_exit(&cportinfo->cport_mutex);
7652 		if (sdinfo != NULL)
7653 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
7654 		return (SATA_SUCCESS);
7655 	}
7656 
7657 	cportinfo->cport_state |= SATA_STATE_READY;
7658 	cportinfo->cport_dev_type = sata_device->satadev_type;
7659 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
7660 
7661 	/*
7662 	 * If we are re-probing the port, there may be
7663 	 * sata_drive_info structure attached
7664 	 * (or sata_pm_info, if PMult is supported).
7665 	 */
7666 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
7667 		/*
7668 		 * There is no device, so remove device info structure,
7669 		 * if necessary. Direct attached drive only!
7670 		 */
7671 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
7672 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
7673 		if (sdinfo != NULL) {
7674 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
7675 			sata_log(sata_hba_inst, CE_WARN,
7676 			    "SATA device detached "
7677 			    "from port %d", cportinfo->cport_addr.cport);
7678 		}
7679 		mutex_exit(&cportinfo->cport_mutex);
7680 		return (SATA_SUCCESS);
7681 	}
7682 
7683 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
7684 		if (sdinfo == NULL) {
7685 			/*
7686 			 * There is some device attached, but there is
7687 			 * no sata_drive_info structure - allocate one
7688 			 */
7689 			mutex_exit(&cportinfo->cport_mutex);
7690 			sdinfo = kmem_zalloc(
7691 			    sizeof (sata_drive_info_t), KM_SLEEP);
7692 			mutex_enter(&cportinfo->cport_mutex);
7693 			/*
7694 			 * Recheck, if port state did not change when we
7695 			 * released mutex.
7696 			 */
7697 			if (cportinfo->cport_state & SATA_STATE_READY) {
7698 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
7699 				sdinfo->satadrv_addr = cportinfo->cport_addr;
7700 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
7701 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
7702 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
7703 			} else {
7704 				/*
7705 				 * Port is not in ready state, we
7706 				 * cannot attach a device.
7707 				 */
7708 				mutex_exit(&cportinfo->cport_mutex);
7709 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
7710 				return (SATA_SUCCESS);
7711 			}
7712 			/*
7713 			 * Since we are adding device, presumably new one,
7714 			 * indicate that it  should be initalized,
7715 			 * as well as some internal framework states).
7716 			 */
7717 			init_device = B_TRUE;
7718 		}
7719 
7720 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
7721 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
7722 	} else {
7723 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
7724 		mutex_exit(&cportinfo->cport_mutex);
7725 		return (SATA_SUCCESS);
7726 	}
7727 	mutex_exit(&cportinfo->cport_mutex);
7728 	/*
7729 	 * Figure out what kind of device we are really
7730 	 * dealing with.
7731 	 */
7732 	rval = sata_probe_device(sata_hba_inst, sata_device);
7733 
7734 	/* Set initial device features, if necessary */
7735 	if (rval == SATA_SUCCESS && init_device == B_TRUE) {
7736 		if (sata_initialize_device(sata_hba_inst, sdinfo) !=
7737 		    SATA_SUCCESS)
7738 			/* retry */
7739 			(void) sata_initialize_device(sata_hba_inst, sdinfo);
7740 	}
7741 	return (rval);
7742 }
7743 
7744 /*
7745  * Initialize device
7746  * Specified device is initialized to a default state.
7747  * At this point only read cache and UDMA modes are set here.
7748  * Write cache mode should be set when a disk is configured.
7749  *
7750  * Only SATA disks are initialized for now.
7751  *
7752  * Returns SATA_SUCCESS if all device features are set successfully,
7753  * SATA_FAILURE otherwise
7754  */
7755 static int
7756 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
7757     sata_drive_info_t *sdinfo)
7758 {
7759 
7760 	sata_save_drive_settings(sdinfo);
7761 
7762 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
7763 
7764 	return (sata_set_drive_features(sata_hba_inst, sdinfo, 0));
7765 }
7766 
7767 
7768 /*
7769  * Initialize write cache mode.
7770  *
7771  * The default write cache setting is provided by sata_write_cache
7772  * static variable:
7773  * 1 - enable
7774  * 0 - disable
7775  * any other value - current drive setting
7776  *
7777  * In the future, it may be overridden by the
7778  * disk-write-cache-enable property setting, if it is defined.
7779  * Returns SATA_SUCCESS if all device features are set successfully,
7780  * SATA_FAILURE otherwise.
7781  */
7782 static int
7783 sata_init_write_cache_mode(sata_hba_inst_t *sata_hba_inst,
7784     sata_drive_info_t *sdinfo)
7785 {
7786 	if (sata_write_cache == 1)
7787 		sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
7788 	else if (sata_write_cache == 0)
7789 		sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
7790 	/*
7791 	 * When sata_write_cache value is not 0 or 1,
7792 	 * a current setting of the drive's write cache is used.
7793 	 *
7794 	 * Now set the write cache mode
7795 	 */
7796 	return (sata_set_drive_features(sata_hba_inst, sdinfo, 0));
7797 }
7798 
7799 
7800 /*
7801  * Validate sata address.
7802  * Specified cport, pmport and qualifier has to match
7803  * passed sata_scsi configuration info.
7804  * The presence of an attached device is not verified.
7805  *
7806  * Returns 0 when address is valid, -1 otherwise.
7807  */
7808 static int
7809 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
7810 	int pmport, int qual)
7811 {
7812 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
7813 		goto invalid_address;
7814 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
7815 		goto invalid_address;
7816 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
7817 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
7818 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
7819 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
7820 		goto invalid_address;
7821 
7822 	return (0);
7823 
7824 invalid_address:
7825 	return (-1);
7826 
7827 }
7828 
7829 /*
7830  * Validate scsi address
7831  * SCSI target address is translated into SATA cport/pmport and compared
7832  * with a controller port/device configuration. LUN has to be 0.
7833  * Returns 0 if a scsi target refers to an attached device,
7834  * returns 1 if address is valid but device is not attached,
7835  * returns -1 if bad address or device is of an unsupported type.
7836  * Upon return sata_device argument is set.
7837  */
7838 static int
7839 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
7840 	struct scsi_address *ap, sata_device_t *sata_device)
7841 {
7842 	int cport, pmport, qual, rval;
7843 
7844 	rval = -1;	/* Invalid address */
7845 	if (ap->a_lun != 0)
7846 		goto out;
7847 
7848 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
7849 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
7850 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
7851 
7852 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
7853 		goto out;
7854 
7855 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
7856 	    0) {
7857 
7858 		sata_cport_info_t *cportinfo;
7859 		sata_pmult_info_t *pmultinfo;
7860 		sata_drive_info_t *sdinfo = NULL;
7861 
7862 		rval = 1;	/* Valid sata address */
7863 
7864 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
7865 		if (qual == SATA_ADDR_DCPORT) {
7866 			if (cportinfo == NULL ||
7867 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
7868 				goto out;
7869 
7870 			if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT ||
7871 			    (cportinfo->cport_dev_type &
7872 			    SATA_VALID_DEV_TYPE) == 0) {
7873 				rval = -1;
7874 				goto out;
7875 			}
7876 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
7877 
7878 		} else if (qual == SATA_ADDR_DPMPORT) {
7879 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
7880 			if (pmultinfo == NULL) {
7881 				rval = -1;
7882 				goto out;
7883 			}
7884 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
7885 			    NULL ||
7886 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
7887 			    pmport) == SATA_DTYPE_NONE)
7888 				goto out;
7889 
7890 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
7891 			    pmport);
7892 		} else {
7893 			rval = -1;
7894 			goto out;
7895 		}
7896 		if ((sdinfo == NULL) ||
7897 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
7898 			goto out;
7899 
7900 		sata_device->satadev_type = sdinfo->satadrv_type;
7901 		sata_device->satadev_addr.qual = qual;
7902 		sata_device->satadev_addr.cport = cport;
7903 		sata_device->satadev_addr.pmport = pmport;
7904 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
7905 		return (0);
7906 	}
7907 out:
7908 	if (rval == 1) {
7909 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
7910 		    "sata_validate_scsi_address: no valid target %x lun %x",
7911 		    ap->a_target, ap->a_lun);
7912 	}
7913 	return (rval);
7914 }
7915 
7916 /*
7917  * Find dip corresponding to passed device number
7918  *
7919  * Returns NULL if invalid device number is passed or device cannot be found,
7920  * Returns dip is device is found.
7921  */
7922 static dev_info_t *
7923 sata_devt_to_devinfo(dev_t dev)
7924 {
7925 	dev_info_t *dip;
7926 #ifndef __lock_lint
7927 	struct devnames *dnp;
7928 	major_t major = getmajor(dev);
7929 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
7930 
7931 	if (major >= devcnt)
7932 		return (NULL);
7933 
7934 	dnp = &devnamesp[major];
7935 	LOCK_DEV_OPS(&(dnp->dn_lock));
7936 	dip = dnp->dn_head;
7937 	while (dip && (ddi_get_instance(dip) != instance)) {
7938 		dip = ddi_get_next(dip);
7939 	}
7940 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
7941 #endif
7942 
7943 	return (dip);
7944 }
7945 
7946 
7947 /*
7948  * Probe device.
7949  * This function issues Identify Device command and initialize local
7950  * sata_drive_info structure if the device can be identified.
7951  * The device type is determined by examining Identify Device
7952  * command response.
7953  * If the sata_hba_inst has linked drive info structure for this
7954  * device address, the Identify Device data is stored into sata_drive_info
7955  * structure linked to the port info structure.
7956  *
7957  * sata_device has to refer to the valid sata port(s) for HBA described
7958  * by sata_hba_inst structure.
7959  *
7960  * Returns: SATA_SUCCESS if device type was successfully probed and port-linked
7961  *	drive info structure was updated;
7962  * 	SATA_FAILURE if there is no device, or device was not probed
7963  *	successully.
7964  * If a device cannot be identified, sata_device's dev_state and dev_type
7965  * fields are set to unknown.
7966  *
7967  */
7968 
7969 static int
7970 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
7971 {
7972 	sata_drive_info_t *sdinfo;
7973 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
7974 	int retry_cnt;
7975 
7976 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
7977 	    sata_device->satadev_addr.cport) &
7978 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
7979 
7980 	sata_device->satadev_type = SATA_DTYPE_NONE;
7981 
7982 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
7983 	    sata_device->satadev_addr.cport)));
7984 
7985 	/* Get pointer to port-linked sata device info structure */
7986 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
7987 	if (sdinfo != NULL) {
7988 		sdinfo->satadrv_state &=
7989 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
7990 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
7991 	} else {
7992 		/* No device to probe */
7993 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
7994 		    sata_device->satadev_addr.cport)));
7995 		sata_device->satadev_type = SATA_DTYPE_NONE;
7996 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
7997 		return (SATA_FAILURE);
7998 	}
7999 	/*
8000 	 * Need to issue both types of identify device command and
8001 	 * determine device type by examining retreived data/status.
8002 	 * First, ATA Identify Device.
8003 	 */
8004 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
8005 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
8006 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8007 	    sata_device->satadev_addr.cport)));
8008 	for (retry_cnt = 0; retry_cnt <= SATA_DEVICE_IDENTIFY_RETRY;
8009 	    retry_cnt++) {
8010 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
8011 		if (sata_identify_device(sata_hba_inst, &new_sdinfo) == 0) {
8012 			/* Got something responding to ATA Identify Device */
8013 			sata_device->satadev_type = new_sdinfo.satadrv_type;
8014 			break;
8015 		}
8016 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
8017 			/*
8018 			 * HBA supports ATAPI - try to issue Identify Packet
8019 			 * Device command.
8020 			 */
8021 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPICD;
8022 			if (sata_identify_device(sata_hba_inst,
8023 			    &new_sdinfo) == 0) {
8024 				/*
8025 				 * Got something responding to Identify Packet
8026 				 * Device cmd.
8027 				 */
8028 				/* Set UDMA mode here as well ? - phase 2 */
8029 				sata_device->satadev_type =
8030 				    new_sdinfo.satadrv_type;
8031 				break;
8032 			}
8033 		}
8034 	}
8035 	if (retry_cnt <= SATA_DEVICE_IDENTIFY_RETRY) {
8036 		/* save device info, if possible */
8037 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
8038 		    sata_device->satadev_addr.cport)));
8039 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
8040 		if (sdinfo == NULL) {
8041 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8042 			    sata_device->satadev_addr.cport)));
8043 			return (SATA_FAILURE);
8044 		}
8045 		/*
8046 		 * Copy drive info into the port-linked drive info structure.
8047 		 */
8048 		*sdinfo = new_sdinfo;
8049 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
8050 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
8051 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
8052 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
8053 			    sata_device->satadev_addr.cport) =
8054 			    sdinfo->satadrv_type;
8055 		else /* SATA_ADDR_DPMPORT */
8056 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
8057 			    sata_device->satadev_addr.cport,
8058 			    sata_device->satadev_addr.pmport) =
8059 			    sdinfo->satadrv_type;
8060 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8061 		    sata_device->satadev_addr.cport)));
8062 		return (SATA_SUCCESS);
8063 	}
8064 
8065 failure:
8066 	/*
8067 	 * Looks like we cannot determine the device type.
8068 	 */
8069 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
8070 	    sata_device->satadev_addr.cport)));
8071 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
8072 	if (sdinfo != NULL) {
8073 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
8074 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
8075 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
8076 		sdinfo->satadrv_state = SATA_STATE_PROBED;
8077 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
8078 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
8079 			    sata_device->satadev_addr.cport) =
8080 			    SATA_DTYPE_UNKNOWN;
8081 		else {
8082 			/* SATA_ADDR_DPMPORT */
8083 			if ((SATA_PMULT_INFO(sata_hba_inst,
8084 			    sata_device->satadev_addr.cport) != NULL) &&
8085 			    (SATA_PMPORT_INFO(sata_hba_inst,
8086 			    sata_device->satadev_addr.cport,
8087 			    sata_device->satadev_addr.pmport) != NULL))
8088 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
8089 				    sata_device->satadev_addr.cport,
8090 				    sata_device->satadev_addr.pmport) =
8091 				    SATA_DTYPE_UNKNOWN;
8092 		}
8093 	}
8094 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8095 	    sata_device->satadev_addr.cport)));
8096 	return (SATA_FAILURE);
8097 }
8098 
8099 
8100 /*
8101  * Get pointer to sata_drive_info structure.
8102  *
8103  * The sata_device has to contain address (cport, pmport and qualifier) for
8104  * specified sata_scsi structure.
8105  *
8106  * Returns NULL if device address is not valid for this HBA configuration.
8107  * Otherwise, returns a pointer to sata_drive_info structure.
8108  *
8109  * This function should be called with a port mutex held.
8110  */
8111 static sata_drive_info_t *
8112 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
8113     sata_device_t *sata_device)
8114 {
8115 	uint8_t cport = sata_device->satadev_addr.cport;
8116 	uint8_t pmport = sata_device->satadev_addr.pmport;
8117 	uint8_t qual = sata_device->satadev_addr.qual;
8118 
8119 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
8120 		return (NULL);
8121 
8122 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
8123 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
8124 		/* Port not probed yet */
8125 		return (NULL);
8126 
8127 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
8128 		return (NULL);
8129 
8130 	if (qual == SATA_ADDR_DCPORT) {
8131 		/* Request for a device on a controller port */
8132 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
8133 		    SATA_DTYPE_PMULT)
8134 			/* Port multiplier attached */
8135 			return (NULL);
8136 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
8137 	}
8138 	if (qual == SATA_ADDR_DPMPORT) {
8139 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
8140 		    SATA_DTYPE_PMULT)
8141 			return (NULL);
8142 
8143 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
8144 			return (NULL);
8145 
8146 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
8147 	}
8148 
8149 	/* we should not get here */
8150 	return (NULL);
8151 }
8152 
8153 
8154 /*
8155  * sata_identify_device.
8156  * Send Identify Device command to SATA HBA driver.
8157  * If command executes successfully, update sata_drive_info structure pointed
8158  * to by sdinfo argument, including Identify Device data.
8159  * If command fails, invalidate data in sata_drive_info.
8160  *
8161  * Cannot be called from interrupt level.
8162  *
8163  * Returns 0 if device was identified as supported device, -1 otherwise.
8164  */
8165 static int
8166 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
8167     sata_drive_info_t *sdinfo)
8168 {
8169 	uint16_t cfg_word;
8170 	int i;
8171 
8172 	/* fetch device identify data */
8173 	if (sata_fetch_device_identify_data(sata_hba_inst, sdinfo) != 0)
8174 		goto fail_unknown;
8175 
8176 	cfg_word = sdinfo->satadrv_id.ai_config;
8177 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK &&
8178 	    (cfg_word & SATA_ATA_TYPE_MASK) != SATA_ATA_TYPE) {
8179 		/* Change device type to reflect Identify Device data */
8180 		if (((cfg_word & SATA_ATAPI_TYPE_MASK) ==
8181 		    SATA_ATAPI_TYPE) &&
8182 		    ((cfg_word & SATA_ATAPI_ID_DEV_TYPE) ==
8183 		    SATA_ATAPI_CDROM_DEV)) {
8184 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
8185 		} else {
8186 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
8187 		}
8188 	} else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD &&
8189 	    (((cfg_word & SATA_ATAPI_TYPE_MASK) != SATA_ATAPI_TYPE) ||
8190 	    ((cfg_word & SATA_ATAPI_ID_DEV_TYPE) != SATA_ATAPI_CDROM_DEV))) {
8191 		/* Change device type to reflect Identify Device data ! */
8192 		if ((sdinfo->satadrv_id.ai_config & SATA_ATA_TYPE_MASK) ==
8193 		    SATA_ATA_TYPE) {
8194 			sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
8195 		} else {
8196 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
8197 		}
8198 	}
8199 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
8200 		if (sdinfo->satadrv_capacity == 0) {
8201 			/* Non-LBA disk. Too bad... */
8202 			sata_log(sata_hba_inst, CE_WARN,
8203 			    "SATA disk device at port %d does not support LBA",
8204 			    sdinfo->satadrv_addr.cport);
8205 			goto fail_unknown;
8206 		}
8207 	}
8208 	/* Check for Ultra DMA modes 6 through 0 being supported */
8209 	for (i = 6; i >= 0; --i) {
8210 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
8211 			break;
8212 	}
8213 	/*
8214 	 * At least UDMA 4 mode has to be supported. If mode 4 or
8215 	 * higher are not supported by the device, fail this
8216 	 * device.
8217 	 */
8218 	if (i < 4) {
8219 		/* No required Ultra DMA mode supported */
8220 		sata_log(sata_hba_inst, CE_WARN,
8221 		    "SATA disk device at port %d does not support UDMA "
8222 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
8223 		SATA_LOG_D((sata_hba_inst, CE_WARN,
8224 		    "mode 4 or higher required, %d supported", i));
8225 		goto fail_unknown;
8226 	}
8227 
8228 	return (0);
8229 
8230 fail_unknown:
8231 	/* Invalidate sata_drive_info ? */
8232 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
8233 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
8234 	return (-1);
8235 }
8236 
8237 /*
8238  * Log/display device information
8239  */
8240 static void
8241 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
8242     sata_drive_info_t *sdinfo)
8243 {
8244 	int valid_version;
8245 	char msg_buf[MAXPATHLEN];
8246 
8247 	/* Show HBA path */
8248 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
8249 
8250 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
8251 
8252 	if (sdinfo->satadrv_type == SATA_DTYPE_UNKNOWN) {
8253 		(void) sprintf(msg_buf,
8254 		    "Unsupported SATA device type (cfg 0x%x) at ",
8255 		    sdinfo->satadrv_id.ai_config);
8256 	} else {
8257 		(void) sprintf(msg_buf, "SATA %s device at",
8258 		    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
8259 		    "disk":"CD/DVD (ATAPI)");
8260 	}
8261 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
8262 		cmn_err(CE_CONT, "?\t%s port %d\n",
8263 		    msg_buf, sdinfo->satadrv_addr.cport);
8264 	else
8265 		cmn_err(CE_CONT, "?\t%s port %d pmport %d\n",
8266 		    msg_buf, sdinfo->satadrv_addr.cport,
8267 		    sdinfo->satadrv_addr.pmport);
8268 
8269 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
8270 	    sizeof (sdinfo->satadrv_id.ai_model));
8271 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
8272 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
8273 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
8274 
8275 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
8276 	    sizeof (sdinfo->satadrv_id.ai_fw));
8277 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
8278 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
8279 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
8280 
8281 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
8282 	    sizeof (sdinfo->satadrv_id.ai_drvser));
8283 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
8284 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
8285 	cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
8286 
8287 #ifdef SATA_DEBUG
8288 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
8289 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
8290 		int i;
8291 		for (i = 14; i >= 2; i--) {
8292 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
8293 				valid_version = i;
8294 				break;
8295 			}
8296 		}
8297 		cmn_err(CE_CONT,
8298 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
8299 		    valid_version,
8300 		    sdinfo->satadrv_id.ai_majorversion,
8301 		    sdinfo->satadrv_id.ai_minorversion);
8302 	}
8303 #endif
8304 	/* Log some info */
8305 	cmn_err(CE_CONT, "?\tsupported features:\n");
8306 	msg_buf[0] = '\0';
8307 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
8308 		(void) strlcat(msg_buf, "48-bit LBA", MAXPATHLEN);
8309 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
8310 		(void) strlcat(msg_buf, "28-bit LBA", MAXPATHLEN);
8311 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
8312 		(void) strlcat(msg_buf, ", DMA", MAXPATHLEN);
8313 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
8314 		(void) strlcat(msg_buf, ", Native Command Queueing",
8315 		    MAXPATHLEN);
8316 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
8317 		(void) strlcat(msg_buf, ", Queuing", MAXPATHLEN);
8318 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
8319 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
8320 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
8321 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
8322 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
8323 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
8324 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
8325 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
8326 		cmn_err(CE_CONT, "?\tSATA1 & SATA2 compatible\n");
8327 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
8328 		cmn_err(CE_CONT, "?\tSATA1 compatible\n");
8329 
8330 #ifdef __i386
8331 	(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
8332 		sdinfo->satadrv_capacity);
8333 #else
8334 	(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
8335 		sdinfo->satadrv_capacity);
8336 #endif
8337 	cmn_err(CE_CONT, "?%s", msg_buf);
8338 }
8339 
8340 
8341 /*
8342  * sata_save_drive_settings extracts current setting of the device and stores
8343  * it for future reference, in case the device setup would need to be restored
8344  * after the device reset.
8345  *
8346  * At the moment only read ahead and write cache settings are saved, if the
8347  * device supports these features at all.
8348  */
8349 static void
8350 sata_save_drive_settings(sata_drive_info_t *sdinfo)
8351 {
8352 	if (!(sdinfo->satadrv_id.ai_cmdset82 & SATA_LOOK_AHEAD) &&
8353 	    !(sdinfo->satadrv_id.ai_cmdset82 & SATA_WRITE_CACHE)) {
8354 		/* None of the features is supported - do nothing */
8355 		return;
8356 	}
8357 
8358 	/* Current setting of Read Ahead (and Read Cache) */
8359 	if (sdinfo->satadrv_id.ai_features85 & SATA_LOOK_AHEAD)
8360 		sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
8361 	else
8362 		sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
8363 
8364 	/* Current setting of Write Cache */
8365 	if (sdinfo->satadrv_id.ai_features85 & SATA_WRITE_CACHE)
8366 		sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
8367 	else
8368 		sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
8369 }
8370 
8371 
8372 /*
8373  * sata_check_capacity function determines a disk capacity
8374  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
8375  *
8376  * NOTE: CHS mode is not supported! If a device does not support LBA,
8377  * this function is not called.
8378  *
8379  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
8380  */
8381 static uint64_t
8382 sata_check_capacity(sata_drive_info_t *sdinfo)
8383 {
8384 	uint64_t capacity = 0;
8385 	int i;
8386 
8387 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
8388 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
8389 		/* Capacity valid only for LBA-addressable disk devices */
8390 		return (0);
8391 
8392 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
8393 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
8394 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
8395 		/* LBA48 mode supported and enabled */
8396 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
8397 		    SATA_DEV_F_LBA28;
8398 		for (i = 3;  i >= 0;  --i) {
8399 			capacity <<= 16;
8400 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
8401 		}
8402 	} else {
8403 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
8404 		capacity <<= 16;
8405 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
8406 		if (capacity >= 0x1000000)
8407 			/* LBA28 mode */
8408 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
8409 	}
8410 	return (capacity);
8411 }
8412 
8413 
8414 /*
8415  * Allocate consistent buffer for DMA transfer
8416  *
8417  * Cannot be called from interrupt level or with mutex held - it may sleep.
8418  *
8419  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
8420  */
8421 static struct buf *
8422 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
8423 {
8424 	struct scsi_address ap;
8425 	struct buf *bp;
8426 	ddi_dma_attr_t	cur_dma_attr;
8427 
8428 	ASSERT(spx->txlt_sata_pkt != NULL);
8429 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
8430 	ap.a_target = SATA_TO_SCSI_TARGET(
8431 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
8432 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
8433 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
8434 	ap.a_lun = 0;
8435 
8436 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
8437 		B_READ, SLEEP_FUNC, NULL);
8438 
8439 	if (bp != NULL) {
8440 		/* Allocate DMA resources for this buffer */
8441 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
8442 		/*
8443 		 * We use a local version of the dma_attr, to account
8444 		 * for a device addressing limitations.
8445 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
8446 		 * will cause dma attributes to be adjusted to a lowest
8447 		 * acceptable level.
8448 		 */
8449 		sata_adjust_dma_attr(NULL,
8450 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
8451 
8452 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
8453 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
8454 			scsi_free_consistent_buf(bp);
8455 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
8456 			bp = NULL;
8457 		}
8458 	}
8459 	return (bp);
8460 }
8461 
8462 /*
8463  * Release local buffer (consistent buffer for DMA transfer) allocated
8464  * via sata_alloc_local_buffer().
8465  */
8466 static void
8467 sata_free_local_buffer(sata_pkt_txlate_t *spx)
8468 {
8469 	ASSERT(spx->txlt_sata_pkt != NULL);
8470 	ASSERT(spx->txlt_dma_cookie_list != NULL);
8471 	ASSERT(spx->txlt_dma_cookie_list_len != 0);
8472 	ASSERT(spx->txlt_buf_dma_handle != NULL);
8473 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
8474 
8475 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
8476 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
8477 
8478 	/* Free DMA resources */
8479 	(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
8480 	ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
8481 	spx->txlt_buf_dma_handle = 0;
8482 
8483 	kmem_free(spx->txlt_dma_cookie_list,
8484 	    spx->txlt_dma_cookie_list_len * sizeof (ddi_dma_cookie_t));
8485 	spx->txlt_dma_cookie_list = NULL;
8486 	spx->txlt_dma_cookie_list_len = 0;
8487 
8488 	/* Free buffer */
8489 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
8490 }
8491 
8492 
8493 
8494 
8495 /*
8496  * Allocate sata_pkt
8497  * Pkt structure version and embedded strcutures version are initialized.
8498  * sata_pkt and sata_pkt_txlate structures are cross-linked.
8499  *
8500  * Since this may be called in interrupt context by sata_scsi_init_pkt,
8501  * callback argument determines if it can sleep or not.
8502  * Hence, it should not be called from interrupt context.
8503  *
8504  * If successful, non-NULL pointer to a sata pkt is returned.
8505  * Upon failure, NULL pointer is returned.
8506  */
8507 static sata_pkt_t *
8508 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
8509 {
8510 	sata_pkt_t *spkt;
8511 	int kmsflag;
8512 
8513 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
8514 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
8515 	if (spkt == NULL) {
8516 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8517 		    "sata_pkt_alloc: failed"));
8518 		return (NULL);
8519 	}
8520 	spkt->satapkt_rev = SATA_PKT_REV;
8521 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
8522 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
8523 	spkt->satapkt_framework_private = spx;
8524 	spx->txlt_sata_pkt = spkt;
8525 	return (spkt);
8526 }
8527 
8528 /*
8529  * Free sata pkt allocated via sata_pkt_alloc()
8530  */
8531 static void
8532 sata_pkt_free(sata_pkt_txlate_t *spx)
8533 {
8534 	ASSERT(spx->txlt_sata_pkt != NULL);
8535 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
8536 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
8537 	spx->txlt_sata_pkt = NULL;
8538 }
8539 
8540 
8541 /*
8542  * Adjust DMA attributes.
8543  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
8544  * from 8 bits to 16 bits, depending on a command being used.
8545  * Limiting max block count arbitrarily to 256 for all read/write
8546  * commands may affects performance, so check both the device and
8547  * controller capability before adjusting dma attributes.
8548  * For ATAPI CD/DVD dma granularity has to be adjusted as well,
8549  * because these devices support block size of 2k rather
8550  * then 512 bytes.
8551  */
8552 void
8553 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
8554     ddi_dma_attr_t *adj_dma_attr)
8555 {
8556 	uint32_t count_max;
8557 
8558 	/* Copy original attributes */
8559 	*adj_dma_attr = *dma_attr;
8560 
8561 	/*
8562 	 * Things to consider: device addressing capability,
8563 	 * "excessive" controller DMA capabilities.
8564 	 * If a device is being probed/initialized, there are
8565 	 * no device info - use default limits then.
8566 	 */
8567 	if (sdinfo == NULL) {
8568 		count_max = dma_attr->dma_attr_granular * 0x100;
8569 		if (dma_attr->dma_attr_count_max > count_max)
8570 			adj_dma_attr->dma_attr_count_max = count_max;
8571 		if (dma_attr->dma_attr_maxxfer > count_max)
8572 			adj_dma_attr->dma_attr_maxxfer = count_max;
8573 		return;
8574 	}
8575 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
8576 		/* arbitrarily modify controller dma granularity */
8577 		adj_dma_attr->dma_attr_granular = SATA_ATAPI_SECTOR_SIZE;
8578 	}
8579 
8580 	if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
8581 		/*
8582 		 * 16-bit sector count may be used - we rely on
8583 		 * the assumption that only read and write cmds
8584 		 * will request more than 256 sectors worth of data
8585 		 */
8586 		count_max = adj_dma_attr->dma_attr_granular * 0x10000;
8587 	} else {
8588 		/*
8589 		 * 8-bit sector count will be used - default limits
8590 		 * for dma attributes
8591 		 */
8592 		count_max = adj_dma_attr->dma_attr_granular * 0x100;
8593 	}
8594 
8595 
8596 	/*
8597 	 * Adjust controler dma attributes, if necessary
8598 	 */
8599 	if (dma_attr->dma_attr_count_max > count_max)
8600 		adj_dma_attr->dma_attr_count_max = count_max;
8601 	if (dma_attr->dma_attr_maxxfer > count_max)
8602 		adj_dma_attr->dma_attr_maxxfer = count_max;
8603 }
8604 
8605 
8606 /*
8607  * Allocate DMA resources for the buffer
8608  * This function handles initial DMA resource allocation as well as
8609  * DMA window shift and may be called repeatedly for the same DMA window
8610  * until all DMA cookies in the DMA window are processed.
8611  *
8612  * Returns DDI_SUCCESS upon successful operation,
8613  * returns failure code returned by failing commands or DDI_FAILURE when
8614  * internal cleanup failed.
8615  */
8616 static int
8617 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
8618     int (*callback)(caddr_t), caddr_t arg,
8619     ddi_dma_attr_t *cur_dma_attr)
8620 {
8621 	int			rval;
8622 	ddi_dma_cookie_t	cookie;
8623 	off_t			offset;
8624 	size_t			size;
8625 	int			max_sg_len, req_sg_len, i;
8626 	uint_t			dma_flags;
8627 	struct buf		*bp;
8628 	uint64_t		max_txfer_len;
8629 	uint64_t		cur_txfer_len;
8630 
8631 	ASSERT(spx->txlt_sata_pkt != NULL);
8632 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8633 	ASSERT(bp != NULL);
8634 
8635 
8636 	if (spx->txlt_buf_dma_handle == NULL) {
8637 		/*
8638 		 * No DMA resources allocated so far - this is a first call
8639 		 * for this sata pkt.
8640 		 */
8641 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
8642 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
8643 
8644 		if (rval != DDI_SUCCESS) {
8645 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8646 			    "sata_dma_buf_setup: no buf DMA resources %x",
8647 			    rval));
8648 			return (rval);
8649 		}
8650 
8651 		if (bp->b_flags & B_READ)
8652 			dma_flags = DDI_DMA_READ;
8653 		else
8654 			dma_flags = DDI_DMA_WRITE;
8655 
8656 		if (flags & PKT_CONSISTENT)
8657 			dma_flags |= DDI_DMA_CONSISTENT;
8658 
8659 		if (flags & PKT_DMA_PARTIAL)
8660 			dma_flags |= DDI_DMA_PARTIAL;
8661 
8662 		rval = ddi_dma_buf_bind_handle(spx->txlt_buf_dma_handle,
8663 		    bp, dma_flags, callback, arg,
8664 		    &cookie, &spx->txlt_curwin_num_dma_cookies);
8665 
8666 		switch (rval) {
8667 		case DDI_DMA_PARTIAL_MAP:
8668 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
8669 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
8670 			/*
8671 			 * Partial DMA mapping.
8672 			 * Retrieve number of DMA windows for this request.
8673 			 */
8674 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
8675 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
8676 				(void) ddi_dma_unbind_handle(
8677 				    spx->txlt_buf_dma_handle);
8678 				(void) ddi_dma_free_handle(
8679 				    &spx->txlt_buf_dma_handle);
8680 				spx->txlt_buf_dma_handle = NULL;
8681 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8682 				    "sata_dma_buf_setup: numwin failed\n"));
8683 				return (DDI_FAILURE);
8684 			}
8685 			spx->txlt_cur_dma_win = 0;
8686 			break;
8687 
8688 		case DDI_DMA_MAPPED:
8689 			/* DMA fully mapped */
8690 			spx->txlt_num_dma_win = 1;
8691 			spx->txlt_cur_dma_win = 0;
8692 			break;
8693 
8694 		default:
8695 			/* DMA mapping failed */
8696 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
8697 			spx->txlt_buf_dma_handle = NULL;
8698 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8699 			    "sata_dma_buf_setup: buf dma handle binding "
8700 			    "failed %x\n", rval));
8701 			return (rval);
8702 		}
8703 		spx->txlt_curwin_processed_dma_cookies = 0;
8704 		spx->txlt_dma_cookie_list = NULL;
8705 	} else {
8706 		/*
8707 		 * DMA setup is reused. Check if we need to process more
8708 		 * cookies in current window, or to get next window, if any.
8709 		 */
8710 
8711 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
8712 		    spx->txlt_curwin_num_dma_cookies);
8713 
8714 		if (spx->txlt_curwin_processed_dma_cookies ==
8715 		    spx->txlt_curwin_num_dma_cookies) {
8716 			/*
8717 			 * All cookies from current DMA window were processed.
8718 			 * Get next DMA window.
8719 			 */
8720 			spx->txlt_cur_dma_win++;
8721 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
8722 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
8723 				    spx->txlt_cur_dma_win, &offset, &size,
8724 				    &cookie,
8725 				    &spx->txlt_curwin_num_dma_cookies);
8726 				spx->txlt_curwin_processed_dma_cookies = 0;
8727 
8728 			} else {
8729 				/* No more windows! End of request! */
8730 				/* What to do? - panic for now */
8731 				ASSERT(spx->txlt_cur_dma_win >=
8732 				    spx->txlt_num_dma_win);
8733 
8734 				spx->txlt_curwin_num_dma_cookies = 0;
8735 				spx->txlt_curwin_processed_dma_cookies = 0;
8736 				spx->txlt_sata_pkt->
8737 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
8738 				return (DDI_SUCCESS);
8739 			}
8740 		}
8741 	}
8742 	/* There better be at least one DMA cookie */
8743 	ASSERT((spx->txlt_curwin_num_dma_cookies -
8744 	    spx->txlt_curwin_processed_dma_cookies) > 0);
8745 
8746 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
8747 		/*
8748 		 * Processing a new DMA window - set-up dma cookies list.
8749 		 * We may reuse previously allocated cookie array if it is
8750 		 * possible.
8751 		 */
8752 		if (spx->txlt_dma_cookie_list != NULL &&
8753 		    spx->txlt_dma_cookie_list_len <
8754 		    spx->txlt_curwin_num_dma_cookies) {
8755 			/*
8756 			 * New DMA window contains more cookies than
8757 			 * the previous one. We need larger cookie list - free
8758 			 * the old one.
8759 			 */
8760 			(void) kmem_free(spx->txlt_dma_cookie_list,
8761 			    spx->txlt_dma_cookie_list_len *
8762 			    sizeof (ddi_dma_cookie_t));
8763 			spx->txlt_dma_cookie_list = NULL;
8764 			spx->txlt_dma_cookie_list_len = 0;
8765 		}
8766 		if (spx->txlt_dma_cookie_list == NULL) {
8767 			/* Allocate new dma cookie array */
8768 			spx->txlt_dma_cookie_list = kmem_zalloc(
8769 			    sizeof (ddi_dma_cookie_t) *
8770 			    spx->txlt_curwin_num_dma_cookies, KM_SLEEP);
8771 			spx->txlt_dma_cookie_list_len =
8772 			    spx->txlt_curwin_num_dma_cookies;
8773 		}
8774 		/*
8775 		 * Copy all DMA cookies into local list, so we will know their
8776 		 * dma_size in advance of setting the sata_pkt.
8777 		 * One cookie was already fetched, so copy it.
8778 		 */
8779 		*(&spx->txlt_dma_cookie_list[0]) = cookie;
8780 		for (i = 1; i < spx->txlt_curwin_num_dma_cookies; i++) {
8781 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle, &cookie);
8782 			*(&spx->txlt_dma_cookie_list[i]) = cookie;
8783 		}
8784 	} else {
8785 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
8786 		    "sata_dma_buf_setup: sliding within DMA window, "
8787 		    "cur cookie %d, total cookies %d\n",
8788 		    spx->txlt_curwin_processed_dma_cookies,
8789 		    spx->txlt_curwin_num_dma_cookies);
8790 	}
8791 
8792 	/*
8793 	 * Set-up sata_pkt cookie list.
8794 	 * No single cookie transfer size would exceed max transfer size of
8795 	 * an ATA command used for addressed device (tha adjustment of the dma
8796 	 * attributes took care of this). But there may be more
8797 	 * then one cookie, so the cmd cookie list has to be
8798 	 * constrained by both a maximum scatter gather list length and
8799 	 * a maximum transfer size restriction of an ATA command.
8800 	 */
8801 
8802 	max_sg_len = cur_dma_attr->dma_attr_sgllen;
8803 	req_sg_len = MIN(max_sg_len,
8804 	    (spx->txlt_curwin_num_dma_cookies -
8805 	    spx->txlt_curwin_processed_dma_cookies));
8806 
8807 	ASSERT(req_sg_len > 0);
8808 
8809 	max_txfer_len = MAX((cur_dma_attr->dma_attr_granular * 0x100),
8810 	    cur_dma_attr->dma_attr_maxxfer);
8811 
8812 	/* One cookie should be always available */
8813 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
8814 	    &spx->txlt_dma_cookie_list[spx->txlt_curwin_processed_dma_cookies];
8815 
8816 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
8817 
8818 	cur_txfer_len =
8819 	    (uint64_t)spx->txlt_dma_cookie_list[
8820 	    spx->txlt_curwin_processed_dma_cookies].dmac_size;
8821 
8822 	spx->txlt_curwin_processed_dma_cookies++;
8823 
8824 	ASSERT(cur_txfer_len <= max_txfer_len);
8825 
8826 	/* Add more cookies to the scatter-gather list */
8827 	for (i = 1; i < req_sg_len; i++) {
8828 		if (cur_txfer_len < max_txfer_len) {
8829 			/*
8830 			 * Check if the next cookie could be used by
8831 			 * this sata_pkt.
8832 			 */
8833 			if ((cur_txfer_len +
8834 			    spx->txlt_dma_cookie_list[
8835 			    spx->txlt_curwin_processed_dma_cookies].
8836 			    dmac_size) <= max_txfer_len) {
8837 				/* Yes, transfer lenght is within bounds */
8838 				spx->txlt_sata_pkt->
8839 				    satapkt_cmd.satacmd_num_dma_cookies++;
8840 				cur_txfer_len +=
8841 				    spx->txlt_dma_cookie_list[
8842 				    spx->txlt_curwin_processed_dma_cookies].
8843 				    dmac_size;
8844 				spx->txlt_curwin_processed_dma_cookies++;
8845 			} else {
8846 				/* No, transfer would exceed max lenght. */
8847 				SATADBG3(SATA_DBG_DMA_SETUP,
8848 				    spx->txlt_sata_hba_inst,
8849 				    "ncookies %d, size 0x%lx, "
8850 				    "max_size 0x%lx\n",
8851 				    spx->txlt_sata_pkt->
8852 				    satapkt_cmd.satacmd_num_dma_cookies,
8853 				    cur_txfer_len, max_txfer_len);
8854 				break;
8855 			}
8856 		} else {
8857 			/* Cmd max transfer length reached */
8858 			SATADBG3(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
8859 			    "Max transfer length? "
8860 			    "ncookies %d, size 0x%lx, max_size 0x%lx\n",
8861 			    spx->txlt_sata_pkt->
8862 			    satapkt_cmd.satacmd_num_dma_cookies,
8863 			    cur_txfer_len, max_txfer_len);
8864 			break;
8865 		}
8866 	}
8867 
8868 	ASSERT(cur_txfer_len != 0);
8869 	spx->txlt_total_residue -= cur_txfer_len;
8870 
8871 	return (DDI_SUCCESS);
8872 }
8873 
8874 /*
8875  * Fetch Device Identify data.
8876  * Send DEVICE IDENTIFY command to a device and get the device identify data.
8877  * The device_info structure has to be set to device type (for selecting proper
8878  * device identify command).
8879  *
8880  * Returns 0 if success, -1 otherwise.
8881  *
8882  * Cannot be called in an interrupt context.
8883  */
8884 
8885 static int
8886 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
8887     sata_drive_info_t *sdinfo)
8888 {
8889 	struct buf *bp;
8890 	sata_pkt_t *spkt;
8891 	sata_cmd_t *scmd;
8892 	sata_pkt_txlate_t *spx;
8893 	int rval;
8894 
8895 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
8896 	spx->txlt_sata_hba_inst = sata_hba_inst;
8897 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
8898 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
8899 	if (spkt == NULL) {
8900 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
8901 		return (-1);
8902 	}
8903 	/* address is needed now */
8904 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
8905 
8906 	/*
8907 	 * Allocate buffer for Identify Data return data
8908 	 */
8909 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
8910 	if (bp == NULL) {
8911 		sata_pkt_free(spx);
8912 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
8913 		SATA_LOG_D((sata_hba_inst, CE_WARN,
8914 		    "sata_fetch_device_identify_data: "
8915 		    "cannot allocate buffer for ID"));
8916 		return (-1);
8917 	}
8918 
8919 	/* Fill sata_pkt */
8920 	sdinfo->satadrv_state = SATA_STATE_PROBING;
8921 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
8922 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
8923 	/* Synchronous mode, no callback */
8924 	spkt->satapkt_comp = NULL;
8925 	/* Timeout 30s */
8926 	spkt->satapkt_time = sata_default_pkt_time;
8927 
8928 	scmd = &spkt->satapkt_cmd;
8929 	scmd->satacmd_bp = bp;
8930 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8931 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
8932 
8933 	/* Build Identify Device cmd in the sata_pkt */
8934 	scmd->satacmd_addr_type = 0;		/* N/A */
8935 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
8936 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
8937 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
8938 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
8939 	scmd->satacmd_features_reg = 0;		/* N/A */
8940 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
8941 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
8942 		/* Identify Packet Device cmd */
8943 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
8944 	} else {
8945 		/* Identify Device cmd - mandatory for all other devices */
8946 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
8947 	}
8948 
8949 	/* Send pkt to SATA HBA driver */
8950 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
8951 	    SATA_TRAN_ACCEPTED ||
8952 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
8953 		/*
8954 		 * Woops, no Identify Data.
8955 		 * Invalidate sata_drive_info ?
8956 		 */
8957 		rval = -1;
8958 	} else {
8959 		/* Update sata_drive_info */
8960 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
8961 			DDI_DMA_SYNC_FORKERNEL);
8962 		if (rval != DDI_SUCCESS) {
8963 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8964 			    "sata_fetch_device_identify_data: "
8965 			    "sync pkt failed"));
8966 			rval = -1;
8967 			goto fail;
8968 		}
8969 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
8970 		    sizeof (sata_id_t));
8971 
8972 		sdinfo->satadrv_features_support = 0;
8973 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
8974 			/*
8975 			 * Retrieve capacity (disks only) and addressing mode
8976 			 */
8977 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
8978 		} else {
8979 			/*
8980 			 * For ATAPI devices one has to issue Get Capacity cmd
8981 			 * (not needed at the moment)
8982 			 */
8983 			sdinfo->satadrv_capacity = 0;
8984 		}
8985 		/* Setup supported features flags */
8986 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
8987 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
8988 
8989 		/* Check for NCQ support */
8990 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
8991 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
8992 			/* SATA compliance */
8993 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
8994 				sdinfo->satadrv_features_support |=
8995 				    SATA_DEV_F_NCQ;
8996 			if (sdinfo->satadrv_id.ai_satacap &
8997 			    (SATA_1_SPEED | SATA_2_SPEED)) {
8998 				if (sdinfo->satadrv_id.ai_satacap &
8999 				    SATA_2_SPEED)
9000 					sdinfo->satadrv_features_support |=
9001 					    SATA_DEV_F_SATA2;
9002 				if (sdinfo->satadrv_id.ai_satacap &
9003 				    SATA_1_SPEED)
9004 					sdinfo->satadrv_features_support |=
9005 					    SATA_DEV_F_SATA1;
9006 			} else {
9007 				sdinfo->satadrv_features_support |=
9008 				    SATA_DEV_F_SATA1;
9009 			}
9010 		}
9011 
9012 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
9013 		if (sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD)
9014 			++sdinfo->satadrv_queue_depth;
9015 
9016 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
9017 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
9018 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
9019 
9020 		rval = 0;
9021 	}
9022 fail:
9023 	/* Free allocated resources */
9024 	sata_free_local_buffer(spx);
9025 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
9026 	sata_pkt_free(spx);
9027 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9028 
9029 	return (rval);
9030 }
9031 
9032 
9033 /*
9034  * SATA spec requires that the device supports at least UDMA 4 mode and
9035  * UDMA mode is selected.
9036  * Some devices (bridged devices) may not come-up with default UDMA mode
9037  * set correctly, so this function is setting it.
9038  *
9039  * Returns SATA_SUCCESS if proper UDMA mode is selected.
9040  * Returns SATA_FAILURE if proper UDMA mode could not be selected.
9041  */
9042 static int
9043 sata_set_udma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
9044 {
9045 	sata_pkt_t *spkt;
9046 	sata_cmd_t *scmd;
9047 	sata_pkt_txlate_t *spx;
9048 	int result = SATA_SUCCESS;
9049 	int i, mode;
9050 
9051 	ASSERT(sdinfo != NULL);
9052 	ASSERT(sata_hba_inst != NULL);
9053 
9054 	/* Find highest Ultra DMA mode supported */
9055 	for (mode = 6; mode >= 0; --mode) {
9056 		if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
9057 			break;
9058 	}
9059 	if (mode < 4)
9060 		return (SATA_FAILURE);
9061 
9062 	/* Find UDMA mode currently selected */
9063 	for (i = 6; i >= 0; --i) {
9064 		if (sdinfo->satadrv_id.ai_ultradma & (1 << (i + 8)))
9065 			break;
9066 	}
9067 
9068 	if (i < mode) {
9069 		/* Set UDMA mode via SET FEATURES COMMAND */
9070 		/* Prepare packet for SET FEATURES COMMAND */
9071 		spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9072 		spx->txlt_sata_hba_inst = sata_hba_inst;
9073 		spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
9074 		spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
9075 		if (spkt == NULL) {
9076 			result = SATA_FAILURE;
9077 			goto failure;
9078 		}
9079 		/* Fill sata_pkt */
9080 		spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
9081 		/* Timeout 30s */
9082 		spkt->satapkt_time = sata_default_pkt_time;
9083 		/* Synchronous mode, no callback, interrupts */
9084 		spkt->satapkt_op_mode =
9085 		    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9086 		spkt->satapkt_comp = NULL;
9087 		scmd = &spkt->satapkt_cmd;
9088 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
9089 		scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9090 		scmd->satacmd_addr_type = 0;
9091 		scmd->satacmd_device_reg = 0;
9092 		scmd->satacmd_status_reg = 0;
9093 		scmd->satacmd_error_reg = 0;
9094 		scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
9095 		scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
9096 		scmd->satacmd_sec_count_lsb =
9097 		    SATAC_TRANSFER_MODE_ULTRA_DMA | mode;
9098 
9099 		/* Transfer command to HBA */
9100 		if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
9101 		    spkt) != SATA_TRAN_ACCEPTED ||
9102 		    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
9103 			/* Pkt execution failed */
9104 			result = SATA_FAILURE;
9105 		}
9106 failure:
9107 		if (result == SATA_FAILURE)
9108 			SATA_LOG_D((sata_hba_inst, CE_WARN,
9109 			    "sata_set_udma_mode: could not set UDMA "
9110 			    "mode %", mode));
9111 
9112 		/* Free allocated resources */
9113 		if (spkt != NULL)
9114 			sata_pkt_free(spx);
9115 		(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
9116 	}
9117 	return (result);
9118 }
9119 
9120 
9121 /*
9122  * Set device caching mode.
9123  * One of the following operations should be specified:
9124  * SATAC_SF_ENABLE_READ_AHEAD
9125  * SATAC_SF_DISABLE_READ_AHEAD
9126  * SATAC_SF_ENABLE_WRITE_CACHE
9127  * SATAC_SF_DISABLE_WRITE_CACHE
9128  *
9129  * If operation fails, system log messgage is emitted.
9130  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
9131  */
9132 
9133 static int
9134 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
9135     int cache_op)
9136 {
9137 	sata_pkt_t *spkt;
9138 	sata_cmd_t *scmd;
9139 	sata_pkt_txlate_t *spx;
9140 	int rval = SATA_SUCCESS;
9141 	char *infop;
9142 
9143 	ASSERT(sdinfo != NULL);
9144 	ASSERT(sata_hba_inst != NULL);
9145 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
9146 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
9147 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
9148 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
9149 
9150 
9151 	/* Prepare packet for SET FEATURES COMMAND */
9152 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9153 	spx->txlt_sata_hba_inst = sata_hba_inst;
9154 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
9155 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
9156 	if (spkt == NULL) {
9157 		rval = SATA_FAILURE;
9158 		goto failure;
9159 	}
9160 	/* Fill sata_pkt */
9161 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
9162 	/* Timeout 30s */
9163 	spkt->satapkt_time = sata_default_pkt_time;
9164 	/* Synchronous mode, no callback, interrupts */
9165 	spkt->satapkt_op_mode =
9166 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9167 	spkt->satapkt_comp = NULL;
9168 	scmd = &spkt->satapkt_cmd;
9169 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
9170 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9171 	scmd->satacmd_addr_type = 0;
9172 	scmd->satacmd_device_reg = 0;
9173 	scmd->satacmd_status_reg = 0;
9174 	scmd->satacmd_error_reg = 0;
9175 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
9176 	scmd->satacmd_features_reg = cache_op;
9177 
9178 	/* Transfer command to HBA */
9179 	if (((*SATA_START_FUNC(sata_hba_inst))(
9180 	    SATA_DIP(sata_hba_inst), spkt) != 0) ||
9181 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
9182 		/* Pkt execution failed */
9183 		switch (cache_op) {
9184 		case SATAC_SF_ENABLE_READ_AHEAD:
9185 			infop = "enabling read ahead failed";
9186 			break;
9187 		case SATAC_SF_DISABLE_READ_AHEAD:
9188 			infop = "disabling read ahead failed";
9189 			break;
9190 		case SATAC_SF_ENABLE_WRITE_CACHE:
9191 			infop = "enabling write cache failed";
9192 			break;
9193 		case SATAC_SF_DISABLE_WRITE_CACHE:
9194 			infop = "disabling write cache failed";
9195 			break;
9196 		}
9197 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
9198 		rval = SATA_FAILURE;
9199 	}
9200 failure:
9201 	/* Free allocated resources */
9202 	if (spkt != NULL)
9203 		sata_pkt_free(spx);
9204 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
9205 	return (rval);
9206 }
9207 
9208 
9209 
9210 /*
9211  * Update port SCR block
9212  */
9213 static void
9214 sata_update_port_scr(sata_port_scr_t *port_scr, sata_device_t *device)
9215 {
9216 	port_scr->sstatus = device->satadev_scr.sstatus;
9217 	port_scr->serror = device->satadev_scr.serror;
9218 	port_scr->scontrol = device->satadev_scr.scontrol;
9219 	port_scr->sactive = device->satadev_scr.sactive;
9220 	port_scr->snotific = device->satadev_scr.snotific;
9221 }
9222 
9223 /*
9224  * Update state and copy port ss* values from passed sata_device structure.
9225  * sata_address is validated - if not valid, nothing is changed in sata_scsi
9226  * configuration struct.
9227  *
9228  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
9229  * regardless of the state in device argument.
9230  *
9231  * Port mutex should be held while calling this function.
9232  */
9233 static void
9234 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
9235 	sata_device_t *sata_device)
9236 {
9237 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst,
9238 	    sata_device->satadev_addr.cport)));
9239 
9240 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
9241 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
9242 
9243 		sata_cport_info_t *cportinfo;
9244 
9245 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
9246 		    sata_device->satadev_addr.cport)
9247 			return;
9248 
9249 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
9250 		    sata_device->satadev_addr.cport);
9251 		sata_update_port_scr(&cportinfo->cport_scr, sata_device);
9252 
9253 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
9254 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
9255 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
9256 		cportinfo->cport_state |=
9257 		    sata_device->satadev_state & SATA_PSTATE_VALID;
9258 	} else {
9259 		sata_pmport_info_t *pmportinfo;
9260 
9261 		if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT) ||
9262 		    (sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
9263 		    SATA_NUM_PMPORTS(sata_hba_inst,
9264 		    sata_device->satadev_addr.cport) <
9265 		    sata_device->satadev_addr.pmport)
9266 			return;
9267 
9268 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
9269 		    sata_device->satadev_addr.cport,
9270 		    sata_device->satadev_addr.pmport);
9271 		sata_update_port_scr(&pmportinfo->pmport_scr, sata_device);
9272 
9273 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
9274 		pmportinfo->pmport_state &=
9275 		    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF |
9276 		    SATA_PSTATE_FAILED);
9277 		pmportinfo->pmport_state |=
9278 		    sata_device->satadev_state & SATA_PSTATE_VALID;
9279 	}
9280 }
9281 
9282 
9283 
9284 /*
9285  * Extract SATA port specification from an IOCTL argument.
9286  *
9287  * This function return the port the user land send us as is, unless it
9288  * cannot retrieve port spec, then -1 is returned.
9289  *
9290  * Note: Only cport  - no port multiplier port.
9291  */
9292 static int32_t
9293 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
9294 {
9295 	int32_t port;
9296 
9297 	/* Extract port number from nvpair in dca structure  */
9298 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
9299 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
9300 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
9301 		    port));
9302 		port = -1;
9303 	}
9304 
9305 	return (port);
9306 }
9307 
9308 /*
9309  * Get dev_info_t pointer to the device node pointed to by port argument.
9310  * NOTE: target argument is a value used in ioctls to identify
9311  * the AP - it is not a sata_address.
9312  * It is a combination of cport, pmport and address qualifier, encodded same
9313  * way as a scsi target number.
9314  * At this moment it carries only cport number.
9315  *
9316  * No PMult hotplug support.
9317  *
9318  * Returns dev_info_t pointer if target device was found, NULL otherwise.
9319  */
9320 
9321 static dev_info_t *
9322 sata_get_target_dip(dev_info_t *dip, int32_t port)
9323 {
9324 	dev_info_t	*cdip = NULL;
9325 	int		target, tgt;
9326 	int		ncport;
9327 	int 		circ;
9328 
9329 	ncport = port & SATA_CFGA_CPORT_MASK;
9330 	target = SATA_TO_SCSI_TARGET(ncport, 0, SATA_ADDR_DCPORT);
9331 
9332 	ndi_devi_enter(dip, &circ);
9333 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
9334 		dev_info_t *next = ddi_get_next_sibling(cdip);
9335 
9336 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
9337 		    DDI_PROP_DONTPASS, "target", -1);
9338 		if (tgt == -1) {
9339 			/*
9340 			 * This is actually an error condition, but not
9341 			 * a fatal one. Just continue the search.
9342 			 */
9343 			cdip = next;
9344 			continue;
9345 		}
9346 
9347 		if (tgt == target)
9348 			break;
9349 
9350 		cdip = next;
9351 	}
9352 	ndi_devi_exit(dip, circ);
9353 
9354 	return (cdip);
9355 }
9356 
9357 
9358 /*
9359  * sata_cfgadm_state:
9360  * Use the sata port state and state of the target node to figure out
9361  * the cfgadm_state.
9362  *
9363  * The port argument is a value with encoded cport,
9364  * pmport and address qualifier, in the same manner as a scsi target number.
9365  * SCSI_TO_SATA_CPORT macro extracts cport number,
9366  * SCSI_TO_SATA_PMPORT extracts pmport number and
9367  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
9368  *
9369  * For now, support is for cports only - no pmultiplier ports.
9370  */
9371 
9372 static void
9373 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
9374     devctl_ap_state_t *ap_state)
9375 {
9376 	uint16_t	cport;
9377 	int		port_state;
9378 
9379 	/* Cport only */
9380 	cport = SCSI_TO_SATA_CPORT(port);
9381 
9382 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
9383 	if (port_state & SATA_PSTATE_SHUTDOWN ||
9384 	    port_state & SATA_PSTATE_FAILED) {
9385 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
9386 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
9387 		if (port_state & SATA_PSTATE_FAILED)
9388 			ap_state->ap_condition = AP_COND_FAILED;
9389 		else
9390 			ap_state->ap_condition = AP_COND_UNKNOWN;
9391 
9392 		return;
9393 	}
9394 
9395 	/* Need to check pmult device port here as well, when supported */
9396 
9397 	/* Port is enabled and ready */
9398 
9399 	switch (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport)) {
9400 	case SATA_DTYPE_NONE:
9401 	{
9402 		/* No device attached */
9403 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
9404 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
9405 		ap_state->ap_condition = AP_COND_OK;
9406 		break;
9407 	}
9408 	case SATA_DTYPE_UNKNOWN:
9409 	case SATA_DTYPE_ATAPINONCD:
9410 	case SATA_DTYPE_PMULT:	/* Until PMult is supported */
9411 	{
9412 		/* Unknown device attached */
9413 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
9414 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
9415 		ap_state->ap_condition = AP_COND_UNKNOWN;
9416 		break;
9417 	}
9418 	case SATA_DTYPE_ATADISK:
9419 	case SATA_DTYPE_ATAPICD:
9420 	{
9421 		dev_info_t *tdip = NULL;
9422 		dev_info_t *dip = NULL;
9423 		int circ;
9424 
9425 		dip = SATA_DIP(sata_hba_inst);
9426 		tdip = sata_get_target_dip(dip, port);
9427 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
9428 		if (tdip != NULL) {
9429 			ndi_devi_enter(dip, &circ);
9430 			mutex_enter(&(DEVI(tdip)->devi_lock));
9431 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
9432 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
9433 				ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
9434 			} else {
9435 				ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
9436 			}
9437 			ap_state->ap_condition = AP_COND_OK;
9438 			mutex_exit(&(DEVI(tdip)->devi_lock));
9439 			ndi_devi_exit(dip, circ);
9440 		} else {
9441 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
9442 			ap_state->ap_condition = AP_COND_UNKNOWN;
9443 		}
9444 		break;
9445 	}
9446 	default:
9447 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
9448 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
9449 		ap_state->ap_condition = AP_COND_UNKNOWN;
9450 		/*
9451 		 * This is actually internal error condition (non fatal),
9452 		 * beacuse we already checked all defined device types.
9453 		 */
9454 		SATA_LOG_D((sata_hba_inst, CE_WARN,
9455 		    "sata_cfgadm_state: Internal error: "
9456 		    "unknown device type"));
9457 		break;
9458 	}
9459 }
9460 
9461 /*
9462  * Start or terminate the thread, depending on flag arg and current state
9463  */
9464 static void
9465 sata_event_thread_control(int startstop)
9466 {
9467 	static 	int sata_event_thread_terminating = 0;
9468 	static 	int sata_event_thread_starting = 0;
9469 	int i;
9470 
9471 	mutex_enter(&sata_event_mutex);
9472 
9473 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
9474 	    sata_event_thread_terminating == 1)) {
9475 		mutex_exit(&sata_event_mutex);
9476 		return;
9477 	}
9478 	if (startstop == 1 && sata_event_thread_starting == 1) {
9479 		mutex_exit(&sata_event_mutex);
9480 		return;
9481 	}
9482 	if (startstop == 1 && sata_event_thread_terminating == 1) {
9483 		sata_event_thread_starting = 1;
9484 		/* wait til terminate operation completes */
9485 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
9486 		while (sata_event_thread_terminating == 1) {
9487 			if (i-- <= 0) {
9488 				sata_event_thread_starting = 0;
9489 				mutex_exit(&sata_event_mutex);
9490 #ifdef SATA_DEBUG
9491 				cmn_err(CE_WARN, "sata_event_thread_control: "
9492 				    "timeout waiting for thread to terminate");
9493 #endif
9494 				return;
9495 			}
9496 			mutex_exit(&sata_event_mutex);
9497 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
9498 			mutex_enter(&sata_event_mutex);
9499 		}
9500 	}
9501 	if (startstop == 1) {
9502 		if (sata_event_thread == NULL) {
9503 			sata_event_thread = thread_create(NULL, 0,
9504 			    (void (*)())sata_event_daemon,
9505 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
9506 		}
9507 		sata_event_thread_starting = 0;
9508 		mutex_exit(&sata_event_mutex);
9509 		return;
9510 	}
9511 
9512 	/*
9513 	 * If we got here, thread may need to be terminated
9514 	 */
9515 	if (sata_event_thread != NULL) {
9516 		int i;
9517 		/* Signal event thread to go away */
9518 		sata_event_thread_terminating = 1;
9519 		sata_event_thread_terminate = 1;
9520 		cv_signal(&sata_event_cv);
9521 		/*
9522 		 * Wait til daemon terminates.
9523 		 */
9524 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
9525 		while (sata_event_thread_terminate == 1) {
9526 			mutex_exit(&sata_event_mutex);
9527 			if (i-- <= 0) {
9528 				/* Daemon did not go away !!! */
9529 #ifdef SATA_DEBUG
9530 				cmn_err(CE_WARN, "sata_event_thread_control: "
9531 				    "cannot terminate event daemon thread");
9532 #endif
9533 				mutex_enter(&sata_event_mutex);
9534 				break;
9535 			}
9536 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
9537 			mutex_enter(&sata_event_mutex);
9538 		}
9539 		sata_event_thread_terminating = 0;
9540 	}
9541 	ASSERT(sata_event_thread_terminating == 0);
9542 	ASSERT(sata_event_thread_starting == 0);
9543 	mutex_exit(&sata_event_mutex);
9544 }
9545 
9546 
9547 /*
9548  * Log sata message
9549  * dev pathname msg line preceeds the logged message.
9550  */
9551 
9552 static	void
9553 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
9554 {
9555 	char pathname[128];
9556 	dev_info_t *dip;
9557 	va_list ap;
9558 
9559 	mutex_enter(&sata_log_mutex);
9560 
9561 	va_start(ap, fmt);
9562 	(void) vsprintf(sata_log_buf, fmt, ap);
9563 	va_end(ap);
9564 
9565 	if (sata_hba_inst != NULL) {
9566 		dip = SATA_DIP(sata_hba_inst);
9567 		(void) ddi_pathname(dip, pathname);
9568 	} else {
9569 		pathname[0] = 0;
9570 	}
9571 	if (level == CE_CONT) {
9572 		if (sata_debug_flags == 0)
9573 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
9574 		else
9575 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
9576 	} else
9577 		cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
9578 
9579 	mutex_exit(&sata_log_mutex);
9580 }
9581 
9582 
9583 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
9584 
9585 /*
9586  * SATA HBA event notification function.
9587  * Events reported by SATA HBA drivers per HBA instance relate to a change in
9588  * a port and/or device state or a controller itself.
9589  * Events for different addresses/addr types cannot be combined.
9590  * A warning message is generated for each event type.
9591  * Events are not processed by this function, so only the
9592  * event flag(s)is set for an affected entity and the event thread is
9593  * waken up. Event daemon thread processes all events.
9594  *
9595  * NOTE: Since more than one event may be reported at the same time, one
9596  * cannot determine a sequence of events when opposite event are reported, eg.
9597  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
9598  * is taking precedence over reported events, i.e. may cause ignoring some
9599  * events.
9600  */
9601 #define	SATA_EVENT_MAX_MSG_LENGTH	79
9602 
9603 void
9604 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
9605 {
9606 	sata_hba_inst_t *sata_hba_inst = NULL;
9607 	sata_address_t *saddr;
9608 	sata_drive_info_t *sdinfo;
9609 	sata_port_stats_t *pstats;
9610 	int cport, pmport;
9611 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
9612 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
9613 	char *lcp;
9614 	static char *err_msg_evnt_1 =
9615 	    "sata_hba_event_notify: invalid port event 0x%x ";
9616 	static char *err_msg_evnt_2 =
9617 	    "sata_hba_event_notify: invalid device event 0x%x ";
9618 	int linkevent;
9619 
9620 	/*
9621 	 * There is a possibility that an event will be generated on HBA
9622 	 * that has not completed attachment or is detaching.
9623 	 * HBA driver should prevent this, but just in case it does not,
9624 	 * we need to ignore events for such HBA.
9625 	 */
9626 	mutex_enter(&sata_mutex);
9627 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
9628 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9629 		if (SATA_DIP(sata_hba_inst) == dip)
9630 			if (sata_hba_inst->satahba_attached == 1)
9631 				break;
9632 	}
9633 	mutex_exit(&sata_mutex);
9634 	if (sata_hba_inst == NULL)
9635 		/* HBA not attached */
9636 		return;
9637 
9638 	ASSERT(sata_device != NULL);
9639 
9640 	/*
9641 	 * Validate address before - do not proceed with invalid address.
9642 	 */
9643 	saddr = &sata_device->satadev_addr;
9644 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
9645 		return;
9646 	if (saddr->qual == SATA_ADDR_PMPORT ||
9647 	    saddr->qual == SATA_ADDR_DPMPORT)
9648 		/* Port Multiplier not supported yet */
9649 		return;
9650 
9651 	cport = saddr->cport;
9652 	pmport = saddr->pmport;
9653 
9654 	buf1[0] = buf2[0] = '\0';
9655 
9656 	/*
9657 	 * Events refer to devices, ports and controllers - each has
9658 	 * unique address. Events for different addresses cannot be combined.
9659 	 */
9660 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
9661 
9662 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
9663 
9664 		/* qualify this event(s) */
9665 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
9666 			/* Invalid event for the device port */
9667 			(void) sprintf(buf2, err_msg_evnt_1,
9668 			    event & SATA_EVNT_PORT_EVENTS);
9669 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
9670 			goto event_info;
9671 		}
9672 		if (saddr->qual == SATA_ADDR_CPORT) {
9673 			/* Controller's device port event */
9674 
9675 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
9676 			    cport_event_flags |=
9677 			    event & SATA_EVNT_PORT_EVENTS;
9678 			pstats =
9679 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
9680 			    cport_stats;
9681 		} else {
9682 			/* Port multiplier's device port event */
9683 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
9684 			    pmport_event_flags |=
9685 			    event & SATA_EVNT_PORT_EVENTS;
9686 			pstats =
9687 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
9688 			    pmport_stats;
9689 		}
9690 
9691 		/*
9692 		 * Add to statistics and log the message. We have to do it
9693 		 * here rather than in the event daemon, because there may be
9694 		 * multiple events occuring before they are processed.
9695 		 */
9696 		linkevent = event &
9697 			(SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
9698 		if (linkevent) {
9699 			if (linkevent == (SATA_EVNT_LINK_LOST |
9700 			    SATA_EVNT_LINK_ESTABLISHED)) {
9701 				/* This is likely event combination */
9702 				(void) strlcat(buf1, "link lost/established, ",
9703 				    SATA_EVENT_MAX_MSG_LENGTH);
9704 
9705 				if (pstats->link_lost < 0xffffffffffffffffULL)
9706 					pstats->link_lost++;
9707 				if (pstats->link_established <
9708 				    0xffffffffffffffffULL)
9709 					pstats->link_established++;
9710 				linkevent = 0;
9711 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
9712 				(void) strlcat(buf1, "link lost, ",
9713 				    SATA_EVENT_MAX_MSG_LENGTH);
9714 
9715 				if (pstats->link_lost < 0xffffffffffffffffULL)
9716 					pstats->link_lost++;
9717 			} else {
9718 				(void) strlcat(buf1, "link established, ",
9719 				    SATA_EVENT_MAX_MSG_LENGTH);
9720 				if (pstats->link_established <
9721 				    0xffffffffffffffffULL)
9722 					pstats->link_established++;
9723 			}
9724 		}
9725 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
9726 			(void) strlcat(buf1, "device attached, ",
9727 			    SATA_EVENT_MAX_MSG_LENGTH);
9728 			if (pstats->device_attached < 0xffffffffffffffffULL)
9729 				pstats->device_attached++;
9730 		}
9731 		if (event & SATA_EVNT_DEVICE_DETACHED) {
9732 			(void) strlcat(buf1, "device detached, ",
9733 			    SATA_EVENT_MAX_MSG_LENGTH);
9734 			if (pstats->device_detached < 0xffffffffffffffffULL)
9735 				pstats->device_detached++;
9736 		}
9737 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
9738 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
9739 			    "port %d power level changed", cport);
9740 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
9741 				pstats->port_pwr_changed++;
9742 		}
9743 
9744 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
9745 			/* There should be no other events for this address */
9746 			(void) sprintf(buf2, err_msg_evnt_1,
9747 			    event & ~SATA_EVNT_PORT_EVENTS);
9748 		}
9749 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
9750 
9751 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
9752 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
9753 
9754 		/* qualify this event */
9755 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
9756 			/* Invalid event for a device */
9757 			(void) sprintf(buf2, err_msg_evnt_2,
9758 			    event & SATA_EVNT_DEVICE_RESET);
9759 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
9760 			goto event_info;
9761 		}
9762 		/* drive event */
9763 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
9764 		if (sdinfo != NULL) {
9765 			if (event & SATA_EVNT_DEVICE_RESET) {
9766 				(void) strlcat(buf1, "device reset, ",
9767 				    SATA_EVENT_MAX_MSG_LENGTH);
9768 				if (sdinfo->satadrv_stats.drive_reset <
9769 				    0xffffffffffffffffULL)
9770 					sdinfo->satadrv_stats.drive_reset++;
9771 				sdinfo->satadrv_event_flags |=
9772 				    SATA_EVNT_DEVICE_RESET;
9773 			}
9774 		}
9775 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
9776 			/* Invalid event for a device */
9777 			(void) sprintf(buf2, err_msg_evnt_2,
9778 			    event & ~SATA_EVNT_DRIVE_EVENTS);
9779 		}
9780 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
9781 	} else {
9782 		if (saddr->qual != SATA_ADDR_NULL) {
9783 			/* Wrong address qualifier */
9784 			SATA_LOG_D((sata_hba_inst, CE_WARN,
9785 			    "sata_hba_event_notify: invalid address 0x%x",
9786 			    *(uint32_t *)saddr));
9787 			return;
9788 		}
9789 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
9790 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
9791 			/* Invalid event for the controller */
9792 			SATA_LOG_D((sata_hba_inst, CE_WARN,
9793 			    "sata_hba_event_notify: invalid event 0x%x for "
9794 			    "controller",
9795 			    event & SATA_EVNT_CONTROLLER_EVENTS));
9796 			return;
9797 		}
9798 		buf1[0] = '\0';
9799 		/* This may be a frequent and not interesting event */
9800 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
9801 		    "controller power level changed\n", NULL);
9802 
9803 		mutex_enter(&sata_hba_inst->satahba_mutex);
9804 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
9805 		    0xffffffffffffffffULL)
9806 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
9807 
9808 		sata_hba_inst->satahba_event_flags |=
9809 		    SATA_EVNT_PWR_LEVEL_CHANGED;
9810 		mutex_exit(&sata_hba_inst->satahba_mutex);
9811 	}
9812 	/*
9813 	 * If we got here, there is something to do with this HBA
9814 	 * instance.
9815 	 */
9816 	mutex_enter(&sata_hba_inst->satahba_mutex);
9817 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
9818 	mutex_exit(&sata_hba_inst->satahba_mutex);
9819 	mutex_enter(&sata_mutex);
9820 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
9821 	mutex_exit(&sata_mutex);
9822 
9823 	/* Tickle event thread */
9824 	mutex_enter(&sata_event_mutex);
9825 	if (sata_event_thread_active == 0)
9826 		cv_signal(&sata_event_cv);
9827 	mutex_exit(&sata_event_mutex);
9828 
9829 event_info:
9830 	if (buf1[0] != '\0') {
9831 		lcp = strrchr(buf1, ',');
9832 		if (lcp != NULL)
9833 			*lcp = '\0';
9834 	}
9835 	if (saddr->qual == SATA_ADDR_CPORT ||
9836 	    saddr->qual == SATA_ADDR_DCPORT) {
9837 		if (buf1[0] != '\0') {
9838 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
9839 			    cport, buf1);
9840 		}
9841 		if (buf2[0] != '\0') {
9842 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
9843 			    cport, buf2);
9844 		}
9845 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
9846 	    saddr->qual == SATA_ADDR_DPMPORT) {
9847 		if (buf1[0] != '\0') {
9848 			sata_log(sata_hba_inst, CE_NOTE,
9849 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
9850 		}
9851 		if (buf2[0] != '\0') {
9852 			sata_log(sata_hba_inst, CE_NOTE,
9853 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
9854 		}
9855 	}
9856 }
9857 
9858 
9859 /*
9860  * Event processing thread.
9861  * Arg is a pointer to the sata_hba_list pointer.
9862  * It is not really needed, because sata_hba_list is global and static
9863  */
9864 static void
9865 sata_event_daemon(void *arg)
9866 {
9867 #ifndef __lock_lint
9868 	_NOTE(ARGUNUSED(arg))
9869 #endif
9870 	sata_hba_inst_t *sata_hba_inst;
9871 	clock_t lbolt;
9872 
9873 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
9874 	    "SATA event daemon started\n", NULL);
9875 loop:
9876 	/*
9877 	 * Process events here. Walk through all registered HBAs
9878 	 */
9879 	mutex_enter(&sata_mutex);
9880 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
9881 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9882 		ASSERT(sata_hba_inst != NULL);
9883 		mutex_enter(&sata_hba_inst->satahba_mutex);
9884 		if (sata_hba_inst->satahba_attached != 1 ||
9885 		    (sata_hba_inst->satahba_event_flags &
9886 		    SATA_EVNT_SKIP) != 0) {
9887 			mutex_exit(&sata_hba_inst->satahba_mutex);
9888 			continue;
9889 		}
9890 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
9891 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
9892 			mutex_exit(&sata_hba_inst->satahba_mutex);
9893 			mutex_exit(&sata_mutex);
9894 			/* Got the controller with pending event */
9895 			sata_process_controller_events(sata_hba_inst);
9896 			/*
9897 			 * Since global mutex was released, there is a
9898 			 * possibility that HBA list has changed, so start
9899 			 * over from the top. Just processed controller
9900 			 * will be passed-over because of the SKIP flag.
9901 			 */
9902 			goto loop;
9903 		}
9904 		mutex_exit(&sata_hba_inst->satahba_mutex);
9905 	}
9906 	/* Clear SKIP flag in all controllers */
9907 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
9908 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9909 		mutex_enter(&sata_hba_inst->satahba_mutex);
9910 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
9911 		mutex_exit(&sata_hba_inst->satahba_mutex);
9912 	}
9913 	mutex_exit(&sata_mutex);
9914 
9915 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
9916 	    "SATA EVENT DAEMON suspending itself", NULL);
9917 
9918 #ifdef SATA_DEBUG
9919 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
9920 		sata_log(sata_hba_inst, CE_WARN,
9921 		    "SATA EVENTS PROCESSING DISABLED\n");
9922 		thread_exit(); /* Daemon will not run again */
9923 	}
9924 #endif
9925 	mutex_enter(&sata_event_mutex);
9926 	sata_event_thread_active = 0;
9927 	mutex_exit(&sata_event_mutex);
9928 	/*
9929 	 * Go to sleep/suspend itself and wake up either because new event or
9930 	 * wait timeout. Exit if there is a termination request (driver
9931 	 * unload).
9932 	 */
9933 	do {
9934 		lbolt = ddi_get_lbolt();
9935 		lbolt += drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
9936 		mutex_enter(&sata_event_mutex);
9937 		(void) cv_timedwait(&sata_event_cv, &sata_event_mutex, lbolt);
9938 
9939 		if (sata_event_thread_active != 0) {
9940 			mutex_exit(&sata_event_mutex);
9941 			continue;
9942 		}
9943 
9944 		/* Check if it is time to go away */
9945 		if (sata_event_thread_terminate == 1) {
9946 			/*
9947 			 * It is up to the thread setting above flag to make
9948 			 * sure that this thread is not killed prematurely.
9949 			 */
9950 			sata_event_thread_terminate = 0;
9951 			sata_event_thread = NULL;
9952 			mutex_exit(&sata_event_mutex);
9953 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
9954 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
9955 			thread_exit();  { _NOTE(NOT_REACHED) }
9956 		}
9957 		mutex_exit(&sata_event_mutex);
9958 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
9959 
9960 	mutex_enter(&sata_event_mutex);
9961 	sata_event_thread_active = 1;
9962 	mutex_exit(&sata_event_mutex);
9963 
9964 	mutex_enter(&sata_mutex);
9965 	sata_event_pending &= ~SATA_EVNT_MAIN;
9966 	mutex_exit(&sata_mutex);
9967 
9968 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
9969 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
9970 
9971 	goto loop;
9972 }
9973 
9974 /*
9975  * Specific HBA instance event processing.
9976  *
9977  * NOTE: At the moment, device event processing is limited to hard disks
9978  * only.
9979  * cports only are supported - no pmports.
9980  */
9981 static void
9982 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
9983 {
9984 	int ncport;
9985 	uint32_t event_flags;
9986 	sata_address_t *saddr;
9987 
9988 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
9989 	    "Processing controller %d event(s)",
9990 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
9991 
9992 	mutex_enter(&sata_hba_inst->satahba_mutex);
9993 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
9994 	event_flags = sata_hba_inst->satahba_event_flags;
9995 	mutex_exit(&sata_hba_inst->satahba_mutex);
9996 	/*
9997 	 * Process controller power change first
9998 	 * HERE
9999 	 */
10000 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
10001 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
10002 
10003 	/*
10004 	 * Search through ports/devices to identify affected port/device.
10005 	 * We may have to process events for more than one port/device.
10006 	 */
10007 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
10008 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
10009 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
10010 		    cport_event_flags;
10011 		/* Check if port was locked by IOCTL processing */
10012 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
10013 			/*
10014 			 * We ignore port events because port is busy
10015 			 * with AP control processing. Set again
10016 			 * controller and main event flag, so that
10017 			 * events may be processed by the next daemon
10018 			 * run.
10019 			 */
10020 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
10021 			mutex_enter(&sata_hba_inst->satahba_mutex);
10022 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
10023 			mutex_exit(&sata_hba_inst->satahba_mutex);
10024 			mutex_enter(&sata_mutex);
10025 			sata_event_pending |= SATA_EVNT_MAIN;
10026 			mutex_exit(&sata_mutex);
10027 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
10028 			    "Event processing postponed until "
10029 			    "AP control processing completes",
10030 			    NULL);
10031 			/* Check other ports */
10032 			continue;
10033 		} else {
10034 			/*
10035 			 * Set BSY flag so that AP control would not
10036 			 * interfere with events processing for
10037 			 * this port.
10038 			 */
10039 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
10040 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
10041 		}
10042 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
10043 
10044 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
10045 
10046 		if ((event_flags &
10047 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
10048 			/*
10049 			 * Got port event.
10050 			 * We need some hierarchy of event processing as they
10051 			 * are affecting each other:
10052 			 * 1. port failed
10053 			 * 2. device detached/attached
10054 			 * 3. link events - link events may trigger device
10055 			 *    detached or device attached events in some
10056 			 *    circumstances.
10057 			 * 4. port power level changed
10058 			 */
10059 			if (event_flags & SATA_EVNT_PORT_FAILED) {
10060 				sata_process_port_failed_event(sata_hba_inst,
10061 				    saddr);
10062 			}
10063 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
10064 				sata_process_device_detached(sata_hba_inst,
10065 				    saddr);
10066 			}
10067 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
10068 				sata_process_device_attached(sata_hba_inst,
10069 				    saddr);
10070 			}
10071 			if (event_flags &
10072 			    (SATA_EVNT_LINK_ESTABLISHED |
10073 			    SATA_EVNT_LINK_LOST)) {
10074 				sata_process_port_link_events(sata_hba_inst,
10075 				    saddr);
10076 			}
10077 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
10078 				sata_process_port_pwr_change(sata_hba_inst,
10079 				    saddr);
10080 			}
10081 		}
10082 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
10083 		    SATA_DTYPE_NONE) {
10084 			/* May have device event */
10085 			sata_process_device_reset(sata_hba_inst, saddr);
10086 		}
10087 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
10088 		/* Release PORT_BUSY flag */
10089 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
10090 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
10091 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
10092 
10093 	} /* End of loop through the controller SATA ports */
10094 }
10095 
10096 /*
10097  * Process HBA power level change reported by HBA driver.
10098  * Not implemented at this time - event is ignored.
10099  */
10100 static void
10101 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
10102 {
10103 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10104 	    "Processing controller power level change", NULL);
10105 
10106 	/* Ignoring it for now */
10107 	mutex_enter(&sata_hba_inst->satahba_mutex);
10108 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
10109 	mutex_exit(&sata_hba_inst->satahba_mutex);
10110 }
10111 
10112 /*
10113  * Process port power level change reported by HBA driver.
10114  * Not implemented at this time - event is ignored.
10115  */
10116 static void
10117 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
10118     sata_address_t *saddr)
10119 {
10120 	sata_cport_info_t *cportinfo;
10121 
10122 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10123 	    "Processing port power level change", NULL);
10124 
10125 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
10126 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10127 	/* Reset event flag */
10128 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
10129 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10130 }
10131 
10132 /*
10133  * Process port failure reported by HBA driver.
10134  * cports support only - no pmports.
10135  */
10136 static void
10137 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
10138     sata_address_t *saddr)
10139 {
10140 	sata_cport_info_t *cportinfo;
10141 
10142 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
10143 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10144 	/* Reset event flag first */
10145 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
10146 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
10147 	if ((cportinfo->cport_state &
10148 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
10149 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10150 		    cport_mutex);
10151 		return;
10152 	}
10153 	/* Fail the port */
10154 	cportinfo->cport_state = SATA_PSTATE_FAILED;
10155 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10156 	sata_log(sata_hba_inst, CE_WARN, "port %d failed", saddr->cport);
10157 }
10158 
10159 /*
10160  * Device Reset Event processing.
10161  * The seqeunce is managed by 3 stage flags:
10162  * - reset event reported,
10163  * - reset event being processed,
10164  * - request to clear device reset state.
10165  */
10166 static void
10167 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
10168     sata_address_t *saddr)
10169 {
10170 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
10171 	sata_drive_info_t *sdinfo;
10172 	sata_cport_info_t *cportinfo;
10173 	sata_device_t sata_device;
10174 	int rval;
10175 
10176 	/* We only care about host sata cport for now */
10177 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
10178 
10179 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10180 
10181 	/* If the port is in SHUTDOWN or FAILED state, ignore reset event. */
10182 	if ((cportinfo->cport_state &
10183 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
10184 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10185 		    cport_mutex);
10186 		return;
10187 	}
10188 
10189 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
10190 	    SATA_VALID_DEV_TYPE) == 0) {
10191 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10192 		    cport_mutex);
10193 		return;
10194 	}
10195 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
10196 	if (sdinfo == NULL) {
10197 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10198 		    cport_mutex);
10199 		return;
10200 	}
10201 
10202 	if ((sdinfo->satadrv_event_flags & SATA_EVNT_DEVICE_RESET) == 0) {
10203 		/* Nothing to do */
10204 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10205 		    cport_mutex);
10206 		return;
10207 	}
10208 
10209 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10210 	    "Processing port %d device reset", saddr->cport);
10211 
10212 	if (sdinfo->satadrv_event_flags & SATA_EVNT_INPROC_DEVICE_RESET) {
10213 		/* Something is weird - new device reset event */
10214 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10215 		    "Overlapping device reset events!", NULL);
10216 		/* Just leave */
10217 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10218 		    cport_mutex);
10219 		return;
10220 	}
10221 
10222 	/* Clear event flag */
10223 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
10224 
10225 	/* It seems that we always need to check the port state first */
10226 	sata_device.satadev_rev = SATA_DEVICE_REV;
10227 	sata_device.satadev_addr = *saddr;
10228 	/*
10229 	 * We have to exit mutex, because the HBA probe port function may
10230 	 * block on its own mutex.
10231 	 */
10232 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10233 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10234 	    (SATA_DIP(sata_hba_inst), &sata_device);
10235 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10236 	sata_update_port_info(sata_hba_inst, &sata_device);
10237 	if (rval != SATA_SUCCESS) {
10238 		/* Something went wrong? Fail the port */
10239 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10240 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10241 		    cport_mutex);
10242 		SATA_LOG_D((sata_hba_inst, CE_WARN, "Port %d probing failed",
10243 		    saddr->cport));
10244 		return;
10245 	}
10246 	if ((sata_device.satadev_scr.sstatus  &
10247 	    SATA_PORT_DEVLINK_UP_MASK) !=
10248 	    SATA_PORT_DEVLINK_UP ||
10249 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
10250 		/*
10251 		 * No device to process, anymore. Some other event processing
10252 		 * would or have already performed port info cleanup.
10253 		 * To be safe (HBA may need it), request clearing device
10254 		 * reset condition.
10255 		 */
10256 		sdinfo->satadrv_event_flags = 0;
10257 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
10258 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10259 		    cport_mutex);
10260 		return;
10261 	}
10262 
10263 	/* Mark device reset processing as active */
10264 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
10265 
10266 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
10267 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10268 
10269 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
10270 	    SATA_FAILURE) {
10271 		/*
10272 		 * Restoring drive setting failed.
10273 		 * Probe the port first, to check if the port state has changed
10274 		 */
10275 		sata_device.satadev_rev = SATA_DEVICE_REV;
10276 		sata_device.satadev_addr = *saddr;
10277 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
10278 		/* probe port */
10279 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10280 		    (SATA_DIP(sata_hba_inst), &sata_device);
10281 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10282 		    cport_mutex);
10283 		if (rval == SATA_SUCCESS &&
10284 		    (sata_device.satadev_state &
10285 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
10286 		    (sata_device.satadev_scr.sstatus  &
10287 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
10288 		    (sata_device.satadev_type & SATA_DTYPE_ATADISK) != 0) {
10289 			/*
10290 			 * We may retry this a bit later - reinstate reset
10291 			 * condition
10292 			 */
10293 			if ((cportinfo->cport_dev_type &
10294 			    SATA_VALID_DEV_TYPE) != 0 &&
10295 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10296 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10297 				sdinfo->satadrv_event_flags |=
10298 				    SATA_EVNT_DEVICE_RESET;
10299 				sdinfo->satadrv_event_flags &=
10300 				    ~SATA_EVNT_INPROC_DEVICE_RESET;
10301 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
10302 				    saddr->cport)->cport_mutex);
10303 				mutex_enter(&sata_hba_inst->satahba_mutex);
10304 				sata_hba_inst->satahba_event_flags |=
10305 				    SATA_EVNT_MAIN;
10306 				mutex_exit(&sata_hba_inst->satahba_mutex);
10307 				return;
10308 			}
10309 		} else {
10310 			/*
10311 			 * No point of retrying - some other event processing
10312 			 * would or already did port info cleanup.
10313 			 * To be safe (HBA may need it),
10314 			 * request clearing device reset condition.
10315 			 */
10316 			sdinfo->satadrv_event_flags = 0;
10317 			sdinfo->satadrv_event_flags |=
10318 			    SATA_EVNT_CLEAR_DEVICE_RESET;
10319 		}
10320 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10321 		    cport_mutex);
10322 		return;
10323 	}
10324 
10325 	/*
10326 	 * Raise the flag indicating that the next sata command could
10327 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
10328 	 * reset is reported.
10329 	 */
10330 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10331 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0 &&
10332 	    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10333 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10334 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
10335 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
10336 	}
10337 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10338 }
10339 
10340 
10341 /*
10342  * Port Link Events processing.
10343  * Every link established event may involve device reset (due to
10344  * COMRESET signal, equivalent of the hard reset) so arbitrarily
10345  * set device reset event for an attached device (if any).
10346  * If the port is in SHUTDOWN or FAILED state, ignore link events.
10347  *
10348  * The link established event processing varies, depending on the state
10349  * of the target node, HBA hotplugging capabilities, state of the port.
10350  * If the link is not active, the link established event is ignored.
10351  * If HBA cannot detect device attachment and there is no target node,
10352  * the link established event triggers device attach event processing.
10353  * Else, link established event triggers device reset event processing.
10354  *
10355  * The link lost event processing varies, depending on a HBA hotplugging
10356  * capability and the state of the port (link active or not active).
10357  * If the link is active, the lost link event is ignored.
10358  * If HBA cannot detect device removal, the lost link event triggers
10359  * device detached event processing after link lost timeout.
10360  * Else, the event is ignored.
10361  *
10362  * NOTE: Only cports are processed for now, i.e. no port multiplier ports
10363  */
10364 static void
10365 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
10366     sata_address_t *saddr)
10367 {
10368 	sata_device_t sata_device;
10369 	sata_cport_info_t *cportinfo;
10370 	sata_drive_info_t *sdinfo;
10371 	int event_flags;
10372 	int rval;
10373 
10374 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10375 	    "Processing port %d link event(s)", saddr->cport);
10376 
10377 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
10378 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10379 	event_flags = cportinfo->cport_event_flags;
10380 
10381 	/* Reset event flags first */
10382 	cportinfo->cport_event_flags &=
10383 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
10384 
10385 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
10386 	if ((cportinfo->cport_state &
10387 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
10388 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10389 		    cport_mutex);
10390 		return;
10391 	}
10392 
10393 	/*
10394 	 * For the sanity sake get current port state.
10395 	 * Set device address only. Other sata_device fields should be
10396 	 * set by HBA driver.
10397 	 */
10398 	sata_device.satadev_rev = SATA_DEVICE_REV;
10399 	sata_device.satadev_addr = *saddr;
10400 	/*
10401 	 * We have to exit mutex, because the HBA probe port function may
10402 	 * block on its own mutex.
10403 	 */
10404 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10405 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10406 	    (SATA_DIP(sata_hba_inst), &sata_device);
10407 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10408 	sata_update_port_info(sata_hba_inst, &sata_device);
10409 	if (rval != SATA_SUCCESS) {
10410 		/* Something went wrong? Fail the port */
10411 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10412 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10413 		    cport_mutex);
10414 		SATA_LOG_D((sata_hba_inst, CE_WARN, "Port %d probing failed",
10415 		    saddr->cport));
10416 		/*
10417 		 * We may want to release device info structure, but
10418 		 * it is not necessary.
10419 		 */
10420 		return;
10421 	} else {
10422 		/* port probed successfully */
10423 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
10424 	}
10425 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
10426 
10427 		if ((sata_device.satadev_scr.sstatus &
10428 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
10429 			/* Ignore event */
10430 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10431 			    "Ignoring port %d link established event - "
10432 			    "link down",
10433 			    saddr->cport);
10434 			goto linklost;
10435 		}
10436 
10437 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10438 		    "Processing port %d link established event",
10439 		    saddr->cport);
10440 
10441 		/*
10442 		 * For the sanity sake check if a device is attached - check
10443 		 * return state of a port probing.
10444 		 */
10445 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
10446 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
10447 			/*
10448 			 * HBA port probe indicated that there is a device
10449 			 * attached. Check if the framework had device info
10450 			 * structure attached for this device.
10451 			 */
10452 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
10453 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
10454 				    NULL);
10455 
10456 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10457 				if ((sdinfo->satadrv_type &
10458 				    SATA_VALID_DEV_TYPE) != 0) {
10459 					/*
10460 					 * Dev info structure is present.
10461 					 * If dev_type is set to known type in
10462 					 * the framework's drive info struct
10463 					 * then the device existed before and
10464 					 * the link was probably lost
10465 					 * momentarily - in such case
10466 					 * we may want to check device
10467 					 * identity.
10468 					 * Identity check is not supported now.
10469 					 *
10470 					 * Link established event
10471 					 * triggers device reset event.
10472 					 */
10473 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
10474 					    satadrv_event_flags |=
10475 					    SATA_EVNT_DEVICE_RESET;
10476 				}
10477 			} else if (cportinfo->cport_dev_type ==
10478 			    SATA_DTYPE_NONE) {
10479 				/*
10480 				 * We got new device attached! If HBA does not
10481 				 * generate device attached events, trigger it
10482 				 * here.
10483 				 */
10484 				if (!(SATA_FEATURES(sata_hba_inst) &
10485 				    SATA_CTLF_HOTPLUG)) {
10486 					cportinfo->cport_event_flags |=
10487 					    SATA_EVNT_DEVICE_ATTACHED;
10488 				}
10489 			}
10490 			/* Reset link lost timeout */
10491 			cportinfo->cport_link_lost_time = 0;
10492 		}
10493 	}
10494 linklost:
10495 	if (event_flags & SATA_EVNT_LINK_LOST) {
10496 		if ((sata_device.satadev_scr.sstatus &
10497 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
10498 			/* Ignore event */
10499 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10500 			    "Ignoring port %d link lost event - link is up",
10501 			    saddr->cport);
10502 			goto done;
10503 		}
10504 #ifdef SATA_DEBUG
10505 		if (cportinfo->cport_link_lost_time == 0) {
10506 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10507 			    "Processing port %d link lost event",
10508 			    saddr->cport);
10509 		}
10510 #endif
10511 		/*
10512 		 * When HBA cannot generate device attached/detached events,
10513 		 * we need to track link lost time and eventually generate
10514 		 * device detach event.
10515 		 */
10516 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
10517 			/* We are tracking link lost time */
10518 			if (cportinfo->cport_link_lost_time == 0) {
10519 				/* save current time (lbolt value) */
10520 				cportinfo->cport_link_lost_time =
10521 				    ddi_get_lbolt();
10522 				/* just keep link lost event */
10523 				cportinfo->cport_event_flags |=
10524 				    SATA_EVNT_LINK_LOST;
10525 			} else {
10526 				clock_t cur_time = ddi_get_lbolt();
10527 				if ((cur_time -
10528 				    cportinfo->cport_link_lost_time) >=
10529 				    drv_usectohz(
10530 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
10531 					/* trigger device detach event */
10532 					cportinfo->cport_event_flags |=
10533 					    SATA_EVNT_DEVICE_DETACHED;
10534 					cportinfo->cport_link_lost_time = 0;
10535 					SATADBG1(SATA_DBG_EVENTS,
10536 					    sata_hba_inst,
10537 					    "Triggering port %d "
10538 					    "device detached event",
10539 					    saddr->cport);
10540 				} else {
10541 					/* keep link lost event */
10542 					cportinfo->cport_event_flags |=
10543 					    SATA_EVNT_LINK_LOST;
10544 				}
10545 			}
10546 		}
10547 		/*
10548 		 * We could change port state to disable/delay access to
10549 		 * the attached device until the link is recovered.
10550 		 */
10551 	}
10552 done:
10553 	event_flags = cportinfo->cport_event_flags;
10554 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10555 	if (event_flags != 0) {
10556 		mutex_enter(&sata_hba_inst->satahba_mutex);
10557 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
10558 		mutex_exit(&sata_hba_inst->satahba_mutex);
10559 		mutex_enter(&sata_mutex);
10560 		sata_event_pending |= SATA_EVNT_MAIN;
10561 		mutex_exit(&sata_mutex);
10562 	}
10563 }
10564 
10565 /*
10566  * Device Detached Event processing.
10567  * Port is probed to find if a device is really gone. If so,
10568  * the device info structure is detached from the SATA port info structure
10569  * and released.
10570  * Port status is updated.
10571  *
10572  * NOTE: Process cports event only, no port multiplier ports.
10573  */
10574 static void
10575 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
10576     sata_address_t *saddr)
10577 {
10578 	sata_cport_info_t *cportinfo;
10579 	sata_drive_info_t *sdevinfo;
10580 	sata_device_t sata_device;
10581 	dev_info_t *tdip;
10582 	int rval;
10583 
10584 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10585 	    "Processing port %d device detached", saddr->cport);
10586 
10587 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
10588 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10589 	/* Clear event flag */
10590 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
10591 
10592 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
10593 	if ((cportinfo->cport_state &
10594 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
10595 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10596 		    cport_mutex);
10597 		return;
10598 	}
10599 	/* For sanity, re-probe the port */
10600 	sata_device.satadev_rev = SATA_DEVICE_REV;
10601 	sata_device.satadev_addr = *saddr;
10602 
10603 	/*
10604 	 * We have to exit mutex, because the HBA probe port function may
10605 	 * block on its own mutex.
10606 	 */
10607 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10608 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10609 	    (SATA_DIP(sata_hba_inst), &sata_device);
10610 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10611 	sata_update_port_info(sata_hba_inst, &sata_device);
10612 	if (rval != SATA_SUCCESS) {
10613 		/* Something went wrong? Fail the port */
10614 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10615 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10616 		    cport_mutex);
10617 		SATA_LOG_D((sata_hba_inst, CE_WARN, "Port %d probing failed",
10618 		    saddr->cport));
10619 		/*
10620 		 * We may want to release device info structure, but
10621 		 * it is not necessary.
10622 		 */
10623 		return;
10624 	} else {
10625 		/* port probed successfully */
10626 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
10627 	}
10628 	/*
10629 	 * Check if a device is still attached. For sanity, check also
10630 	 * link status - if no link, there is no device.
10631 	 */
10632 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
10633 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
10634 	    SATA_DTYPE_NONE) {
10635 		/*
10636 		 * Device is still attached - ignore detach event.
10637 		 */
10638 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10639 		    cport_mutex);
10640 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10641 		    "Ignoring detach - device still attached to port %d",
10642 		    sata_device.satadev_addr.cport);
10643 		return;
10644 	}
10645 	/*
10646 	 * We need to detach and release device info structure here
10647 	 */
10648 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10649 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10650 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10651 		(void) kmem_free((void *)sdevinfo,
10652 		    sizeof (sata_drive_info_t));
10653 	}
10654 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10655 	/*
10656 	 * Device cannot be reached anymore, even if the target node may be
10657 	 * still present.
10658 	 */
10659 
10660 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10661 	sata_log(sata_hba_inst, CE_WARN, "SATA device detached at port %d",
10662 	    sata_device.satadev_addr.cport);
10663 
10664 	/*
10665 	 * Try to offline a device and remove target node if it still exists
10666 	 */
10667 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport);
10668 	if (tdip != NULL) {
10669 		/*
10670 		 * target node exist - unconfigure device first, then remove
10671 		 * the node
10672 		 */
10673 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
10674 			/*
10675 			 * PROBLEM - no device, but target node remained
10676 			 * This happens when the file was open or node was
10677 			 * waiting for resources.
10678 			 */
10679 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10680 			    "sata_process_device_detached: "
10681 			    "Failed to unconfigure removed device."));
10682 		}
10683 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10684 			/*
10685 			 * PROBLEM - no device, but target node remained
10686 			 * This happens when the file was open or node was
10687 			 * waiting for resources.
10688 			 */
10689 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10690 			    "sata_process_device_detached: "
10691 			    "Failed to remove target node for "
10692 			    "removed device."));
10693 		}
10694 	}
10695 	/*
10696 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
10697 	 * with the hint: SE_HINT_REMOVE
10698 	 */
10699 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
10700 }
10701 
10702 
10703 /*
10704  * Device Attached Event processing.
10705  * Port state is checked to verify that a device is really attached. If so,
10706  * the device info structure is created and attached to the SATA port info
10707  * structure.
10708  *
10709  * This function cannot be called in interrupt context (it may sleep).
10710  *
10711  * NOTE: Process cports event only, no port multiplier ports.
10712  */
10713 static void
10714 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
10715     sata_address_t *saddr)
10716 {
10717 	sata_cport_info_t *cportinfo;
10718 	sata_drive_info_t *sdevinfo;
10719 	sata_device_t sata_device;
10720 	dev_info_t *tdip;
10721 	int rval;
10722 
10723 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10724 	    "Processing port %d device attached", saddr->cport);
10725 
10726 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
10727 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10728 
10729 	/* Clear event flag first */
10730 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
10731 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
10732 	if ((cportinfo->cport_state &
10733 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
10734 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10735 		    cport_mutex);
10736 		return;
10737 	}
10738 
10739 	/*
10740 	 * If the sata_drive_info structure is found attached to the port info,
10741 	 * something went wrong in the event reporting and processing sequence.
10742 	 * To recover, arbitrarily release device info structure and issue
10743 	 * a warning.
10744 	 */
10745 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10746 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10747 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10748 		(void) kmem_free((void *)sdevinfo,
10749 		    sizeof (sata_drive_info_t));
10750 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10751 		    "Arbitrarily detaching old device info."));
10752 	}
10753 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10754 
10755 	/* For sanity, re-probe the port */
10756 	sata_device.satadev_rev = SATA_DEVICE_REV;
10757 	sata_device.satadev_addr = *saddr;
10758 
10759 	/*
10760 	 * We have to exit mutex, because the HBA probe port function may
10761 	 * block on its own mutex.
10762 	 */
10763 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10764 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10765 	    (SATA_DIP(sata_hba_inst), &sata_device);
10766 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10767 	sata_update_port_info(sata_hba_inst, &sata_device);
10768 	if (rval != SATA_SUCCESS) {
10769 		/* Something went wrong? Fail the port */
10770 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10771 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10772 		    cport_mutex);
10773 		SATA_LOG_D((sata_hba_inst, CE_WARN, "Port %d probing failed",
10774 		    saddr->cport));
10775 		return;
10776 	} else {
10777 		/* port probed successfully */
10778 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
10779 	}
10780 	/*
10781 	 * Check if a device is still attached. For sanity, check also
10782 	 * link status - if no link, there is no device.
10783 	 */
10784 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10785 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
10786 	    SATA_DTYPE_NONE) {
10787 		/*
10788 		 * No device - ignore attach event.
10789 		 */
10790 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
10791 		    cport_mutex);
10792 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10793 		    "Ignoring attach - no device connected to port %d",
10794 		    sata_device.satadev_addr.cport);
10795 		return;
10796 	}
10797 
10798 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10799 	/*
10800 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
10801 	 * with the hint: SE_HINT_INSERT
10802 	 */
10803 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
10804 
10805 	/*
10806 	 * Make sure that there is no target node for that device.
10807 	 * If so, release it. It should not happen, unless we had problem
10808 	 * removing the node when device was detached.
10809 	 */
10810 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport);
10811 	if (tdip != NULL) {
10812 
10813 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10814 		    "sata_process_device_attached: "
10815 		    "old device target node exists!!!"));
10816 		/*
10817 		 * target node exist - unconfigure device first, then remove
10818 		 * the node
10819 		 */
10820 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
10821 			/*
10822 			 * PROBLEM - no device, but target node remained
10823 			 * This happens when the file was open or node was
10824 			 * waiting for resources.
10825 			 */
10826 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10827 			    "sata_process_device_attached: "
10828 			    "Failed to unconfigure old target node!"));
10829 		}
10830 		/* Following call will retry node offlining and removing it */
10831 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10832 			/* PROBLEM - no device, but target node remained */
10833 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10834 			    "sata_process_device_attached: "
10835 			    "Failed to remove old target node!"));
10836 			/*
10837 			 * It is not clear, what should be done here.
10838 			 * For now, we will not attach a new device
10839 			 */
10840 			return;
10841 		}
10842 	}
10843 
10844 	/*
10845 	 * Reprobing port will take care of the creation of the device info
10846 	 * structure and determination of the device type.
10847 	 */
10848 	sata_device.satadev_addr = *saddr;
10849 	(void) sata_reprobe_port(sata_hba_inst, &sata_device);
10850 	/*
10851 	 * If device was successfully attached, an explicit
10852 	 * 'configure' command is needed to configure it.
10853 	 */
10854 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10855 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
10856 	    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
10857 		sata_log(sata_hba_inst, CE_WARN,
10858 		    "SATA device attached at port %d", saddr->cport);
10859 
10860 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10861 			sata_drive_info_t new_sdinfo;
10862 
10863 			/* Log device info data */
10864 			new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(cportinfo));
10865 			sata_show_drive_info(sata_hba_inst, &new_sdinfo);
10866 		}
10867 	}
10868 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
10869 }
10870 
10871 
10872 /*
10873  * sata_set_drive_featues function compares current device features setting
10874  * with the saved device features settings and, if there is a difference,
10875  * it restores device features setting to the previously saved state.
10876  * Device Identify data has to be current.
10877  * At the moment only read ahead and write cache settings are considered.
10878  *
10879  * This function cannot be called in the interrupt context (it may sleep).
10880  *
10881  * The input argument sdinfo should point to the drive info structure
10882  * to be updated after features are set.
10883  *
10884  * Returns TRUE if successful or there was nothing to do.
10885  * Returns FALSE if device features cound not be set .
10886  *
10887  * Note: This function may fail the port, making it inaccessible.
10888  * Explicit port disconnect/connect or physical device
10889  * detach/attach is required to re-evaluate it's state afterwards
10890  */
10891 
10892 static int
10893 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
10894     sata_drive_info_t *sdinfo, int restore)
10895 {
10896 	int rval = SATA_SUCCESS;
10897 	sata_drive_info_t new_sdinfo;
10898 	char *finfo = "sata_set_drive_features: cannot";
10899 	char *finfox;
10900 	int cache_op;
10901 
10902 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
10903 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
10904 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
10905 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
10906 		/*
10907 		 * Cannot get device identification - retry later
10908 		 */
10909 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10910 		    "%s fetch device identify data\n", finfo));
10911 		return (SATA_FAILURE);
10912 	}
10913 	/* Arbitrarily set UDMA mode */
10914 	if (sata_set_udma_mode(sata_hba_inst, &new_sdinfo) != SATA_SUCCESS) {
10915 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10916 		    "%s set UDMA mode\n", finfo));
10917 		return (SATA_FAILURE);
10918 	}
10919 
10920 	if (!(new_sdinfo.satadrv_id.ai_cmdset82 & SATA_LOOK_AHEAD) &&
10921 	    !(new_sdinfo.satadrv_id.ai_cmdset82 & SATA_WRITE_CACHE)) {
10922 		/* None of the features is supported - do nothing */
10923 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10924 		    "settable features not supported\n", NULL);
10925 		return (SATA_SUCCESS);
10926 	}
10927 
10928 	if (((new_sdinfo.satadrv_id.ai_features85 & SATA_LOOK_AHEAD) &&
10929 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
10930 	    ((new_sdinfo.satadrv_id.ai_features85 & SATA_WRITE_CACHE) &&
10931 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
10932 		/* Nothing to do */
10933 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
10934 		    "no device features to set\n", NULL);
10935 		return (SATA_SUCCESS);
10936 	}
10937 
10938 	finfox = (restore != 0) ? " restore device features" :
10939 	    " initialize device features\n";
10940 
10941 	if (!((new_sdinfo.satadrv_id.ai_features85 & SATA_LOOK_AHEAD) &&
10942 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD))) {
10943 		if (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)
10944 			/* Enable read ahead / read cache */
10945 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
10946 		else
10947 			/* Disable read ahead  / read cache */
10948 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
10949 
10950 		/* Try to set read cache mode */
10951 		if (sata_set_cache_mode(sata_hba_inst, &new_sdinfo,
10952 		    cache_op) != SATA_SUCCESS) {
10953 			/* Pkt execution failed */
10954 			rval = SATA_FAILURE;
10955 		}
10956 	}
10957 
10958 	if (!((new_sdinfo.satadrv_id.ai_features85 & SATA_WRITE_CACHE) &&
10959 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
10960 		if (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE)
10961 			/* Enable write cache */
10962 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
10963 		else
10964 			/* Disable write cache */
10965 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
10966 
10967 		/* Try to set write cache mode */
10968 		if (sata_set_cache_mode(sata_hba_inst, &new_sdinfo,
10969 		    cache_op) != SATA_SUCCESS) {
10970 			/* Pkt execution failed */
10971 			rval = SATA_FAILURE;
10972 		}
10973 	}
10974 
10975 	if (rval == SATA_FAILURE)
10976 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10977 		    "%s %s", finfo, finfox));
10978 
10979 	/*
10980 	 * We need to fetch Device Identify data again
10981 	 */
10982 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
10983 		/*
10984 		 * Cannot get device identification - retry later
10985 		 */
10986 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10987 		    "%s cannot re-fetch device identify data\n"));
10988 		rval = SATA_FAILURE;
10989 	}
10990 	/* Copy device sata info. */
10991 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
10992 
10993 	return (rval);
10994 }
10995 
10996 
10997 /*
10998  *
10999  * Returns 1 if threshold exceeded, 0 if threshold no exceeded, -1 if
11000  * unable to determine.
11001  *
11002  * Cannot be called in an interrupt context.
11003  *
11004  * Called by sata_build_lsense_page_2f()
11005  */
11006 
11007 static int
11008 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
11009     sata_drive_info_t *sdinfo)
11010 {
11011 	sata_pkt_t *spkt;
11012 	sata_cmd_t *scmd;
11013 	sata_pkt_txlate_t *spx;
11014 	int rval;
11015 
11016 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
11017 	spx->txlt_sata_hba_inst = sata_hba_inst;
11018 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
11019 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
11020 	if (spkt == NULL) {
11021 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11022 		return (-1);
11023 	}
11024 	/* address is needed now */
11025 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11026 
11027 
11028 	/* Fill sata_pkt */
11029 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11030 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
11031 	/* Synchronous mode, no callback */
11032 	spkt->satapkt_comp = NULL;
11033 	/* Timeout 30s */
11034 	spkt->satapkt_time = sata_default_pkt_time;
11035 
11036 	scmd = &spkt->satapkt_cmd;
11037 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
11038 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
11039 
11040 	/* Set up which registers need to be returned */
11041 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
11042 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
11043 
11044 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
11045 	scmd->satacmd_addr_type = 0;		/* N/A */
11046 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
11047 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
11048 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
11049 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
11050 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
11051 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
11052 	scmd->satacmd_cmd_reg = SATAC_SMART;
11053 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11054 	    sdinfo->satadrv_addr.cport)));
11055 
11056 
11057 	/* Send pkt to SATA HBA driver */
11058 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
11059 	    SATA_TRAN_ACCEPTED ||
11060 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
11061 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11062 		    sdinfo->satadrv_addr.cport)));
11063 		/*
11064 		 * Whoops, no SMART RETURN STATUS
11065 		 */
11066 		rval = -1;
11067 	} else {
11068 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11069 		    sdinfo->satadrv_addr.cport)));
11070 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
11071 			rval = -1;
11072 			goto fail;
11073 		}
11074 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
11075 			rval = -1;
11076 			goto fail;
11077 		}
11078 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
11079 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
11080 			rval = 0;
11081 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
11082 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
11083 			rval = 1;
11084 		else {
11085 			rval = -1;
11086 			goto fail;
11087 		}
11088 	}
11089 fail:
11090 	/* Free allocated resources */
11091 	sata_pkt_free(spx);
11092 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
11093 
11094 	return (rval);
11095 }
11096 
11097 /*
11098  *
11099  * Returns 0 if succeeded, -1 otherwise
11100  *
11101  * Cannot be called in an interrupt context.
11102  *
11103  */
11104 static int
11105 sata_fetch_smart_data(
11106 	sata_hba_inst_t *sata_hba_inst,
11107 	sata_drive_info_t *sdinfo,
11108 	struct smart_data *smart_data)
11109 {
11110 	sata_pkt_t *spkt;
11111 	sata_cmd_t *scmd;
11112 	sata_pkt_txlate_t *spx;
11113 	int rval;
11114 
11115 #if ! defined(lint)
11116 	ASSERT(sizeof (struct smart_data) == 512);
11117 #endif
11118 
11119 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
11120 	spx->txlt_sata_hba_inst = sata_hba_inst;
11121 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
11122 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
11123 	if (spkt == NULL) {
11124 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11125 		return (-1);
11126 	}
11127 	/* address is needed now */
11128 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11129 
11130 
11131 	/* Fill sata_pkt */
11132 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11133 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
11134 	/* Synchronous mode, no callback */
11135 	spkt->satapkt_comp = NULL;
11136 	/* Timeout 30s */
11137 	spkt->satapkt_time = sata_default_pkt_time;
11138 
11139 	scmd = &spkt->satapkt_cmd;
11140 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
11141 
11142 	/*
11143 	 * Allocate buffer for SMART data
11144 	 */
11145 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
11146 	    sizeof (struct smart_data));
11147 	if (scmd->satacmd_bp == NULL) {
11148 		sata_pkt_free(spx);
11149 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11150 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11151 		    "sata_fetch_smart_data: "
11152 		    "cannot allocate buffer"));
11153 		return (-1);
11154 	}
11155 
11156 
11157 	/* Build SMART_READ_DATA cmd in the sata_pkt */
11158 	scmd->satacmd_addr_type = 0;		/* N/A */
11159 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
11160 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
11161 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
11162 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
11163 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
11164 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
11165 	scmd->satacmd_cmd_reg = SATAC_SMART;
11166 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11167 	    sdinfo->satadrv_addr.cport)));
11168 
11169 	/* Send pkt to SATA HBA driver */
11170 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
11171 	    SATA_TRAN_ACCEPTED ||
11172 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
11173 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11174 		    sdinfo->satadrv_addr.cport)));
11175 		/*
11176 		 * Whoops, no SMART DATA available
11177 		 */
11178 		rval = -1;
11179 		goto fail;
11180 	} else {
11181 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11182 		    sdinfo->satadrv_addr.cport)));
11183 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
11184 			DDI_DMA_SYNC_FORKERNEL);
11185 		if (rval != DDI_SUCCESS) {
11186 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
11187 			    "sata_fetch_smart_data: "
11188 			    "sync pkt failed"));
11189 			rval = -1;
11190 			goto fail;
11191 		}
11192 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
11193 		    sizeof (struct smart_data));
11194 	}
11195 
11196 fail:
11197 	/* Free allocated resources */
11198 	sata_free_local_buffer(spx);
11199 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
11200 	sata_pkt_free(spx);
11201 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
11202 
11203 	return (rval);
11204 }
11205 
11206 /*
11207  * Used by LOG SENSE page 0x10
11208  *
11209  * return 0 for success, -1 otherwise
11210  *
11211  */
11212 static int
11213 sata_ext_smart_selftest_read_log(
11214 	sata_hba_inst_t *sata_hba_inst,
11215 	sata_drive_info_t *sdinfo,
11216 	struct smart_ext_selftest_log *ext_selftest_log,
11217 	uint16_t block_num)
11218 {
11219 	sata_pkt_txlate_t *spx;
11220 	sata_pkt_t *spkt;
11221 	sata_cmd_t *scmd;
11222 	int rval;
11223 
11224 #if ! defined(lint)
11225 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
11226 #endif
11227 
11228 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
11229 	spx->txlt_sata_hba_inst = sata_hba_inst;
11230 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
11231 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
11232 	if (spkt == NULL) {
11233 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11234 		return (-1);
11235 	}
11236 	/* address is needed now */
11237 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11238 
11239 
11240 	/* Fill sata_pkt */
11241 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11242 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
11243 	/* Synchronous mode, no callback */
11244 	spkt->satapkt_comp = NULL;
11245 	/* Timeout 30s */
11246 	spkt->satapkt_time = sata_default_pkt_time;
11247 
11248 	scmd = &spkt->satapkt_cmd;
11249 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
11250 
11251 	/*
11252 	 * Allocate buffer for SMART extended self-test log
11253 	 */
11254 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
11255 	    sizeof (struct smart_ext_selftest_log));
11256 	if (scmd->satacmd_bp == NULL) {
11257 		sata_pkt_free(spx);
11258 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11259 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11260 		    "sata_ext_smart_selftest_log: "
11261 		    "cannot allocate buffer"));
11262 		return (-1);
11263 	}
11264 
11265 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
11266 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
11267 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
11268 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
11269 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
11270 	scmd->satacmd_lba_low_msb = 0;
11271 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
11272 	scmd->satacmd_lba_mid_msb = block_num >> 8;
11273 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
11274 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
11275 
11276 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11277 	    sdinfo->satadrv_addr.cport)));
11278 
11279 	/* Send pkt to SATA HBA driver */
11280 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
11281 	    SATA_TRAN_ACCEPTED ||
11282 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
11283 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11284 		    sdinfo->satadrv_addr.cport)));
11285 
11286 		/*
11287 		 * Whoops, no SMART selftest log info available
11288 		 */
11289 		rval = -1;
11290 		goto fail;
11291 	} else {
11292 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11293 		    sdinfo->satadrv_addr.cport)));
11294 
11295 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
11296 			DDI_DMA_SYNC_FORKERNEL);
11297 		if (rval != DDI_SUCCESS) {
11298 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
11299 			    "sata_ext_smart_selftest_log: "
11300 			    "sync pkt failed"));
11301 			rval = -1;
11302 			goto fail;
11303 		}
11304 		bcopy(scmd->satacmd_bp->b_un.b_addr,
11305 		    (uint8_t *)ext_selftest_log,
11306 		    sizeof (struct smart_ext_selftest_log));
11307 		rval = 0;
11308 	}
11309 
11310 fail:
11311 	/* Free allocated resources */
11312 	sata_free_local_buffer(spx);
11313 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
11314 	sata_pkt_free(spx);
11315 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
11316 
11317 	return (rval);
11318 }
11319 
11320 /*
11321  * Returns 0 for success, -1 otherwise
11322  *
11323  * SMART self-test log data is returned in buffer pointed to by selftest_log
11324  */
11325 static int
11326 sata_smart_selftest_log(
11327 	sata_hba_inst_t *sata_hba_inst,
11328 	sata_drive_info_t *sdinfo,
11329 	struct smart_selftest_log *selftest_log)
11330 {
11331 	sata_pkt_t *spkt;
11332 	sata_cmd_t *scmd;
11333 	sata_pkt_txlate_t *spx;
11334 	int rval;
11335 
11336 #if ! defined(lint)
11337 	ASSERT(sizeof (struct smart_selftest_log) == 512);
11338 #endif
11339 
11340 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
11341 	spx->txlt_sata_hba_inst = sata_hba_inst;
11342 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
11343 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
11344 	if (spkt == NULL) {
11345 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11346 		return (-1);
11347 	}
11348 	/* address is needed now */
11349 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11350 
11351 
11352 	/* Fill sata_pkt */
11353 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11354 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
11355 	/* Synchronous mode, no callback */
11356 	spkt->satapkt_comp = NULL;
11357 	/* Timeout 30s */
11358 	spkt->satapkt_time = sata_default_pkt_time;
11359 
11360 	scmd = &spkt->satapkt_cmd;
11361 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
11362 
11363 	/*
11364 	 * Allocate buffer for Identify Data return data
11365 	 */
11366 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
11367 	    sizeof (struct smart_selftest_log));
11368 	if (scmd->satacmd_bp == NULL) {
11369 		sata_pkt_free(spx);
11370 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11371 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11372 		    "sata_smart_selftest_log: "
11373 		    "cannot allocate buffer"));
11374 		return (-1);
11375 	}
11376 
11377 	/* Build SMART_READ_DATA cmd in the sata_pkt */
11378 	scmd->satacmd_addr_type = 0;		/* N/A */
11379 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
11380 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
11381 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
11382 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
11383 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
11384 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
11385 	scmd->satacmd_cmd_reg = SATAC_SMART;
11386 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11387 	    sdinfo->satadrv_addr.cport)));
11388 
11389 	/* Send pkt to SATA HBA driver */
11390 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
11391 	    SATA_TRAN_ACCEPTED ||
11392 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
11393 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11394 		    sdinfo->satadrv_addr.cport)));
11395 		/*
11396 		 * Whoops, no SMART DATA available
11397 		 */
11398 		rval = -1;
11399 		goto fail;
11400 	} else {
11401 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11402 		    sdinfo->satadrv_addr.cport)));
11403 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
11404 			DDI_DMA_SYNC_FORKERNEL);
11405 		if (rval != DDI_SUCCESS) {
11406 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
11407 			    "sata_smart_selftest_log: "
11408 			    "sync pkt failed"));
11409 			rval = -1;
11410 			goto fail;
11411 		}
11412 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
11413 		    sizeof (struct smart_selftest_log));
11414 		rval = 0;
11415 	}
11416 
11417 fail:
11418 	/* Free allocated resources */
11419 	sata_free_local_buffer(spx);
11420 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
11421 	sata_pkt_free(spx);
11422 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
11423 
11424 	return (rval);
11425 }
11426 
11427 
11428 /*
11429  * Returns 0 for success, -1 otherwise
11430  *
11431  * SMART READ LOG data is returned in buffer pointed to by smart_log
11432  */
11433 static int
11434 sata_smart_read_log(
11435 	sata_hba_inst_t *sata_hba_inst,
11436 	sata_drive_info_t *sdinfo,
11437 	uint8_t *smart_log,		/* where the data should be returned */
11438 	uint8_t which_log,		/* which log should be returned */
11439 	uint8_t log_size)		/* # of 512 bytes in log */
11440 {
11441 	sata_pkt_t *spkt;
11442 	sata_cmd_t *scmd;
11443 	sata_pkt_txlate_t *spx;
11444 	int rval;
11445 
11446 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
11447 	spx->txlt_sata_hba_inst = sata_hba_inst;
11448 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
11449 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
11450 	if (spkt == NULL) {
11451 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11452 		return (-1);
11453 	}
11454 	/* address is needed now */
11455 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11456 
11457 
11458 	/* Fill sata_pkt */
11459 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11460 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
11461 	/* Synchronous mode, no callback */
11462 	spkt->satapkt_comp = NULL;
11463 	/* Timeout 30s */
11464 	spkt->satapkt_time = sata_default_pkt_time;
11465 
11466 	scmd = &spkt->satapkt_cmd;
11467 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
11468 
11469 	/*
11470 	 * Allocate buffer for SMART READ LOG
11471 	 */
11472 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
11473 	if (scmd->satacmd_bp == NULL) {
11474 		sata_pkt_free(spx);
11475 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11476 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11477 		    "sata_smart_read_log: " "cannot allocate buffer"));
11478 		return (-1);
11479 	}
11480 
11481 	/* Build SMART_READ_DATA cmd in the sata_pkt */
11482 	scmd->satacmd_addr_type = 0;		/* N/A */
11483 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
11484 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
11485 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
11486 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
11487 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
11488 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
11489 	scmd->satacmd_cmd_reg = SATAC_SMART;
11490 
11491 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11492 	    sdinfo->satadrv_addr.cport)));
11493 
11494 	/* Send pkt to SATA HBA driver */
11495 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
11496 	    SATA_TRAN_ACCEPTED ||
11497 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
11498 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11499 		    sdinfo->satadrv_addr.cport)));
11500 
11501 		/*
11502 		 * Whoops, no SMART DATA available
11503 		 */
11504 		rval = -1;
11505 		goto fail;
11506 	} else {
11507 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11508 		    sdinfo->satadrv_addr.cport)));
11509 
11510 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
11511 			DDI_DMA_SYNC_FORKERNEL);
11512 		if (rval != DDI_SUCCESS) {
11513 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
11514 			    "sata_smart_read_log: " "sync pkt failed"));
11515 			rval = -1;
11516 			goto fail;
11517 		}
11518 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
11519 		rval = 0;
11520 	}
11521 
11522 fail:
11523 	/* Free allocated resources */
11524 	sata_free_local_buffer(spx);
11525 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
11526 	sata_pkt_free(spx);
11527 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
11528 
11529 	return (rval);
11530 }
11531 
11532 /*
11533  * Used by LOG SENSE page 0x10
11534  *
11535  * return 0 for success, -1 otherwise
11536  *
11537  */
11538 static int
11539 sata_read_log_ext_directory(
11540 	sata_hba_inst_t *sata_hba_inst,
11541 	sata_drive_info_t *sdinfo,
11542 	struct read_log_ext_directory *logdir)
11543 {
11544 	sata_pkt_txlate_t *spx;
11545 	sata_pkt_t *spkt;
11546 	sata_cmd_t *scmd;
11547 	int rval;
11548 
11549 #if ! defined(lint)
11550 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
11551 #endif
11552 
11553 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
11554 	spx->txlt_sata_hba_inst = sata_hba_inst;
11555 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
11556 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
11557 	if (spkt == NULL) {
11558 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11559 		return (-1);
11560 	}
11561 
11562 	/* Fill sata_pkt */
11563 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
11564 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
11565 	/* Synchronous mode, no callback */
11566 	spkt->satapkt_comp = NULL;
11567 	/* Timeout 30s */
11568 	spkt->satapkt_time = sata_default_pkt_time;
11569 
11570 	scmd = &spkt->satapkt_cmd;
11571 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
11572 
11573 	/*
11574 	 * Allocate buffer for SMART extended self-test log
11575 	 */
11576 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
11577 	    sizeof (struct read_log_ext_directory));
11578 	if (scmd->satacmd_bp == NULL) {
11579 		sata_pkt_free(spx);
11580 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
11581 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11582 		    "sata_read_log_ext_directory: "
11583 		    "cannot allocate buffer"));
11584 		return (-1);
11585 	}
11586 
11587 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
11588 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
11589 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
11590 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
11591 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
11592 	scmd->satacmd_lba_low_msb = 0;
11593 	scmd->satacmd_lba_mid_lsb = 0;
11594 	scmd->satacmd_lba_mid_msb = 0;
11595 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
11596 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
11597 
11598 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11599 	    sdinfo->satadrv_addr.cport)));
11600 
11601 	/* Send pkt to SATA HBA driver */
11602 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
11603 	    SATA_TRAN_ACCEPTED ||
11604 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
11605 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11606 		    sdinfo->satadrv_addr.cport)));
11607 		/*
11608 		 * Whoops, no SMART selftest log info available
11609 		 */
11610 		rval = -1;
11611 		goto fail;
11612 	} else {
11613 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11614 		    sdinfo->satadrv_addr.cport)));
11615 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
11616 			DDI_DMA_SYNC_FORKERNEL);
11617 		if (rval != DDI_SUCCESS) {
11618 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
11619 			    "sata_read_log_ext_directory: "
11620 			    "sync pkt failed"));
11621 			rval = -1;
11622 			goto fail;
11623 		}
11624 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
11625 		    sizeof (struct read_log_ext_directory));
11626 		rval = 0;
11627 	}
11628 
11629 fail:
11630 	/* Free allocated resources */
11631 	sata_free_local_buffer(spx);
11632 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
11633 	sata_pkt_free(spx);
11634 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
11635 
11636 	return (rval);
11637 }
11638 
11639 static void
11640 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
11641     int hint)
11642 {
11643 	char ap[MAXPATHLEN];
11644 	nvlist_t *ev_attr_list = NULL;
11645 	int err;
11646 
11647 	/* Allocate and build sysevent attribute list */
11648 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
11649 	if (err != 0) {
11650 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11651 		    "sata_gen_sysevent: "
11652 		    "cannot allocate memory for sysevent attributes\n"));
11653 		return;
11654 	}
11655 	/* Add hint attribute */
11656 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
11657 	if (err != 0) {
11658 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11659 		    "sata_gen_sysevent: "
11660 		    "failed to add DR_HINT attr for sysevent"));
11661 		nvlist_free(ev_attr_list);
11662 		return;
11663 	}
11664 	/*
11665 	 * Add AP attribute.
11666 	 * Get controller pathname and convert it into AP pathname by adding
11667 	 * a target number.
11668 	 */
11669 	(void) snprintf(ap, MAXPATHLEN, "/devices");
11670 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
11671 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
11672 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
11673 
11674 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
11675 	if (err != 0) {
11676 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11677 		    "sata_gen_sysevent: "
11678 		    "failed to add DR_AP_ID attr for sysevent"));
11679 		nvlist_free(ev_attr_list);
11680 		return;
11681 	}
11682 
11683 	/* Generate/log sysevent */
11684 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
11685 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
11686 	if (err != DDI_SUCCESS) {
11687 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11688 		    "sata_gen_sysevent: "
11689 		    "cannot log sysevent, err code %x\n", err));
11690 	}
11691 
11692 	nvlist_free(ev_attr_list);
11693 }
11694 
11695 /*
11696  * sata_xlate_errors() is used to translate (S)ATA error
11697  * information to SCSI information returned in the SCSI
11698  * packet.
11699  */
11700 static void
11701 sata_xlate_errors(sata_pkt_txlate_t *spx)
11702 {
11703 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
11704 	struct scsi_extended_sense *sense;
11705 
11706 	scsipkt->pkt_reason = CMD_INCOMPLETE;
11707 	*scsipkt->pkt_scbp = STATUS_CHECK;
11708 	sense = sata_arq_sense(spx);
11709 
11710 	switch (spx->txlt_sata_pkt->satapkt_reason) {
11711 	case SATA_PKT_PORT_ERROR:
11712 		/*
11713 		 * We have no device data. Assume no data transfered.
11714 		 */
11715 		sense->es_key = KEY_HARDWARE_ERROR;
11716 		break;
11717 
11718 	case SATA_PKT_DEV_ERROR:
11719 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
11720 		    SATA_STATUS_ERR) {
11721 			/*
11722 			 * determine dev error reason from error
11723 			 * reg content
11724 			 */
11725 			sata_decode_device_error(spx, sense);
11726 			break;
11727 		}
11728 		/* No extended sense key - no info available */
11729 		break;
11730 
11731 	case SATA_PKT_TIMEOUT:
11732 		/*
11733 		 * scsipkt->pkt_reason = CMD_TIMEOUT; This causes problems.
11734 		 */
11735 		scsipkt->pkt_reason = CMD_INCOMPLETE;
11736 		/* No extended sense key */
11737 		break;
11738 
11739 	case SATA_PKT_ABORTED:
11740 		scsipkt->pkt_reason = CMD_ABORTED;
11741 		/* No extended sense key */
11742 		break;
11743 
11744 	case SATA_PKT_RESET:
11745 		/*
11746 		 * pkt aborted either by an explicit reset request from
11747 		 * a host, or due to error recovery
11748 		 */
11749 		scsipkt->pkt_reason = CMD_RESET;
11750 		break;
11751 
11752 	default:
11753 		scsipkt->pkt_reason = CMD_TRAN_ERR;
11754 		break;
11755 	}
11756 }
11757