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