xref: /titanic_50/usr/src/uts/common/io/sata/impl/sata.c (revision 4a8d0ea71c9a4e51c6a916a083ced6b499eb207f)
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 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 
28 /*
29  * SATA Framework
30  * Generic SATA Host Adapter Implementation
31  */
32 
33 #include <sys/conf.h>
34 #include <sys/file.h>
35 #include <sys/ddi.h>
36 #include <sys/sunddi.h>
37 #include <sys/modctl.h>
38 #include <sys/cmn_err.h>
39 #include <sys/errno.h>
40 #include <sys/thread.h>
41 #include <sys/kstat.h>
42 #include <sys/note.h>
43 #include <sys/sysevent.h>
44 #include <sys/sysevent/eventdefs.h>
45 #include <sys/sysevent/dr.h>
46 #include <sys/taskq.h>
47 #include <sys/disp.h>
48 
49 #include <sys/sata/impl/sata.h>
50 #include <sys/sata/sata_hba.h>
51 #include <sys/sata/sata_defs.h>
52 #include <sys/sata/sata_cfgadm.h>
53 
54 /* Debug flags - defined in sata.h */
55 int	sata_debug_flags = 0;
56 int	sata_msg = 0;
57 
58 /*
59  * Flags enabling selected SATA HBA framework functionality
60  */
61 #define	SATA_ENABLE_QUEUING		1
62 #define	SATA_ENABLE_NCQ			2
63 #define	SATA_ENABLE_PROCESS_EVENTS	4
64 int sata_func_enable =
65 	SATA_ENABLE_PROCESS_EVENTS | SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ;
66 
67 /*
68  * Global variable setting default maximum queue depth (NCQ or TCQ)
69  * Note:minimum queue depth is 1
70  */
71 int sata_max_queue_depth = SATA_MAX_QUEUE_DEPTH; /* max NCQ/TCQ queue depth */
72 
73 /*
74  * Currently used default NCQ/TCQ queue depth. It is set-up during the driver
75  * initialization, using value from sata_max_queue_depth
76  * It is adjusted to minimum supported by the controller and by the device,
77  * if queueing is enabled.
78  */
79 static	int sata_current_max_qdepth;
80 
81 /*
82  * Global variable determining the default behavior after device hotpluggin.
83  * If non-zero, the hotplugged device is onlined (if possible) without explicit
84  * IOCTL request (AP_CONFIGURE).
85  * If zero, hotplugged device is identified, but not onlined.
86  * Enabling (AP_CONNECT) device port with an attached device does not result
87  * in device onlining regardless of the flag setting
88  */
89 int sata_auto_online = 0;
90 
91 #ifdef SATA_DEBUG
92 
93 #define	SATA_LOG_D(args)	sata_log args
94 uint64_t mbuf_count = 0;
95 uint64_t mbuffail_count = 0;
96 
97 sata_atapi_cmd_t sata_atapi_trace[64];
98 uint32_t sata_atapi_trace_index = 0;
99 int sata_atapi_trace_save = 1;
100 static	void sata_save_atapi_trace(sata_pkt_txlate_t *, int);
101 #define	SATAATAPITRACE(spx, count)	if (sata_atapi_trace_save) \
102     sata_save_atapi_trace(spx, count);
103 
104 #else
105 #define	SATA_LOG_D(arg)
106 #define	SATAATAPITRACE(spx, count)
107 #endif
108 
109 #if 0
110 static void
111 sata_test_atapi_packet_command(sata_hba_inst_t *, int);
112 #endif
113 
114 #ifdef SATA_INJECT_FAULTS
115 
116 #define		SATA_INJECT_PKT_FAULT	1
117 uint32_t	sata_inject_fault = 0;
118 
119 uint32_t	sata_inject_fault_count = 0;
120 uint32_t	sata_inject_fault_pause_count = 0;
121 uint32_t	sata_fault_type = 0;
122 uint32_t	sata_fault_cmd = 0;
123 dev_info_t	*sata_fault_ctrl = NULL;
124 sata_device_t	sata_fault_device;
125 
126 static	void sata_inject_pkt_fault(sata_pkt_t *, int *, int);
127 
128 #endif
129 
130 #define	LEGACY_HWID_LEN	64	/* Model (40) + Serial (20) + pad */
131 
132 static char sata_rev_tag[] = {"1.42"};
133 
134 /*
135  * SATA cb_ops functions
136  */
137 static 	int sata_hba_open(dev_t *, int, int, cred_t *);
138 static 	int sata_hba_close(dev_t, int, int, cred_t *);
139 static 	int sata_hba_ioctl(dev_t, int, intptr_t, int, cred_t *,	int *);
140 
141 /*
142  * SCSA required entry points
143  */
144 static	int sata_scsi_tgt_init(dev_info_t *, dev_info_t *,
145     scsi_hba_tran_t *, struct scsi_device *);
146 static	int sata_scsi_tgt_probe(struct scsi_device *,
147     int (*callback)(void));
148 static void sata_scsi_tgt_free(dev_info_t *, dev_info_t *,
149     scsi_hba_tran_t *, struct scsi_device *);
150 static 	int sata_scsi_start(struct scsi_address *, struct scsi_pkt *);
151 static 	int sata_scsi_abort(struct scsi_address *, struct scsi_pkt *);
152 static 	int sata_scsi_reset(struct scsi_address *, int);
153 static 	int sata_scsi_getcap(struct scsi_address *, char *, int);
154 static 	int sata_scsi_setcap(struct scsi_address *, char *, int, int);
155 static 	struct scsi_pkt *sata_scsi_init_pkt(struct scsi_address *,
156     struct scsi_pkt *, struct buf *, int, int, int, int, int (*)(caddr_t),
157     caddr_t);
158 static 	void sata_scsi_destroy_pkt(struct scsi_address *, struct scsi_pkt *);
159 static 	void sata_scsi_dmafree(struct scsi_address *, struct scsi_pkt *);
160 static 	void sata_scsi_sync_pkt(struct scsi_address *, struct scsi_pkt *);
161 
162 /*
163  * SATA HBA interface functions are defined in sata_hba.h header file
164  */
165 
166 /* Event processing functions */
167 static	void sata_event_daemon(void *);
168 static	void sata_event_thread_control(int);
169 static	void sata_process_controller_events(sata_hba_inst_t *sata_hba_inst);
170 static	void sata_process_device_reset(sata_hba_inst_t *, sata_address_t *);
171 static	void sata_process_port_failed_event(sata_hba_inst_t *,
172     sata_address_t *);
173 static	void sata_process_port_link_events(sata_hba_inst_t *,
174     sata_address_t *);
175 static	void sata_process_device_detached(sata_hba_inst_t *, sata_address_t *);
176 static	void sata_process_device_attached(sata_hba_inst_t *, sata_address_t *);
177 static	void sata_process_port_pwr_change(sata_hba_inst_t *, sata_address_t *);
178 static	void sata_process_cntrl_pwr_level_change(sata_hba_inst_t *);
179 static	void sata_process_target_node_cleanup(sata_hba_inst_t *,
180     sata_address_t *);
181 static	void sata_process_device_autoonline(sata_hba_inst_t *,
182     sata_address_t *saddr);
183 
184 /*
185  * Local translation functions
186  */
187 static	int sata_txlt_inquiry(sata_pkt_txlate_t *);
188 static	int sata_txlt_test_unit_ready(sata_pkt_txlate_t *);
189 static	int sata_txlt_start_stop_unit(sata_pkt_txlate_t *);
190 static	int sata_txlt_read_capacity(sata_pkt_txlate_t *);
191 static	int sata_txlt_request_sense(sata_pkt_txlate_t *);
192 static 	int sata_txlt_read(sata_pkt_txlate_t *);
193 static 	int sata_txlt_write(sata_pkt_txlate_t *);
194 static 	int sata_txlt_log_sense(sata_pkt_txlate_t *);
195 static 	int sata_txlt_log_select(sata_pkt_txlate_t *);
196 static 	int sata_txlt_mode_sense(sata_pkt_txlate_t *);
197 static 	int sata_txlt_mode_select(sata_pkt_txlate_t *);
198 static 	int sata_txlt_synchronize_cache(sata_pkt_txlate_t *);
199 static 	int sata_txlt_write_buffer(sata_pkt_txlate_t *);
200 static 	int sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *);
201 
202 static 	int sata_hba_start(sata_pkt_txlate_t *, int *);
203 static	int sata_txlt_invalid_command(sata_pkt_txlate_t *);
204 static	int sata_txlt_lba_out_of_range(sata_pkt_txlate_t *);
205 static 	void sata_txlt_rw_completion(sata_pkt_t *);
206 static 	void sata_txlt_nodata_cmd_completion(sata_pkt_t *);
207 static 	void sata_txlt_download_mcode_cmd_completion(sata_pkt_t *);
208 static 	int sata_emul_rw_completion(sata_pkt_txlate_t *);
209 static 	struct scsi_extended_sense *sata_immediate_error_response(
210     sata_pkt_txlate_t *, int);
211 static	struct scsi_extended_sense *sata_arq_sense(sata_pkt_txlate_t *);
212 
213 static 	int sata_txlt_atapi(sata_pkt_txlate_t *);
214 static 	void sata_txlt_atapi_completion(sata_pkt_t *);
215 
216 /*
217  * Local functions for ioctl
218  */
219 static	int32_t sata_get_port_num(sata_hba_inst_t *,  struct devctl_iocdata *);
220 static	void sata_cfgadm_state(sata_hba_inst_t *, int32_t,
221     devctl_ap_state_t *);
222 static	dev_info_t *sata_get_target_dip(dev_info_t *, int32_t);
223 static	dev_info_t *sata_get_scsi_target_dip(dev_info_t *, sata_address_t *);
224 static	dev_info_t *sata_devt_to_devinfo(dev_t);
225 static	int sata_ioctl_connect(sata_hba_inst_t *, sata_device_t *);
226 static	int sata_ioctl_disconnect(sata_hba_inst_t *, sata_device_t *);
227 static	int sata_ioctl_configure(sata_hba_inst_t *, sata_device_t *);
228 static	int sata_ioctl_unconfigure(sata_hba_inst_t *, sata_device_t *);
229 static	int sata_ioctl_activate(sata_hba_inst_t *, sata_device_t *);
230 static	int sata_ioctl_deactivate(sata_hba_inst_t *, sata_device_t *);
231 static	int sata_ioctl_reset_port(sata_hba_inst_t *, sata_device_t *);
232 static	int sata_ioctl_reset_device(sata_hba_inst_t *, sata_device_t *);
233 static	int sata_ioctl_reset_all(sata_hba_inst_t *);
234 static	int sata_ioctl_port_self_test(sata_hba_inst_t *, sata_device_t *);
235 static	int sata_ioctl_get_device_path(sata_hba_inst_t *, sata_device_t *,
236     sata_ioctl_data_t *, int mode);
237 static	int sata_ioctl_get_ap_type(sata_hba_inst_t *, sata_device_t *,
238     sata_ioctl_data_t *, int mode);
239 static	int sata_ioctl_get_model_info(sata_hba_inst_t *, sata_device_t *,
240     sata_ioctl_data_t *, int mode);
241 static	int sata_ioctl_get_revfirmware_info(sata_hba_inst_t *, sata_device_t *,
242     sata_ioctl_data_t *, int mode);
243 static	int sata_ioctl_get_serialnumber_info(sata_hba_inst_t *,
244     sata_device_t *, sata_ioctl_data_t *, int mode);
245 
246 /*
247  * Local functions
248  */
249 static 	void sata_remove_hba_instance(dev_info_t *);
250 static 	int sata_validate_sata_hba_tran(dev_info_t *, sata_hba_tran_t *);
251 static 	void sata_probe_ports(sata_hba_inst_t *);
252 static 	int sata_reprobe_port(sata_hba_inst_t *, sata_device_t *, int);
253 static 	int sata_add_device(dev_info_t *, sata_hba_inst_t *, int cport,
254     int pmport);
255 static 	dev_info_t *sata_create_target_node(dev_info_t *, sata_hba_inst_t *,
256     sata_address_t *);
257 static 	int sata_validate_scsi_address(sata_hba_inst_t *,
258     struct scsi_address *, sata_device_t *);
259 static 	int sata_validate_sata_address(sata_hba_inst_t *, int, int, int);
260 static	sata_pkt_t *sata_pkt_alloc(sata_pkt_txlate_t *, int (*)(caddr_t));
261 static	void sata_pkt_free(sata_pkt_txlate_t *);
262 static	int sata_dma_buf_setup(sata_pkt_txlate_t *, int, int (*)(caddr_t),
263     caddr_t, ddi_dma_attr_t *);
264 static	void sata_common_free_dma_rsrcs(sata_pkt_txlate_t *);
265 static	int sata_probe_device(sata_hba_inst_t *, sata_device_t *);
266 static	sata_drive_info_t *sata_get_device_info(sata_hba_inst_t *,
267     sata_device_t *);
268 static 	int sata_identify_device(sata_hba_inst_t *, sata_drive_info_t *);
269 static	void sata_reidentify_device(sata_pkt_txlate_t *);
270 static	struct buf *sata_alloc_local_buffer(sata_pkt_txlate_t *, int);
271 static 	void sata_free_local_buffer(sata_pkt_txlate_t *);
272 static 	uint64_t sata_check_capacity(sata_drive_info_t *);
273 void 	sata_adjust_dma_attr(sata_drive_info_t *, ddi_dma_attr_t *,
274     ddi_dma_attr_t *);
275 static 	int sata_fetch_device_identify_data(sata_hba_inst_t *,
276     sata_drive_info_t *);
277 static	void sata_update_port_info(sata_hba_inst_t *, sata_device_t *);
278 static	void sata_update_port_scr(sata_port_scr_t *, sata_device_t *);
279 static	int sata_set_dma_mode(sata_hba_inst_t *, sata_drive_info_t *);
280 static	int sata_set_cache_mode(sata_hba_inst_t *, sata_drive_info_t *, int);
281 static	int sata_set_rmsn(sata_hba_inst_t *, sata_drive_info_t *, int);
282 static	int sata_set_drive_features(sata_hba_inst_t *,
283     sata_drive_info_t *, int flag);
284 static	void sata_init_write_cache_mode(sata_drive_info_t *sdinfo);
285 static	int sata_initialize_device(sata_hba_inst_t *, sata_drive_info_t *);
286 static	void sata_identdev_to_inquiry(sata_hba_inst_t *, sata_drive_info_t *,
287     uint8_t *);
288 static	int sata_get_atapi_inquiry_data(sata_hba_inst_t *, sata_address_t *,
289     struct scsi_inquiry *);
290 static	int sata_build_msense_page_1(sata_drive_info_t *, int, uint8_t *);
291 static	int sata_build_msense_page_8(sata_drive_info_t *, int, uint8_t *);
292 static	int sata_build_msense_page_1a(sata_drive_info_t *, int, uint8_t *);
293 static	int sata_build_msense_page_1c(sata_drive_info_t *, int, uint8_t *);
294 static	int sata_mode_select_page_8(sata_pkt_txlate_t *,
295     struct mode_cache_scsi3 *, int, int *, int *, int *);
296 static	int sata_mode_select_page_1c(sata_pkt_txlate_t *,
297     struct mode_info_excpt_page *, int, int *, int *, int *);
298 static	int sata_build_msense_page_30(sata_drive_info_t *, int, uint8_t *);
299 static	int sata_mode_select_page_30(sata_pkt_txlate_t *,
300     struct mode_acoustic_management *, int, int *, int *, int *);
301 
302 static	int sata_build_lsense_page_0(sata_drive_info_t *, uint8_t *);
303 static	int sata_build_lsense_page_10(sata_drive_info_t *, uint8_t *,
304     sata_hba_inst_t *);
305 static	int sata_build_lsense_page_2f(sata_drive_info_t *, uint8_t *,
306     sata_hba_inst_t *);
307 static	int sata_build_lsense_page_30(sata_drive_info_t *, uint8_t *,
308     sata_hba_inst_t *);
309 static	void sata_save_drive_settings(sata_drive_info_t *);
310 static	void sata_show_drive_info(sata_hba_inst_t *, sata_drive_info_t *);
311 static	void sata_log(sata_hba_inst_t *, uint_t, char *fmt, ...);
312 static	int sata_fetch_smart_return_status(sata_hba_inst_t *,
313     sata_drive_info_t *);
314 static	int sata_fetch_smart_data(sata_hba_inst_t *, sata_drive_info_t *,
315     struct smart_data *);
316 static	int sata_smart_selftest_log(sata_hba_inst_t *,
317     sata_drive_info_t *,
318     struct smart_selftest_log *);
319 static	int sata_ext_smart_selftest_read_log(sata_hba_inst_t *,
320     sata_drive_info_t *, struct smart_ext_selftest_log *, uint16_t);
321 static	int sata_smart_read_log(sata_hba_inst_t *, sata_drive_info_t *,
322     uint8_t *, uint8_t, uint8_t);
323 static	int sata_read_log_ext_directory(sata_hba_inst_t *, sata_drive_info_t *,
324     struct read_log_ext_directory *);
325 static	void sata_gen_sysevent(sata_hba_inst_t *, sata_address_t *, int);
326 static	void sata_xlate_errors(sata_pkt_txlate_t *);
327 static	void sata_decode_device_error(sata_pkt_txlate_t *,
328     struct scsi_extended_sense *);
329 static	void sata_set_device_removed(dev_info_t *);
330 static	boolean_t sata_check_device_removed(dev_info_t *);
331 static	void sata_set_target_node_cleanup(sata_hba_inst_t *, sata_address_t *);
332 static	int sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *,
333     sata_drive_info_t *);
334 static	int sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *,
335     sata_drive_info_t *);
336 static	void sata_atapi_packet_cmd_setup(sata_cmd_t *, sata_drive_info_t *);
337 static	void sata_fixed_sense_data_preset(struct scsi_extended_sense *);
338 static  void sata_target_devid_register(dev_info_t *, sata_drive_info_t *);
339 static  int sata_check_modser(char *, int);
340 
341 
342 
343 /*
344  * SATA Framework will ignore SATA HBA driver cb_ops structure and
345  * register following one with SCSA framework.
346  * Open & close are provided, so scsi framework will not use its own
347  */
348 static struct cb_ops sata_cb_ops = {
349 	sata_hba_open,			/* open */
350 	sata_hba_close,			/* close */
351 	nodev,				/* strategy */
352 	nodev,				/* print */
353 	nodev,				/* dump */
354 	nodev,				/* read */
355 	nodev,				/* write */
356 	sata_hba_ioctl,			/* ioctl */
357 	nodev,				/* devmap */
358 	nodev,				/* mmap */
359 	nodev,				/* segmap */
360 	nochpoll,			/* chpoll */
361 	ddi_prop_op,			/* cb_prop_op */
362 	0,				/* streamtab */
363 	D_NEW | D_MP,			/* cb_flag */
364 	CB_REV,				/* rev */
365 	nodev,				/* aread */
366 	nodev				/* awrite */
367 };
368 
369 
370 extern struct mod_ops mod_miscops;
371 extern uchar_t	scsi_cdb_size[];
372 
373 static struct modlmisc modlmisc = {
374 	&mod_miscops,			/* Type of module */
375 	"SATA Module"			/* module name */
376 };
377 
378 
379 static struct modlinkage modlinkage = {
380 	MODREV_1,
381 	(void *)&modlmisc,
382 	NULL
383 };
384 
385 /*
386  * Default sata pkt timeout. Used when a target driver scsi_pkt time is zero,
387  * i.e. when scsi_pkt has not timeout specified.
388  */
389 static int sata_default_pkt_time = 60;	/* 60 seconds */
390 
391 /*
392  * Intermediate buffer device access attributes - they are required,
393  * but not necessarily used.
394  */
395 static ddi_device_acc_attr_t sata_acc_attr = {
396 	DDI_DEVICE_ATTR_V0,
397 	DDI_STRUCTURE_LE_ACC,
398 	DDI_STRICTORDER_ACC
399 };
400 
401 
402 /*
403  * Mutexes protecting structures in multithreaded operations.
404  * Because events are relatively rare, a single global mutex protecting
405  * data structures should be sufficient. To increase performance, add
406  * separate mutex per each sata port and use global mutex only to protect
407  * common data structures.
408  */
409 static	kmutex_t sata_mutex;		/* protects sata_hba_list */
410 static	kmutex_t sata_log_mutex;	/* protects log */
411 
412 static 	char sata_log_buf[256];
413 
414 /* Default write cache setting for SATA hard disks */
415 int	sata_write_cache = 1;		/* enabled */
416 
417 /* Default write cache setting for SATA ATAPI CD/DVD */
418 int	sata_atapicdvd_write_cache = 1; /* enabled */
419 
420 /* Default write cache setting for SATA ATAPI tape */
421 int	sata_atapitape_write_cache = 1; /* enabled */
422 
423 /* Default write cache setting for SATA ATAPI disk */
424 int	sata_atapidisk_write_cache = 1;	/* enabled */
425 
426 /*
427  * Linked list of HBA instances
428  */
429 static 	sata_hba_inst_t *sata_hba_list = NULL;
430 static 	sata_hba_inst_t *sata_hba_list_tail = NULL;
431 /*
432  * Pointer to per-instance SATA HBA soft structure is stored in sata_hba_tran
433  * structure and in sata soft state.
434  */
435 
436 /*
437  * Event daemon related variables
438  */
439 static 	kmutex_t sata_event_mutex;
440 static 	kcondvar_t sata_event_cv;
441 static 	kthread_t *sata_event_thread = NULL;
442 static 	int sata_event_thread_terminate = 0;
443 static 	int sata_event_pending = 0;
444 static 	int sata_event_thread_active = 0;
445 extern 	pri_t minclsyspri;
446 
447 /*
448  * NCQ error recovery command
449  */
450 static const sata_cmd_t sata_rle_cmd = {
451 	SATA_CMD_REV,
452 	NULL,
453 	{
454 		SATA_DIR_READ
455 	},
456 	ATA_ADDR_LBA48,
457 	0,
458 	0,
459 	0,
460 	0,
461 	0,
462 	1,
463 	READ_LOG_EXT_NCQ_ERROR_RECOVERY,
464 	0,
465 	0,
466 	0,
467 	SATAC_READ_LOG_EXT,
468 	0,
469 	0,
470 	0,
471 };
472 
473 /*
474  * ATAPI error recovery CDB
475  */
476 static const uint8_t sata_rqsense_cdb[SATA_ATAPI_RQSENSE_CDB_LEN] = {
477 	SCMD_REQUEST_SENSE,
478 	0,			/* Only fixed RQ format is supported */
479 	0,
480 	0,
481 	SATA_ATAPI_MIN_RQSENSE_LEN, /* Less data may be returned */
482 	0
483 };
484 
485 
486 /* Warlock directives */
487 
488 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran))
489 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_device))
490 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_ops))
491 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_extended_sense))
492 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_arq_status))
493 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_attr))
494 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_cookie_t))
495 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", devctl_ap_state))
496 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_info::devi_state))
497 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_list))
498 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_list))
499 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_next))
500 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_prev))
501 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", \
502     sata_hba_inst::satahba_scsi_tran))
503 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_tran))
504 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_dip))
505 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_hba_inst::satahba_attached))
506 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_inst::satahba_dev_port))
507 _NOTE(MUTEX_PROTECTS_DATA(sata_hba_inst::satahba_mutex,
508     sata_hba_inst::satahba_event_flags))
509 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
510     sata_cport_info::cport_devp))
511 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_devp))
512 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_cport_info::cport_addr))
513 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
514     sata_cport_info::cport_dev_type))
515 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_dev_type))
516 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
517     sata_cport_info::cport_state))
518 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_state))
519 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
520     sata_pmport_info::pmport_state))
521 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_state))
522 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_dev_type))
523 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_sata_drive))
524 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_dev_port))
525 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_num_dev_ports))
526 #ifdef SATA_DEBUG
527 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuf_count))
528 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuffail_count))
529 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace))
530 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace_index))
531 #endif
532 
533 /* End of warlock directives */
534 
535 /* ************** loadable module configuration functions ************** */
536 
537 int
538 _init()
539 {
540 	int rval;
541 
542 	mutex_init(&sata_mutex, NULL, MUTEX_DRIVER, NULL);
543 	mutex_init(&sata_event_mutex, NULL, MUTEX_DRIVER, NULL);
544 	mutex_init(&sata_log_mutex, NULL, MUTEX_DRIVER, NULL);
545 	cv_init(&sata_event_cv, NULL, CV_DRIVER, NULL);
546 	if ((rval = mod_install(&modlinkage)) != 0) {
547 #ifdef SATA_DEBUG
548 		cmn_err(CE_WARN, "sata: _init: mod_install failed\n");
549 #endif
550 		mutex_destroy(&sata_log_mutex);
551 		cv_destroy(&sata_event_cv);
552 		mutex_destroy(&sata_event_mutex);
553 		mutex_destroy(&sata_mutex);
554 	}
555 	return (rval);
556 }
557 
558 int
559 _fini()
560 {
561 	int rval;
562 
563 	if ((rval = mod_remove(&modlinkage)) != 0)
564 		return (rval);
565 
566 	mutex_destroy(&sata_log_mutex);
567 	cv_destroy(&sata_event_cv);
568 	mutex_destroy(&sata_event_mutex);
569 	mutex_destroy(&sata_mutex);
570 	return (rval);
571 }
572 
573 int
574 _info(struct modinfo *modinfop)
575 {
576 	return (mod_info(&modlinkage, modinfop));
577 }
578 
579 
580 
581 /* ********************* SATA HBA entry points ********************* */
582 
583 
584 /*
585  * Called by SATA HBA from _init().
586  * Registers HBA driver instance/sata framework pair with scsi framework, by
587  * calling scsi_hba_init().
588  *
589  * SATA HBA driver cb_ops are ignored - SATA HBA framework cb_ops are used
590  * instead. SATA HBA framework cb_ops pointer overwrites SATA HBA driver
591  * cb_ops pointer in SATA HBA driver dev_ops structure.
592  * SATA HBA framework cb_ops supplies cb_open cb_close and cb_ioctl vectors.
593  *
594  * Return status of the scsi_hba_init() is returned to a calling SATA HBA
595  * driver.
596  */
597 int
598 sata_hba_init(struct modlinkage *modlp)
599 {
600 	int rval;
601 	struct dev_ops *hba_ops;
602 
603 	SATADBG1(SATA_DBG_HBA_IF, NULL,
604 	    "sata_hba_init: name %s \n",
605 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
606 	/*
607 	 * Fill-up cb_ops and dev_ops when necessary
608 	 */
609 	hba_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
610 	/*
611 	 * Provide pointer to SATA dev_ops
612 	 */
613 	hba_ops->devo_cb_ops = &sata_cb_ops;
614 
615 	/*
616 	 * Register SATA HBA with SCSI framework
617 	 */
618 	if ((rval = scsi_hba_init(modlp)) != 0) {
619 		SATADBG1(SATA_DBG_HBA_IF, NULL,
620 		    "sata_hba_init: scsi hba init failed\n", NULL);
621 		return (rval);
622 	}
623 
624 	return (0);
625 }
626 
627 
628 /* HBA attach stages */
629 #define	HBA_ATTACH_STAGE_SATA_HBA_INST	1
630 #define	HBA_ATTACH_STAGE_SCSI_ATTACHED	2
631 #define	HBA_ATTACH_STAGE_SETUP		4
632 #define	HBA_ATTACH_STAGE_LINKED		8
633 
634 
635 /*
636  *
637  * Called from SATA HBA driver's attach routine to attach an instance of
638  * the HBA.
639  *
640  * For DDI_ATTACH command:
641  * sata_hba_inst structure is allocated here and initialized with pointers to
642  * SATA framework implementation of required scsi tran functions.
643  * The scsi_tran's tran_hba_private field is used by SATA Framework to point
644  * to the soft structure (sata_hba_inst) allocated by SATA framework for
645  * SATA HBA instance related data.
646  * The scsi_tran's tran_hba_private field is used by SATA framework to
647  * store a pointer to per-HBA-instance of sata_hba_inst structure.
648  * The sata_hba_inst structure is cross-linked to scsi tran structure.
649  * Among other info, a pointer to sata_hba_tran structure is stored in
650  * sata_hba_inst. The sata_hba_inst structures for different HBA instances are
651  * linked together into the list, pointed to by sata_hba_list.
652  * On the first HBA instance attach the sata event thread is initialized.
653  * Attachment points are created for all SATA ports of the HBA being attached.
654  * All HBA instance's SATA ports are probed and type of plugged devices is
655  * determined. For each device of a supported type, a target node is created.
656  *
657  * DDI_SUCCESS is returned when attachment process is successful,
658  * DDI_FAILURE is returned otherwise.
659  *
660  * For DDI_RESUME command:
661  * Not implemented at this time (postponed until phase 2 of the development).
662  */
663 int
664 sata_hba_attach(dev_info_t *dip, sata_hba_tran_t *sata_tran,
665     ddi_attach_cmd_t cmd)
666 {
667 	sata_hba_inst_t	*sata_hba_inst;
668 	scsi_hba_tran_t *scsi_tran = NULL;
669 	int hba_attach_state = 0;
670 	char taskq_name[MAXPATHLEN];
671 
672 	SATADBG3(SATA_DBG_HBA_IF, NULL,
673 	    "sata_hba_attach: node %s (%s%d)\n",
674 	    ddi_node_name(dip), ddi_driver_name(dip),
675 	    ddi_get_instance(dip));
676 
677 	if (cmd == DDI_RESUME) {
678 		/*
679 		 * Postponed until phase 2 of the development
680 		 */
681 		return (DDI_FAILURE);
682 	}
683 
684 	if (cmd != DDI_ATTACH) {
685 		return (DDI_FAILURE);
686 	}
687 
688 	/* cmd == DDI_ATTACH */
689 
690 	if (sata_validate_sata_hba_tran(dip, sata_tran) != SATA_SUCCESS) {
691 		SATA_LOG_D((NULL, CE_WARN,
692 		    "sata_hba_attach: invalid sata_hba_tran"));
693 		return (DDI_FAILURE);
694 	}
695 	/*
696 	 * Allocate and initialize SCSI tran structure.
697 	 * SATA copy of tran_bus_config is provided to create port nodes.
698 	 */
699 	scsi_tran = scsi_hba_tran_alloc(dip, SCSI_HBA_CANSLEEP);
700 	if (scsi_tran == NULL)
701 		return (DDI_FAILURE);
702 	/*
703 	 * Allocate soft structure for SATA HBA instance.
704 	 * There is a separate softstate for each HBA instance.
705 	 */
706 	sata_hba_inst = kmem_zalloc(sizeof (struct sata_hba_inst), KM_SLEEP);
707 	ASSERT(sata_hba_inst != NULL); /* this should not fail */
708 	mutex_init(&sata_hba_inst->satahba_mutex, NULL, MUTEX_DRIVER, NULL);
709 	hba_attach_state |= HBA_ATTACH_STAGE_SATA_HBA_INST;
710 
711 	/*
712 	 * scsi_trans's tran_hba_private is used by SATA Framework to point to
713 	 * soft structure allocated by SATA framework for
714 	 * SATA HBA instance related data.
715 	 */
716 	scsi_tran->tran_hba_private	= sata_hba_inst;
717 	scsi_tran->tran_tgt_private	= NULL;
718 
719 	scsi_tran->tran_tgt_init	= sata_scsi_tgt_init;
720 	scsi_tran->tran_tgt_probe	= sata_scsi_tgt_probe;
721 	scsi_tran->tran_tgt_free	= sata_scsi_tgt_free;
722 
723 	scsi_tran->tran_start		= sata_scsi_start;
724 	scsi_tran->tran_reset		= sata_scsi_reset;
725 	scsi_tran->tran_abort		= sata_scsi_abort;
726 	scsi_tran->tran_getcap		= sata_scsi_getcap;
727 	scsi_tran->tran_setcap		= sata_scsi_setcap;
728 	scsi_tran->tran_init_pkt	= sata_scsi_init_pkt;
729 	scsi_tran->tran_destroy_pkt	= sata_scsi_destroy_pkt;
730 
731 	scsi_tran->tran_dmafree		= sata_scsi_dmafree;
732 	scsi_tran->tran_sync_pkt	= sata_scsi_sync_pkt;
733 
734 	scsi_tran->tran_reset_notify	= NULL;
735 	scsi_tran->tran_get_bus_addr	= NULL;
736 	scsi_tran->tran_quiesce		= NULL;
737 	scsi_tran->tran_unquiesce	= NULL;
738 	scsi_tran->tran_bus_reset	= NULL;
739 
740 	if (scsi_hba_attach_setup(dip, sata_tran->sata_tran_hba_dma_attr,
741 	    scsi_tran, 0) != DDI_SUCCESS) {
742 #ifdef SATA_DEBUG
743 		cmn_err(CE_WARN, "?SATA: %s%d hba scsi attach failed",
744 		    ddi_driver_name(dip), ddi_get_instance(dip));
745 #endif
746 		goto fail;
747 	}
748 	hba_attach_state |= HBA_ATTACH_STAGE_SCSI_ATTACHED;
749 
750 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "sata")) {
751 		if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
752 		    "sata", 1) != DDI_PROP_SUCCESS) {
753 			SATA_LOG_D((NULL, CE_WARN, "sata_hba_attach: "
754 			    "failed to create hba sata prop"));
755 			goto fail;
756 		}
757 	}
758 
759 	/*
760 	 * Save pointers in hba instance soft state.
761 	 */
762 	sata_hba_inst->satahba_scsi_tran = scsi_tran;
763 	sata_hba_inst->satahba_tran = sata_tran;
764 	sata_hba_inst->satahba_dip = dip;
765 
766 	/*
767 	 * Create a task queue to handle emulated commands completion
768 	 * Use node name, dash, instance number as the queue name.
769 	 */
770 	taskq_name[0] = '\0';
771 	(void) strlcat(taskq_name, DEVI(dip)->devi_node_name,
772 	    sizeof (taskq_name));
773 	(void) snprintf(taskq_name + strlen(taskq_name),
774 	    sizeof (taskq_name) - strlen(taskq_name),
775 	    "-%d", DEVI(dip)->devi_instance);
776 	sata_hba_inst->satahba_taskq = taskq_create(taskq_name, 1,
777 	    minclsyspri, 1, sata_tran->sata_tran_hba_num_cports * 4,
778 	    TASKQ_DYNAMIC);
779 
780 	hba_attach_state |= HBA_ATTACH_STAGE_SETUP;
781 
782 	/*
783 	 * Create events thread if not created yet.
784 	 */
785 	sata_event_thread_control(1);
786 
787 	/*
788 	 * Link this hba instance into the list.
789 	 */
790 	mutex_enter(&sata_mutex);
791 
792 	if (sata_hba_list == NULL) {
793 		/*
794 		 * The first instance of HBA is attached.
795 		 * Set current/active default maximum NCQ/TCQ queue depth for
796 		 * all SATA devices. It is done here and now, to eliminate the
797 		 * possibility of the dynamic, programatic modification of the
798 		 * queue depth via global (and public) sata_max_queue_depth
799 		 * variable (this would require special handling in HBA drivers)
800 		 */
801 		sata_current_max_qdepth = sata_max_queue_depth;
802 		if (sata_current_max_qdepth > 32)
803 			sata_current_max_qdepth = 32;
804 		else if (sata_current_max_qdepth < 1)
805 			sata_current_max_qdepth = 1;
806 	}
807 
808 	sata_hba_inst->satahba_next = NULL;
809 	sata_hba_inst->satahba_prev = sata_hba_list_tail;
810 	if (sata_hba_list == NULL) {
811 		sata_hba_list = sata_hba_inst;
812 	}
813 	if (sata_hba_list_tail != NULL) {
814 		sata_hba_list_tail->satahba_next = sata_hba_inst;
815 	}
816 	sata_hba_list_tail = sata_hba_inst;
817 	mutex_exit(&sata_mutex);
818 	hba_attach_state |= HBA_ATTACH_STAGE_LINKED;
819 
820 	/*
821 	 * Create SATA HBA devctl minor node for sata_hba_open, close, ioctl
822 	 * SATA HBA driver should not use its own open/close entry points.
823 	 *
824 	 * Make sure that instance number doesn't overflow
825 	 * when forming minor numbers.
826 	 */
827 	ASSERT(ddi_get_instance(dip) <= (L_MAXMIN >> INST_MINOR_SHIFT));
828 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
829 	    INST2DEVCTL(ddi_get_instance(dip)),
830 	    DDI_NT_SATA_NEXUS, 0) != DDI_SUCCESS) {
831 #ifdef SATA_DEBUG
832 		cmn_err(CE_WARN, "sata_hba_attach: "
833 		    "cannot create devctl minor node");
834 #endif
835 		goto fail;
836 	}
837 
838 
839 	/*
840 	 * Set-up kstats here, if necessary.
841 	 * (postponed until future phase of the development).
842 	 */
843 
844 	/*
845 	 * Indicate that HBA is attached. This will enable events processing
846 	 * for this HBA.
847 	 */
848 	sata_hba_inst->satahba_attached = 1;
849 	/*
850 	 * Probe controller ports. This operation will describe a current
851 	 * controller/port/multipliers/device configuration and will create
852 	 * attachment points.
853 	 * We may end-up with just a controller with no devices attached.
854 	 * For the ports with a supported device attached, device target nodes
855 	 * are created and devices are initialized.
856 	 */
857 	sata_probe_ports(sata_hba_inst);
858 
859 	return (DDI_SUCCESS);
860 
861 fail:
862 	if (hba_attach_state & HBA_ATTACH_STAGE_LINKED) {
863 		(void) sata_remove_hba_instance(dip);
864 		if (sata_hba_list == NULL)
865 			sata_event_thread_control(0);
866 	}
867 
868 	if (hba_attach_state & HBA_ATTACH_STAGE_SETUP) {
869 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
870 		taskq_destroy(sata_hba_inst->satahba_taskq);
871 	}
872 
873 	if (hba_attach_state & HBA_ATTACH_STAGE_SCSI_ATTACHED)
874 		(void) scsi_hba_detach(dip);
875 
876 	if (hba_attach_state & HBA_ATTACH_STAGE_SATA_HBA_INST) {
877 		mutex_destroy(&sata_hba_inst->satahba_mutex);
878 		kmem_free((void *)sata_hba_inst,
879 		    sizeof (struct sata_hba_inst));
880 		scsi_hba_tran_free(scsi_tran);
881 	}
882 
883 	sata_log(NULL, CE_WARN, "?SATA: %s%d hba attach failed",
884 	    ddi_driver_name(dip), ddi_get_instance(dip));
885 
886 	return (DDI_FAILURE);
887 }
888 
889 
890 /*
891  * Called by SATA HBA from to detach an instance of the driver.
892  *
893  * For DDI_DETACH command:
894  * Free local structures allocated for SATA HBA instance during
895  * sata_hba_attach processing.
896  *
897  * Returns DDI_SUCCESS when HBA was detached, DDI_FAILURE otherwise.
898  *
899  * For DDI_SUSPEND command:
900  * Not implemented at this time (postponed until phase 2 of the development)
901  * Returnd DDI_SUCCESS.
902  *
903  * When the last HBA instance is detached, the event daemon is terminated.
904  *
905  * NOTE: cport support only, no port multiplier support.
906  */
907 int
908 sata_hba_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
909 {
910 	dev_info_t	*tdip;
911 	sata_hba_inst_t	*sata_hba_inst;
912 	scsi_hba_tran_t *scsi_hba_tran;
913 	sata_cport_info_t *cportinfo;
914 	sata_drive_info_t *sdinfo;
915 	int ncport;
916 
917 	SATADBG3(SATA_DBG_HBA_IF, NULL, "sata_hba_detach: node %s (%s%d)\n",
918 	    ddi_node_name(dip), ddi_driver_name(dip), ddi_get_instance(dip));
919 
920 	switch (cmd) {
921 	case DDI_DETACH:
922 
923 		if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
924 			return (DDI_FAILURE);
925 
926 		sata_hba_inst = scsi_hba_tran->tran_hba_private;
927 		if (sata_hba_inst == NULL)
928 			return (DDI_FAILURE);
929 
930 		if (scsi_hba_detach(dip) == DDI_FAILURE) {
931 			sata_hba_inst->satahba_attached = 1;
932 			return (DDI_FAILURE);
933 		}
934 
935 		/*
936 		 * Free all target nodes - at this point
937 		 * devices should be at least offlined
938 		 * otherwise scsi_hba_detach() should not be called.
939 		 */
940 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
941 		    ncport++) {
942 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
943 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
944 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
945 				if (sdinfo != NULL) {
946 					tdip = sata_get_target_dip(dip,
947 					    ncport);
948 					if (tdip != NULL) {
949 						if (ndi_devi_offline(tdip,
950 						    NDI_DEVI_REMOVE) !=
951 						    NDI_SUCCESS) {
952 							SATA_LOG_D((
953 							    sata_hba_inst,
954 							    CE_WARN,
955 							    "sata_hba_detach: "
956 							    "Target node not "
957 							    "removed !"));
958 							return (DDI_FAILURE);
959 						}
960 					}
961 				}
962 			}
963 		}
964 		/*
965 		 * Disable sata event daemon processing for this HBA
966 		 */
967 		sata_hba_inst->satahba_attached = 0;
968 
969 		/*
970 		 * Remove event daemon thread, if it is last HBA instance.
971 		 */
972 
973 		mutex_enter(&sata_mutex);
974 		if (sata_hba_list->satahba_next == NULL) {
975 			mutex_exit(&sata_mutex);
976 			sata_event_thread_control(0);
977 			mutex_enter(&sata_mutex);
978 		}
979 		mutex_exit(&sata_mutex);
980 
981 		/* Remove this HBA instance from the HBA list */
982 		sata_remove_hba_instance(dip);
983 
984 		/*
985 		 * At this point there should be no target nodes attached.
986 		 * Detach and destroy device and port info structures.
987 		 */
988 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
989 		    ncport++) {
990 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
991 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
992 				sdinfo =
993 				    cportinfo->cport_devp.cport_sata_drive;
994 				if (sdinfo != NULL) {
995 					/* Release device structure */
996 					kmem_free(sdinfo,
997 					    sizeof (sata_drive_info_t));
998 				}
999 				/* Release cport info */
1000 				mutex_destroy(&cportinfo->cport_mutex);
1001 				kmem_free(cportinfo,
1002 				    sizeof (sata_cport_info_t));
1003 			}
1004 		}
1005 
1006 		scsi_hba_tran_free(sata_hba_inst->satahba_scsi_tran);
1007 
1008 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
1009 
1010 		taskq_destroy(sata_hba_inst->satahba_taskq);
1011 
1012 		mutex_destroy(&sata_hba_inst->satahba_mutex);
1013 		kmem_free((void *)sata_hba_inst,
1014 		    sizeof (struct sata_hba_inst));
1015 
1016 		return (DDI_SUCCESS);
1017 
1018 	case DDI_SUSPEND:
1019 		/*
1020 		 * Postponed until phase 2
1021 		 */
1022 		return (DDI_FAILURE);
1023 
1024 	default:
1025 		return (DDI_FAILURE);
1026 	}
1027 }
1028 
1029 
1030 /*
1031  * Called by an HBA drive from _fini() routine.
1032  * Unregisters SATA HBA instance/SATA framework pair from the scsi framework.
1033  */
1034 void
1035 sata_hba_fini(struct modlinkage *modlp)
1036 {
1037 	SATADBG1(SATA_DBG_HBA_IF, NULL,
1038 	    "sata_hba_fini: name %s\n",
1039 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
1040 
1041 	scsi_hba_fini(modlp);
1042 }
1043 
1044 
1045 /*
1046  * Default open and close routine for sata_hba framework.
1047  *
1048  */
1049 /*
1050  * Open devctl node.
1051  *
1052  * Returns:
1053  * 0 if node was open successfully, error code otherwise.
1054  *
1055  *
1056  */
1057 
1058 static int
1059 sata_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
1060 {
1061 #ifndef __lock_lint
1062 	_NOTE(ARGUNUSED(credp))
1063 #endif
1064 	int rv = 0;
1065 	dev_info_t *dip;
1066 	scsi_hba_tran_t *scsi_hba_tran;
1067 	sata_hba_inst_t	*sata_hba_inst;
1068 
1069 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_open: entered", NULL);
1070 
1071 	if (otyp != OTYP_CHR)
1072 		return (EINVAL);
1073 
1074 	dip = sata_devt_to_devinfo(*devp);
1075 	if (dip == NULL)
1076 		return (ENXIO);
1077 
1078 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1079 		return (ENXIO);
1080 
1081 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1082 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1083 		return (ENXIO);
1084 
1085 	mutex_enter(&sata_mutex);
1086 	if (flags & FEXCL) {
1087 		if (sata_hba_inst->satahba_open_flag != 0) {
1088 			rv = EBUSY;
1089 		} else {
1090 			sata_hba_inst->satahba_open_flag =
1091 			    SATA_DEVCTL_EXOPENED;
1092 		}
1093 	} else {
1094 		if (sata_hba_inst->satahba_open_flag == SATA_DEVCTL_EXOPENED) {
1095 			rv = EBUSY;
1096 		} else {
1097 			sata_hba_inst->satahba_open_flag =
1098 			    SATA_DEVCTL_SOPENED;
1099 		}
1100 	}
1101 	mutex_exit(&sata_mutex);
1102 
1103 	return (rv);
1104 }
1105 
1106 
1107 /*
1108  * Close devctl node.
1109  * Returns:
1110  * 0 if node was closed successfully, error code otherwise.
1111  *
1112  */
1113 
1114 static int
1115 sata_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
1116 {
1117 #ifndef __lock_lint
1118 	_NOTE(ARGUNUSED(credp))
1119 	_NOTE(ARGUNUSED(flag))
1120 #endif
1121 	dev_info_t *dip;
1122 	scsi_hba_tran_t *scsi_hba_tran;
1123 	sata_hba_inst_t	*sata_hba_inst;
1124 
1125 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_close: entered", NULL);
1126 
1127 	if (otyp != OTYP_CHR)
1128 		return (EINVAL);
1129 
1130 	dip = sata_devt_to_devinfo(dev);
1131 	if (dip == NULL)
1132 		return (ENXIO);
1133 
1134 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1135 		return (ENXIO);
1136 
1137 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1138 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1139 		return (ENXIO);
1140 
1141 	mutex_enter(&sata_mutex);
1142 	sata_hba_inst->satahba_open_flag = 0;
1143 	mutex_exit(&sata_mutex);
1144 	return (0);
1145 }
1146 
1147 
1148 
1149 /*
1150  * Standard IOCTL commands for SATA hotplugging.
1151  * Implemented DEVCTL_AP commands:
1152  * DEVCTL_AP_CONNECT
1153  * DEVCTL_AP_DISCONNECT
1154  * DEVCTL_AP_CONFIGURE
1155  * DEVCTL_UNCONFIGURE
1156  * DEVCTL_AP_CONTROL
1157  *
1158  * Commands passed to default ndi ioctl handler:
1159  * DEVCTL_DEVICE_GETSTATE
1160  * DEVCTL_DEVICE_ONLINE
1161  * DEVCTL_DEVICE_OFFLINE
1162  * DEVCTL_DEVICE_REMOVE
1163  * DEVCTL_DEVICE_INSERT
1164  * DEVCTL_BUS_GETSTATE
1165  *
1166  * All other cmds are passed to HBA if it provide ioctl handler, or failed
1167  * if not.
1168  *
1169  * Returns:
1170  * 0 if successful,
1171  * error code if operation failed.
1172  *
1173  * NOTE: Port Multiplier is not supported.
1174  *
1175  */
1176 
1177 static int
1178 sata_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
1179     int *rvalp)
1180 {
1181 #ifndef __lock_lint
1182 	_NOTE(ARGUNUSED(credp))
1183 	_NOTE(ARGUNUSED(rvalp))
1184 #endif
1185 	int rv = 0;
1186 	int32_t	comp_port = -1;
1187 	dev_info_t *dip;
1188 	devctl_ap_state_t ap_state;
1189 	struct devctl_iocdata *dcp = NULL;
1190 	scsi_hba_tran_t *scsi_hba_tran;
1191 	sata_hba_inst_t *sata_hba_inst;
1192 	sata_device_t sata_device;
1193 	sata_cport_info_t *cportinfo;
1194 	int cport, pmport, qual;
1195 	int rval = SATA_SUCCESS;
1196 
1197 	dip = sata_devt_to_devinfo(dev);
1198 	if (dip == NULL)
1199 		return (ENXIO);
1200 
1201 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1202 		return (ENXIO);
1203 
1204 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1205 	if (sata_hba_inst == NULL)
1206 		return (ENXIO);
1207 
1208 	if (sata_hba_inst->satahba_tran == NULL)
1209 		return (ENXIO);
1210 
1211 	switch (cmd) {
1212 
1213 	case DEVCTL_DEVICE_GETSTATE:
1214 	case DEVCTL_DEVICE_ONLINE:
1215 	case DEVCTL_DEVICE_OFFLINE:
1216 	case DEVCTL_DEVICE_REMOVE:
1217 	case DEVCTL_BUS_GETSTATE:
1218 		/*
1219 		 * There may be more cases that we want to pass to default
1220 		 * handler rather than fail them.
1221 		 */
1222 		return (ndi_devctl_ioctl(dip, cmd, arg, mode, 0));
1223 	}
1224 
1225 	/* read devctl ioctl data */
1226 	if (cmd != DEVCTL_AP_CONTROL) {
1227 		if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS)
1228 			return (EFAULT);
1229 
1230 		if ((comp_port = sata_get_port_num(sata_hba_inst, dcp)) ==
1231 		    -1) {
1232 			if (dcp)
1233 				ndi_dc_freehdl(dcp);
1234 			return (EINVAL);
1235 		}
1236 
1237 		cport = SCSI_TO_SATA_CPORT(comp_port);
1238 		pmport = SCSI_TO_SATA_PMPORT(comp_port);
1239 		/* Only cport is considered now, i.e. SATA_ADDR_CPORT */
1240 		qual = SATA_ADDR_CPORT;
1241 		if (sata_validate_sata_address(sata_hba_inst, cport, pmport,
1242 		    qual) != 0) {
1243 			ndi_dc_freehdl(dcp);
1244 			return (EINVAL);
1245 		}
1246 
1247 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1248 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1249 		    cport_mutex);
1250 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1251 			/*
1252 			 * Cannot process ioctl request now. Come back later.
1253 			 */
1254 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1255 			    cport_mutex);
1256 			ndi_dc_freehdl(dcp);
1257 			return (EBUSY);
1258 		}
1259 		/* Block event processing for this port */
1260 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1261 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1262 
1263 		sata_device.satadev_addr.cport = cport;
1264 		sata_device.satadev_addr.pmport = pmport;
1265 		sata_device.satadev_addr.qual = qual;
1266 		sata_device.satadev_rev = SATA_DEVICE_REV;
1267 	}
1268 
1269 	switch (cmd) {
1270 
1271 	case DEVCTL_AP_DISCONNECT:
1272 
1273 		/*
1274 		 * Normally, cfgadm sata plugin will try to offline
1275 		 * (unconfigure) device before this request. Nevertheless,
1276 		 * if a device is still configured, we need to
1277 		 * attempt to offline and unconfigure device first, and we will
1278 		 * deactivate the port regardless of the unconfigure
1279 		 * operation results.
1280 		 *
1281 		 */
1282 		rv = sata_ioctl_disconnect(sata_hba_inst, &sata_device);
1283 
1284 		break;
1285 
1286 	case DEVCTL_AP_UNCONFIGURE:
1287 
1288 		/*
1289 		 * The unconfigure operation uses generic nexus operation to
1290 		 * offline a device. It leaves a target device node attached.
1291 		 * and obviously sata_drive_info attached as well, because
1292 		 * from the hardware point of view nothing has changed.
1293 		 */
1294 		rv = sata_ioctl_unconfigure(sata_hba_inst, &sata_device);
1295 		break;
1296 
1297 	case DEVCTL_AP_CONNECT:
1298 	{
1299 		/*
1300 		 * The sata cfgadm pluging will invoke this operation only if
1301 		 * port was found in the disconnect state (failed state
1302 		 * is also treated as the disconnected state).
1303 		 * If port activation is successful and a device is found
1304 		 * attached to the port, the initialization sequence is
1305 		 * executed to probe the port and attach
1306 		 * a device structure to a port structure. The device is not
1307 		 * set in configured state (system-wise) by this operation.
1308 		 */
1309 
1310 		rv = sata_ioctl_connect(sata_hba_inst, &sata_device);
1311 
1312 		break;
1313 	}
1314 
1315 	case DEVCTL_AP_CONFIGURE:
1316 	{
1317 		/*
1318 		 * A port may be in an active or shutdown state.
1319 		 * If port is in a failed state, operation is aborted.
1320 		 * If a port is in a shutdown state, sata_tran_port_activate()
1321 		 * is invoked prior to any other operation.
1322 		 *
1323 		 * Onlining the device involves creating a new target node.
1324 		 * If there is an old target node present (belonging to
1325 		 * previously removed device), the operation is aborted - the
1326 		 * old node has to be released and removed before configure
1327 		 * operation is attempted.
1328 		 */
1329 
1330 		rv = sata_ioctl_configure(sata_hba_inst, &sata_device);
1331 
1332 		break;
1333 	}
1334 
1335 	case DEVCTL_AP_GETSTATE:
1336 
1337 		sata_cfgadm_state(sata_hba_inst, comp_port, &ap_state);
1338 
1339 		ap_state.ap_last_change = (time_t)-1;
1340 		ap_state.ap_error_code = 0;
1341 		ap_state.ap_in_transition = 0;
1342 
1343 		/* Copy the return AP-state information to the user space */
1344 		if (ndi_dc_return_ap_state(&ap_state, dcp) != NDI_SUCCESS) {
1345 			rv = EFAULT;
1346 		}
1347 		break;
1348 
1349 	case DEVCTL_AP_CONTROL:
1350 	{
1351 		/*
1352 		 * Generic devctl for hardware specific functionality
1353 		 */
1354 		sata_ioctl_data_t	ioc;
1355 
1356 		ASSERT(dcp == NULL);
1357 
1358 		/* Copy in user ioctl data first */
1359 #ifdef _MULTI_DATAMODEL
1360 		if (ddi_model_convert_from(mode & FMODELS) ==
1361 		    DDI_MODEL_ILP32) {
1362 
1363 			sata_ioctl_data_32_t	ioc32;
1364 
1365 			if (ddi_copyin((void *)arg, (void *)&ioc32,
1366 			    sizeof (ioc32), mode) != 0) {
1367 				rv = EFAULT;
1368 				break;
1369 			}
1370 			ioc.cmd 	= (uint_t)ioc32.cmd;
1371 			ioc.port	= (uint_t)ioc32.port;
1372 			ioc.get_size	= (uint_t)ioc32.get_size;
1373 			ioc.buf		= (caddr_t)(uintptr_t)ioc32.buf;
1374 			ioc.bufsiz	= (uint_t)ioc32.bufsiz;
1375 			ioc.misc_arg	= (uint_t)ioc32.misc_arg;
1376 		} else
1377 #endif /* _MULTI_DATAMODEL */
1378 		if (ddi_copyin((void *)arg, (void *)&ioc, sizeof (ioc),
1379 		    mode) != 0) {
1380 			return (EFAULT);
1381 		}
1382 
1383 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
1384 		    "sata_hba_ioctl: DEVCTL_AP_CONTROL "
1385 		    "cmd 0x%x, port 0x%x", ioc.cmd, ioc.port);
1386 
1387 		/*
1388 		 * To avoid BE/LE and 32/64 issues, a get_size always returns
1389 		 * a 32-bit number.
1390 		 */
1391 		if (ioc.get_size != 0 && ioc.bufsiz != (sizeof (uint32_t))) {
1392 			return (EINVAL);
1393 		}
1394 		/* validate address */
1395 		cport = SCSI_TO_SATA_CPORT(ioc.port);
1396 		pmport = SCSI_TO_SATA_PMPORT(ioc.port);
1397 		qual = SCSI_TO_SATA_ADDR_QUAL(ioc.port);
1398 
1399 		/* Override address qualifier - handle cport only for now */
1400 		qual = SATA_ADDR_CPORT;
1401 
1402 		if (sata_validate_sata_address(sata_hba_inst, cport,
1403 		    pmport, qual) != 0)
1404 			return (EINVAL);
1405 
1406 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1407 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1408 		    cport_mutex);
1409 		/* Is the port locked by event processing daemon ? */
1410 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1411 			/*
1412 			 * Cannot process ioctl request now. Come back later
1413 			 */
1414 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1415 			    cport_mutex);
1416 			return (EBUSY);
1417 		}
1418 		/* Block event processing for this port */
1419 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1420 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1421 
1422 
1423 		sata_device.satadev_addr.cport = cport;
1424 		sata_device.satadev_addr.pmport = pmport;
1425 		sata_device.satadev_addr.qual = qual;
1426 		sata_device.satadev_rev = SATA_DEVICE_REV;
1427 
1428 		switch (ioc.cmd) {
1429 
1430 		case SATA_CFGA_RESET_PORT:
1431 			/*
1432 			 * There is no protection for configured device.
1433 			 */
1434 			rv = sata_ioctl_reset_port(sata_hba_inst, &sata_device);
1435 			break;
1436 
1437 		case SATA_CFGA_RESET_DEVICE:
1438 			/*
1439 			 * There is no protection for configured device.
1440 			 */
1441 			rv = sata_ioctl_reset_device(sata_hba_inst,
1442 			    &sata_device);
1443 			break;
1444 
1445 		case SATA_CFGA_RESET_ALL:
1446 			/*
1447 			 * There is no protection for configured devices.
1448 			 */
1449 			rv = sata_ioctl_reset_all(sata_hba_inst);
1450 			/*
1451 			 * We return here, because common return is for
1452 			 * a single port operation - we have already unlocked
1453 			 * all ports and no dc handle was allocated.
1454 			 */
1455 			return (rv);
1456 
1457 		case SATA_CFGA_PORT_DEACTIVATE:
1458 			/*
1459 			 * Arbitrarily unconfigure attached device, if any.
1460 			 * Even if the unconfigure fails, proceed with the
1461 			 * port deactivation.
1462 			 */
1463 			rv = sata_ioctl_deactivate(sata_hba_inst, &sata_device);
1464 
1465 			break;
1466 
1467 		case SATA_CFGA_PORT_ACTIVATE:
1468 
1469 			rv = sata_ioctl_activate(sata_hba_inst, &sata_device);
1470 			break;
1471 
1472 		case SATA_CFGA_PORT_SELF_TEST:
1473 
1474 			rv = sata_ioctl_port_self_test(sata_hba_inst,
1475 			    &sata_device);
1476 			break;
1477 
1478 		case SATA_CFGA_GET_DEVICE_PATH:
1479 			if (qual == SATA_ADDR_CPORT)
1480 				sata_device.satadev_addr.qual =
1481 				    SATA_ADDR_DCPORT;
1482 			else
1483 				sata_device.satadev_addr.qual =
1484 				    SATA_ADDR_DPMPORT;
1485 			rv = sata_ioctl_get_device_path(sata_hba_inst,
1486 			    &sata_device, &ioc, mode);
1487 			break;
1488 
1489 		case SATA_CFGA_GET_AP_TYPE:
1490 
1491 			rv = sata_ioctl_get_ap_type(sata_hba_inst,
1492 			    &sata_device, &ioc, mode);
1493 			break;
1494 
1495 		case SATA_CFGA_GET_MODEL_INFO:
1496 
1497 			rv = sata_ioctl_get_model_info(sata_hba_inst,
1498 			    &sata_device, &ioc, mode);
1499 			break;
1500 
1501 		case SATA_CFGA_GET_REVFIRMWARE_INFO:
1502 
1503 			rv = sata_ioctl_get_revfirmware_info(sata_hba_inst,
1504 			    &sata_device, &ioc, mode);
1505 			break;
1506 
1507 		case SATA_CFGA_GET_SERIALNUMBER_INFO:
1508 
1509 			rv = sata_ioctl_get_serialnumber_info(sata_hba_inst,
1510 			    &sata_device, &ioc, mode);
1511 			break;
1512 
1513 		default:
1514 			rv = EINVAL;
1515 			break;
1516 
1517 		} /* End of DEVCTL_AP_CONTROL cmd switch */
1518 
1519 		break;
1520 	}
1521 
1522 	default:
1523 	{
1524 		/*
1525 		 * If we got here, we got an IOCTL that SATA HBA Framework
1526 		 * does not recognize. Pass ioctl to HBA driver, in case
1527 		 * it could process it.
1528 		 */
1529 		sata_hba_tran_t *sata_tran = sata_hba_inst->satahba_tran;
1530 		dev_info_t	*mydip = SATA_DIP(sata_hba_inst);
1531 
1532 		SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1533 		    "IOCTL 0x%2x not supported in SATA framework, "
1534 		    "passthrough to HBA", cmd);
1535 
1536 		if (sata_tran->sata_tran_ioctl == NULL) {
1537 			rv = EINVAL;
1538 			break;
1539 		}
1540 		rval = (*sata_tran->sata_tran_ioctl)(mydip, cmd, arg);
1541 		if (rval != 0) {
1542 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1543 			    "IOCTL 0x%2x failed in HBA", cmd);
1544 			rv = rval;
1545 		}
1546 		break;
1547 	}
1548 
1549 	} /* End of main IOCTL switch */
1550 
1551 	if (dcp) {
1552 		ndi_dc_freehdl(dcp);
1553 	}
1554 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1555 	cportinfo->cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
1556 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1557 
1558 	return (rv);
1559 }
1560 
1561 
1562 /*
1563  * Create error retrieval sata packet
1564  *
1565  * A sata packet is allocated and set-up to contain specified error retrieval
1566  * command and appropriate dma-able data buffer.
1567  * No association with any scsi packet is made and no callback routine is
1568  * specified.
1569  *
1570  * Returns a pointer to sata packet upon successfull packet creation.
1571  * Returns NULL, if packet cannot be created.
1572  */
1573 sata_pkt_t *
1574 sata_get_error_retrieval_pkt(dev_info_t *dip, sata_device_t *sata_device,
1575     int pkt_type)
1576 {
1577 	sata_hba_inst_t	*sata_hba_inst;
1578 	sata_pkt_txlate_t *spx;
1579 	sata_pkt_t *spkt;
1580 	sata_drive_info_t *sdinfo;
1581 
1582 	mutex_enter(&sata_mutex);
1583 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1584 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1585 		if (SATA_DIP(sata_hba_inst) == dip)
1586 			break;
1587 	}
1588 	mutex_exit(&sata_mutex);
1589 	ASSERT(sata_hba_inst != NULL);
1590 
1591 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
1592 	if (sdinfo == NULL) {
1593 		sata_log(sata_hba_inst, CE_WARN,
1594 		    "sata: error recovery request for non-attached device at "
1595 		    "cport %d", sata_device->satadev_addr.cport);
1596 		return (NULL);
1597 	}
1598 
1599 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1600 	spx->txlt_sata_hba_inst = sata_hba_inst;
1601 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
1602 	spkt = sata_pkt_alloc(spx, NULL);
1603 	if (spkt == NULL) {
1604 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1605 		return (NULL);
1606 	}
1607 	/* address is needed now */
1608 	spkt->satapkt_device.satadev_addr = sata_device->satadev_addr;
1609 
1610 	switch (pkt_type) {
1611 	case SATA_ERR_RETR_PKT_TYPE_NCQ:
1612 		if (sata_ncq_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1613 			return (spkt);
1614 		break;
1615 
1616 	case SATA_ERR_RETR_PKT_TYPE_ATAPI:
1617 		if (sata_atapi_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1618 			return (spkt);
1619 		break;
1620 
1621 	default:
1622 		break;
1623 	}
1624 
1625 	sata_pkt_free(spx);
1626 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1627 	return (NULL);
1628 
1629 }
1630 
1631 
1632 /*
1633  * Free error retrieval sata packet
1634  *
1635  * Free sata packet and any associated resources allocated previously by
1636  * sata_get_error_retrieval_pkt().
1637  *
1638  * Void return.
1639  */
1640 void
1641 sata_free_error_retrieval_pkt(sata_pkt_t *sata_pkt)
1642 {
1643 	sata_pkt_txlate_t *spx =
1644 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1645 
1646 	ASSERT(sata_pkt != NULL);
1647 
1648 	sata_free_local_buffer(spx);
1649 	sata_pkt_free(spx);
1650 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1651 
1652 }
1653 
1654 /*
1655  * sata_name_child is for composing the name of the node
1656  * the format of the name is "target,0".
1657  */
1658 static int
1659 sata_name_child(dev_info_t *dip, char *name, int namelen)
1660 {
1661 	int target;
1662 
1663 	target = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1664 	    DDI_PROP_DONTPASS, "target", -1);
1665 	if (target == -1)
1666 		return (DDI_FAILURE);
1667 	(void) snprintf(name, namelen, "%x,0", target);
1668 	return (DDI_SUCCESS);
1669 }
1670 
1671 
1672 
1673 /* ****************** SCSA required entry points *********************** */
1674 
1675 /*
1676  * Implementation of scsi tran_tgt_init.
1677  * sata_scsi_tgt_init() initializes scsi_device structure
1678  *
1679  * If successful, DDI_SUCCESS is returned.
1680  * DDI_FAILURE is returned if addressed device does not exist
1681  */
1682 
1683 static int
1684 sata_scsi_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
1685     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
1686 {
1687 #ifndef __lock_lint
1688 	_NOTE(ARGUNUSED(hba_dip))
1689 	_NOTE(ARGUNUSED(tgt_dip))
1690 #endif
1691 	sata_device_t		sata_device;
1692 	sata_drive_info_t	*sdinfo;
1693 	struct sata_id		*sid;
1694 	sata_hba_inst_t		*sata_hba_inst;
1695 	char			model[SATA_ID_MODEL_LEN + 1];
1696 	char			fw[SATA_ID_FW_LEN + 1];
1697 	char			*vid, *pid;
1698 	int			i;
1699 
1700 	/*
1701 	 * Fail tran_tgt_init for .conf stub node
1702 	 */
1703 	if (ndi_dev_is_persistent_node(tgt_dip) == 0) {
1704 		(void) ndi_merge_node(tgt_dip, sata_name_child);
1705 		ddi_set_name_addr(tgt_dip, NULL);
1706 		return (DDI_FAILURE);
1707 	}
1708 
1709 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
1710 
1711 	/* Validate scsi device address */
1712 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
1713 	    &sata_device) != 0)
1714 		return (DDI_FAILURE);
1715 
1716 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1717 	    sata_device.satadev_addr.cport)));
1718 
1719 	/* sata_device now contains a valid sata address */
1720 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
1721 	if (sdinfo == NULL) {
1722 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1723 		    sata_device.satadev_addr.cport)));
1724 		return (DDI_FAILURE);
1725 	}
1726 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1727 	    sata_device.satadev_addr.cport)));
1728 
1729 	/*
1730 	 * Check if we need to create a legacy devid (i.e cmdk style) for
1731 	 * the target disks.
1732 	 *
1733 	 * HBA devinfo node will have the property "use-cmdk-devid-format"
1734 	 * if we need to create cmdk-style devid for all the disk devices
1735 	 * attached to this controller. This property may have been set
1736 	 * from HBA driver's .conf file or by the HBA driver in its
1737 	 * attach(9F) function.
1738 	 */
1739 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
1740 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
1741 	    "use-cmdk-devid-format", 0) == 1)) {
1742 		/* register a legacy devid for this target node */
1743 		sata_target_devid_register(tgt_dip, sdinfo);
1744 	}
1745 
1746 
1747 	/*
1748 	 * 'Identify Device Data' does not always fit in standard SCSI
1749 	 * INQUIRY data, so establish INQUIRY_* properties with full-form
1750 	 * of information.
1751 	 */
1752 	sid = &sdinfo->satadrv_id;
1753 #ifdef	_LITTLE_ENDIAN
1754 	swab(sid->ai_model, model, SATA_ID_MODEL_LEN);
1755 	swab(sid->ai_fw, fw, SATA_ID_FW_LEN);
1756 #else	/* _LITTLE_ENDIAN */
1757 	bcopy(sid->ai_model, model, SATA_ID_MODEL_LEN);
1758 	bcopy(sid->ai_fw, fw, SATA_ID_FW_LEN);
1759 #endif	/* _LITTLE_ENDIAN */
1760 	model[SATA_ID_MODEL_LEN] = 0;
1761 	fw[SATA_ID_FW_LEN] = 0;
1762 
1763 	/* split model into into vid/pid */
1764 	for (i = 0, pid = model; i < SATA_ID_MODEL_LEN; i++, pid++)
1765 		if ((*pid == ' ') || (*pid == '\t'))
1766 			break;
1767 	if (i < SATA_ID_MODEL_LEN) {
1768 		vid = model;
1769 		*pid++ = 0;		/* terminate vid, establish pid */
1770 	} else {
1771 		vid = NULL;		/* vid will stay "ATA     " */
1772 		pid = model;		/* model is all pid */
1773 	}
1774 
1775 	if (vid)
1776 		(void) scsi_hba_prop_update_inqstring(sd, INQUIRY_VENDOR_ID,
1777 		    vid, strlen(vid));
1778 	if (pid)
1779 		(void) scsi_hba_prop_update_inqstring(sd, INQUIRY_PRODUCT_ID,
1780 		    pid, strlen(pid));
1781 	(void) scsi_hba_prop_update_inqstring(sd, INQUIRY_REVISION_ID,
1782 	    fw, strlen(fw));
1783 
1784 	return (DDI_SUCCESS);
1785 }
1786 
1787 /*
1788  * Implementation of scsi tran_tgt_probe.
1789  * Probe target, by calling default scsi routine scsi_hba_probe()
1790  */
1791 static int
1792 sata_scsi_tgt_probe(struct scsi_device *sd, int (*callback)(void))
1793 {
1794 	sata_hba_inst_t *sata_hba_inst =
1795 	    (sata_hba_inst_t *)(sd->sd_address.a_hba_tran->tran_hba_private);
1796 	int rval;
1797 
1798 	rval = scsi_hba_probe(sd, callback);
1799 
1800 	if (rval == SCSIPROBE_EXISTS) {
1801 		/*
1802 		 * Set property "pm-capable" on the target device node, so that
1803 		 * the target driver will not try to fetch scsi cycle counters
1804 		 * before enabling device power-management.
1805 		 */
1806 		if ((ddi_prop_update_int(DDI_DEV_T_NONE, sd->sd_dev,
1807 		    "pm-capable", 1)) != DDI_PROP_SUCCESS) {
1808 			sata_log(sata_hba_inst, CE_WARN,
1809 			    "SATA device at port %d: "
1810 			    "will not be power-managed ",
1811 			    SCSI_TO_SATA_CPORT(sd->sd_address.a_target));
1812 			SATA_LOG_D((sata_hba_inst, CE_WARN,
1813 			    "failure updating pm-capable property"));
1814 		}
1815 	}
1816 	return (rval);
1817 }
1818 
1819 /*
1820  * Implementation of scsi tran_tgt_free.
1821  * Release all resources allocated for scsi_device
1822  */
1823 static void
1824 sata_scsi_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
1825     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
1826 {
1827 #ifndef __lock_lint
1828 	_NOTE(ARGUNUSED(hba_dip))
1829 #endif
1830 	sata_device_t		sata_device;
1831 	sata_drive_info_t	*sdinfo;
1832 	sata_hba_inst_t		*sata_hba_inst;
1833 	ddi_devid_t		devid;
1834 
1835 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
1836 
1837 	/* Validate scsi device address */
1838 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
1839 	    &sata_device) != 0)
1840 		return;
1841 
1842 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1843 	    sata_device.satadev_addr.cport)));
1844 
1845 	/* sata_device now should contain a valid sata address */
1846 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
1847 	if (sdinfo == NULL) {
1848 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1849 		    sata_device.satadev_addr.cport)));
1850 		return;
1851 	}
1852 	/*
1853 	 * We did not allocate any resources in sata_scsi_tgt_init()
1854 	 * other than few properties.
1855 	 * Free them.
1856 	 */
1857 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1858 	    sata_device.satadev_addr.cport)));
1859 	(void) ndi_prop_remove(DDI_DEV_T_NONE, tgt_dip, "pm-capable");
1860 
1861 	/*
1862 	 * If devid was previously created but not freed up from
1863 	 * sd(7D) driver (i.e during detach(9F)) then do it here.
1864 	 */
1865 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
1866 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
1867 	    "use-cmdk-devid-format", 0) == 1) &&
1868 	    (ddi_devid_get(tgt_dip, &devid) == DDI_SUCCESS)) {
1869 		ddi_devid_unregister(tgt_dip);
1870 		ddi_devid_free(devid);
1871 	}
1872 }
1873 
1874 /*
1875  * Implementation of scsi tran_init_pkt
1876  * Upon successful return, scsi pkt buffer has DMA resources allocated.
1877  *
1878  * It seems that we should always allocate pkt, even if the address is
1879  * for non-existing device - just use some default for dma_attr.
1880  * The reason is that there is no way to communicate this to a caller here.
1881  * Subsequent call to sata_scsi_start may fail appropriately.
1882  * Simply returning NULL does not seem to discourage a target driver...
1883  *
1884  * Returns a pointer to initialized scsi_pkt, or NULL otherwise.
1885  */
1886 static struct scsi_pkt *
1887 sata_scsi_init_pkt(struct scsi_address *ap, struct scsi_pkt *pkt,
1888     struct buf *bp, int cmdlen, int statuslen, int tgtlen, int flags,
1889     int (*callback)(caddr_t), caddr_t arg)
1890 {
1891 	sata_hba_inst_t *sata_hba_inst =
1892 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
1893 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
1894 	sata_device_t sata_device;
1895 	sata_drive_info_t *sdinfo;
1896 	sata_pkt_txlate_t *spx;
1897 	ddi_dma_attr_t cur_dma_attr;
1898 	int rval;
1899 	boolean_t new_pkt = TRUE;
1900 
1901 	ASSERT(ap->a_hba_tran->tran_hba_dip == dip);
1902 
1903 	/*
1904 	 * We need to translate the address, even if it could be
1905 	 * a bogus one, for a non-existing device
1906 	 */
1907 	sata_device.satadev_addr.qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
1908 	sata_device.satadev_addr.cport = SCSI_TO_SATA_CPORT(ap->a_target);
1909 	sata_device.satadev_addr.pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
1910 	sata_device.satadev_rev = SATA_DEVICE_REV;
1911 
1912 	if (pkt == NULL) {
1913 		/*
1914 		 * Have to allocate a brand new scsi packet.
1915 		 * We need to operate with auto request sense enabled.
1916 		 */
1917 		pkt = scsi_hba_pkt_alloc(dip, ap, cmdlen,
1918 		    MAX(statuslen, sizeof (struct scsi_arq_status)),
1919 		    tgtlen, sizeof (sata_pkt_txlate_t), callback, arg);
1920 
1921 		if (pkt == NULL)
1922 			return (NULL);
1923 
1924 		/* Fill scsi packet structure */
1925 		pkt->pkt_comp		= (void (*)())NULL;
1926 		pkt->pkt_time		= 0;
1927 		pkt->pkt_resid		= 0;
1928 		pkt->pkt_statistics	= 0;
1929 		pkt->pkt_reason		= 0;
1930 
1931 		/*
1932 		 * pkt_hba_private will point to sata pkt txlate structure
1933 		 */
1934 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
1935 		bzero(spx, sizeof (sata_pkt_txlate_t));
1936 
1937 		spx->txlt_scsi_pkt = pkt;
1938 		spx->txlt_sata_hba_inst = sata_hba_inst;
1939 
1940 		/* Allocate sata_pkt */
1941 		spx->txlt_sata_pkt = sata_pkt_alloc(spx, callback);
1942 		if (spx->txlt_sata_pkt == NULL) {
1943 			/* Could not allocate sata pkt */
1944 			scsi_hba_pkt_free(ap, pkt);
1945 			return (NULL);
1946 		}
1947 		/* Set sata address */
1948 		spx->txlt_sata_pkt->satapkt_device.satadev_addr =
1949 		    sata_device.satadev_addr;
1950 		spx->txlt_sata_pkt->satapkt_device.satadev_rev =
1951 		    sata_device.satadev_rev;
1952 
1953 		if ((bp == NULL) || (bp->b_bcount == 0))
1954 			return (pkt);
1955 
1956 		spx->txlt_total_residue = bp->b_bcount;
1957 	} else {
1958 		new_pkt = FALSE;
1959 		/*
1960 		 * Packet was preallocated/initialized by previous call
1961 		 */
1962 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
1963 
1964 		if ((bp == NULL) || (bp->b_bcount == 0)) {
1965 			return (pkt);
1966 		}
1967 
1968 		/* Pkt is available already: spx->txlt_scsi_pkt == pkt; */
1969 	}
1970 
1971 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
1972 
1973 	/*
1974 	 * We use an adjusted version of the dma_attr, to account
1975 	 * for device addressing limitations.
1976 	 * sata_adjust_dma_attr() will handle sdinfo == NULL which may
1977 	 * happen when a device is not yet configured.
1978 	 */
1979 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1980 	    sata_device.satadev_addr.cport)));
1981 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
1982 	    &spx->txlt_sata_pkt->satapkt_device);
1983 	/* NULL sdinfo may be passsed to sata_adjust_dma_attr() */
1984 	sata_adjust_dma_attr(sdinfo,
1985 	    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
1986 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1987 	    sata_device.satadev_addr.cport)));
1988 	/*
1989 	 * Allocate necessary DMA resources for the packet's data buffer
1990 	 * NOTE:
1991 	 * In case of read/write commands, DMA resource allocation here is
1992 	 * based on the premise that the transfer length specified in
1993 	 * the read/write scsi cdb will match exactly DMA resources -
1994 	 * returning correct packet residue is crucial.
1995 	 */
1996 	if ((rval = sata_dma_buf_setup(spx, flags, callback, arg,
1997 	    &cur_dma_attr)) != DDI_SUCCESS) {
1998 		/*
1999 		 * If a DMA allocation request fails with
2000 		 * DDI_DMA_NOMAPPING, indicate the error by calling
2001 		 * bioerror(9F) with bp and an error code of EFAULT.
2002 		 * If a DMA allocation request fails with
2003 		 * DDI_DMA_TOOBIG, indicate the error by calling
2004 		 * bioerror(9F) with bp and an error code of EINVAL.
2005 		 * For DDI_DMA_NORESOURCES, we may have some of them allocated.
2006 		 * Request may be repeated later - there is no real error.
2007 		 */
2008 		switch (rval) {
2009 		case DDI_DMA_NORESOURCES:
2010 			bioerror(bp, 0);
2011 			break;
2012 		case DDI_DMA_NOMAPPING:
2013 		case DDI_DMA_BADATTR:
2014 			bioerror(bp, EFAULT);
2015 			break;
2016 		case DDI_DMA_TOOBIG:
2017 		default:
2018 			bioerror(bp, EINVAL);
2019 			break;
2020 		}
2021 		if (new_pkt == TRUE) {
2022 			/*
2023 			 * Since this is a new packet, we can clean-up
2024 			 * everything
2025 			 */
2026 			sata_scsi_destroy_pkt(ap, pkt);
2027 		} else {
2028 			/*
2029 			 * This is a re-used packet. It will be target driver's
2030 			 * responsibility to eventually destroy it (which
2031 			 * will free allocated resources).
2032 			 * Here, we just "complete" the request, leaving
2033 			 * allocated resources intact, so the request may
2034 			 * be retried.
2035 			 */
2036 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2037 			sata_pkt_free(spx);
2038 		}
2039 		return (NULL);
2040 	}
2041 	/* Set number of bytes that are not yet accounted for */
2042 	pkt->pkt_resid = spx->txlt_total_residue;
2043 	ASSERT(pkt->pkt_resid >= 0);
2044 
2045 	return (pkt);
2046 }
2047 
2048 /*
2049  * Implementation of scsi tran_start.
2050  * Translate scsi cmd into sata operation and return status.
2051  * ATAPI CDBs are passed to ATAPI devices - the device determines what commands
2052  * are supported.
2053  * For SATA hard disks, supported scsi commands:
2054  * SCMD_INQUIRY
2055  * SCMD_TEST_UNIT_READY
2056  * SCMD_START_STOP
2057  * SCMD_READ_CAPACITY
2058  * SCMD_REQUEST_SENSE
2059  * SCMD_LOG_SENSE_G1
2060  * SCMD_LOG_SELECT_G1
2061  * SCMD_MODE_SENSE	(specific pages)
2062  * SCMD_MODE_SENSE_G1	(specific pages)
2063  * SCMD_MODE_SELECT	(specific pages)
2064  * SCMD_MODE_SELECT_G1	(specific pages)
2065  * SCMD_SYNCHRONIZE_CACHE
2066  * SCMD_SYNCHRONIZE_CACHE_G1
2067  * SCMD_READ
2068  * SCMD_READ_G1
2069  * SCMD_READ_G4
2070  * SCMD_READ_G5
2071  * SCMD_WRITE
2072  * SCMD_WRITE_BUFFER
2073  * SCMD_WRITE_G1
2074  * SCMD_WRITE_G4
2075  * SCMD_WRITE_G5
2076  * SCMD_SEEK		(noop)
2077  * SCMD_SDIAG
2078  *
2079  * All other commands are rejected as unsupported.
2080  *
2081  * Returns:
2082  * TRAN_ACCEPT if command was executed successfully or accepted by HBA driver
2083  * for execution. TRAN_ACCEPT may be returned also if device was removed but
2084  * a callback could be scheduled.
2085  * TRAN_BADPKT if cmd was directed to invalid address.
2086  * TRAN_FATAL_ERROR is command was rejected due to hardware error, including
2087  * some unspecified error. TRAN_FATAL_ERROR may be also returned if a device
2088  * was removed and there was no callback specified in scsi pkt.
2089  * TRAN_BUSY if command could not be executed becasue HBA driver or SATA
2090  * framework was busy performing some other operation(s).
2091  *
2092  */
2093 static int
2094 sata_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
2095 {
2096 	sata_hba_inst_t *sata_hba_inst =
2097 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2098 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2099 	sata_drive_info_t *sdinfo;
2100 	struct buf *bp;
2101 	int cport;
2102 	int rval;
2103 
2104 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2105 	    "sata_scsi_start: cmd 0x%02x\n", pkt->pkt_cdbp[0]);
2106 
2107 	ASSERT(spx != NULL &&
2108 	    spx->txlt_scsi_pkt == pkt && spx->txlt_sata_pkt != NULL);
2109 
2110 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
2111 
2112 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2113 	sdinfo = sata_get_device_info(sata_hba_inst,
2114 	    &spx->txlt_sata_pkt->satapkt_device);
2115 	if (sdinfo == NULL ||
2116 	    SATA_CPORT_INFO(sata_hba_inst, cport)->cport_tgtnode_clean ==
2117 	    B_FALSE ||
2118 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2119 
2120 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2121 		pkt->pkt_reason = CMD_DEV_GONE;
2122 		/*
2123 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
2124 		 * only in callback function (for normal requests) and
2125 		 * in the dump code path.
2126 		 * So, if the callback is available, we need to do
2127 		 * the callback rather than returning TRAN_FATAL_ERROR here.
2128 		 */
2129 		if (pkt->pkt_comp != NULL) {
2130 			/* scsi callback required */
2131 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2132 			    (task_func_t *)pkt->pkt_comp,
2133 			    (void *)pkt, TQ_SLEEP) == NULL)
2134 				/* Scheduling the callback failed */
2135 				return (TRAN_BUSY);
2136 			return (TRAN_ACCEPT);
2137 		}
2138 		/* No callback available */
2139 		return (TRAN_FATAL_ERROR);
2140 	}
2141 
2142 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
2143 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2144 		rval = sata_txlt_atapi(spx);
2145 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2146 		    "sata_scsi_start atapi: rval %d\n", rval);
2147 		return (rval);
2148 	}
2149 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2150 
2151 	/* ATA Disk commands processing starts here */
2152 
2153 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2154 
2155 	switch (pkt->pkt_cdbp[0]) {
2156 
2157 	case SCMD_INQUIRY:
2158 		/* Mapped to identify device */
2159 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2160 			bp_mapin(bp);
2161 		rval = sata_txlt_inquiry(spx);
2162 		break;
2163 
2164 	case SCMD_TEST_UNIT_READY:
2165 		/*
2166 		 * SAT "SATA to ATA Translation" doc specifies translation
2167 		 * to ATA CHECK POWER MODE.
2168 		 */
2169 		rval = sata_txlt_test_unit_ready(spx);
2170 		break;
2171 
2172 	case SCMD_START_STOP:
2173 		/* Mapping depends on the command */
2174 		rval = sata_txlt_start_stop_unit(spx);
2175 		break;
2176 
2177 	case SCMD_READ_CAPACITY:
2178 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2179 			bp_mapin(bp);
2180 		rval = sata_txlt_read_capacity(spx);
2181 		break;
2182 
2183 	case SCMD_REQUEST_SENSE:
2184 		/*
2185 		 * Always No Sense, since we force ARQ
2186 		 */
2187 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2188 			bp_mapin(bp);
2189 		rval = sata_txlt_request_sense(spx);
2190 		break;
2191 
2192 	case SCMD_LOG_SENSE_G1:
2193 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2194 			bp_mapin(bp);
2195 		rval = sata_txlt_log_sense(spx);
2196 		break;
2197 
2198 	case SCMD_LOG_SELECT_G1:
2199 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2200 			bp_mapin(bp);
2201 		rval = sata_txlt_log_select(spx);
2202 		break;
2203 
2204 	case SCMD_MODE_SENSE:
2205 	case SCMD_MODE_SENSE_G1:
2206 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2207 			bp_mapin(bp);
2208 		rval = sata_txlt_mode_sense(spx);
2209 		break;
2210 
2211 
2212 	case SCMD_MODE_SELECT:
2213 	case SCMD_MODE_SELECT_G1:
2214 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2215 			bp_mapin(bp);
2216 		rval = sata_txlt_mode_select(spx);
2217 		break;
2218 
2219 	case SCMD_SYNCHRONIZE_CACHE:
2220 	case SCMD_SYNCHRONIZE_CACHE_G1:
2221 		rval = sata_txlt_synchronize_cache(spx);
2222 		break;
2223 
2224 	case SCMD_READ:
2225 	case SCMD_READ_G1:
2226 	case SCMD_READ_G4:
2227 	case SCMD_READ_G5:
2228 		rval = sata_txlt_read(spx);
2229 		break;
2230 	case SCMD_WRITE_BUFFER:
2231 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2232 			bp_mapin(bp);
2233 		rval = sata_txlt_write_buffer(spx);
2234 		break;
2235 
2236 	case SCMD_WRITE:
2237 	case SCMD_WRITE_G1:
2238 	case SCMD_WRITE_G4:
2239 	case SCMD_WRITE_G5:
2240 		rval = sata_txlt_write(spx);
2241 		break;
2242 
2243 	case SCMD_SEEK:
2244 		rval = sata_txlt_nodata_cmd_immediate(spx);
2245 		break;
2246 
2247 		/* Other cases will be filed later */
2248 		/* postponed until phase 2 of the development */
2249 	default:
2250 		rval = sata_txlt_invalid_command(spx);
2251 		break;
2252 	}
2253 
2254 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2255 	    "sata_scsi_start: rval %d\n", rval);
2256 
2257 	return (rval);
2258 }
2259 
2260 /*
2261  * Implementation of scsi tran_abort.
2262  * Abort specific pkt or all packets.
2263  *
2264  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2265  *
2266  * May be called from an interrupt level.
2267  */
2268 static int
2269 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2270 {
2271 	sata_hba_inst_t *sata_hba_inst =
2272 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2273 	sata_device_t	sata_device;
2274 	sata_pkt_t	*sata_pkt;
2275 
2276 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2277 	    "sata_scsi_abort: %s at target: 0x%x\n",
2278 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2279 
2280 	/* Validate address */
2281 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2282 		/* Invalid address */
2283 		return (0);
2284 
2285 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2286 	    sata_device.satadev_addr.cport)));
2287 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2288 		/* invalid address */
2289 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2290 		    sata_device.satadev_addr.cport)));
2291 		return (0);
2292 	}
2293 	if (scsi_pkt == NULL) {
2294 		/*
2295 		 * Abort all packets.
2296 		 * Although we do not have specific packet, we still need
2297 		 * dummy packet structure to pass device address to HBA.
2298 		 * Allocate one, without sleeping. Fail if pkt cannot be
2299 		 * allocated.
2300 		 */
2301 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2302 		if (sata_pkt == NULL) {
2303 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2304 			    sata_device.satadev_addr.cport)));
2305 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2306 			    "could not allocate sata_pkt"));
2307 			return (0);
2308 		}
2309 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2310 		sata_pkt->satapkt_device = sata_device;
2311 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2312 	} else {
2313 		if (scsi_pkt->pkt_ha_private == NULL) {
2314 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2315 			    sata_device.satadev_addr.cport)));
2316 			return (0); /* Bad scsi pkt */
2317 		}
2318 		/* extract pointer to sata pkt */
2319 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2320 		    txlt_sata_pkt;
2321 	}
2322 
2323 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2324 	    sata_device.satadev_addr.cport)));
2325 	/* Send abort request to HBA */
2326 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2327 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2328 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2329 	    SATA_SUCCESS) {
2330 		if (scsi_pkt == NULL)
2331 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2332 		/* Success */
2333 		return (1);
2334 	}
2335 	/* Else, something did not go right */
2336 	if (scsi_pkt == NULL)
2337 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
2338 	/* Failure */
2339 	return (0);
2340 }
2341 
2342 
2343 /*
2344  * Implementation of scsi tran_reset.
2345  * RESET_ALL request is translated into port reset.
2346  * RESET_TARGET requests is translated into a device reset,
2347  * RESET_LUN request is accepted only for LUN 0 and translated into
2348  * device reset.
2349  * The target reset should cause all HBA active and queued packets to
2350  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
2351  * the return. HBA should report reset event for the device.
2352  *
2353  * Returns 1 upon success, 0 upon failure.
2354  */
2355 static int
2356 sata_scsi_reset(struct scsi_address *ap, int level)
2357 {
2358 	sata_hba_inst_t	*sata_hba_inst =
2359 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2360 	sata_device_t	sata_device;
2361 	int		val;
2362 
2363 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2364 	    "sata_scsi_reset: level %d target: 0x%x\n",
2365 	    level, ap->a_target);
2366 
2367 	/* Validate address */
2368 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
2369 	if (val == -1)
2370 		/* Invalid address */
2371 		return (0);
2372 
2373 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2374 	    sata_device.satadev_addr.cport)));
2375 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2376 		/* invalid address */
2377 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2378 		    sata_device.satadev_addr.cport)));
2379 		return (0);
2380 	}
2381 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2382 	    sata_device.satadev_addr.cport)));
2383 	if (level == RESET_ALL) {
2384 		/* port reset - cport only */
2385 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2386 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2387 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2388 			return (1);
2389 		else
2390 			return (0);
2391 
2392 	} else if (val == 0 &&
2393 	    (level == RESET_TARGET || level == RESET_LUN)) {
2394 		/* reset device (device attached) */
2395 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2396 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2397 			return (1);
2398 		else
2399 			return (0);
2400 	}
2401 	return (0);
2402 }
2403 
2404 
2405 /*
2406  * Implementation of scsi tran_getcap (get transport/device capabilities).
2407  * Supported capabilities for SATA hard disks:
2408  * auto-rqsense		(always supported)
2409  * tagged-qing		(supported if HBA supports it)
2410  * untagged-qing	(could be supported if disk supports it, but because
2411  *			 caching behavior allowing untagged queuing actually
2412  *			 results in reduced performance.  sd tries to throttle
2413  *			 back to only 3 outstanding commands, which may
2414  *			 work for real SCSI disks, but with read ahead
2415  *			 caching, having more than 1 outstanding command
2416  *			 results in cache thrashing.)
2417  * sector_size
2418  * dma_max
2419  * interconnect-type	(INTERCONNECT_SATA)
2420  *
2421  * Supported capabilities for ATAPI CD/DVD devices:
2422  * auto-rqsense		(always supported)
2423  * sector_size
2424  * dma_max
2425  * max-cdb-length
2426  * interconnect-type	(INTERCONNECT_SATA)
2427  *
2428  * Supported capabilities for ATAPI TAPE devices:
2429  * auto-rqsense		(always supported)
2430  * dma_max
2431  * max-cdb-length
2432  *
2433  * Supported capabilities for SATA ATAPI hard disks:
2434  * auto-rqsense		(always supported)
2435  * interconnect-type	(INTERCONNECT_SATA)
2436  * max-cdb-length
2437  *
2438  * Request for other capabilities is rejected as unsupported.
2439  *
2440  * Returns supported capability value, or -1 if capability is unsuppported or
2441  * the address is invalid - no device.
2442  */
2443 
2444 static int
2445 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
2446 {
2447 
2448 	sata_hba_inst_t 	*sata_hba_inst =
2449 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2450 	sata_device_t		sata_device;
2451 	sata_drive_info_t	*sdinfo;
2452 	ddi_dma_attr_t		adj_dma_attr;
2453 	int 			rval;
2454 
2455 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2456 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
2457 	    ap->a_target, cap);
2458 
2459 	/*
2460 	 * We want to process the capabilities on per port granularity.
2461 	 * So, we are specifically restricting ourselves to whom != 0
2462 	 * to exclude the controller wide handling.
2463 	 */
2464 	if (cap == NULL || whom == 0)
2465 		return (-1);
2466 
2467 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2468 		/* Invalid address */
2469 		return (-1);
2470 	}
2471 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2472 	    sata_device.satadev_addr.cport)));
2473 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
2474 	    NULL) {
2475 		/* invalid address */
2476 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2477 		    sata_device.satadev_addr.cport)));
2478 		return (-1);
2479 	}
2480 
2481 	switch (scsi_hba_lookup_capstr(cap)) {
2482 	case SCSI_CAP_ARQ:
2483 		rval = 1;		/* ARQ supported, turned on */
2484 		break;
2485 
2486 	case SCSI_CAP_SECTOR_SIZE:
2487 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
2488 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
2489 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
2490 			rval = SATA_ATAPI_SECTOR_SIZE;
2491 		else rval = -1;
2492 		break;
2493 
2494 	/*
2495 	 * untagged queuing cause a performance inversion because of
2496 	 * the way sd operates.  Because of this reason we do not
2497 	 * use it when available.
2498 	 */
2499 	case SCSI_CAP_UNTAGGED_QING:
2500 		if (sdinfo->satadrv_features_enabled &
2501 		    SATA_DEV_F_E_UNTAGGED_QING)
2502 			rval = 1;	/* Untagged queuing available */
2503 		else
2504 			rval = -1;	/* Untagged queuing not available */
2505 		break;
2506 
2507 	case SCSI_CAP_TAGGED_QING:
2508 		if ((sdinfo->satadrv_features_enabled &
2509 		    SATA_DEV_F_E_TAGGED_QING) &&
2510 		    (sdinfo->satadrv_max_queue_depth > 1))
2511 			rval = 1;	/* Tagged queuing available */
2512 		else
2513 			rval = -1;	/* Tagged queuing not available */
2514 		break;
2515 
2516 	case SCSI_CAP_DMA_MAX:
2517 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
2518 		    &adj_dma_attr);
2519 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
2520 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
2521 		break;
2522 
2523 	case SCSI_CAP_INTERCONNECT_TYPE:
2524 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
2525 		break;
2526 
2527 	case SCSI_CAP_CDB_LEN:
2528 		if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI)
2529 			rval = sdinfo->satadrv_atapi_cdb_len;
2530 		else
2531 			rval = -1;
2532 		break;
2533 
2534 	default:
2535 		rval = -1;
2536 		break;
2537 	}
2538 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2539 	    sata_device.satadev_addr.cport)));
2540 	return (rval);
2541 }
2542 
2543 /*
2544  * Implementation of scsi tran_setcap
2545  *
2546  * Only SCSI_CAP_UNTAGGED_QING and  SCSI_CAP_TAGGED_QING are changeable.
2547  *
2548  */
2549 static int
2550 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
2551 {
2552 	sata_hba_inst_t	*sata_hba_inst =
2553 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2554 	sata_device_t	sata_device;
2555 	sata_drive_info_t	*sdinfo;
2556 	int		rval;
2557 
2558 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2559 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
2560 
2561 	/*
2562 	 * We want to process the capabilities on per port granularity.
2563 	 * So, we are specifically restricting ourselves to whom != 0
2564 	 * to exclude the controller wide handling.
2565 	 */
2566 	if (cap == NULL || whom == 0) {
2567 		return (-1);
2568 	}
2569 
2570 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2571 		/* Invalid address */
2572 		return (-1);
2573 	}
2574 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2575 	    sata_device.satadev_addr.cport)));
2576 	if ((sdinfo = sata_get_device_info(sata_hba_inst,
2577 	    &sata_device)) == NULL) {
2578 		/* invalid address */
2579 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2580 		    sata_device.satadev_addr.cport)));
2581 		return (-1);
2582 	}
2583 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2584 	    sata_device.satadev_addr.cport)));
2585 
2586 	switch (scsi_hba_lookup_capstr(cap)) {
2587 	case SCSI_CAP_ARQ:
2588 	case SCSI_CAP_SECTOR_SIZE:
2589 	case SCSI_CAP_DMA_MAX:
2590 	case SCSI_CAP_INTERCONNECT_TYPE:
2591 		rval = 0;
2592 		break;
2593 	case SCSI_CAP_UNTAGGED_QING:
2594 		if (SATA_QDEPTH(sata_hba_inst) > 1) {
2595 			rval = 1;
2596 			if (value == 1) {
2597 				sdinfo->satadrv_features_enabled |=
2598 				    SATA_DEV_F_E_UNTAGGED_QING;
2599 			} else if (value == 0) {
2600 				sdinfo->satadrv_features_enabled &=
2601 				    ~SATA_DEV_F_E_UNTAGGED_QING;
2602 			} else {
2603 				rval = -1;
2604 			}
2605 		} else {
2606 			rval = 0;
2607 		}
2608 		break;
2609 	case SCSI_CAP_TAGGED_QING:
2610 		/* This can TCQ or NCQ */
2611 		if (sata_func_enable & SATA_ENABLE_QUEUING &&
2612 		    ((sdinfo->satadrv_features_support & SATA_DEV_F_TCQ &&
2613 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_QCMD) ||
2614 		    (sata_func_enable & SATA_ENABLE_NCQ &&
2615 		    sdinfo->satadrv_features_support & SATA_DEV_F_NCQ &&
2616 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_NCQ)) &&
2617 		    (sdinfo->satadrv_max_queue_depth > 1)) {
2618 			rval = 1;
2619 			if (value == 1) {
2620 				sdinfo->satadrv_features_enabled |=
2621 				    SATA_DEV_F_E_TAGGED_QING;
2622 			} else if (value == 0) {
2623 				sdinfo->satadrv_features_enabled &=
2624 				    ~SATA_DEV_F_E_TAGGED_QING;
2625 			} else {
2626 				rval = -1;
2627 			}
2628 		} else {
2629 			rval = 0;
2630 		}
2631 		break;
2632 	default:
2633 		rval = -1;
2634 		break;
2635 	}
2636 	return (rval);
2637 }
2638 
2639 /*
2640  * Implementations of scsi tran_destroy_pkt.
2641  * Free resources allocated by sata_scsi_init_pkt()
2642  */
2643 static void
2644 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2645 {
2646 	sata_pkt_txlate_t *spx;
2647 
2648 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2649 
2650 	sata_common_free_dma_rsrcs(spx);
2651 
2652 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2653 	sata_pkt_free(spx);
2654 
2655 	scsi_hba_pkt_free(ap, pkt);
2656 }
2657 
2658 /*
2659  * Implementation of scsi tran_dmafree.
2660  * Free DMA resources allocated by sata_scsi_init_pkt()
2661  */
2662 
2663 static void
2664 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
2665 {
2666 #ifndef __lock_lint
2667 	_NOTE(ARGUNUSED(ap))
2668 #endif
2669 	sata_pkt_txlate_t *spx;
2670 
2671 	ASSERT(pkt != NULL);
2672 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2673 
2674 	sata_common_free_dma_rsrcs(spx);
2675 }
2676 
2677 /*
2678  * Implementation of scsi tran_sync_pkt.
2679  *
2680  * The assumption below is that pkt is unique - there is no need to check ap
2681  *
2682  * Synchronize DMA buffer and, if the intermediate buffer is used, copy data
2683  * into/from the real buffer.
2684  */
2685 static void
2686 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2687 {
2688 #ifndef __lock_lint
2689 	_NOTE(ARGUNUSED(ap))
2690 #endif
2691 	int rval;
2692 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2693 	struct buf *bp;
2694 	int direction;
2695 
2696 	ASSERT(spx != NULL);
2697 	if (spx->txlt_buf_dma_handle != NULL) {
2698 		direction = spx->txlt_sata_pkt->
2699 		    satapkt_cmd.satacmd_flags.sata_data_direction;
2700 		if (spx->txlt_sata_pkt != NULL &&
2701 		    direction != SATA_DIR_NODATA_XFER) {
2702 			if (spx->txlt_tmp_buf != NULL) {
2703 				/* Intermediate DMA buffer used */
2704 				bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2705 
2706 				if (direction & SATA_DIR_WRITE) {
2707 					bcopy(bp->b_un.b_addr,
2708 					    spx->txlt_tmp_buf, bp->b_bcount);
2709 				}
2710 			}
2711 			/* Sync the buffer for device or for CPU */
2712 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle,   0, 0,
2713 			    (direction & SATA_DIR_WRITE) ?
2714 			    DDI_DMA_SYNC_FORDEV :  DDI_DMA_SYNC_FORCPU);
2715 			ASSERT(rval == DDI_SUCCESS);
2716 			if (spx->txlt_tmp_buf != NULL &&
2717 			    !(direction & SATA_DIR_WRITE)) {
2718 				/* Intermediate DMA buffer used for read */
2719 				bcopy(spx->txlt_tmp_buf,
2720 				    bp->b_un.b_addr, bp->b_bcount);
2721 			}
2722 
2723 		}
2724 	}
2725 }
2726 
2727 
2728 
2729 /* *******************  SATA - SCSI Translation functions **************** */
2730 /*
2731  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
2732  * translation.
2733  */
2734 
2735 /*
2736  * Checks if a device exists and can be access and translates common
2737  * scsi_pkt data to sata_pkt data.
2738  *
2739  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_CMPLT if device exists and
2740  * sata_pkt was set-up.
2741  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_DEV_GONE if device does not
2742  * exist and pkt_comp callback was scheduled.
2743  * Returns other TRAN_XXXXX values when error occured and command should be
2744  * rejected with the returned TRAN_XXXXX value.
2745  *
2746  * This function should be called with port mutex held.
2747  */
2748 static int
2749 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx, int *reason)
2750 {
2751 	sata_drive_info_t *sdinfo;
2752 	sata_device_t sata_device;
2753 	const struct sata_cmd_flags sata_initial_cmd_flags = {
2754 		SATA_DIR_NODATA_XFER,
2755 		/* all other values to 0/FALSE */
2756 	};
2757 	/*
2758 	 * Pkt_reason has to be set if the pkt_comp callback is invoked,
2759 	 * and that implies TRAN_ACCEPT return value. Any other returned value
2760 	 * indicates that the scsi packet was not accepted (the reason will not
2761 	 * be checked by the scsi target driver).
2762 	 * To make debugging easier, we set pkt_reason to know value here.
2763 	 * It may be changed later when different completion reason is
2764 	 * determined.
2765 	 */
2766 	spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
2767 	*reason = CMD_TRAN_ERR;
2768 
2769 	/* Validate address */
2770 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
2771 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
2772 
2773 	case -1:
2774 		/* Invalid address or invalid device type */
2775 		return (TRAN_BADPKT);
2776 	case 1:
2777 		/* valid address but no device - it has disappeared ? */
2778 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
2779 		*reason = CMD_DEV_GONE;
2780 		/*
2781 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
2782 		 * only in callback function (for normal requests) and
2783 		 * in the dump code path.
2784 		 * So, if the callback is available, we need to do
2785 		 * the callback rather than returning TRAN_FATAL_ERROR here.
2786 		 */
2787 		if (spx->txlt_scsi_pkt->pkt_comp != NULL) {
2788 			/* scsi callback required */
2789 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2790 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2791 			    (void *)spx->txlt_scsi_pkt,
2792 			    TQ_SLEEP) == NULL)
2793 				/* Scheduling the callback failed */
2794 				return (TRAN_BUSY);
2795 
2796 			return (TRAN_ACCEPT);
2797 		}
2798 		return (TRAN_FATAL_ERROR);
2799 	default:
2800 		/* all OK; pkt reason will be overwritten later */
2801 		break;
2802 	}
2803 	/*
2804 	 * If in an interrupt context, reject packet if it is to be
2805 	 * executed in polling mode
2806 	 */
2807 	if (servicing_interrupt() &&
2808 	    (spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
2809 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
2810 		    "sata_scsi_start: rejecting synchronous command because "
2811 		    "of interrupt context\n", NULL);
2812 		return (TRAN_BUSY);
2813 	}
2814 
2815 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
2816 	    &spx->txlt_sata_pkt->satapkt_device);
2817 
2818 	/*
2819 	 * If device is in reset condition, reject the packet with
2820 	 * TRAN_BUSY, unless:
2821 	 * 1. system is panicking (dumping)
2822 	 * In such case only one thread is running and there is no way to
2823 	 * process reset.
2824 	 * 2. cfgadm operation is is progress (internal APCTL lock is set)
2825 	 * Some cfgadm operations involve drive commands, so reset condition
2826 	 * needs to be ignored for IOCTL operations.
2827 	 */
2828 	if ((sdinfo->satadrv_event_flags &
2829 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
2830 
2831 		if (!ddi_in_panic() &&
2832 		    ((SATA_CPORT_EVENT_FLAGS(spx->txlt_sata_hba_inst,
2833 		    sata_device.satadev_addr.cport) &
2834 		    SATA_APCTL_LOCK_PORT_BUSY) == 0)) {
2835 			spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
2836 			*reason = CMD_INCOMPLETE;
2837 			SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
2838 			    "sata_scsi_start: rejecting command because "
2839 			    "of device reset state\n", NULL);
2840 			return (TRAN_BUSY);
2841 		}
2842 	}
2843 
2844 	/*
2845 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
2846 	 * sata_scsi_pkt_init() because pkt init had to work also with
2847 	 * non-existing devices.
2848 	 * Now we know that the packet was set-up for a real device, so its
2849 	 * type is known.
2850 	 */
2851 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
2852 
2853 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
2854 	if ((SATA_CPORT_INFO(spx->txlt_sata_hba_inst,
2855 	    sata_device.satadev_addr.cport)->cport_event_flags &
2856 	    SATA_APCTL_LOCK_PORT_BUSY) != 0) {
2857 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
2858 		    sata_ignore_dev_reset = B_TRUE;
2859 	}
2860 	/*
2861 	 * At this point the generic translation routine determined that the
2862 	 * scsi packet should be accepted. Packet completion reason may be
2863 	 * changed later when a different completion reason is determined.
2864 	 */
2865 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
2866 	*reason = CMD_CMPLT;
2867 
2868 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
2869 		/* Synchronous execution */
2870 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
2871 		    SATA_OPMODE_POLLING;
2872 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
2873 		    sata_ignore_dev_reset = ddi_in_panic();
2874 	} else {
2875 		/* Asynchronous execution */
2876 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
2877 		    SATA_OPMODE_INTERRUPTS;
2878 	}
2879 	/* Convert queuing information */
2880 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
2881 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
2882 		    B_TRUE;
2883 	else if (spx->txlt_scsi_pkt->pkt_flags &
2884 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
2885 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
2886 		    B_TRUE;
2887 
2888 	/* Always limit pkt time */
2889 	if (spx->txlt_scsi_pkt->pkt_time == 0)
2890 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
2891 	else
2892 		/* Pass on scsi_pkt time */
2893 		spx->txlt_sata_pkt->satapkt_time =
2894 		    spx->txlt_scsi_pkt->pkt_time;
2895 
2896 	return (TRAN_ACCEPT);
2897 }
2898 
2899 
2900 /*
2901  * Translate ATA Identify Device data to SCSI Inquiry data.
2902  * This function may be called only for ATA devices.
2903  * This function should not be called for ATAPI devices - they
2904  * respond directly to SCSI Inquiry command.
2905  *
2906  * SATA Identify Device data has to be valid in sata_rive_info.
2907  * Buffer has to accomodate the inquiry length (36 bytes).
2908  *
2909  * This function should be called with a port mutex held.
2910  */
2911 static	void
2912 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
2913     sata_drive_info_t *sdinfo, uint8_t *buf)
2914 {
2915 
2916 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
2917 	struct sata_id *sid = &sdinfo->satadrv_id;
2918 
2919 	/* Start with a nice clean slate */
2920 	bzero((void *)inq, sizeof (struct scsi_inquiry));
2921 
2922 	/*
2923 	 * Rely on the dev_type for setting paripheral qualifier.
2924 	 * Assume that  DTYPE_RODIRECT applies to CD/DVD R/W devices.
2925 	 * It could be that DTYPE_OPTICAL could also qualify in the future.
2926 	 * ATAPI Inquiry may provide more data to the target driver.
2927 	 */
2928 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
2929 	    DTYPE_DIRECT : DTYPE_RODIRECT; /* DTYPE_UNKNOWN; */
2930 
2931 	inq->inq_rmb = sid->ai_config & SATA_REM_MEDIA ? 1 : 0;
2932 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
2933 	inq->inq_iso = 0;	/* ISO version */
2934 	inq->inq_ecma = 0;	/* ECMA version */
2935 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
2936 	inq->inq_aenc = 0;	/* Async event notification cap. */
2937 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg - NO */
2938 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
2939 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
2940 	inq->inq_len = 31;	/* Additional length */
2941 	inq->inq_dualp = 0;	/* dual port device - NO */
2942 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
2943 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
2944 	inq->inq_linked = 0;	/* Supports linked commands - NO */
2945 				/*
2946 				 * Queuing support - controller has to
2947 				 * support some sort of command queuing.
2948 				 */
2949 	if (SATA_QDEPTH(sata_hba_inst) > 1)
2950 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
2951 	else
2952 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
2953 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
2954 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
2955 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
2956 
2957 #ifdef	_LITTLE_ENDIAN
2958 	/* Swap text fields to match SCSI format */
2959 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
2960 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
2961 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
2962 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
2963 	else
2964 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
2965 #else	/* _LITTLE_ENDIAN */
2966 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
2967 	bcopy(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
2968 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
2969 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
2970 	else
2971 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
2972 #endif	/* _LITTLE_ENDIAN */
2973 }
2974 
2975 
2976 /*
2977  * Scsi response set up for invalid command (command not supported)
2978  *
2979  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
2980  */
2981 static int
2982 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
2983 {
2984 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
2985 	struct scsi_extended_sense *sense;
2986 
2987 	scsipkt->pkt_reason = CMD_CMPLT;
2988 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
2989 	    STATE_SENT_CMD | STATE_GOT_STATUS;
2990 
2991 	*scsipkt->pkt_scbp = STATUS_CHECK;
2992 
2993 	sense = sata_arq_sense(spx);
2994 	sense->es_key = KEY_ILLEGAL_REQUEST;
2995 	sense->es_add_code = SD_SCSI_ASC_INVALID_COMMAND_CODE;
2996 
2997 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
2998 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
2999 
3000 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3001 	    scsipkt->pkt_comp != NULL)
3002 		/* scsi callback required */
3003 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3004 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3005 		    (void *)spx->txlt_scsi_pkt,
3006 		    TQ_SLEEP) == NULL)
3007 			/* Scheduling the callback failed */
3008 			return (TRAN_BUSY);
3009 	return (TRAN_ACCEPT);
3010 }
3011 
3012 /*
3013  * Scsi response setup for
3014  * emulated non-data command that requires no action/return data
3015  *
3016  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3017  */
3018 static 	int
3019 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3020 {
3021 	int rval;
3022 	int reason;
3023 
3024 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3025 
3026 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3027 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3028 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3029 		return (rval);
3030 	}
3031 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3032 
3033 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3034 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3035 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3036 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3037 
3038 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3039 	    "Scsi_pkt completion reason %x\n",
3040 	    spx->txlt_scsi_pkt->pkt_reason);
3041 
3042 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3043 	    spx->txlt_scsi_pkt->pkt_comp != NULL)
3044 		/* scsi callback required */
3045 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3046 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3047 		    (void *)spx->txlt_scsi_pkt,
3048 		    TQ_SLEEP) == NULL)
3049 			/* Scheduling the callback failed */
3050 			return (TRAN_BUSY);
3051 	return (TRAN_ACCEPT);
3052 }
3053 
3054 
3055 /*
3056  * SATA translate command: Inquiry / Identify Device
3057  * Use cached Identify Device data for now, rather than issuing actual
3058  * Device Identify cmd request. If device is detached and re-attached,
3059  * asynchromous event processing should fetch and refresh Identify Device
3060  * data.
3061  * Two VPD pages are supported now:
3062  * Vital Product Data page
3063  * Unit Serial Number page
3064  *
3065  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3066  */
3067 
3068 #define	EVPD			1	/* Extended Vital Product Data flag */
3069 #define	CMDDT			2	/* Command Support Data - Obsolete */
3070 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VDP Pages Page COde */
3071 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3072 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3073 
3074 static int
3075 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3076 {
3077 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3078 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3079 	sata_drive_info_t *sdinfo;
3080 	struct scsi_extended_sense *sense;
3081 	int count;
3082 	uint8_t *p;
3083 	int i, j;
3084 	uint8_t page_buf[0xff]; /* Max length */
3085 	int rval, reason;
3086 
3087 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3088 
3089 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3090 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3091 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3092 		return (rval);
3093 	}
3094 
3095 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3096 	    &spx->txlt_sata_pkt->satapkt_device);
3097 
3098 	ASSERT(sdinfo != NULL);
3099 
3100 	scsipkt->pkt_reason = CMD_CMPLT;
3101 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3102 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3103 
3104 	/* Reject not supported request */
3105 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3106 		*scsipkt->pkt_scbp = STATUS_CHECK;
3107 		sense = sata_arq_sense(spx);
3108 		sense->es_key = KEY_ILLEGAL_REQUEST;
3109 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3110 		goto done;
3111 	}
3112 
3113 	/* Valid Inquiry request */
3114 	*scsipkt->pkt_scbp = STATUS_GOOD;
3115 
3116 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3117 
3118 		/*
3119 		 * Because it is fully emulated command storing data
3120 		 * programatically in the specified buffer, release
3121 		 * preallocated DMA resources before storing data in the buffer,
3122 		 * so no unwanted DMA sync would take place.
3123 		 */
3124 		sata_scsi_dmafree(NULL, scsipkt);
3125 
3126 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3127 			/* Standard Inquiry Data request */
3128 			struct scsi_inquiry inq;
3129 			unsigned int bufsize;
3130 
3131 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3132 			    sdinfo, (uint8_t *)&inq);
3133 			/* Copy no more than requested */
3134 			count = MIN(bp->b_bcount,
3135 			    sizeof (struct scsi_inquiry));
3136 			bufsize = scsipkt->pkt_cdbp[4];
3137 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3138 			count = MIN(count, bufsize);
3139 			bcopy(&inq, bp->b_un.b_addr, count);
3140 
3141 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3142 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3143 			    bufsize - count : 0;
3144 		} else {
3145 			/*
3146 			 * peripheral_qualifier = 0;
3147 			 *
3148 			 * We are dealing only with HD and will be
3149 			 * dealing with CD/DVD devices soon
3150 			 */
3151 			uint8_t peripheral_device_type =
3152 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3153 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3154 
3155 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3156 			case INQUIRY_SUP_VPD_PAGE:
3157 				/*
3158 				 * Request for suported Vital Product Data
3159 				 * pages - assuming only 2 page codes
3160 				 * supported.
3161 				 */
3162 				page_buf[0] = peripheral_device_type;
3163 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3164 				page_buf[2] = 0;
3165 				page_buf[3] = 2; /* page length */
3166 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3167 				page_buf[5] = INQUIRY_USN_PAGE;
3168 				/* Copy no more than requested */
3169 				count = MIN(bp->b_bcount, 6);
3170 				bcopy(page_buf, bp->b_un.b_addr, count);
3171 				break;
3172 
3173 			case INQUIRY_USN_PAGE:
3174 				/*
3175 				 * Request for Unit Serial Number page.
3176 				 * Set-up the page.
3177 				 */
3178 				page_buf[0] = peripheral_device_type;
3179 				page_buf[1] = INQUIRY_USN_PAGE;
3180 				page_buf[2] = 0;
3181 				/* remaining page length */
3182 				page_buf[3] = SATA_ID_SERIAL_LEN;
3183 
3184 				/*
3185 				 * Copy serial number from Identify Device data
3186 				 * words into the inquiry page and swap bytes
3187 				 * when necessary.
3188 				 */
3189 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3190 #ifdef	_LITTLE_ENDIAN
3191 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3192 #else
3193 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3194 #endif
3195 				/*
3196 				 * Least significant character of the serial
3197 				 * number shall appear as the last byte,
3198 				 * according to SBC-3 spec.
3199 				 * Count trailing spaces to determine the
3200 				 * necessary shift length.
3201 				 */
3202 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3203 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3204 					if (*(p - j) != '\0' &&
3205 					    *(p - j) != '\040')
3206 						break;
3207 				}
3208 
3209 				/*
3210 				 * Shift SN string right, so that the last
3211 				 * non-blank character would appear in last
3212 				 * byte of SN field in the page.
3213 				 * 'j' is the shift length.
3214 				 */
3215 				for (i = 0;
3216 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3217 				    i++, p--)
3218 					*p = *(p - j);
3219 
3220 				/*
3221 				 * Add leading spaces - same number as the
3222 				 * shift size
3223 				 */
3224 				for (; j > 0; j--)
3225 					page_buf[4 + j - 1] = '\040';
3226 
3227 				count = MIN(bp->b_bcount,
3228 				    SATA_ID_SERIAL_LEN + 4);
3229 				bcopy(page_buf, bp->b_un.b_addr, count);
3230 				break;
3231 
3232 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3233 				/*
3234 				 * We may want to implement this page, when
3235 				 * identifiers are common for SATA devices
3236 				 * But not now.
3237 				 */
3238 				/*FALLTHROUGH*/
3239 
3240 			default:
3241 				/* Request for unsupported VPD page */
3242 				*scsipkt->pkt_scbp = STATUS_CHECK;
3243 				sense = sata_arq_sense(spx);
3244 				sense->es_key = KEY_ILLEGAL_REQUEST;
3245 				sense->es_add_code =
3246 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3247 				goto done;
3248 			}
3249 		}
3250 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3251 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3252 		    scsipkt->pkt_cdbp[4] - count : 0;
3253 	}
3254 done:
3255 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3256 
3257 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3258 	    "Scsi_pkt completion reason %x\n",
3259 	    scsipkt->pkt_reason);
3260 
3261 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3262 	    scsipkt->pkt_comp != NULL) {
3263 		/* scsi callback required */
3264 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3265 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3266 		    TQ_SLEEP) == NULL)
3267 			/* Scheduling the callback failed */
3268 			return (TRAN_BUSY);
3269 	}
3270 	return (TRAN_ACCEPT);
3271 }
3272 
3273 /*
3274  * SATA translate command: Request Sense.
3275  * Emulated command (ATA version for SATA hard disks)
3276  * Always NO SENSE, because any sense data should be reported by ARQ sense.
3277  *
3278  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3279  *
3280  * Note: There is a mismatch between already implemented Informational
3281  * Exception Mode Select page 0x1C and this function.
3282  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3283  * NO SENSE and set additional sense code to the exception code - this is not
3284  * implemented here.
3285  */
3286 static int
3287 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3288 {
3289 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3290 	struct scsi_extended_sense sense;
3291 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3292 	int rval, reason;
3293 
3294 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3295 
3296 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3297 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3298 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3299 		return (rval);
3300 	}
3301 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3302 
3303 
3304 	scsipkt->pkt_reason = CMD_CMPLT;
3305 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3306 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3307 	*scsipkt->pkt_scbp = STATUS_GOOD;
3308 
3309 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3310 		/*
3311 		 * Because it is fully emulated command storing data
3312 		 * programatically in the specified buffer, release
3313 		 * preallocated DMA resources before storing data in the buffer,
3314 		 * so no unwanted DMA sync would take place.
3315 		 */
3316 		int count = MIN(bp->b_bcount,
3317 		    sizeof (struct scsi_extended_sense));
3318 		sata_scsi_dmafree(NULL, scsipkt);
3319 		bzero(&sense, sizeof (struct scsi_extended_sense));
3320 		sense.es_valid = 0;	/* Valid LBA */
3321 		sense.es_class = 7;	/* Response code 0x70 - current err */
3322 		sense.es_key = KEY_NO_SENSE;
3323 		sense.es_add_len = 6;	/* Additional length */
3324 		/* Copy no more than requested */
3325 		bcopy(&sense, bp->b_un.b_addr, count);
3326 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3327 		scsipkt->pkt_resid = 0;
3328 	}
3329 
3330 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3331 	    "Scsi_pkt completion reason %x\n",
3332 	    scsipkt->pkt_reason);
3333 
3334 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3335 	    scsipkt->pkt_comp != NULL)
3336 		/* scsi callback required */
3337 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3338 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3339 		    TQ_SLEEP) == NULL)
3340 			/* Scheduling the callback failed */
3341 			return (TRAN_BUSY);
3342 	return (TRAN_ACCEPT);
3343 }
3344 
3345 /*
3346  * SATA translate command: Test Unit Ready
3347  * At the moment this is an emulated command (ATA version for SATA hard disks).
3348  * May be translated into Check Power Mode command in the future
3349  *
3350  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3351  */
3352 static int
3353 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3354 {
3355 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3356 	struct scsi_extended_sense *sense;
3357 	int power_state;
3358 	int rval, reason;
3359 
3360 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3361 
3362 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3363 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3364 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3365 		return (rval);
3366 	}
3367 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3368 
3369 	/* At this moment, emulate it rather than execute anything */
3370 	power_state = SATA_PWRMODE_ACTIVE;
3371 
3372 	scsipkt->pkt_reason = CMD_CMPLT;
3373 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3374 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3375 
3376 	switch (power_state) {
3377 	case SATA_PWRMODE_ACTIVE:
3378 	case SATA_PWRMODE_IDLE:
3379 		*scsipkt->pkt_scbp = STATUS_GOOD;
3380 		break;
3381 	default:
3382 		/* PWR mode standby */
3383 		*scsipkt->pkt_scbp = STATUS_CHECK;
3384 		sense = sata_arq_sense(spx);
3385 		sense->es_key = KEY_NOT_READY;
3386 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
3387 		break;
3388 	}
3389 
3390 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3391 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3392 
3393 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3394 	    scsipkt->pkt_comp != NULL)
3395 		/* scsi callback required */
3396 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3397 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3398 		    TQ_SLEEP) == NULL)
3399 			/* Scheduling the callback failed */
3400 			return (TRAN_BUSY);
3401 
3402 	return (TRAN_ACCEPT);
3403 }
3404 
3405 
3406 /*
3407  * SATA translate command: Start Stop Unit
3408  * Translation depends on a command:
3409  *	Start Unit translated into Idle Immediate
3410  *	Stop Unit translated into Standby Immediate
3411  *	Unload Media / NOT SUPPORTED YET
3412  *	Load Media / NOT SUPPROTED YET
3413  * Power condition bits are ignored, so is Immediate bit
3414  * Requesting synchronous execution.
3415  *
3416  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
3417  * appropriate values in scsi_pkt fields.
3418  */
3419 static int
3420 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
3421 {
3422 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3423 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3424 	struct scsi_extended_sense *sense;
3425 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3426 	int cport = SATA_TXLT_CPORT(spx);
3427 	int rval, reason;
3428 	int synch;
3429 
3430 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3431 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
3432 
3433 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3434 
3435 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3436 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3437 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3438 		return (rval);
3439 	}
3440 
3441 	if (scsipkt->pkt_cdbp[4] & 2) {
3442 		/* Load/Unload Media - invalid request */
3443 		*scsipkt->pkt_scbp = STATUS_CHECK;
3444 		sense = sata_arq_sense(spx);
3445 		sense->es_key = KEY_ILLEGAL_REQUEST;
3446 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3447 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3448 
3449 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3450 		    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3451 
3452 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3453 		    scsipkt->pkt_comp != NULL)
3454 			/* scsi callback required */
3455 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3456 			    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3457 			    TQ_SLEEP) == NULL)
3458 				/* Scheduling the callback failed */
3459 				return (TRAN_BUSY);
3460 
3461 		return (TRAN_ACCEPT);
3462 	}
3463 	scmd->satacmd_addr_type = 0;
3464 	scmd->satacmd_sec_count_lsb = 0;
3465 	scmd->satacmd_lba_low_lsb = 0;
3466 	scmd->satacmd_lba_mid_lsb = 0;
3467 	scmd->satacmd_lba_high_lsb = 0;
3468 	scmd->satacmd_features_reg = 0;
3469 	scmd->satacmd_device_reg = 0;
3470 	scmd->satacmd_status_reg = 0;
3471 	if (scsipkt->pkt_cdbp[4] & 1) {
3472 		/* Start Unit */
3473 		scmd->satacmd_cmd_reg = SATAC_IDLE_IM;
3474 	} else {
3475 		/* Stop Unit */
3476 		scmd->satacmd_cmd_reg = SATAC_STANDBY_IM;
3477 	}
3478 
3479 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
3480 		/* Need to set-up a callback function */
3481 		spx->txlt_sata_pkt->satapkt_comp =
3482 		    sata_txlt_nodata_cmd_completion;
3483 		synch = FALSE;
3484 	} else {
3485 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
3486 		synch = TRUE;
3487 	}
3488 
3489 	/* Transfer command to HBA */
3490 	if (sata_hba_start(spx, &rval) != 0) {
3491 		/* Pkt not accepted for execution */
3492 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3493 		return (rval);
3494 	}
3495 
3496 	/*
3497 	 * If execution is non-synchronous,
3498 	 * a callback function will handle potential errors, translate
3499 	 * the response and will do a callback to a target driver.
3500 	 * If it was synchronous, check execution status using the same
3501 	 * framework callback.
3502 	 */
3503 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3504 	if (synch) {
3505 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3506 		    "synchronous execution status %x\n",
3507 		    spx->txlt_sata_pkt->satapkt_reason);
3508 
3509 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
3510 	}
3511 	return (TRAN_ACCEPT);
3512 
3513 }
3514 
3515 
3516 /*
3517  * SATA translate command:  Read Capacity.
3518  * Emulated command for SATA disks.
3519  * Capacity is retrieved from cached Idenifty Device data.
3520  * Identify Device data shows effective disk capacity, not the native
3521  * capacity, which may be limitted by Set Max Address command.
3522  * This is ATA version for SATA hard disks.
3523  *
3524  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3525  */
3526 static int
3527 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
3528 {
3529 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3530 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3531 	sata_drive_info_t *sdinfo;
3532 	uint64_t val;
3533 	uchar_t *rbuf;
3534 	int rval, reason;
3535 
3536 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3537 	    "sata_txlt_read_capacity: ", NULL);
3538 
3539 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3540 
3541 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3542 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3543 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3544 		return (rval);
3545 	}
3546 
3547 	scsipkt->pkt_reason = CMD_CMPLT;
3548 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3549 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3550 	*scsipkt->pkt_scbp = STATUS_GOOD;
3551 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3552 		/*
3553 		 * Because it is fully emulated command storing data
3554 		 * programatically in the specified buffer, release
3555 		 * preallocated DMA resources before storing data in the buffer,
3556 		 * so no unwanted DMA sync would take place.
3557 		 */
3558 		sata_scsi_dmafree(NULL, scsipkt);
3559 
3560 		sdinfo = sata_get_device_info(
3561 		    spx->txlt_sata_hba_inst,
3562 		    &spx->txlt_sata_pkt->satapkt_device);
3563 		/* Last logical block address */
3564 		val = sdinfo->satadrv_capacity - 1;
3565 		rbuf = (uchar_t *)bp->b_un.b_addr;
3566 		/* Need to swap endians to match scsi format */
3567 		rbuf[0] = (val >> 24) & 0xff;
3568 		rbuf[1] = (val >> 16) & 0xff;
3569 		rbuf[2] = (val >> 8) & 0xff;
3570 		rbuf[3] = val & 0xff;
3571 		/* block size - always 512 bytes, for now */
3572 		rbuf[4] = 0;
3573 		rbuf[5] = 0;
3574 		rbuf[6] = 0x02;
3575 		rbuf[7] = 0;
3576 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3577 		scsipkt->pkt_resid = 0;
3578 
3579 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
3580 		    sdinfo->satadrv_capacity -1);
3581 	}
3582 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3583 	/*
3584 	 * If a callback was requested, do it now.
3585 	 */
3586 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3587 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3588 
3589 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3590 	    scsipkt->pkt_comp != NULL)
3591 		/* scsi callback required */
3592 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3593 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3594 		    TQ_SLEEP) == NULL)
3595 			/* Scheduling the callback failed */
3596 			return (TRAN_BUSY);
3597 
3598 	return (TRAN_ACCEPT);
3599 }
3600 
3601 /*
3602  * SATA translate command: Mode Sense.
3603  * Translated into appropriate SATA command or emulated.
3604  * Saved Values Page Control (03) are not supported.
3605  *
3606  * NOTE: only caching mode sense page is currently implemented.
3607  *
3608  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3609  */
3610 
3611 static int
3612 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
3613 {
3614 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
3615 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3616 	sata_drive_info_t *sdinfo;
3617 	sata_id_t *sata_id;
3618 	struct scsi_extended_sense *sense;
3619 	int 		len, bdlen, count, alc_len;
3620 	int		pc;	/* Page Control code */
3621 	uint8_t		*buf;	/* mode sense buffer */
3622 	int		rval, reason;
3623 
3624 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3625 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
3626 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
3627 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
3628 
3629 	buf = kmem_zalloc(1024, KM_SLEEP);
3630 
3631 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3632 
3633 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3634 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3635 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3636 		kmem_free(buf, 1024);
3637 		return (rval);
3638 	}
3639 
3640 	scsipkt->pkt_reason = CMD_CMPLT;
3641 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3642 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3643 
3644 	pc = scsipkt->pkt_cdbp[2] >> 6;
3645 
3646 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3647 		/*
3648 		 * Because it is fully emulated command storing data
3649 		 * programatically in the specified buffer, release
3650 		 * preallocated DMA resources before storing data in the buffer,
3651 		 * so no unwanted DMA sync would take place.
3652 		 */
3653 		sata_scsi_dmafree(NULL, scsipkt);
3654 
3655 		len = 0;
3656 		bdlen = 0;
3657 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
3658 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
3659 			    (scsipkt->pkt_cdbp[0] & 0x10))
3660 				bdlen = 16;
3661 			else
3662 				bdlen = 8;
3663 		}
3664 		/* Build mode parameter header */
3665 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
3666 			/* 4-byte mode parameter header */
3667 			buf[len++] = 0;   	/* mode data length */
3668 			buf[len++] = 0;		/* medium type */
3669 			buf[len++] = 0;		/* dev-specific param */
3670 			buf[len++] = bdlen;	/* Block Descriptor length */
3671 		} else {
3672 			/* 8-byte mode parameter header */
3673 			buf[len++] = 0;		/* mode data length */
3674 			buf[len++] = 0;
3675 			buf[len++] = 0;		/* medium type */
3676 			buf[len++] = 0;		/* dev-specific param */
3677 			if (bdlen == 16)
3678 				buf[len++] = 1;	/* long lba descriptor */
3679 			else
3680 				buf[len++] = 0;
3681 			buf[len++] = 0;
3682 			buf[len++] = 0;		/* Block Descriptor length */
3683 			buf[len++] = bdlen;
3684 		}
3685 
3686 		sdinfo = sata_get_device_info(
3687 		    spx->txlt_sata_hba_inst,
3688 		    &spx->txlt_sata_pkt->satapkt_device);
3689 
3690 		/* Build block descriptor only if not disabled (DBD) */
3691 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
3692 			/* Block descriptor - direct-access device format */
3693 			if (bdlen == 8) {
3694 				/* build regular block descriptor */
3695 				buf[len++] =
3696 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
3697 				buf[len++] =
3698 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
3699 				buf[len++] =
3700 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
3701 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
3702 				buf[len++] = 0; /* density code */
3703 				buf[len++] = 0;
3704 				if (sdinfo->satadrv_type ==
3705 				    SATA_DTYPE_ATADISK)
3706 					buf[len++] = 2;
3707 				else
3708 					/* ATAPI */
3709 					buf[len++] = 8;
3710 				buf[len++] = 0;
3711 			} else if (bdlen == 16) {
3712 				/* Long LBA Accepted */
3713 				/* build long lba block descriptor */
3714 #ifndef __lock_lint
3715 				buf[len++] =
3716 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
3717 				buf[len++] =
3718 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
3719 				buf[len++] =
3720 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
3721 				buf[len++] =
3722 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
3723 #endif
3724 				buf[len++] =
3725 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
3726 				buf[len++] =
3727 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
3728 				buf[len++] =
3729 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
3730 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
3731 				buf[len++] = 0;
3732 				buf[len++] = 0; /* density code */
3733 				buf[len++] = 0;
3734 				buf[len++] = 0;
3735 				if (sdinfo->satadrv_type ==
3736 				    SATA_DTYPE_ATADISK)
3737 					buf[len++] = 2;
3738 				else
3739 					/* ATAPI */
3740 					buf[len++] = 8;
3741 				buf[len++] = 0;
3742 			}
3743 		}
3744 
3745 		sata_id = &sdinfo->satadrv_id;
3746 
3747 		/*
3748 		 * Add requested pages.
3749 		 * Page 3 and 4 are obsolete and we are not supporting them.
3750 		 * We deal now with:
3751 		 * caching (read/write cache control).
3752 		 * We should eventually deal with following mode pages:
3753 		 * error recovery  (0x01),
3754 		 * power condition (0x1a),
3755 		 * exception control page (enables SMART) (0x1c),
3756 		 * enclosure management (ses),
3757 		 * protocol-specific port mode (port control).
3758 		 */
3759 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
3760 		case MODEPAGE_RW_ERRRECOV:
3761 			/* DAD_MODE_ERR_RECOV */
3762 			/* R/W recovery */
3763 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
3764 			break;
3765 		case MODEPAGE_CACHING:
3766 			/* DAD_MODE_CACHE */
3767 			/* Reject not supported request for saved parameters */
3768 			if (pc == 3) {
3769 				*scsipkt->pkt_scbp = STATUS_CHECK;
3770 				sense = sata_arq_sense(spx);
3771 				sense->es_key = KEY_ILLEGAL_REQUEST;
3772 				sense->es_add_code =
3773 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
3774 				goto done;
3775 			}
3776 
3777 			/* caching */
3778 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
3779 			break;
3780 		case MODEPAGE_INFO_EXCPT:
3781 			/* exception cntrl */
3782 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
3783 				len += sata_build_msense_page_1c(sdinfo, pc,
3784 				    buf+len);
3785 			}
3786 			else
3787 				goto err;
3788 			break;
3789 		case MODEPAGE_POWER_COND:
3790 			/* DAD_MODE_POWER_COND */
3791 			/* power condition */
3792 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
3793 			break;
3794 
3795 		case MODEPAGE_ACOUSTIC_MANAG:
3796 			/* acoustic management */
3797 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
3798 			break;
3799 		case MODEPAGE_ALLPAGES:
3800 			/* all pages */
3801 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
3802 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
3803 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
3804 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
3805 				len += sata_build_msense_page_1c(sdinfo, pc,
3806 				    buf+len);
3807 			}
3808 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
3809 			break;
3810 		default:
3811 		err:
3812 			/* Invalid request */
3813 			*scsipkt->pkt_scbp = STATUS_CHECK;
3814 			sense = sata_arq_sense(spx);
3815 			sense->es_key = KEY_ILLEGAL_REQUEST;
3816 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3817 			goto done;
3818 		}
3819 
3820 		/* fix total mode data length */
3821 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
3822 			/* 4-byte mode parameter header */
3823 			buf[0] = len - 1;   	/* mode data length */
3824 		} else {
3825 			buf[0] = (len -2) >> 8;
3826 			buf[1] = (len -2) & 0xff;
3827 		}
3828 
3829 
3830 		/* Check allocation length */
3831 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
3832 			alc_len = scsipkt->pkt_cdbp[4];
3833 		} else {
3834 			alc_len = scsipkt->pkt_cdbp[7];
3835 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
3836 		}
3837 		/*
3838 		 * We do not check for possible parameters truncation
3839 		 * (alc_len < len) assuming that the target driver works
3840 		 * correctly. Just avoiding overrun.
3841 		 * Copy no more than requested and possible, buffer-wise.
3842 		 */
3843 		count = MIN(alc_len, len);
3844 		count = MIN(bp->b_bcount, count);
3845 		bcopy(buf, bp->b_un.b_addr, count);
3846 
3847 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3848 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
3849 	}
3850 	*scsipkt->pkt_scbp = STATUS_GOOD;
3851 done:
3852 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3853 	(void) kmem_free(buf, 1024);
3854 
3855 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3856 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3857 
3858 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3859 	    scsipkt->pkt_comp != NULL)
3860 		/* scsi callback required */
3861 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3862 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3863 		    TQ_SLEEP) == NULL)
3864 			/* Scheduling the callback failed */
3865 			return (TRAN_BUSY);
3866 
3867 	return (TRAN_ACCEPT);
3868 }
3869 
3870 
3871 /*
3872  * SATA translate command: Mode Select.
3873  * Translated into appropriate SATA command or emulated.
3874  * Saving parameters is not supported.
3875  * Changing device capacity is not supported (although theoretically
3876  * possible by executing SET FEATURES/SET MAX ADDRESS)
3877  *
3878  * Assumption is that the target driver is working correctly.
3879  *
3880  * More than one SATA command may be executed to perform operations specified
3881  * by mode select pages. The first error terminates further execution.
3882  * Operations performed successully are not backed-up in such case.
3883  *
3884  * NOTE: Implemented pages:
3885  * - caching page
3886  * - informational exception page
3887  * - acoustic management page
3888  * Caching setup is remembered so it could be re-stored in case of
3889  * an unexpected device reset.
3890  *
3891  * Returns TRAN_XXXX.
3892  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
3893  */
3894 
3895 static int
3896 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
3897 {
3898 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3899 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3900 	struct scsi_extended_sense *sense;
3901 	int len, pagelen, count, pllen;
3902 	uint8_t *buf;	/* mode select buffer */
3903 	int rval, stat, reason;
3904 	uint_t nointr_flag;
3905 	int dmod = 0;
3906 
3907 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3908 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
3909 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
3910 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
3911 
3912 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3913 
3914 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
3915 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3916 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3917 		return (rval);
3918 	}
3919 	/*
3920 	 * If in interrupt context, reject this packet because it may result
3921 	 * in issuing a synchronous command to HBA.
3922 	 */
3923 	if (servicing_interrupt()) {
3924 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
3925 		    "sata_txlt_mode_select: rejecting command because "
3926 		    "of interrupt context\n", NULL);
3927 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3928 		return (TRAN_BUSY);
3929 	}
3930 
3931 	rval = TRAN_ACCEPT;
3932 
3933 	scsipkt->pkt_reason = CMD_CMPLT;
3934 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3935 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3936 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
3937 
3938 	/* Reject not supported request */
3939 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
3940 		*scsipkt->pkt_scbp = STATUS_CHECK;
3941 		sense = sata_arq_sense(spx);
3942 		sense->es_key = KEY_ILLEGAL_REQUEST;
3943 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3944 		goto done;
3945 	}
3946 
3947 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
3948 		pllen = scsipkt->pkt_cdbp[4];
3949 	} else {
3950 		pllen = scsipkt->pkt_cdbp[7];
3951 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
3952 	}
3953 
3954 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
3955 
3956 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
3957 		buf = (uint8_t *)bp->b_un.b_addr;
3958 		count = MIN(bp->b_bcount, pllen);
3959 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3960 		scsipkt->pkt_resid = 0;
3961 		pllen = count;
3962 
3963 		/*
3964 		 * Check the header to skip the block descriptor(s) - we
3965 		 * do not support setting device capacity.
3966 		 * Existing macros do not recognize long LBA dscriptor,
3967 		 * hence manual calculation.
3968 		 */
3969 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
3970 			/* 6-bytes CMD, 4 bytes header */
3971 			if (count <= 4)
3972 				goto done;		/* header only */
3973 			len = buf[3] + 4;
3974 		} else {
3975 			/* 10-bytes CMD, 8 bytes header */
3976 			if (count <= 8)
3977 				goto done;		/* header only */
3978 			len = buf[6];
3979 			len = (len << 8) + buf[7] + 8;
3980 		}
3981 		if (len >= count)
3982 			goto done;	/* header + descriptor(s) only */
3983 
3984 		pllen -= len;		/* remaining data length */
3985 
3986 		/*
3987 		 * We may be executing SATA command and want to execute it
3988 		 * in SYNCH mode, regardless of scsi_pkt setting.
3989 		 * Save scsi_pkt setting and indicate SYNCH mode
3990 		 */
3991 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3992 		    scsipkt->pkt_comp != NULL) {
3993 			scsipkt->pkt_flags |= FLAG_NOINTR;
3994 		}
3995 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
3996 
3997 		/*
3998 		 * len is now the offset to a first mode select page
3999 		 * Process all pages
4000 		 */
4001 		while (pllen > 0) {
4002 			switch ((int)buf[len]) {
4003 			case MODEPAGE_CACHING:
4004 				/* No support for SP (saving) */
4005 				if (scsipkt->pkt_cdbp[1] & 0x01) {
4006 					*scsipkt->pkt_scbp = STATUS_CHECK;
4007 					sense = sata_arq_sense(spx);
4008 					sense->es_key = KEY_ILLEGAL_REQUEST;
4009 					sense->es_add_code =
4010 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4011 					goto done;
4012 				}
4013 				stat = sata_mode_select_page_8(spx,
4014 				    (struct mode_cache_scsi3 *)&buf[len],
4015 				    pllen, &pagelen, &rval, &dmod);
4016 				/*
4017 				 * The pagelen value indicates the number of
4018 				 * parameter bytes already processed.
4019 				 * The rval is the return value from
4020 				 * sata_tran_start().
4021 				 * The stat indicates the overall status of
4022 				 * the operation(s).
4023 				 */
4024 				if (stat != SATA_SUCCESS)
4025 					/*
4026 					 * Page processing did not succeed -
4027 					 * all error info is already set-up,
4028 					 * just return
4029 					 */
4030 					pllen = 0; /* this breaks the loop */
4031 				else {
4032 					len += pagelen;
4033 					pllen -= pagelen;
4034 				}
4035 				break;
4036 
4037 			case MODEPAGE_INFO_EXCPT:
4038 				stat = sata_mode_select_page_1c(spx,
4039 				    (struct mode_info_excpt_page *)&buf[len],
4040 				    pllen, &pagelen, &rval, &dmod);
4041 				/*
4042 				 * The pagelen value indicates the number of
4043 				 * parameter bytes already processed.
4044 				 * The rval is the return value from
4045 				 * sata_tran_start().
4046 				 * The stat indicates the overall status of
4047 				 * the operation(s).
4048 				 */
4049 				if (stat != SATA_SUCCESS)
4050 					/*
4051 					 * Page processing did not succeed -
4052 					 * all error info is already set-up,
4053 					 * just return
4054 					 */
4055 					pllen = 0; /* this breaks the loop */
4056 				else {
4057 					len += pagelen;
4058 					pllen -= pagelen;
4059 				}
4060 				break;
4061 
4062 			case MODEPAGE_ACOUSTIC_MANAG:
4063 				stat = sata_mode_select_page_30(spx,
4064 				    (struct mode_acoustic_management *)
4065 				    &buf[len], pllen, &pagelen, &rval, &dmod);
4066 				/*
4067 				 * The pagelen value indicates the number of
4068 				 * parameter bytes already processed.
4069 				 * The rval is the return value from
4070 				 * sata_tran_start().
4071 				 * The stat indicates the overall status of
4072 				 * the operation(s).
4073 				 */
4074 				if (stat != SATA_SUCCESS)
4075 					/*
4076 					 * Page processing did not succeed -
4077 					 * all error info is already set-up,
4078 					 * just return
4079 					 */
4080 					pllen = 0; /* this breaks the loop */
4081 				else {
4082 					len += pagelen;
4083 					pllen -= pagelen;
4084 				}
4085 
4086 				break;
4087 			default:
4088 				*scsipkt->pkt_scbp = STATUS_CHECK;
4089 				sense = sata_arq_sense(spx);
4090 				sense->es_key = KEY_ILLEGAL_REQUEST;
4091 				sense->es_add_code =
4092 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
4093 				goto done;
4094 			}
4095 		}
4096 	}
4097 done:
4098 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4099 	/*
4100 	 * If device parameters were modified, fetch and store the new
4101 	 * Identify Device data. Since port mutex could have been released
4102 	 * for accessing HBA driver, we need to re-check device existence.
4103 	 */
4104 	if (dmod != 0) {
4105 		sata_drive_info_t new_sdinfo, *sdinfo;
4106 		int rv = 0;
4107 
4108 		/*
4109 		 * Following statement has to be changed if this function is
4110 		 * used for devices other than SATA hard disks.
4111 		 */
4112 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
4113 
4114 		new_sdinfo.satadrv_addr =
4115 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
4116 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
4117 		    &new_sdinfo);
4118 
4119 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4120 		/*
4121 		 * Since port mutex could have been released when
4122 		 * accessing HBA driver, we need to re-check that the
4123 		 * framework still holds the device info structure.
4124 		 */
4125 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4126 		    &spx->txlt_sata_pkt->satapkt_device);
4127 		if (sdinfo != NULL) {
4128 			/*
4129 			 * Device still has info structure in the
4130 			 * sata framework. Copy newly fetched info
4131 			 */
4132 			if (rv == 0) {
4133 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
4134 				sata_save_drive_settings(sdinfo);
4135 			} else {
4136 				/*
4137 				 * Could not fetch new data - invalidate
4138 				 * sata_drive_info. That makes device
4139 				 * unusable.
4140 				 */
4141 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
4142 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
4143 			}
4144 		}
4145 		if (rv != 0 || sdinfo == NULL) {
4146 			/*
4147 			 * This changes the overall mode select completion
4148 			 * reason to a failed one !!!!!
4149 			 */
4150 			*scsipkt->pkt_scbp = STATUS_CHECK;
4151 			sense = sata_arq_sense(spx);
4152 			scsipkt->pkt_reason = CMD_INCOMPLETE;
4153 			rval = TRAN_ACCEPT;
4154 		}
4155 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4156 	}
4157 	/* Restore the scsi pkt flags */
4158 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
4159 	scsipkt->pkt_flags |= nointr_flag;
4160 
4161 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4162 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4163 
4164 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4165 	    scsipkt->pkt_comp != NULL)
4166 		/* scsi callback required */
4167 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4168 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4169 		    TQ_SLEEP) == NULL)
4170 			/* Scheduling the callback failed */
4171 			return (TRAN_BUSY);
4172 
4173 	return (rval);
4174 }
4175 
4176 
4177 
4178 /*
4179  * Translate command: Log Sense
4180  */
4181 static 	int
4182 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
4183 {
4184 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4185 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4186 	sata_drive_info_t *sdinfo;
4187 	struct scsi_extended_sense *sense;
4188 	int 		len, count, alc_len;
4189 	int		pc;	/* Page Control code */
4190 	int		page_code;	/* Page code */
4191 	uint8_t		*buf;	/* log sense buffer */
4192 	int		rval, reason;
4193 #define	MAX_LOG_SENSE_PAGE_SIZE	512
4194 
4195 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4196 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
4197 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4198 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4199 
4200 	buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
4201 
4202 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4203 
4204 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4205 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4206 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4207 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4208 		return (rval);
4209 	}
4210 	/*
4211 	 * If in interrupt context, reject this packet because it may result
4212 	 * in issuing a synchronous command to HBA.
4213 	 */
4214 	if (servicing_interrupt()) {
4215 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
4216 		    "sata_log_sense: rejecting command because "
4217 		    "of interrupt context\n", NULL);
4218 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4219 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4220 		return (TRAN_BUSY);
4221 	}
4222 
4223 	scsipkt->pkt_reason = CMD_CMPLT;
4224 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4225 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4226 
4227 	pc = scsipkt->pkt_cdbp[2] >> 6;
4228 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
4229 
4230 	/* Reject not supported request for all but cumulative values */
4231 	switch (pc) {
4232 	case PC_CUMULATIVE_VALUES:
4233 		break;
4234 	default:
4235 		*scsipkt->pkt_scbp = STATUS_CHECK;
4236 		sense = sata_arq_sense(spx);
4237 		sense->es_key = KEY_ILLEGAL_REQUEST;
4238 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4239 		goto done;
4240 	}
4241 
4242 	switch (page_code) {
4243 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
4244 	case PAGE_CODE_SELF_TEST_RESULTS:
4245 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
4246 	case PAGE_CODE_SMART_READ_DATA:
4247 		break;
4248 	default:
4249 		*scsipkt->pkt_scbp = STATUS_CHECK;
4250 		sense = sata_arq_sense(spx);
4251 		sense->es_key = KEY_ILLEGAL_REQUEST;
4252 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4253 		goto done;
4254 	}
4255 
4256 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4257 		/*
4258 		 * Because log sense uses local buffers for data retrieval from
4259 		 * the devices and sets the data programatically in the
4260 		 * original specified buffer, release preallocated DMA
4261 		 * resources before storing data in the original buffer,
4262 		 * so no unwanted DMA sync would take place.
4263 		 */
4264 		sata_id_t *sata_id;
4265 
4266 		sata_scsi_dmafree(NULL, scsipkt);
4267 
4268 		len = 0;
4269 
4270 		/* Build log parameter header */
4271 		buf[len++] = page_code;	/* page code as in the CDB */
4272 		buf[len++] = 0;		/* reserved */
4273 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
4274 		buf[len++] = 0;		/* (LSB) */
4275 
4276 		sdinfo = sata_get_device_info(
4277 		    spx->txlt_sata_hba_inst,
4278 		    &spx->txlt_sata_pkt->satapkt_device);
4279 
4280 		/*
4281 		 * Add requested pages.
4282 		 */
4283 		switch (page_code) {
4284 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
4285 			len = sata_build_lsense_page_0(sdinfo, buf + len);
4286 			break;
4287 		case PAGE_CODE_SELF_TEST_RESULTS:
4288 			sata_id = &sdinfo->satadrv_id;
4289 			if ((! (sata_id->ai_cmdset84 &
4290 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
4291 			    (! (sata_id->ai_features87 &
4292 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
4293 				*scsipkt->pkt_scbp = STATUS_CHECK;
4294 				sense = sata_arq_sense(spx);
4295 				sense->es_key = KEY_ILLEGAL_REQUEST;
4296 				sense->es_add_code =
4297 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4298 
4299 				goto done;
4300 			}
4301 			len = sata_build_lsense_page_10(sdinfo, buf + len,
4302 			    spx->txlt_sata_hba_inst);
4303 			break;
4304 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
4305 			sata_id = &sdinfo->satadrv_id;
4306 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
4307 				*scsipkt->pkt_scbp = STATUS_CHECK;
4308 				sense = sata_arq_sense(spx);
4309 				sense->es_key = KEY_ILLEGAL_REQUEST;
4310 				sense->es_add_code =
4311 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4312 
4313 				goto done;
4314 			}
4315 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
4316 				*scsipkt->pkt_scbp = STATUS_CHECK;
4317 				sense = sata_arq_sense(spx);
4318 				sense->es_key = KEY_ABORTED_COMMAND;
4319 				sense->es_add_code =
4320 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
4321 				sense->es_qual_code =
4322 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
4323 
4324 				goto done;
4325 			}
4326 
4327 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
4328 			    spx->txlt_sata_hba_inst);
4329 			break;
4330 		case PAGE_CODE_SMART_READ_DATA:
4331 			sata_id = &sdinfo->satadrv_id;
4332 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
4333 				*scsipkt->pkt_scbp = STATUS_CHECK;
4334 				sense = sata_arq_sense(spx);
4335 				sense->es_key = KEY_ILLEGAL_REQUEST;
4336 				sense->es_add_code =
4337 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4338 
4339 				goto done;
4340 			}
4341 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
4342 				*scsipkt->pkt_scbp = STATUS_CHECK;
4343 				sense = sata_arq_sense(spx);
4344 				sense->es_key = KEY_ABORTED_COMMAND;
4345 				sense->es_add_code =
4346 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
4347 				sense->es_qual_code =
4348 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
4349 
4350 				goto done;
4351 			}
4352 
4353 			/* This page doesn't include a page header */
4354 			len = sata_build_lsense_page_30(sdinfo, buf,
4355 			    spx->txlt_sata_hba_inst);
4356 			goto no_header;
4357 		default:
4358 			/* Invalid request */
4359 			*scsipkt->pkt_scbp = STATUS_CHECK;
4360 			sense = sata_arq_sense(spx);
4361 			sense->es_key = KEY_ILLEGAL_REQUEST;
4362 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4363 			goto done;
4364 		}
4365 
4366 		/* set parameter log sense data length */
4367 		buf[2] = len >> 8;	/* log sense length (MSB) */
4368 		buf[3] = len & 0xff;	/* log sense length (LSB) */
4369 
4370 		len += SCSI_LOG_PAGE_HDR_LEN;
4371 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
4372 
4373 no_header:
4374 		/* Check allocation length */
4375 		alc_len = scsipkt->pkt_cdbp[7];
4376 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4377 
4378 		/*
4379 		 * We do not check for possible parameters truncation
4380 		 * (alc_len < len) assuming that the target driver works
4381 		 * correctly. Just avoiding overrun.
4382 		 * Copy no more than requested and possible, buffer-wise.
4383 		 */
4384 		count = MIN(alc_len, len);
4385 		count = MIN(bp->b_bcount, count);
4386 		bcopy(buf, bp->b_un.b_addr, count);
4387 
4388 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4389 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4390 	}
4391 	*scsipkt->pkt_scbp = STATUS_GOOD;
4392 done:
4393 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4394 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
4395 
4396 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4397 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4398 
4399 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4400 	    scsipkt->pkt_comp != NULL)
4401 		/* scsi callback required */
4402 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4403 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4404 		    TQ_SLEEP) == NULL)
4405 			/* Scheduling the callback failed */
4406 			return (TRAN_BUSY);
4407 
4408 	return (TRAN_ACCEPT);
4409 }
4410 
4411 /*
4412  * Translate command: Log Select
4413  * Not implemented at this time - returns invalid command response.
4414  */
4415 static 	int
4416 sata_txlt_log_select(sata_pkt_txlate_t *spx)
4417 {
4418 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4419 	    "sata_txlt_log_select\n", NULL);
4420 
4421 	return (sata_txlt_invalid_command(spx));
4422 }
4423 
4424 
4425 /*
4426  * Translate command: Read (various types).
4427  * Translated into appropriate type of ATA READ command
4428  * for SATA hard disks.
4429  * Both the device capabilities and requested operation mode are
4430  * considered.
4431  *
4432  * Following scsi cdb fields are ignored:
4433  * rdprotect, dpo, fua, fua_nv, group_number.
4434  *
4435  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
4436  * enable variable sata_func_enable), the capability of the controller and
4437  * capability of a device are checked and if both support queueing, read
4438  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
4439  * command rather than plain READ_XXX command.
4440  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
4441  * both the controller and device suport such functionality, the read
4442  * request will be translated to READ_FPDMA_QUEUED command.
4443  * In both cases the maximum queue depth is derived as minimum of:
4444  * HBA capability,device capability and sata_max_queue_depth variable setting.
4445  * The value passed to HBA driver is decremented by 1, because only 5 bits are
4446  * used to pass max queue depth value, and the maximum possible queue depth
4447  * is 32.
4448  *
4449  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4450  * appropriate values in scsi_pkt fields.
4451  */
4452 static int
4453 sata_txlt_read(sata_pkt_txlate_t *spx)
4454 {
4455 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4456 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4457 	sata_drive_info_t *sdinfo;
4458 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
4459 	int cport = SATA_TXLT_CPORT(spx);
4460 	uint16_t sec_count;
4461 	uint64_t lba;
4462 	int rval, reason;
4463 	int synch;
4464 
4465 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4466 
4467 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4468 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4469 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4470 		return (rval);
4471 	}
4472 
4473 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4474 	    &spx->txlt_sata_pkt->satapkt_device);
4475 
4476 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
4477 	/*
4478 	 * Extract LBA and sector count from scsi CDB.
4479 	 */
4480 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
4481 	case SCMD_READ:
4482 		/* 6-byte scsi read cmd : 0x08 */
4483 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
4484 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
4485 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4486 		sec_count = scsipkt->pkt_cdbp[4];
4487 		/* sec_count 0 will be interpreted as 256 by a device */
4488 		break;
4489 	case SCMD_READ_G1:
4490 		/* 10-bytes scsi read command : 0x28 */
4491 		lba = scsipkt->pkt_cdbp[2];
4492 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4493 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4494 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4495 		sec_count = scsipkt->pkt_cdbp[7];
4496 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4497 		break;
4498 	case SCMD_READ_G5:
4499 		/* 12-bytes scsi read command : 0xA8 */
4500 		lba = scsipkt->pkt_cdbp[2];
4501 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4502 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4503 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4504 		sec_count = scsipkt->pkt_cdbp[6];
4505 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
4506 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4507 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
4508 		break;
4509 	case SCMD_READ_G4:
4510 		/* 16-bytes scsi read command : 0x88 */
4511 		lba = scsipkt->pkt_cdbp[2];
4512 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4513 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4514 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4515 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
4516 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
4517 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
4518 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
4519 		sec_count = scsipkt->pkt_cdbp[10];
4520 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
4521 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
4522 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
4523 		break;
4524 	default:
4525 		/* Unsupported command */
4526 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4527 		return (sata_txlt_invalid_command(spx));
4528 	}
4529 
4530 	/*
4531 	 * Check if specified address exceeds device capacity
4532 	 */
4533 	if ((lba >= sdinfo->satadrv_capacity) ||
4534 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
4535 		/* LBA out of range */
4536 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4537 		return (sata_txlt_lba_out_of_range(spx));
4538 	}
4539 
4540 	/*
4541 	 * For zero-length transfer, emulate good completion of the command
4542 	 * (reasons for rejecting the command were already checked).
4543 	 * No DMA resources were allocated.
4544 	 */
4545 	if (spx->txlt_dma_cookie_list == NULL) {
4546 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4547 		return (sata_emul_rw_completion(spx));
4548 	}
4549 
4550 	/*
4551 	 * Build cmd block depending on the device capability and
4552 	 * requested operation mode.
4553 	 * Do not bother with non-dma mode - we are working only with
4554 	 * devices supporting DMA.
4555 	 */
4556 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
4557 	scmd->satacmd_device_reg = SATA_ADH_LBA;
4558 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
4559 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
4560 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
4561 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
4562 		scmd->satacmd_sec_count_msb = sec_count >> 8;
4563 #ifndef __lock_lint
4564 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
4565 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
4566 		scmd->satacmd_lba_high_msb = lba >> 40;
4567 #endif
4568 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
4569 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
4570 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
4571 	}
4572 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
4573 	scmd->satacmd_lba_low_lsb = lba & 0xff;
4574 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
4575 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
4576 	scmd->satacmd_features_reg = 0;
4577 	scmd->satacmd_status_reg = 0;
4578 	scmd->satacmd_error_reg = 0;
4579 
4580 	/*
4581 	 * Check if queueing commands should be used and switch
4582 	 * to appropriate command if possible
4583 	 */
4584 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
4585 		boolean_t using_queuing;
4586 
4587 		/* Queuing supported by controller and device? */
4588 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
4589 		    (sdinfo->satadrv_features_support &
4590 		    SATA_DEV_F_NCQ) &&
4591 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4592 		    SATA_CTLF_NCQ)) {
4593 			using_queuing = B_TRUE;
4594 
4595 			/* NCQ supported - use FPDMA READ */
4596 			scmd->satacmd_cmd_reg =
4597 			    SATAC_READ_FPDMA_QUEUED;
4598 			scmd->satacmd_features_reg_ext =
4599 			    scmd->satacmd_sec_count_msb;
4600 			scmd->satacmd_sec_count_msb = 0;
4601 		} else if ((sdinfo->satadrv_features_support &
4602 		    SATA_DEV_F_TCQ) &&
4603 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4604 		    SATA_CTLF_QCMD)) {
4605 			using_queuing = B_TRUE;
4606 
4607 			/* Legacy queueing */
4608 			if (sdinfo->satadrv_features_support &
4609 			    SATA_DEV_F_LBA48) {
4610 				scmd->satacmd_cmd_reg =
4611 				    SATAC_READ_DMA_QUEUED_EXT;
4612 				scmd->satacmd_features_reg_ext =
4613 				    scmd->satacmd_sec_count_msb;
4614 				scmd->satacmd_sec_count_msb = 0;
4615 			} else {
4616 				scmd->satacmd_cmd_reg =
4617 				    SATAC_READ_DMA_QUEUED;
4618 			}
4619 		} else	/* NCQ nor legacy queuing not supported */
4620 			using_queuing = B_FALSE;
4621 
4622 		/*
4623 		 * If queuing, the sector count goes in the features register
4624 		 * and the secount count will contain the tag.
4625 		 */
4626 		if (using_queuing) {
4627 			scmd->satacmd_features_reg =
4628 			    scmd->satacmd_sec_count_lsb;
4629 			scmd->satacmd_sec_count_lsb = 0;
4630 			scmd->satacmd_flags.sata_queued = B_TRUE;
4631 
4632 			/* Set-up maximum queue depth */
4633 			scmd->satacmd_flags.sata_max_queue_depth =
4634 			    sdinfo->satadrv_max_queue_depth - 1;
4635 		} else if (sdinfo->satadrv_features_enabled &
4636 		    SATA_DEV_F_E_UNTAGGED_QING) {
4637 			/*
4638 			 * Although NCQ/TCQ is not enabled, untagged queuing
4639 			 * may be still used.
4640 			 * Set-up the maximum untagged queue depth.
4641 			 * Use controller's queue depth from sata_hba_tran.
4642 			 * SATA HBA drivers may ignore this value and rely on
4643 			 * the internal limits.For drivers that do not
4644 			 * ignore untaged queue depth, limit the value to
4645 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
4646 			 * largest value that can be passed via
4647 			 * satacmd_flags.sata_max_queue_depth.
4648 			 */
4649 			scmd->satacmd_flags.sata_max_queue_depth =
4650 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
4651 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
4652 
4653 		} else {
4654 			scmd->satacmd_flags.sata_max_queue_depth = 0;
4655 		}
4656 	} else
4657 		scmd->satacmd_flags.sata_max_queue_depth = 0;
4658 
4659 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
4660 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
4661 	    scmd->satacmd_cmd_reg, lba, sec_count);
4662 
4663 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
4664 		/* Need callback function */
4665 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
4666 		synch = FALSE;
4667 	} else
4668 		synch = TRUE;
4669 
4670 	/* Transfer command to HBA */
4671 	if (sata_hba_start(spx, &rval) != 0) {
4672 		/* Pkt not accepted for execution */
4673 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4674 		return (rval);
4675 	}
4676 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4677 	/*
4678 	 * If execution is non-synchronous,
4679 	 * a callback function will handle potential errors, translate
4680 	 * the response and will do a callback to a target driver.
4681 	 * If it was synchronous, check execution status using the same
4682 	 * framework callback.
4683 	 */
4684 	if (synch) {
4685 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4686 		    "synchronous execution status %x\n",
4687 		    spx->txlt_sata_pkt->satapkt_reason);
4688 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
4689 	}
4690 	return (TRAN_ACCEPT);
4691 }
4692 
4693 
4694 /*
4695  * SATA translate command: Write (various types)
4696  * Translated into appropriate type of ATA WRITE command
4697  * for SATA hard disks.
4698  * Both the device capabilities and requested operation mode are
4699  * considered.
4700  *
4701  * Following scsi cdb fields are ignored:
4702  * rwprotect, dpo, fua, fua_nv, group_number.
4703  *
4704  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
4705  * enable variable sata_func_enable), the capability of the controller and
4706  * capability of a device are checked and if both support queueing, write
4707  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
4708  * command rather than plain WRITE_XXX command.
4709  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
4710  * both the controller and device suport such functionality, the write
4711  * request will be translated to WRITE_FPDMA_QUEUED command.
4712  * In both cases the maximum queue depth is derived as minimum of:
4713  * HBA capability,device capability and sata_max_queue_depth variable setting.
4714  * The value passed to HBA driver is decremented by 1, because only 5 bits are
4715  * used to pass max queue depth value, and the maximum possible queue depth
4716  * is 32.
4717  *
4718  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4719  * appropriate values in scsi_pkt fields.
4720  */
4721 static int
4722 sata_txlt_write(sata_pkt_txlate_t *spx)
4723 {
4724 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4725 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4726 	sata_drive_info_t *sdinfo;
4727 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
4728 	int cport = SATA_TXLT_CPORT(spx);
4729 	uint16_t sec_count;
4730 	uint64_t lba;
4731 	int rval, reason;
4732 	int synch;
4733 
4734 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4735 
4736 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
4737 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4738 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4739 		return (rval);
4740 	}
4741 
4742 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4743 	    &spx->txlt_sata_pkt->satapkt_device);
4744 
4745 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
4746 	/*
4747 	 * Extract LBA and sector count from scsi CDB
4748 	 */
4749 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
4750 	case SCMD_WRITE:
4751 		/* 6-byte scsi read cmd : 0x0A */
4752 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
4753 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
4754 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4755 		sec_count = scsipkt->pkt_cdbp[4];
4756 		/* sec_count 0 will be interpreted as 256 by a device */
4757 		break;
4758 	case SCMD_WRITE_G1:
4759 		/* 10-bytes scsi write command : 0x2A */
4760 		lba = scsipkt->pkt_cdbp[2];
4761 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4762 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4763 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4764 		sec_count = scsipkt->pkt_cdbp[7];
4765 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4766 		break;
4767 	case SCMD_WRITE_G5:
4768 		/* 12-bytes scsi read command : 0xAA */
4769 		lba = scsipkt->pkt_cdbp[2];
4770 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4771 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4772 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4773 		sec_count = scsipkt->pkt_cdbp[6];
4774 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
4775 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
4776 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
4777 		break;
4778 	case SCMD_WRITE_G4:
4779 		/* 16-bytes scsi write command : 0x8A */
4780 		lba = scsipkt->pkt_cdbp[2];
4781 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
4782 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
4783 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
4784 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
4785 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
4786 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
4787 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
4788 		sec_count = scsipkt->pkt_cdbp[10];
4789 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
4790 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
4791 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
4792 		break;
4793 	default:
4794 		/* Unsupported command */
4795 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4796 		return (sata_txlt_invalid_command(spx));
4797 	}
4798 
4799 	/*
4800 	 * Check if specified address and length exceeds device capacity
4801 	 */
4802 	if ((lba >= sdinfo->satadrv_capacity) ||
4803 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
4804 		/* LBA out of range */
4805 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4806 		return (sata_txlt_lba_out_of_range(spx));
4807 	}
4808 
4809 	/*
4810 	 * For zero-length transfer, emulate good completion of the command
4811 	 * (reasons for rejecting the command were already checked).
4812 	 * No DMA resources were allocated.
4813 	 */
4814 	if (spx->txlt_dma_cookie_list == NULL) {
4815 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4816 		return (sata_emul_rw_completion(spx));
4817 	}
4818 
4819 	/*
4820 	 * Build cmd block depending on the device capability and
4821 	 * requested operation mode.
4822 	 * Do not bother with non-dma mode- we are working only with
4823 	 * devices supporting DMA.
4824 	 */
4825 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
4826 	scmd->satacmd_device_reg = SATA_ADH_LBA;
4827 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
4828 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
4829 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
4830 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
4831 		scmd->satacmd_sec_count_msb = sec_count >> 8;
4832 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
4833 #ifndef __lock_lint
4834 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
4835 		scmd->satacmd_lba_high_msb = lba >> 40;
4836 #endif
4837 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
4838 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
4839 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
4840 	}
4841 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
4842 	scmd->satacmd_lba_low_lsb = lba & 0xff;
4843 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
4844 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
4845 	scmd->satacmd_features_reg = 0;
4846 	scmd->satacmd_status_reg = 0;
4847 	scmd->satacmd_error_reg = 0;
4848 
4849 	/*
4850 	 * Check if queueing commands should be used and switch
4851 	 * to appropriate command if possible
4852 	 */
4853 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
4854 		boolean_t using_queuing;
4855 
4856 		/* Queuing supported by controller and device? */
4857 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
4858 		    (sdinfo->satadrv_features_support &
4859 		    SATA_DEV_F_NCQ) &&
4860 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4861 		    SATA_CTLF_NCQ)) {
4862 			using_queuing = B_TRUE;
4863 
4864 			/* NCQ supported - use FPDMA WRITE */
4865 			scmd->satacmd_cmd_reg =
4866 			    SATAC_WRITE_FPDMA_QUEUED;
4867 			scmd->satacmd_features_reg_ext =
4868 			    scmd->satacmd_sec_count_msb;
4869 			scmd->satacmd_sec_count_msb = 0;
4870 		} else if ((sdinfo->satadrv_features_support &
4871 		    SATA_DEV_F_TCQ) &&
4872 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
4873 		    SATA_CTLF_QCMD)) {
4874 			using_queuing = B_TRUE;
4875 
4876 			/* Legacy queueing */
4877 			if (sdinfo->satadrv_features_support &
4878 			    SATA_DEV_F_LBA48) {
4879 				scmd->satacmd_cmd_reg =
4880 				    SATAC_WRITE_DMA_QUEUED_EXT;
4881 				scmd->satacmd_features_reg_ext =
4882 				    scmd->satacmd_sec_count_msb;
4883 				scmd->satacmd_sec_count_msb = 0;
4884 			} else {
4885 				scmd->satacmd_cmd_reg =
4886 				    SATAC_WRITE_DMA_QUEUED;
4887 			}
4888 		} else	/*  NCQ nor legacy queuing not supported */
4889 			using_queuing = B_FALSE;
4890 
4891 		if (using_queuing) {
4892 			scmd->satacmd_features_reg =
4893 			    scmd->satacmd_sec_count_lsb;
4894 			scmd->satacmd_sec_count_lsb = 0;
4895 			scmd->satacmd_flags.sata_queued = B_TRUE;
4896 			/* Set-up maximum queue depth */
4897 			scmd->satacmd_flags.sata_max_queue_depth =
4898 			    sdinfo->satadrv_max_queue_depth - 1;
4899 		} else if (sdinfo->satadrv_features_enabled &
4900 		    SATA_DEV_F_E_UNTAGGED_QING) {
4901 			/*
4902 			 * Although NCQ/TCQ is not enabled, untagged queuing
4903 			 * may be still used.
4904 			 * Set-up the maximum untagged queue depth.
4905 			 * Use controller's queue depth from sata_hba_tran.
4906 			 * SATA HBA drivers may ignore this value and rely on
4907 			 * the internal limits. For drivera that do not
4908 			 * ignore untaged queue depth, limit the value to
4909 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
4910 			 * largest value that can be passed via
4911 			 * satacmd_flags.sata_max_queue_depth.
4912 			 */
4913 			scmd->satacmd_flags.sata_max_queue_depth =
4914 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
4915 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
4916 
4917 		} else {
4918 			scmd->satacmd_flags.sata_max_queue_depth = 0;
4919 		}
4920 	} else
4921 		scmd->satacmd_flags.sata_max_queue_depth = 0;
4922 
4923 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4924 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
4925 	    scmd->satacmd_cmd_reg, lba, sec_count);
4926 
4927 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
4928 		/* Need callback function */
4929 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
4930 		synch = FALSE;
4931 	} else
4932 		synch = TRUE;
4933 
4934 	/* Transfer command to HBA */
4935 	if (sata_hba_start(spx, &rval) != 0) {
4936 		/* Pkt not accepted for execution */
4937 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4938 		return (rval);
4939 	}
4940 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4941 
4942 	/*
4943 	 * If execution is non-synchronous,
4944 	 * a callback function will handle potential errors, translate
4945 	 * the response and will do a callback to a target driver.
4946 	 * If it was synchronous, check execution status using the same
4947 	 * framework callback.
4948 	 */
4949 	if (synch) {
4950 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4951 		    "synchronous execution status %x\n",
4952 		    spx->txlt_sata_pkt->satapkt_reason);
4953 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
4954 	}
4955 	return (TRAN_ACCEPT);
4956 }
4957 
4958 
4959 /*
4960  * Implements SCSI SBC WRITE BUFFER command download microcode option
4961  */
4962 static int
4963 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
4964 {
4965 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
4966 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
4967 
4968 	sata_hba_inst_t *sata_hba_inst = SATA_TXLT_HBA_INST(spx);
4969 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4970 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
4971 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4972 
4973 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4974 	struct scsi_extended_sense *sense;
4975 	int rval, mode, sector_count, reason;
4976 	int cport = SATA_TXLT_CPORT(spx);
4977 
4978 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
4979 
4980 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4981 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
4982 
4983 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4984 
4985 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason)) != TRAN_ACCEPT) {
4986 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4987 		return (rval);
4988 	}
4989 	/*
4990 	 * If in interrupt context, reject this packet because it would issue
4991 	 * a synchronous command to HBA.
4992 	 */
4993 	if (servicing_interrupt()) {
4994 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
4995 		    "sata_txlt_write_buffer: rejecting command because "
4996 		    "of interrupt context\n", NULL);
4997 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4998 		return (TRAN_BUSY);
4999 	}
5000 
5001 	/* Use synchronous mode */
5002 	spx->txlt_sata_pkt->satapkt_op_mode
5003 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
5004 
5005 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5006 
5007 	scsipkt->pkt_reason = CMD_CMPLT;
5008 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5009 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5010 
5011 	/*
5012 	 * The SCSI to ATA translation specification only calls
5013 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
5014 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
5015 	 * ATA 8 (draft) got rid of download microcode for temp
5016 	 * and it is even optional for ATA 7, so it may be aborted.
5017 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
5018 	 * it is not specified and the buffer offset for SCSI is a 16-bit
5019 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
5020 	 * sectors.  Thus the offset really doesn't buy us anything.
5021 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
5022 	 * is revised, this can be revisisted.
5023 	 */
5024 	/* Reject not supported request */
5025 	switch (mode) {
5026 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
5027 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
5028 		break;
5029 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
5030 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
5031 		break;
5032 	default:
5033 		goto bad_param;
5034 	}
5035 
5036 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
5037 
5038 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
5039 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
5040 		goto bad_param;
5041 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
5042 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
5043 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
5044 	scmd->satacmd_lba_mid_lsb = 0;
5045 	scmd->satacmd_lba_high_lsb = 0;
5046 	scmd->satacmd_device_reg = 0;
5047 	spx->txlt_sata_pkt->satapkt_comp = NULL;
5048 	scmd->satacmd_addr_type = 0;
5049 
5050 	/* Transfer command to HBA */
5051 	if (sata_hba_start(spx, &rval) != 0) {
5052 		/* Pkt not accepted for execution */
5053 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
5054 		return (rval);
5055 	}
5056 
5057 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
5058 
5059 	/* Then we need synchronous check the status of the disk */
5060 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5061 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
5062 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5063 		scsipkt->pkt_reason = CMD_CMPLT;
5064 
5065 		/* Download commmand succeed, so probe and identify device */
5066 		sata_reidentify_device(spx);
5067 	} else {
5068 		/* Something went wrong, microcode download command failed */
5069 		scsipkt->pkt_reason = CMD_INCOMPLETE;
5070 		*scsipkt->pkt_scbp = STATUS_CHECK;
5071 		sense = sata_arq_sense(spx);
5072 		switch (sata_pkt->satapkt_reason) {
5073 		case SATA_PKT_PORT_ERROR:
5074 			/*
5075 			 * We have no device data. Assume no data transfered.
5076 			 */
5077 			sense->es_key = KEY_HARDWARE_ERROR;
5078 			break;
5079 
5080 		case SATA_PKT_DEV_ERROR:
5081 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
5082 			    SATA_STATUS_ERR) {
5083 				/*
5084 				 * determine dev error reason from error
5085 				 * reg content
5086 				 */
5087 				sata_decode_device_error(spx, sense);
5088 				break;
5089 			}
5090 			/* No extended sense key - no info available */
5091 			break;
5092 
5093 		case SATA_PKT_TIMEOUT:
5094 			scsipkt->pkt_reason = CMD_TIMEOUT;
5095 			scsipkt->pkt_statistics |=
5096 			    STAT_TIMEOUT | STAT_DEV_RESET;
5097 			/* No extended sense key ? */
5098 			break;
5099 
5100 		case SATA_PKT_ABORTED:
5101 			scsipkt->pkt_reason = CMD_ABORTED;
5102 			scsipkt->pkt_statistics |= STAT_ABORTED;
5103 			/* No extended sense key ? */
5104 			break;
5105 
5106 		case SATA_PKT_RESET:
5107 			/* pkt aborted by an explicit reset from a host */
5108 			scsipkt->pkt_reason = CMD_RESET;
5109 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
5110 			break;
5111 
5112 		default:
5113 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
5114 			    "sata_txlt_nodata_cmd_completion: "
5115 			    "invalid packet completion reason %d",
5116 			    sata_pkt->satapkt_reason));
5117 			scsipkt->pkt_reason = CMD_TRAN_ERR;
5118 			break;
5119 		}
5120 
5121 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5122 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5123 
5124 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
5125 			/* scsi callback required */
5126 			scsi_hba_pkt_comp(scsipkt);
5127 	}
5128 	return (TRAN_ACCEPT);
5129 
5130 bad_param:
5131 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5132 	*scsipkt->pkt_scbp = STATUS_CHECK;
5133 	sense = sata_arq_sense(spx);
5134 	sense->es_key = KEY_ILLEGAL_REQUEST;
5135 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5136 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5137 	    scsipkt->pkt_comp != NULL) {
5138 		/* scsi callback required */
5139 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5140 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5141 		    TQ_SLEEP) == 0) {
5142 			/* Scheduling the callback failed */
5143 			rval = TRAN_BUSY;
5144 		}
5145 	}
5146 	return (rval);
5147 }
5148 
5149 /*
5150  * Re-identify device after doing a firmware download.
5151  */
5152 static void
5153 sata_reidentify_device(sata_pkt_txlate_t *spx)
5154 {
5155 #define	DOWNLOAD_WAIT_TIME_SECS	60
5156 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
5157 	int rval;
5158 	int retry_cnt;
5159 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5160 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
5161 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
5162 	sata_drive_info_t *sdinfo;
5163 
5164 	/*
5165 	 * Before returning good status, probe device.
5166 	 * Device probing will get IDENTIFY DEVICE data, if possible.
5167 	 * The assumption is that the new microcode is applied by the
5168 	 * device. It is a caller responsibility to verify this.
5169 	 */
5170 	for (retry_cnt = 0;
5171 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
5172 	    retry_cnt++) {
5173 		rval = sata_probe_device(sata_hba_inst, &sata_device);
5174 
5175 		if (rval == SATA_SUCCESS) { /* Set default features */
5176 			sdinfo = sata_get_device_info(sata_hba_inst,
5177 			    &sata_device);
5178 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
5179 			    SATA_SUCCESS) {
5180 				/* retry */
5181 				rval = sata_initialize_device(sata_hba_inst,
5182 				    sdinfo);
5183 				if (rval == SATA_RETRY)
5184 					sata_log(sata_hba_inst, CE_WARN,
5185 					    "SATA device at port %d pmport %d -"
5186 					    " default device features could not"
5187 					    " be set. Device may not operate "
5188 					    "as expected.",
5189 					    sata_device.satadev_addr.cport,
5190 					    sata_device.satadev_addr.pmport);
5191 			}
5192 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
5193 				scsi_hba_pkt_comp(scsipkt);
5194 			return;
5195 		} else if (rval == SATA_RETRY) {
5196 			delay(drv_usectohz(1000000 *
5197 			    DOWNLOAD_WAIT_INTERVAL_SECS));
5198 			continue;
5199 		} else	/* failed - no reason to retry */
5200 			break;
5201 	}
5202 
5203 	/*
5204 	 * Something went wrong, device probing failed.
5205 	 */
5206 	SATA_LOG_D((sata_hba_inst, CE_WARN,
5207 	    "Cannot probe device after downloading microcode\n"));
5208 
5209 	/* Reset device to force retrying the probe. */
5210 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
5211 	    (SATA_DIP(sata_hba_inst), &sata_device);
5212 
5213 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
5214 		scsi_hba_pkt_comp(scsipkt);
5215 }
5216 
5217 
5218 /*
5219  * Translate command: Synchronize Cache.
5220  * Translates into Flush Cache command for SATA hard disks.
5221  *
5222  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5223  * appropriate values in scsi_pkt fields.
5224  */
5225 static 	int
5226 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
5227 {
5228 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5229 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5230 	int cport = SATA_TXLT_CPORT(spx);
5231 	int rval, reason;
5232 	int synch;
5233 
5234 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5235 
5236 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
5237 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5238 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5239 		return (rval);
5240 	}
5241 
5242 	scmd->satacmd_addr_type = 0;
5243 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
5244 	scmd->satacmd_device_reg = 0;
5245 	scmd->satacmd_sec_count_lsb = 0;
5246 	scmd->satacmd_lba_low_lsb = 0;
5247 	scmd->satacmd_lba_mid_lsb = 0;
5248 	scmd->satacmd_lba_high_lsb = 0;
5249 	scmd->satacmd_features_reg = 0;
5250 	scmd->satacmd_status_reg = 0;
5251 	scmd->satacmd_error_reg = 0;
5252 
5253 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5254 	    "sata_txlt_synchronize_cache\n", NULL);
5255 
5256 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5257 		/* Need to set-up a callback function */
5258 		spx->txlt_sata_pkt->satapkt_comp =
5259 		    sata_txlt_nodata_cmd_completion;
5260 		synch = FALSE;
5261 	} else
5262 		synch = TRUE;
5263 
5264 	/* Transfer command to HBA */
5265 	if (sata_hba_start(spx, &rval) != 0) {
5266 		/* Pkt not accepted for execution */
5267 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5268 		return (rval);
5269 	}
5270 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5271 
5272 	/*
5273 	 * If execution non-synchronous, it had to be completed
5274 	 * a callback function will handle potential errors, translate
5275 	 * the response and will do a callback to a target driver.
5276 	 * If it was synchronous, check status, using the same
5277 	 * framework callback.
5278 	 */
5279 	if (synch) {
5280 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5281 		    "synchronous execution status %x\n",
5282 		    spx->txlt_sata_pkt->satapkt_reason);
5283 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
5284 	}
5285 	return (TRAN_ACCEPT);
5286 }
5287 
5288 
5289 /*
5290  * Send pkt to SATA HBA driver
5291  *
5292  * This function may be called only if the operation is requested by scsi_pkt,
5293  * i.e. scsi_pkt is not NULL.
5294  *
5295  * This function has to be called with cport mutex held. It does release
5296  * the mutex when it calls HBA driver sata_tran_start function and
5297  * re-acquires it afterwards.
5298  *
5299  * If return value is 0, pkt was accepted, -1 otherwise
5300  * rval is set to appropriate sata_scsi_start return value.
5301  *
5302  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
5303  * have called the sata_pkt callback function for this packet.
5304  *
5305  * The scsi callback has to be performed by the caller of this routine.
5306  *
5307  * Note 2: No port multiplier support for now.
5308  */
5309 static int
5310 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
5311 {
5312 	int stat, cport;
5313 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
5314 	sata_drive_info_t *sdinfo;
5315 	sata_device_t *sata_device;
5316 	uint8_t cmd;
5317 	struct sata_cmd_flags cmd_flags;
5318 
5319 	ASSERT(spx->txlt_sata_pkt != NULL);
5320 
5321 	cport = SATA_TXLT_CPORT(spx);
5322 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5323 
5324 	sdinfo = sata_get_device_info(sata_hba_inst,
5325 	    &spx->txlt_sata_pkt->satapkt_device);
5326 	ASSERT(sdinfo != NULL);
5327 
5328 	/* Clear device reset state? */
5329 	if (sdinfo->satadrv_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
5330 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
5331 		    sata_clear_dev_reset = B_TRUE;
5332 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_CLEAR_DEVICE_RESET;
5333 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5334 		    "sata_hba_start: clearing device reset state\n", NULL);
5335 	}
5336 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
5337 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
5338 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
5339 
5340 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5341 
5342 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5343 	    "Sata cmd 0x%2x\n", cmd);
5344 
5345 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
5346 	    spx->txlt_sata_pkt);
5347 
5348 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5349 	/*
5350 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
5351 	 * with the sata callback, the sata_pkt could be already destroyed
5352 	 * by the time we check ther return status from the hba_start()
5353 	 * function, because sata_scsi_destroy_pkt() could have been already
5354 	 * called (perhaps in the interrupt context). So, in such case, there
5355 	 * should be no references to it. In other cases, sata_pkt still
5356 	 * exists.
5357 	 */
5358 	if (stat == SATA_TRAN_ACCEPTED) {
5359 		/*
5360 		 * pkt accepted for execution.
5361 		 * If it was executed synchronously, it is already completed
5362 		 * and pkt completion_reason indicates completion status.
5363 		 */
5364 		*rval = TRAN_ACCEPT;
5365 		return (0);
5366 	}
5367 
5368 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
5369 	switch (stat) {
5370 	case SATA_TRAN_QUEUE_FULL:
5371 		/*
5372 		 * Controller detected queue full condition.
5373 		 */
5374 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
5375 		    "sata_hba_start: queue full\n", NULL);
5376 
5377 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
5378 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
5379 
5380 		*rval = TRAN_BUSY;
5381 		break;
5382 
5383 	case SATA_TRAN_PORT_ERROR:
5384 		/*
5385 		 * Communication/link with device or general port error
5386 		 * detected before pkt execution begun.
5387 		 */
5388 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
5389 		    SATA_ADDR_CPORT ||
5390 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
5391 		    SATA_ADDR_DCPORT)
5392 			sata_log(sata_hba_inst, CE_CONT,
5393 			    "SATA port %d error",
5394 			    sata_device->satadev_addr.cport);
5395 		else
5396 			sata_log(sata_hba_inst, CE_CONT,
5397 			    "SATA port %d pmport %d error\n",
5398 			    sata_device->satadev_addr.cport,
5399 			    sata_device->satadev_addr.pmport);
5400 
5401 		/*
5402 		 * Update the port/device structure.
5403 		 * sata_pkt should be still valid. Since port error is
5404 		 * returned, sata_device content should reflect port
5405 		 * state - it means, that sata address have been changed,
5406 		 * because original packet's sata address refered to a device
5407 		 * attached to some port.
5408 		 */
5409 		sata_update_port_info(sata_hba_inst, sata_device);
5410 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
5411 		*rval = TRAN_FATAL_ERROR;
5412 		break;
5413 
5414 	case SATA_TRAN_CMD_UNSUPPORTED:
5415 		/*
5416 		 * Command rejected by HBA as unsupported. It was HBA driver
5417 		 * that rejected the command, command was not sent to
5418 		 * an attached device.
5419 		 */
5420 		if ((sdinfo != NULL) &&
5421 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
5422 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5423 			    "sat_hba_start: cmd 0x%2x rejected "
5424 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
5425 
5426 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5427 		(void) sata_txlt_invalid_command(spx);
5428 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
5429 
5430 		*rval = TRAN_ACCEPT;
5431 		break;
5432 
5433 	case SATA_TRAN_BUSY:
5434 		/*
5435 		 * Command rejected by HBA because other operation prevents
5436 		 * accepting the packet, or device is in RESET condition.
5437 		 */
5438 		if (sdinfo != NULL) {
5439 			sdinfo->satadrv_state =
5440 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
5441 
5442 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
5443 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5444 				    "sata_hba_start: cmd 0x%2x rejected "
5445 				    "because of device reset condition\n",
5446 				    cmd);
5447 			} else {
5448 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
5449 				    "sata_hba_start: cmd 0x%2x rejected "
5450 				    "with SATA_TRAN_BUSY status\n",
5451 				    cmd);
5452 			}
5453 		}
5454 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
5455 		*rval = TRAN_BUSY;
5456 		break;
5457 
5458 	default:
5459 		/* Unrecognized HBA response */
5460 		SATA_LOG_D((sata_hba_inst, CE_WARN,
5461 		    "sata_hba_start: unrecognized HBA response "
5462 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
5463 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
5464 		*rval = TRAN_FATAL_ERROR;
5465 		break;
5466 	}
5467 
5468 	/*
5469 	 * If we got here, the packet was rejected.
5470 	 * Check if we need to remember reset state clearing request
5471 	 */
5472 	if (cmd_flags.sata_clear_dev_reset) {
5473 		/*
5474 		 * Check if device is still configured - it may have
5475 		 * disapeared from the configuration
5476 		 */
5477 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
5478 		if (sdinfo != NULL) {
5479 			/*
5480 			 * Restore the flag that requests clearing of
5481 			 * the device reset state,
5482 			 * so the next sata packet may carry it to HBA.
5483 			 */
5484 			sdinfo->satadrv_event_flags |=
5485 			    SATA_EVNT_CLEAR_DEVICE_RESET;
5486 		}
5487 	}
5488 	return (-1);
5489 }
5490 
5491 /*
5492  * Scsi response setup for invalid LBA
5493  *
5494  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
5495  */
5496 static int
5497 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
5498 {
5499 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5500 	struct scsi_extended_sense *sense;
5501 
5502 	scsipkt->pkt_reason = CMD_CMPLT;
5503 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5504 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5505 	*scsipkt->pkt_scbp = STATUS_CHECK;
5506 
5507 	*scsipkt->pkt_scbp = STATUS_CHECK;
5508 	sense = sata_arq_sense(spx);
5509 	sense->es_key = KEY_ILLEGAL_REQUEST;
5510 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
5511 
5512 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5513 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5514 
5515 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5516 	    scsipkt->pkt_comp != NULL)
5517 		/* scsi callback required */
5518 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5519 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5520 		    TQ_SLEEP) == NULL)
5521 			/* Scheduling the callback failed */
5522 			return (TRAN_BUSY);
5523 	return (TRAN_ACCEPT);
5524 }
5525 
5526 
5527 /*
5528  * Analyze device status and error registers and translate them into
5529  * appropriate scsi sense codes.
5530  * NOTE: non-packet commands only for now
5531  */
5532 static void
5533 sata_decode_device_error(sata_pkt_txlate_t *spx,
5534     struct scsi_extended_sense *sense)
5535 {
5536 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
5537 
5538 	ASSERT(sense != NULL);
5539 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
5540 	    SATA_STATUS_ERR);
5541 
5542 
5543 	if (err_reg & SATA_ERROR_ICRC) {
5544 		sense->es_key = KEY_ABORTED_COMMAND;
5545 		sense->es_add_code = 0x08; /* Communication failure */
5546 		return;
5547 	}
5548 
5549 	if (err_reg & SATA_ERROR_UNC) {
5550 		sense->es_key = KEY_MEDIUM_ERROR;
5551 		/* Information bytes (LBA) need to be set by a caller */
5552 		return;
5553 	}
5554 
5555 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
5556 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
5557 		sense->es_key = KEY_UNIT_ATTENTION;
5558 		sense->es_add_code = 0x3a; /* No media present */
5559 		return;
5560 	}
5561 
5562 	if (err_reg & SATA_ERROR_IDNF) {
5563 		if (err_reg & SATA_ERROR_ABORT) {
5564 			sense->es_key = KEY_ABORTED_COMMAND;
5565 		} else {
5566 			sense->es_key = KEY_ILLEGAL_REQUEST;
5567 			sense->es_add_code = 0x21; /* LBA out of range */
5568 		}
5569 		return;
5570 	}
5571 
5572 	if (err_reg & SATA_ERROR_ABORT) {
5573 		ASSERT(spx->txlt_sata_pkt != NULL);
5574 		sense->es_key = KEY_ABORTED_COMMAND;
5575 		return;
5576 	}
5577 }
5578 
5579 /*
5580  * Extract error LBA from sata_pkt.satapkt_cmd register fields
5581  */
5582 static void
5583 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
5584 {
5585 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
5586 
5587 	*lba = 0;
5588 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
5589 		*lba = sata_cmd->satacmd_lba_high_msb;
5590 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
5591 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
5592 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
5593 		*lba = sata_cmd->satacmd_device_reg & 0xf;
5594 	}
5595 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
5596 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
5597 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
5598 }
5599 
5600 /*
5601  * This is fixed sense format - if LBA exceeds the info field size,
5602  * no valid info will be returned (valid bit in extended sense will
5603  * be set to 0).
5604  */
5605 static struct scsi_extended_sense *
5606 sata_arq_sense(sata_pkt_txlate_t *spx)
5607 {
5608 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5609 	struct scsi_arq_status *arqs;
5610 	struct scsi_extended_sense *sense;
5611 
5612 	/* Fill ARQ sense data */
5613 	scsipkt->pkt_state |= STATE_ARQ_DONE;
5614 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
5615 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
5616 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
5617 	arqs->sts_rqpkt_reason = CMD_CMPLT;
5618 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5619 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
5620 	arqs->sts_rqpkt_resid = 0;
5621 	sense = &arqs->sts_sensedata;
5622 	bzero(sense, sizeof (struct scsi_extended_sense));
5623 	sata_fixed_sense_data_preset(sense);
5624 	return (sense);
5625 }
5626 
5627 
5628 /*
5629  * Emulated SATA Read/Write command completion for zero-length requests.
5630  * This request always succedes, so in synchronous mode it always returns
5631  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
5632  * callback cannot be scheduled.
5633  */
5634 static int
5635 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
5636 {
5637 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5638 
5639 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5640 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5641 	scsipkt->pkt_reason = CMD_CMPLT;
5642 	*scsipkt->pkt_scbp = STATUS_GOOD;
5643 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5644 		/* scsi callback required - have to schedule it */
5645 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5646 		    (task_func_t *)scsipkt->pkt_comp,
5647 		    (void *)scsipkt, TQ_SLEEP) == NULL)
5648 			/* Scheduling the callback failed */
5649 			return (TRAN_BUSY);
5650 	}
5651 	return (TRAN_ACCEPT);
5652 }
5653 
5654 
5655 /*
5656  * Translate completion status of SATA read/write commands into scsi response.
5657  * pkt completion_reason is checked to determine the completion status.
5658  * Do scsi callback if necessary.
5659  *
5660  * Note: this function may be called also for synchronously executed
5661  * commands.
5662  * This function may be used only if scsi_pkt is non-NULL.
5663  */
5664 static void
5665 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
5666 {
5667 	sata_pkt_txlate_t *spx =
5668 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
5669 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
5670 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5671 	struct scsi_extended_sense *sense;
5672 	uint64_t lba;
5673 	struct buf *bp;
5674 	int rval;
5675 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5676 		/* Normal completion */
5677 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5678 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
5679 		scsipkt->pkt_reason = CMD_CMPLT;
5680 		*scsipkt->pkt_scbp = STATUS_GOOD;
5681 		if (spx->txlt_tmp_buf != NULL) {
5682 			/* Temporary buffer was used */
5683 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5684 			if (bp->b_flags & B_READ) {
5685 				rval = ddi_dma_sync(
5686 				    spx->txlt_buf_dma_handle, 0, 0,
5687 				    DDI_DMA_SYNC_FORCPU);
5688 				ASSERT(rval == DDI_SUCCESS);
5689 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
5690 				    bp->b_bcount);
5691 			}
5692 		}
5693 	} else {
5694 		/*
5695 		 * Something went wrong - analyze return
5696 		 */
5697 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5698 		    STATE_SENT_CMD | STATE_GOT_STATUS;
5699 		scsipkt->pkt_reason = CMD_INCOMPLETE;
5700 		*scsipkt->pkt_scbp = STATUS_CHECK;
5701 		sense = sata_arq_sense(spx);
5702 		ASSERT(sense != NULL);
5703 
5704 		/*
5705 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
5706 		 * extract from device registers the failing LBA.
5707 		 */
5708 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
5709 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
5710 			    (scmd->satacmd_lba_mid_msb != 0 ||
5711 			    scmd->satacmd_lba_high_msb != 0)) {
5712 				/*
5713 				 * We have problem reporting this cmd LBA
5714 				 * in fixed sense data format, because of
5715 				 * the size of the scsi LBA fields.
5716 				 */
5717 				sense->es_valid = 0;
5718 			} else {
5719 				sata_extract_error_lba(spx, &lba);
5720 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
5721 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
5722 				sense->es_info_3 = (lba & 0xFF00) >> 8;
5723 				sense->es_info_4 = lba & 0xFF;
5724 			}
5725 		} else {
5726 			/* Invalid extended sense info */
5727 			sense->es_valid = 0;
5728 		}
5729 
5730 		switch (sata_pkt->satapkt_reason) {
5731 		case SATA_PKT_PORT_ERROR:
5732 			/* We may want to handle DEV GONE state as well */
5733 			/*
5734 			 * We have no device data. Assume no data transfered.
5735 			 */
5736 			sense->es_key = KEY_HARDWARE_ERROR;
5737 			break;
5738 
5739 		case SATA_PKT_DEV_ERROR:
5740 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
5741 			    SATA_STATUS_ERR) {
5742 				/*
5743 				 * determine dev error reason from error
5744 				 * reg content
5745 				 */
5746 				sata_decode_device_error(spx, sense);
5747 				if (sense->es_key == KEY_MEDIUM_ERROR) {
5748 					switch (scmd->satacmd_cmd_reg) {
5749 					case SATAC_READ_DMA:
5750 					case SATAC_READ_DMA_EXT:
5751 					case SATAC_READ_DMA_QUEUED:
5752 					case SATAC_READ_DMA_QUEUED_EXT:
5753 					case SATAC_READ_FPDMA_QUEUED:
5754 						/* Unrecovered read error */
5755 						sense->es_add_code =
5756 						    SD_SCSI_ASC_UNREC_READ_ERR;
5757 						break;
5758 					case SATAC_WRITE_DMA:
5759 					case SATAC_WRITE_DMA_EXT:
5760 					case SATAC_WRITE_DMA_QUEUED:
5761 					case SATAC_WRITE_DMA_QUEUED_EXT:
5762 					case SATAC_WRITE_FPDMA_QUEUED:
5763 						/* Write error */
5764 						sense->es_add_code =
5765 						    SD_SCSI_ASC_WRITE_ERR;
5766 						break;
5767 					default:
5768 						/* Internal error */
5769 						SATA_LOG_D((
5770 						    spx->txlt_sata_hba_inst,
5771 						    CE_WARN,
5772 						    "sata_txlt_rw_completion :"
5773 						    "internal error - invalid "
5774 						    "command 0x%2x",
5775 						    scmd->satacmd_cmd_reg));
5776 						break;
5777 					}
5778 				}
5779 				break;
5780 			}
5781 			/* No extended sense key - no info available */
5782 			scsipkt->pkt_reason = CMD_INCOMPLETE;
5783 			break;
5784 
5785 		case SATA_PKT_TIMEOUT:
5786 			scsipkt->pkt_reason = CMD_TIMEOUT;
5787 			scsipkt->pkt_statistics |=
5788 			    STAT_TIMEOUT | STAT_DEV_RESET;
5789 			sense->es_key = KEY_ABORTED_COMMAND;
5790 			break;
5791 
5792 		case SATA_PKT_ABORTED:
5793 			scsipkt->pkt_reason = CMD_ABORTED;
5794 			scsipkt->pkt_statistics |= STAT_ABORTED;
5795 			sense->es_key = KEY_ABORTED_COMMAND;
5796 			break;
5797 
5798 		case SATA_PKT_RESET:
5799 			scsipkt->pkt_reason = CMD_RESET;
5800 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
5801 			sense->es_key = KEY_ABORTED_COMMAND;
5802 			break;
5803 
5804 		default:
5805 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
5806 			    "sata_txlt_rw_completion: "
5807 			    "invalid packet completion reason"));
5808 			scsipkt->pkt_reason = CMD_TRAN_ERR;
5809 			break;
5810 		}
5811 	}
5812 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5813 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5814 
5815 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
5816 		/* scsi callback required */
5817 		scsi_hba_pkt_comp(scsipkt);
5818 }
5819 
5820 
5821 /*
5822  * Translate completion status of non-data commands (i.e. commands returning
5823  * no data).
5824  * pkt completion_reason is checked to determine the completion status.
5825  * Do scsi callback if necessary (FLAG_NOINTR == 0)
5826  *
5827  * Note: this function may be called also for synchronously executed
5828  * commands.
5829  * This function may be used only if scsi_pkt is non-NULL.
5830  */
5831 
5832 static 	void
5833 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
5834 {
5835 	sata_pkt_txlate_t *spx =
5836 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
5837 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5838 	struct scsi_extended_sense *sense;
5839 
5840 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5841 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5842 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
5843 		/* Normal completion */
5844 		scsipkt->pkt_reason = CMD_CMPLT;
5845 		*scsipkt->pkt_scbp = STATUS_GOOD;
5846 	} else {
5847 		/* Something went wrong */
5848 		scsipkt->pkt_reason = CMD_INCOMPLETE;
5849 		*scsipkt->pkt_scbp = STATUS_CHECK;
5850 		sense = sata_arq_sense(spx);
5851 		switch (sata_pkt->satapkt_reason) {
5852 		case SATA_PKT_PORT_ERROR:
5853 			/*
5854 			 * We have no device data. Assume no data transfered.
5855 			 */
5856 			sense->es_key = KEY_HARDWARE_ERROR;
5857 			break;
5858 
5859 		case SATA_PKT_DEV_ERROR:
5860 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
5861 			    SATA_STATUS_ERR) {
5862 				/*
5863 				 * determine dev error reason from error
5864 				 * reg content
5865 				 */
5866 				sata_decode_device_error(spx, sense);
5867 				break;
5868 			}
5869 			/* No extended sense key - no info available */
5870 			break;
5871 
5872 		case SATA_PKT_TIMEOUT:
5873 			scsipkt->pkt_reason = CMD_TIMEOUT;
5874 			scsipkt->pkt_statistics |=
5875 			    STAT_TIMEOUT | STAT_DEV_RESET;
5876 			/* No extended sense key ? */
5877 			break;
5878 
5879 		case SATA_PKT_ABORTED:
5880 			scsipkt->pkt_reason = CMD_ABORTED;
5881 			scsipkt->pkt_statistics |= STAT_ABORTED;
5882 			/* No extended sense key ? */
5883 			break;
5884 
5885 		case SATA_PKT_RESET:
5886 			/* pkt aborted by an explicit reset from a host */
5887 			scsipkt->pkt_reason = CMD_RESET;
5888 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
5889 			break;
5890 
5891 		default:
5892 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
5893 			    "sata_txlt_nodata_cmd_completion: "
5894 			    "invalid packet completion reason %d",
5895 			    sata_pkt->satapkt_reason));
5896 			scsipkt->pkt_reason = CMD_TRAN_ERR;
5897 			break;
5898 		}
5899 
5900 	}
5901 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5902 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5903 
5904 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
5905 		/* scsi callback required */
5906 		scsi_hba_pkt_comp(scsipkt);
5907 }
5908 
5909 
5910 /*
5911  * Build Mode sense R/W recovery page
5912  * NOT IMPLEMENTED
5913  */
5914 
5915 static int
5916 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
5917 {
5918 #ifndef __lock_lint
5919 	_NOTE(ARGUNUSED(sdinfo))
5920 	_NOTE(ARGUNUSED(pcntrl))
5921 	_NOTE(ARGUNUSED(buf))
5922 #endif
5923 	return (0);
5924 }
5925 
5926 /*
5927  * Build Mode sense caching page  -  scsi-3 implementation.
5928  * Page length distinguishes previous format from scsi-3 format.
5929  * buf must have space for 0x12 bytes.
5930  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
5931  *
5932  */
5933 static int
5934 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
5935 {
5936 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
5937 	sata_id_t *sata_id = &sdinfo->satadrv_id;
5938 
5939 	/*
5940 	 * Most of the fields are set to 0, being not supported and/or disabled
5941 	 */
5942 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
5943 
5944 	/* Saved paramters not supported */
5945 	if (pcntrl == 3)
5946 		return (0);
5947 	if (pcntrl == 0 || pcntrl == 2) {
5948 		/*
5949 		 * For now treat current and default parameters as same
5950 		 * That may have to change, if target driver will complain
5951 		 */
5952 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
5953 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
5954 
5955 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
5956 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
5957 			page->dra = 1;		/* Read Ahead disabled */
5958 			page->rcd = 1;		/* Read Cache disabled */
5959 		}
5960 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
5961 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
5962 			page->wce = 1;		/* Write Cache enabled */
5963 	} else {
5964 		/* Changeable parameters */
5965 		page->mode_page.code = MODEPAGE_CACHING;
5966 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
5967 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
5968 			page->dra = 1;
5969 			page->rcd = 1;
5970 		}
5971 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
5972 			page->wce = 1;
5973 	}
5974 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
5975 	    sizeof (struct mode_page));
5976 }
5977 
5978 /*
5979  * Build Mode sense exception cntrl page
5980  */
5981 static int
5982 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
5983 {
5984 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
5985 	sata_id_t *sata_id = &sdinfo->satadrv_id;
5986 
5987 	/*
5988 	 * Most of the fields are set to 0, being not supported and/or disabled
5989 	 */
5990 	bzero(buf, PAGELENGTH_INFO_EXCPT);
5991 
5992 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
5993 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
5994 
5995 	/* Indicate that this is page is saveable */
5996 	page->mode_page.ps = 1;
5997 
5998 	/*
5999 	 * We will return the same data for default, current and saved page.
6000 	 * The only changeable bit is dexcpt and that bit is required
6001 	 * by the ATA specification to be preserved across power cycles.
6002 	 */
6003 	if (pcntrl != 1) {
6004 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
6005 		page->mrie = MRIE_ONLY_ON_REQUEST;
6006 	}
6007 	else
6008 		page->dexcpt = 1;	/* Only changeable parameter */
6009 
6010 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_info_excpt_page));
6011 }
6012 
6013 
6014 static int
6015 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6016 {
6017 	struct mode_acoustic_management *page =
6018 	    (struct mode_acoustic_management *)buf;
6019 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6020 
6021 	/*
6022 	 * Most of the fields are set to 0, being not supported and/or disabled
6023 	 */
6024 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
6025 
6026 	switch (pcntrl) {
6027 	case P_CNTRL_DEFAULT:
6028 		/*  default paramters not supported */
6029 		return (0);
6030 
6031 	case P_CNTRL_CURRENT:
6032 	case P_CNTRL_SAVED:
6033 		/* Saved and current are supported and are identical */
6034 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
6035 		page->mode_page.length =
6036 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
6037 		page->mode_page.ps = 1;
6038 
6039 		/* Word 83 indicates if feature is supported */
6040 		/* If feature is not supported */
6041 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
6042 			page->acoustic_manag_enable =
6043 			    ACOUSTIC_DISABLED;
6044 		} else {
6045 			page->acoustic_manag_enable =
6046 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
6047 			    != 0);
6048 			/* Word 94 inidicates the value */
6049 #ifdef	_LITTLE_ENDIAN
6050 			page->acoustic_manag_level =
6051 			    (uchar_t)sata_id->ai_acoustic;
6052 			page->vendor_recommended_value =
6053 			    sata_id->ai_acoustic >> 8;
6054 #else
6055 			page->acoustic_manag_level =
6056 			    sata_id->ai_acoustic >> 8;
6057 			page->vendor_recommended_value =
6058 			    (uchar_t)sata_id->ai_acoustic;
6059 #endif
6060 		}
6061 		break;
6062 
6063 	case P_CNTRL_CHANGEABLE:
6064 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
6065 		page->mode_page.length =
6066 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
6067 		page->mode_page.ps = 1;
6068 
6069 		/* Word 83 indicates if the feature is supported */
6070 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
6071 			page->acoustic_manag_enable =
6072 			    ACOUSTIC_ENABLED;
6073 			page->acoustic_manag_level = 0xff;
6074 		}
6075 		break;
6076 	}
6077 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
6078 	    sizeof (struct mode_page));
6079 }
6080 
6081 
6082 /*
6083  * Build Mode sense power condition page
6084  * NOT IMPLEMENTED.
6085  */
6086 static int
6087 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
6088 {
6089 #ifndef __lock_lint
6090 	_NOTE(ARGUNUSED(sdinfo))
6091 	_NOTE(ARGUNUSED(pcntrl))
6092 	_NOTE(ARGUNUSED(buf))
6093 #endif
6094 	return (0);
6095 }
6096 
6097 
6098 /*
6099  * Process mode select caching page 8 (scsi3 format only).
6100  * Read Ahead (same as read cache) and Write Cache may be turned on and off
6101  * if these features are supported by the device. If these features are not
6102  * supported, quietly ignore them.
6103  * This function fails only if the SET FEATURE command sent to
6104  * the device fails. The page format is not varified, assuming that the
6105  * target driver operates correctly - if parameters length is too short,
6106  * we just drop the page.
6107  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
6108  * setting have to be changed.
6109  * SET FEATURE command is executed synchronously, i.e. we wait here until
6110  * it is completed, regardless of the scsi pkt directives.
6111  *
6112  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
6113  * changing DRA will change RCD.
6114  *
6115  * More than one SATA command may be executed to perform operations specified
6116  * by mode select pages. The first error terminates further execution.
6117  * Operations performed successully are not backed-up in such case.
6118  *
6119  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
6120  * If operation resulted in changing device setup, dmod flag should be set to
6121  * one (1). If parameters were not changed, dmod flag should be set to 0.
6122  * Upon return, if operation required sending command to the device, the rval
6123  * should be set to the value returned by sata_hba_start. If operation
6124  * did not require device access, rval should be set to TRAN_ACCEPT.
6125  * The pagelen should be set to the length of the page.
6126  *
6127  * This function has to be called with a port mutex held.
6128  *
6129  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
6130  */
6131 int
6132 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
6133     int parmlen, int *pagelen, int *rval, int *dmod)
6134 {
6135 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6136 	sata_drive_info_t *sdinfo;
6137 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6138 	sata_id_t *sata_id;
6139 	struct scsi_extended_sense *sense;
6140 	int wce, dra;	/* Current settings */
6141 
6142 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6143 	    &spx->txlt_sata_pkt->satapkt_device);
6144 	sata_id = &sdinfo->satadrv_id;
6145 	*dmod = 0;
6146 
6147 	/* Verify parameters length. If too short, drop it */
6148 	if (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
6149 	    sizeof (struct mode_page) < parmlen) {
6150 		*scsipkt->pkt_scbp = STATUS_CHECK;
6151 		sense = sata_arq_sense(spx);
6152 		sense->es_key = KEY_ILLEGAL_REQUEST;
6153 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
6154 		*pagelen = parmlen;
6155 		*rval = TRAN_ACCEPT;
6156 		return (SATA_FAILURE);
6157 	}
6158 
6159 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
6160 
6161 	/*
6162 	 * We can manipulate only write cache and read ahead
6163 	 * (read cache) setting.
6164 	 */
6165 	if (!SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
6166 	    !SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
6167 		/*
6168 		 * None of the features is supported - ignore
6169 		 */
6170 		*rval = TRAN_ACCEPT;
6171 		return (SATA_SUCCESS);
6172 	}
6173 
6174 	/* Current setting of Read Ahead (and Read Cache) */
6175 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
6176 		dra = 0;	/* 0 == not disabled */
6177 	else
6178 		dra = 1;
6179 	/* Current setting of Write Cache */
6180 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
6181 		wce = 1;
6182 	else
6183 		wce = 0;
6184 
6185 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
6186 		/* nothing to do */
6187 		*rval = TRAN_ACCEPT;
6188 		return (SATA_SUCCESS);
6189 	}
6190 
6191 	/*
6192 	 * Need to flip some setting
6193 	 * Set-up Internal SET FEATURES command(s)
6194 	 */
6195 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6196 	scmd->satacmd_addr_type = 0;
6197 	scmd->satacmd_device_reg = 0;
6198 	scmd->satacmd_status_reg = 0;
6199 	scmd->satacmd_error_reg = 0;
6200 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
6201 	if (page->dra != dra || page->rcd != dra) {
6202 		/* Need to flip read ahead setting */
6203 		if (dra == 0)
6204 			/* Disable read ahead / read cache */
6205 			scmd->satacmd_features_reg =
6206 			    SATAC_SF_DISABLE_READ_AHEAD;
6207 		else
6208 			/* Enable read ahead  / read cache */
6209 			scmd->satacmd_features_reg =
6210 			    SATAC_SF_ENABLE_READ_AHEAD;
6211 
6212 		/* Transfer command to HBA */
6213 		if (sata_hba_start(spx, rval) != 0)
6214 			/*
6215 			 * Pkt not accepted for execution.
6216 			 */
6217 			return (SATA_FAILURE);
6218 
6219 		*dmod = 1;
6220 
6221 		/* Now process return */
6222 		if (spx->txlt_sata_pkt->satapkt_reason !=
6223 		    SATA_PKT_COMPLETED) {
6224 			goto failure;	/* Terminate */
6225 		}
6226 	}
6227 
6228 	/* Note that the packet is not removed, so it could be re-used */
6229 	if (page->wce != wce) {
6230 		/* Need to flip Write Cache setting */
6231 		if (page->wce == 1)
6232 			/* Enable write cache */
6233 			scmd->satacmd_features_reg =
6234 			    SATAC_SF_ENABLE_WRITE_CACHE;
6235 		else
6236 			/* Disable write cache */
6237 			scmd->satacmd_features_reg =
6238 			    SATAC_SF_DISABLE_WRITE_CACHE;
6239 
6240 		/* Transfer command to HBA */
6241 		if (sata_hba_start(spx, rval) != 0)
6242 			/*
6243 			 * Pkt not accepted for execution.
6244 			 */
6245 			return (SATA_FAILURE);
6246 
6247 		*dmod = 1;
6248 
6249 		/* Now process return */
6250 		if (spx->txlt_sata_pkt->satapkt_reason !=
6251 		    SATA_PKT_COMPLETED) {
6252 			goto failure;
6253 		}
6254 	}
6255 	return (SATA_SUCCESS);
6256 
6257 failure:
6258 	sata_xlate_errors(spx);
6259 
6260 	return (SATA_FAILURE);
6261 }
6262 
6263 /*
6264  * Process mode select informational exceptions control page 0x1c
6265  *
6266  * The only changeable bit is dexcpt (disable exceptions).
6267  * MRIE (method of reporting informational exceptions) must be
6268  * "only on request".
6269  * This page applies to informational exceptions that report
6270  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
6271  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
6272  * Informational exception conditions occur as the result of background scan
6273  * errors, background self-test errors, or vendor specific events within a
6274  * logical unit. An informational exception condition may occur asynchronous
6275  * to any commands.
6276  *
6277  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
6278  * If operation resulted in changing device setup, dmod flag should be set to
6279  * one (1). If parameters were not changed, dmod flag should be set to 0.
6280  * Upon return, if operation required sending command to the device, the rval
6281  * should be set to the value returned by sata_hba_start. If operation
6282  * did not require device access, rval should be set to TRAN_ACCEPT.
6283  * The pagelen should be set to the length of the page.
6284  *
6285  * This function has to be called with a port mutex held.
6286  *
6287  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
6288  *
6289  * Cannot be called in the interrupt context.
6290  */
6291 static	int
6292 sata_mode_select_page_1c(
6293 	sata_pkt_txlate_t *spx,
6294 	struct mode_info_excpt_page *page,
6295 	int parmlen,
6296 	int *pagelen,
6297 	int *rval,
6298 	int *dmod)
6299 {
6300 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6301 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6302 	sata_drive_info_t *sdinfo;
6303 	sata_id_t *sata_id;
6304 	struct scsi_extended_sense *sense;
6305 
6306 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6307 	    &spx->txlt_sata_pkt->satapkt_device);
6308 	sata_id = &sdinfo->satadrv_id;
6309 
6310 	*dmod = 0;
6311 
6312 	/* Verify parameters length. If too short, drop it */
6313 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) < parmlen) ||
6314 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
6315 		*scsipkt->pkt_scbp = STATUS_CHECK;
6316 		sense = sata_arq_sense(spx);
6317 		sense->es_key = KEY_ILLEGAL_REQUEST;
6318 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
6319 		*pagelen = parmlen;
6320 		*rval = TRAN_ACCEPT;
6321 		return (SATA_FAILURE);
6322 	}
6323 
6324 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
6325 
6326 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
6327 		*scsipkt->pkt_scbp = STATUS_CHECK;
6328 		sense = sata_arq_sense(spx);
6329 		sense->es_key = KEY_ILLEGAL_REQUEST;
6330 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6331 		*pagelen = parmlen;
6332 		*rval = TRAN_ACCEPT;
6333 		return (SATA_FAILURE);
6334 	}
6335 
6336 	/* If already in the state requested, we are done */
6337 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
6338 		/* nothing to do */
6339 		*rval = TRAN_ACCEPT;
6340 		return (SATA_SUCCESS);
6341 	}
6342 
6343 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6344 
6345 	/* Build SMART_ENABLE or SMART_DISABLE command */
6346 	scmd->satacmd_addr_type = 0;		/* N/A */
6347 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
6348 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
6349 	scmd->satacmd_features_reg = page->dexcpt ?
6350 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
6351 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
6352 	scmd->satacmd_cmd_reg = SATAC_SMART;
6353 
6354 	/* Transfer command to HBA */
6355 	if (sata_hba_start(spx, rval) != 0)
6356 		/*
6357 		 * Pkt not accepted for execution.
6358 		 */
6359 		return (SATA_FAILURE);
6360 
6361 	*dmod = 1;	/* At least may have been modified */
6362 
6363 	/* Now process return */
6364 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
6365 		return (SATA_SUCCESS);
6366 
6367 	/* Packet did not complete successfully */
6368 	sata_xlate_errors(spx);
6369 
6370 	return (SATA_FAILURE);
6371 }
6372 
6373 /*
6374  * Process mode select acoustic management control page 0x30
6375  *
6376  *
6377  * This function has to be called with a port mutex held.
6378  *
6379  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
6380  *
6381  * Cannot be called in the interrupt context.
6382  */
6383 int
6384 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
6385     mode_acoustic_management *page, int parmlen, int *pagelen,
6386     int *rval, int *dmod)
6387 {
6388 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6389 	sata_drive_info_t *sdinfo;
6390 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6391 	sata_id_t *sata_id;
6392 	struct scsi_extended_sense *sense;
6393 
6394 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6395 	    &spx->txlt_sata_pkt->satapkt_device);
6396 	sata_id = &sdinfo->satadrv_id;
6397 	*dmod = 0;
6398 
6399 	/* If parmlen is too short or the feature is not supported, drop it */
6400 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
6401 	    sizeof (struct mode_page)) < parmlen) ||
6402 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
6403 		*scsipkt->pkt_scbp = STATUS_CHECK;
6404 		sense = sata_arq_sense(spx);
6405 		sense->es_key = KEY_ILLEGAL_REQUEST;
6406 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
6407 		*pagelen = parmlen;
6408 		*rval = TRAN_ACCEPT;
6409 		return (SATA_FAILURE);
6410 	}
6411 
6412 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
6413 	    sizeof (struct mode_page);
6414 
6415 	/*
6416 	 * We can enable and disable acoustice management and
6417 	 * set the acoustic management level.
6418 	 */
6419 
6420 	/*
6421 	 * Set-up Internal SET FEATURES command(s)
6422 	 */
6423 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
6424 	scmd->satacmd_addr_type = 0;
6425 	scmd->satacmd_device_reg = 0;
6426 	scmd->satacmd_status_reg = 0;
6427 	scmd->satacmd_error_reg = 0;
6428 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
6429 	if (page->acoustic_manag_enable) {
6430 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
6431 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
6432 	} else {	/* disabling acoustic management */
6433 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
6434 	}
6435 
6436 	/* Transfer command to HBA */
6437 	if (sata_hba_start(spx, rval) != 0)
6438 		/*
6439 		 * Pkt not accepted for execution.
6440 		 */
6441 		return (SATA_FAILURE);
6442 
6443 	/* Now process return */
6444 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
6445 		sata_xlate_errors(spx);
6446 		return (SATA_FAILURE);
6447 	}
6448 
6449 	*dmod = 1;
6450 
6451 	return (SATA_SUCCESS);
6452 }
6453 
6454 
6455 
6456 
6457 /*
6458  * sata_build_lsense_page0() is used to create the
6459  * SCSI LOG SENSE page 0 (supported log pages)
6460  *
6461  * Currently supported pages are 0, 0x10, 0x2f and 0x30
6462  * (supported log pages, self-test results, informational exceptions
6463  *  and Sun vendor specific ATA SMART data).
6464  *
6465  * Takes a sata_drive_info t * and the address of a buffer
6466  * in which to create the page information.
6467  *
6468  * Returns the number of bytes valid in the buffer.
6469  */
6470 static	int
6471 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
6472 {
6473 	struct log_parameter *lpp = (struct log_parameter *)buf;
6474 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
6475 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
6476 	sata_id_t *sata_id = &sdinfo->satadrv_id;
6477 
6478 	lpp->param_code[0] = 0;
6479 	lpp->param_code[1] = 0;
6480 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
6481 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
6482 
6483 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
6484 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
6485 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
6486 			++num_pages_supported;
6487 		}
6488 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
6489 		++num_pages_supported;
6490 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
6491 		++num_pages_supported;
6492 	}
6493 
6494 	lpp->param_len = num_pages_supported;
6495 
6496 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
6497 	    num_pages_supported);
6498 }
6499 
6500 /*
6501  * sata_build_lsense_page_10() is used to create the
6502  * SCSI LOG SENSE page 0x10 (self-test results)
6503  *
6504  * Takes a sata_drive_info t * and the address of a buffer
6505  * in which to create the page information as well as a sata_hba_inst_t *.
6506  *
6507  * Returns the number of bytes valid in the buffer.
6508  *
6509  * Note: Self test and SMART data is accessible in device log pages.
6510  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
6511  * of data can be transferred by a single command), or by the General Purpose
6512  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
6513  * - approximately 33MB - can be transferred by a single command.
6514  * The SCT Command response (either error or command) is the same for both
6515  * the SMART and GPL methods of issuing commands.
6516  * This function uses READ LOG EXT command when drive supports LBA48, and
6517  * SMART READ command otherwise.
6518  *
6519  * Since above commands are executed in a synchronous mode, this function
6520  * should not be called in an interrupt context.
6521  */
6522 static	int
6523 sata_build_lsense_page_10(
6524 	sata_drive_info_t *sdinfo,
6525 	uint8_t *buf,
6526 	sata_hba_inst_t *sata_hba_inst)
6527 {
6528 	struct log_parameter *lpp = (struct log_parameter *)buf;
6529 	int rval;
6530 
6531 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
6532 		struct smart_ext_selftest_log *ext_selftest_log;
6533 
6534 		ext_selftest_log = kmem_zalloc(
6535 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
6536 
6537 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
6538 		    ext_selftest_log, 0);
6539 		if (rval == 0) {
6540 			int index, start_index;
6541 			struct smart_ext_selftest_log_entry *entry;
6542 			static const struct smart_ext_selftest_log_entry empty =
6543 			    {0};
6544 			uint16_t block_num;
6545 			int count;
6546 			boolean_t only_one_block = B_FALSE;
6547 
6548 			index = ext_selftest_log->
6549 			    smart_ext_selftest_log_index[0];
6550 			index |= ext_selftest_log->
6551 			    smart_ext_selftest_log_index[1] << 8;
6552 			if (index == 0)
6553 				goto out;
6554 
6555 			--index;	/* Correct for 0 origin */
6556 			start_index = index;	/* remember where we started */
6557 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6558 			if (block_num != 0) {
6559 				rval = sata_ext_smart_selftest_read_log(
6560 				    sata_hba_inst, sdinfo, ext_selftest_log,
6561 				    block_num);
6562 				if (rval != 0)
6563 					goto out;
6564 			}
6565 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6566 			entry =
6567 			    &ext_selftest_log->
6568 			    smart_ext_selftest_log_entries[index];
6569 
6570 			for (count = 1;
6571 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
6572 			    ++count) {
6573 				uint8_t status;
6574 				uint8_t code;
6575 				uint8_t sense_key;
6576 				uint8_t add_sense_code;
6577 				uint8_t add_sense_code_qual;
6578 
6579 				/* If this is an unused entry, we are done */
6580 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
6581 					/* Broken firmware on some disks */
6582 					if (index + 1 ==
6583 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
6584 						--entry;
6585 						--index;
6586 						if (bcmp(entry, &empty,
6587 						    sizeof (empty)) == 0)
6588 							goto out;
6589 					} else
6590 						goto out;
6591 				}
6592 
6593 				if (only_one_block &&
6594 				    start_index == index)
6595 					goto out;
6596 
6597 				lpp->param_code[0] = 0;
6598 				lpp->param_code[1] = count;
6599 				lpp->param_ctrl_flags =
6600 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
6601 				lpp->param_len =
6602 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
6603 
6604 				status = entry->smart_ext_selftest_log_status;
6605 				status >>= 4;
6606 				switch (status) {
6607 				case 0:
6608 				default:
6609 					sense_key = KEY_NO_SENSE;
6610 					add_sense_code =
6611 					    SD_SCSI_ASC_NO_ADD_SENSE;
6612 					add_sense_code_qual = 0;
6613 					break;
6614 				case 1:
6615 					sense_key = KEY_ABORTED_COMMAND;
6616 					add_sense_code =
6617 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6618 					add_sense_code_qual = SCSI_COMPONENT_81;
6619 					break;
6620 				case 2:
6621 					sense_key = KEY_ABORTED_COMMAND;
6622 					add_sense_code =
6623 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6624 					add_sense_code_qual = SCSI_COMPONENT_82;
6625 					break;
6626 				case 3:
6627 					sense_key = KEY_ABORTED_COMMAND;
6628 					add_sense_code =
6629 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6630 					add_sense_code_qual = SCSI_COMPONENT_83;
6631 					break;
6632 				case 4:
6633 					sense_key = KEY_HARDWARE_ERROR;
6634 					add_sense_code =
6635 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6636 					add_sense_code_qual = SCSI_COMPONENT_84;
6637 					break;
6638 				case 5:
6639 					sense_key = KEY_HARDWARE_ERROR;
6640 					add_sense_code =
6641 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6642 					add_sense_code_qual = SCSI_COMPONENT_85;
6643 					break;
6644 				case 6:
6645 					sense_key = KEY_HARDWARE_ERROR;
6646 					add_sense_code =
6647 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6648 					add_sense_code_qual = SCSI_COMPONENT_86;
6649 					break;
6650 				case 7:
6651 					sense_key = KEY_MEDIUM_ERROR;
6652 					add_sense_code =
6653 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6654 					add_sense_code_qual = SCSI_COMPONENT_87;
6655 					break;
6656 				case 8:
6657 					sense_key = KEY_HARDWARE_ERROR;
6658 					add_sense_code =
6659 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6660 					add_sense_code_qual = SCSI_COMPONENT_88;
6661 					break;
6662 				}
6663 				code = 0;	/* unspecified */
6664 				status |= (code << 4);
6665 				lpp->param_values[0] = status;
6666 				lpp->param_values[1] = 0; /* unspecified */
6667 				lpp->param_values[2] = entry->
6668 				    smart_ext_selftest_log_timestamp[1];
6669 				lpp->param_values[3] = entry->
6670 				    smart_ext_selftest_log_timestamp[0];
6671 				if (status != 0) {
6672 					lpp->param_values[4] = 0;
6673 					lpp->param_values[5] = 0;
6674 					lpp->param_values[6] = entry->
6675 					    smart_ext_selftest_log_failing_lba
6676 					    [5];
6677 					lpp->param_values[7] = entry->
6678 					    smart_ext_selftest_log_failing_lba
6679 					    [4];
6680 					lpp->param_values[8] = entry->
6681 					    smart_ext_selftest_log_failing_lba
6682 					    [3];
6683 					lpp->param_values[9] = entry->
6684 					    smart_ext_selftest_log_failing_lba
6685 					    [2];
6686 					lpp->param_values[10] = entry->
6687 					    smart_ext_selftest_log_failing_lba
6688 					    [1];
6689 					lpp->param_values[11] = entry->
6690 					    smart_ext_selftest_log_failing_lba
6691 					    [0];
6692 				} else {	/* No bad block address */
6693 					lpp->param_values[4] = 0xff;
6694 					lpp->param_values[5] = 0xff;
6695 					lpp->param_values[6] = 0xff;
6696 					lpp->param_values[7] = 0xff;
6697 					lpp->param_values[8] = 0xff;
6698 					lpp->param_values[9] = 0xff;
6699 					lpp->param_values[10] = 0xff;
6700 					lpp->param_values[11] = 0xff;
6701 				}
6702 
6703 				lpp->param_values[12] = sense_key;
6704 				lpp->param_values[13] = add_sense_code;
6705 				lpp->param_values[14] = add_sense_code_qual;
6706 				lpp->param_values[15] = 0; /* undefined */
6707 
6708 				lpp = (struct log_parameter *)
6709 				    (((uint8_t *)lpp) +
6710 				    SCSI_LOG_PARAM_HDR_LEN +
6711 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
6712 
6713 				--index;	/* Back up to previous entry */
6714 				if (index < 0) {
6715 					if (block_num > 0) {
6716 						--block_num;
6717 					} else {
6718 						struct read_log_ext_directory
6719 						    logdir;
6720 
6721 						rval =
6722 						    sata_read_log_ext_directory(
6723 						    sata_hba_inst, sdinfo,
6724 						    &logdir);
6725 						if (rval == -1)
6726 							goto out;
6727 						if ((logdir.read_log_ext_vers
6728 						    [0] == 0) &&
6729 						    (logdir.read_log_ext_vers
6730 						    [1] == 0))
6731 							goto out;
6732 						block_num =
6733 						    logdir.read_log_ext_nblks
6734 						    [EXT_SMART_SELFTEST_LOG_PAGE
6735 						    - 1][0];
6736 						block_num |= logdir.
6737 						    read_log_ext_nblks
6738 						    [EXT_SMART_SELFTEST_LOG_PAGE
6739 						    - 1][1] << 8;
6740 						--block_num;
6741 						only_one_block =
6742 						    (block_num == 0);
6743 					}
6744 					rval = sata_ext_smart_selftest_read_log(
6745 					    sata_hba_inst, sdinfo,
6746 					    ext_selftest_log, block_num);
6747 					if (rval != 0)
6748 						goto out;
6749 
6750 					index =
6751 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
6752 					    1;
6753 				}
6754 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
6755 				entry = &ext_selftest_log->
6756 				    smart_ext_selftest_log_entries[index];
6757 			}
6758 		}
6759 out:
6760 		kmem_free(ext_selftest_log,
6761 		    sizeof (struct smart_ext_selftest_log));
6762 	} else {
6763 		struct smart_selftest_log *selftest_log;
6764 
6765 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
6766 		    KM_SLEEP);
6767 
6768 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
6769 		    selftest_log);
6770 
6771 		if (rval == 0) {
6772 			int index;
6773 			int count;
6774 			struct smart_selftest_log_entry *entry;
6775 			static const struct smart_selftest_log_entry empty =
6776 			    { 0 };
6777 
6778 			index = selftest_log->smart_selftest_log_index;
6779 			if (index == 0)
6780 				goto done;
6781 			--index;	/* Correct for 0 origin */
6782 			entry = &selftest_log->
6783 			    smart_selftest_log_entries[index];
6784 			for (count = 1;
6785 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
6786 			    ++count) {
6787 				uint8_t status;
6788 				uint8_t code;
6789 				uint8_t sense_key;
6790 				uint8_t add_sense_code;
6791 				uint8_t add_sense_code_qual;
6792 
6793 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
6794 					goto done;
6795 
6796 				lpp->param_code[0] = 0;
6797 				lpp->param_code[1] = count;
6798 				lpp->param_ctrl_flags =
6799 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
6800 				lpp->param_len =
6801 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
6802 
6803 				status = entry->smart_selftest_log_status;
6804 				status >>= 4;
6805 				switch (status) {
6806 				case 0:
6807 				default:
6808 					sense_key = KEY_NO_SENSE;
6809 					add_sense_code =
6810 					    SD_SCSI_ASC_NO_ADD_SENSE;
6811 					break;
6812 				case 1:
6813 					sense_key = KEY_ABORTED_COMMAND;
6814 					add_sense_code =
6815 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6816 					add_sense_code_qual = SCSI_COMPONENT_81;
6817 					break;
6818 				case 2:
6819 					sense_key = KEY_ABORTED_COMMAND;
6820 					add_sense_code =
6821 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6822 					add_sense_code_qual = SCSI_COMPONENT_82;
6823 					break;
6824 				case 3:
6825 					sense_key = KEY_ABORTED_COMMAND;
6826 					add_sense_code =
6827 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6828 					add_sense_code_qual = SCSI_COMPONENT_83;
6829 					break;
6830 				case 4:
6831 					sense_key = KEY_HARDWARE_ERROR;
6832 					add_sense_code =
6833 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6834 					add_sense_code_qual = SCSI_COMPONENT_84;
6835 					break;
6836 				case 5:
6837 					sense_key = KEY_HARDWARE_ERROR;
6838 					add_sense_code =
6839 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6840 					add_sense_code_qual = SCSI_COMPONENT_85;
6841 					break;
6842 				case 6:
6843 					sense_key = KEY_HARDWARE_ERROR;
6844 					add_sense_code =
6845 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6846 					add_sense_code_qual = SCSI_COMPONENT_86;
6847 					break;
6848 				case 7:
6849 					sense_key = KEY_MEDIUM_ERROR;
6850 					add_sense_code =
6851 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6852 					add_sense_code_qual = SCSI_COMPONENT_87;
6853 					break;
6854 				case 8:
6855 					sense_key = KEY_HARDWARE_ERROR;
6856 					add_sense_code =
6857 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
6858 					add_sense_code_qual = SCSI_COMPONENT_88;
6859 					break;
6860 				}
6861 				code = 0;	/* unspecified */
6862 				status |= (code << 4);
6863 				lpp->param_values[0] = status;
6864 				lpp->param_values[1] = 0; /* unspecified */
6865 				lpp->param_values[2] = entry->
6866 				    smart_selftest_log_timestamp[1];
6867 				lpp->param_values[3] = entry->
6868 				    smart_selftest_log_timestamp[0];
6869 				if (status != 0) {
6870 					lpp->param_values[4] = 0;
6871 					lpp->param_values[5] = 0;
6872 					lpp->param_values[6] = 0;
6873 					lpp->param_values[7] = 0;
6874 					lpp->param_values[8] = entry->
6875 					    smart_selftest_log_failing_lba[3];
6876 					lpp->param_values[9] = entry->
6877 					    smart_selftest_log_failing_lba[2];
6878 					lpp->param_values[10] = entry->
6879 					    smart_selftest_log_failing_lba[1];
6880 					lpp->param_values[11] = entry->
6881 					    smart_selftest_log_failing_lba[0];
6882 				} else {	/* No block address */
6883 					lpp->param_values[4] = 0xff;
6884 					lpp->param_values[5] = 0xff;
6885 					lpp->param_values[6] = 0xff;
6886 					lpp->param_values[7] = 0xff;
6887 					lpp->param_values[8] = 0xff;
6888 					lpp->param_values[9] = 0xff;
6889 					lpp->param_values[10] = 0xff;
6890 					lpp->param_values[11] = 0xff;
6891 				}
6892 				lpp->param_values[12] = sense_key;
6893 				lpp->param_values[13] = add_sense_code;
6894 				lpp->param_values[14] = add_sense_code_qual;
6895 				lpp->param_values[15] = 0; /* undefined */
6896 
6897 				lpp = (struct log_parameter *)
6898 				    (((uint8_t *)lpp) +
6899 				    SCSI_LOG_PARAM_HDR_LEN +
6900 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
6901 				--index;	/* back up to previous entry */
6902 				if (index < 0) {
6903 					index =
6904 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
6905 				}
6906 				entry = &selftest_log->
6907 				    smart_selftest_log_entries[index];
6908 			}
6909 		}
6910 done:
6911 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
6912 	}
6913 
6914 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
6915 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
6916 }
6917 
6918 /*
6919  * sata_build_lsense_page_2f() is used to create the
6920  * SCSI LOG SENSE page 0x2f (informational exceptions)
6921  *
6922  * Takes a sata_drive_info t * and the address of a buffer
6923  * in which to create the page information as well as a sata_hba_inst_t *.
6924  *
6925  * Returns the number of bytes valid in the buffer.
6926  *
6927  * Because it invokes function(s) that send synchronously executed command
6928  * to the HBA, it cannot be called in the interrupt context.
6929  */
6930 static	int
6931 sata_build_lsense_page_2f(
6932 	sata_drive_info_t *sdinfo,
6933 	uint8_t *buf,
6934 	sata_hba_inst_t *sata_hba_inst)
6935 {
6936 	struct log_parameter *lpp = (struct log_parameter *)buf;
6937 	int rval;
6938 	uint8_t *smart_data;
6939 	uint8_t temp;
6940 	sata_id_t *sata_id;
6941 #define	SMART_NO_TEMP	0xff
6942 
6943 	lpp->param_code[0] = 0;
6944 	lpp->param_code[1] = 0;
6945 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
6946 
6947 	/* Now get the SMART status w.r.t. threshold exceeded */
6948 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
6949 	switch (rval) {
6950 	case 1:
6951 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
6952 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
6953 		break;
6954 	case 0:
6955 	case -1:	/* failed to get data */
6956 		lpp->param_values[0] = 0;	/* No failure predicted */
6957 		lpp->param_values[1] = 0;
6958 		break;
6959 #if defined(SATA_DEBUG)
6960 	default:
6961 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
6962 		/* NOTREACHED */
6963 #endif
6964 	}
6965 
6966 	sata_id = &sdinfo->satadrv_id;
6967 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
6968 		temp = SMART_NO_TEMP;
6969 	else {
6970 		/* Now get the temperature */
6971 		smart_data = kmem_zalloc(512, KM_SLEEP);
6972 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
6973 		    SCT_STATUS_LOG_PAGE, 1);
6974 		if (rval == -1)
6975 			temp = SMART_NO_TEMP;
6976 		else {
6977 			temp = smart_data[200];
6978 			if (temp & 0x80) {
6979 				if (temp & 0x7f)
6980 					temp = 0;
6981 				else
6982 					temp = SMART_NO_TEMP;
6983 			}
6984 		}
6985 		kmem_free(smart_data, 512);
6986 	}
6987 
6988 	lpp->param_values[2] = temp;	/* most recent temperature */
6989 	lpp->param_values[3] = 0;	/* required vendor specific byte */
6990 
6991 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
6992 
6993 
6994 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
6995 }
6996 
6997 /*
6998  * sata_build_lsense_page_30() is used to create the
6999  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
7000  *
7001  * Takes a sata_drive_info t * and the address of a buffer
7002  * in which to create the page information as well as a sata_hba_inst_t *.
7003  *
7004  * Returns the number of bytes valid in the buffer.
7005  */
7006 static int
7007 sata_build_lsense_page_30(
7008 	sata_drive_info_t *sdinfo,
7009 	uint8_t *buf,
7010 	sata_hba_inst_t *sata_hba_inst)
7011 {
7012 	struct smart_data *smart_data = (struct smart_data *)buf;
7013 	int rval;
7014 
7015 	/* Now do the SMART READ DATA */
7016 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
7017 	if (rval == -1)
7018 		return (0);
7019 
7020 	return (sizeof (struct smart_data));
7021 }
7022 
7023 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
7024 
7025 /*
7026  * Start command for ATAPI device.
7027  * This function processes scsi_pkt requests.
7028  * Now CD/DVD, tape and ATAPI disk devices are supported.
7029  * Most commands are packet without any translation into Packet Command.
7030  * Some may be trapped and executed as SATA commands (not clear which one).
7031  *
7032  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
7033  * execution).
7034  * Returns other TRAN_XXXX codes if command is not accepted or completed
7035  * (see return values for sata_hba_start()).
7036  *
7037  * Note:
7038  * Inquiry cdb format differs between transport version 2 and 3.
7039  * However, the transport version 3 devices that were checked did not adhere
7040  * to the specification (ignored MSB of the allocation length). Therefore,
7041  * the transport version is not checked, but Inquiry allocation length is
7042  * truncated to 255 bytes if the original allocation length set-up by the
7043  * target driver is greater than 255 bytes.
7044  */
7045 static int
7046 sata_txlt_atapi(sata_pkt_txlate_t *spx)
7047 {
7048 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7049 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7050 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7051 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
7052 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
7053 	    &spx->txlt_sata_pkt->satapkt_device);
7054 	int cport = SATA_TXLT_CPORT(spx);
7055 	int cdblen;
7056 	int rval, reason;
7057 	int synch;
7058 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
7059 
7060 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
7061 
7062 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason)) !=
7063 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
7064 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
7065 		return (rval);
7066 	}
7067 
7068 	/*
7069 	 * ATAPI device executes some ATA commands in addition to those
7070 	 * commands sent via PACKET command. These ATA commands may be
7071 	 * executed by the regular SATA translation functions. None needs
7072 	 * to be captured now.
7073 	 *
7074 	 * Commands sent via PACKET command include:
7075 	 *	MMC command set for ATAPI CD/DVD device
7076 	 *	SSC command set for ATAPI TAPE device
7077 	 *	SBC command set for ATAPI disk device
7078 	 *
7079 	 */
7080 
7081 	/* Check the size of cdb */
7082 	cdblen = scsi_cdb_size[GETGROUP(cdbp)];
7083 	if (cdblen > sdinfo->satadrv_atapi_cdb_len) {
7084 		sata_log(NULL, CE_WARN,
7085 		    "sata: invalid ATAPI cdb length %d",
7086 		    scsipkt->pkt_cdblen);
7087 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
7088 		return (TRAN_BADPKT);
7089 	}
7090 
7091 	SATAATAPITRACE(spx, cdblen);
7092 
7093 	/*
7094 	 * For non-read/write commands we need to
7095 	 * map buffer
7096 	 */
7097 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
7098 	case SCMD_READ:
7099 	case SCMD_READ_G1:
7100 	case SCMD_READ_G5:
7101 	case SCMD_READ_G4:
7102 	case SCMD_WRITE:
7103 	case SCMD_WRITE_G1:
7104 	case SCMD_WRITE_G5:
7105 	case SCMD_WRITE_G4:
7106 		break;
7107 	default:
7108 		if (bp != NULL) {
7109 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
7110 				bp_mapin(bp);
7111 		}
7112 		break;
7113 	}
7114 	/*
7115 	 * scmd->satacmd_flags.sata_data_direction default -
7116 	 * SATA_DIR_NODATA_XFER - is set by
7117 	 * sata_txlt_generic_pkt_info().
7118 	 */
7119 	if (scmd->satacmd_bp) {
7120 		if (scmd->satacmd_bp->b_flags & B_READ) {
7121 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
7122 		} else {
7123 			scmd->satacmd_flags.sata_data_direction =
7124 			    SATA_DIR_WRITE;
7125 		}
7126 	}
7127 
7128 	/*
7129 	 * Set up ATAPI packet command.
7130 	 */
7131 
7132 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
7133 
7134 	/* Copy cdb into sata_cmd */
7135 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
7136 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
7137 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
7138 
7139 	/* See note in the command header */
7140 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
7141 		if (scmd->satacmd_acdb[3] != 0)
7142 			scmd->satacmd_acdb[4] = 255;
7143 	}
7144 
7145 #ifdef SATA_DEBUG
7146 	if (sata_debug_flags & SATA_DBG_ATAPI) {
7147 		uint8_t *p = scmd->satacmd_acdb;
7148 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
7149 
7150 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
7151 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
7152 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
7153 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
7154 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
7155 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
7156 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
7157 	}
7158 #endif
7159 
7160 	/*
7161 	 * Preset request sense data to NO SENSE.
7162 	 * If there is no way to get error information via Request Sense,
7163 	 * the packet request sense data would not have to be modified by HBA,
7164 	 * but it could be returned as is.
7165 	 */
7166 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
7167 	sata_fixed_sense_data_preset(
7168 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
7169 
7170 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
7171 		/* Need callback function */
7172 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
7173 		synch = FALSE;
7174 	} else
7175 		synch = TRUE;
7176 
7177 	/* Transfer command to HBA */
7178 	if (sata_hba_start(spx, &rval) != 0) {
7179 		/* Pkt not accepted for execution */
7180 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
7181 		return (rval);
7182 	}
7183 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
7184 	/*
7185 	 * If execution is non-synchronous,
7186 	 * a callback function will handle potential errors, translate
7187 	 * the response and will do a callback to a target driver.
7188 	 * If it was synchronous, use the same framework callback to check
7189 	 * an execution status.
7190 	 */
7191 	if (synch) {
7192 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7193 		    "synchronous execution status %x\n",
7194 		    spx->txlt_sata_pkt->satapkt_reason);
7195 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
7196 	}
7197 	return (TRAN_ACCEPT);
7198 }
7199 
7200 
7201 /*
7202  * ATAPI Packet command completion.
7203  *
7204  * Failure of the command passed via Packet command are considered device
7205  * error. SATA HBA driver would have to retrieve error data (via Request
7206  * Sense command delivered via error retrieval sata packet) and copy it
7207  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
7208  */
7209 static void
7210 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
7211 {
7212 	sata_pkt_txlate_t *spx =
7213 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7214 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7215 	struct scsi_extended_sense *sense;
7216 	struct buf *bp;
7217 	int rval;
7218 
7219 #ifdef SATA_DEBUG
7220 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
7221 #endif
7222 
7223 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7224 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7225 
7226 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7227 		/* Normal completion */
7228 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
7229 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
7230 		scsipkt->pkt_reason = CMD_CMPLT;
7231 		*scsipkt->pkt_scbp = STATUS_GOOD;
7232 		if (spx->txlt_tmp_buf != NULL) {
7233 			/* Temporary buffer was used */
7234 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7235 			if (bp->b_flags & B_READ) {
7236 				rval = ddi_dma_sync(
7237 				    spx->txlt_buf_dma_handle, 0, 0,
7238 				    DDI_DMA_SYNC_FORCPU);
7239 				ASSERT(rval == DDI_SUCCESS);
7240 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7241 				    bp->b_bcount);
7242 			}
7243 		}
7244 	} else {
7245 		/*
7246 		 * Something went wrong - analyze return
7247 		 */
7248 		*scsipkt->pkt_scbp = STATUS_CHECK;
7249 		sense = sata_arq_sense(spx);
7250 
7251 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
7252 			/*
7253 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
7254 			 * Under this condition ERR bit is set for ATA command,
7255 			 * and CHK bit set for ATAPI command.
7256 			 *
7257 			 * Please check st_intr & sdintr about how pkt_reason
7258 			 * is used.
7259 			 */
7260 			scsipkt->pkt_reason = CMD_CMPLT;
7261 
7262 			/*
7263 			 * We may not have ARQ data if there was a double
7264 			 * error. But sense data in sata packet was pre-set
7265 			 * with NO SENSE so it is valid even if HBA could
7266 			 * not retrieve a real sense data.
7267 			 * Just copy this sense data into scsi pkt sense area.
7268 			 */
7269 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
7270 			    SATA_ATAPI_MIN_RQSENSE_LEN);
7271 #ifdef SATA_DEBUG
7272 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
7273 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
7274 				    "sata_txlt_atapi_completion: %02x\n"
7275 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
7276 				    "          %02x %02x %02x %02x %02x %02x "
7277 				    "          %02x %02x %02x %02x %02x %02x\n",
7278 				    scsipkt->pkt_reason,
7279 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
7280 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
7281 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
7282 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
7283 				    rqsp[16], rqsp[17]);
7284 			}
7285 #endif
7286 		} else {
7287 			switch (sata_pkt->satapkt_reason) {
7288 			case SATA_PKT_PORT_ERROR:
7289 				/*
7290 				 * We have no device data.
7291 				 */
7292 				scsipkt->pkt_reason = CMD_INCOMPLETE;
7293 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
7294 				    STATE_GOT_TARGET | STATE_SENT_CMD |
7295 				    STATE_GOT_STATUS);
7296 				sense->es_key = KEY_HARDWARE_ERROR;
7297 				break;
7298 
7299 			case SATA_PKT_TIMEOUT:
7300 				scsipkt->pkt_reason = CMD_TIMEOUT;
7301 				scsipkt->pkt_statistics |=
7302 				    STAT_TIMEOUT | STAT_DEV_RESET;
7303 				/*
7304 				 * Need to check if HARDWARE_ERROR/
7305 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
7306 				 * appropriate.
7307 				 */
7308 				break;
7309 
7310 			case SATA_PKT_ABORTED:
7311 				scsipkt->pkt_reason = CMD_ABORTED;
7312 				scsipkt->pkt_statistics |= STAT_ABORTED;
7313 				/* Should we set key COMMAND_ABPRTED? */
7314 				break;
7315 
7316 			case SATA_PKT_RESET:
7317 				scsipkt->pkt_reason = CMD_RESET;
7318 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
7319 				/*
7320 				 * May be we should set Unit Attention /
7321 				 * Reset. Perhaps the same should be
7322 				 * returned for disks....
7323 				 */
7324 				sense->es_key = KEY_UNIT_ATTENTION;
7325 				sense->es_add_code = SD_SCSI_ASC_RESET;
7326 				break;
7327 
7328 			default:
7329 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7330 				    "sata_txlt_atapi_completion: "
7331 				    "invalid packet completion reason"));
7332 				scsipkt->pkt_reason = CMD_TRAN_ERR;
7333 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
7334 				    STATE_GOT_TARGET | STATE_SENT_CMD |
7335 				    STATE_GOT_STATUS);
7336 				break;
7337 			}
7338 		}
7339 	}
7340 
7341 	SATAATAPITRACE(spx, 0);
7342 
7343 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
7344 	    scsipkt->pkt_comp != NULL) {
7345 		/* scsi callback required */
7346 		(*scsipkt->pkt_comp)(scsipkt);
7347 	}
7348 }
7349 
7350 /*
7351  * Set up error retrieval sata command for ATAPI Packet Command error data
7352  * recovery.
7353  *
7354  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
7355  * returns SATA_FAILURE otherwise.
7356  */
7357 
7358 static int
7359 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
7360 {
7361 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
7362 	sata_cmd_t *scmd;
7363 	struct buf *bp;
7364 
7365 	/*
7366 	 * Allocate dma-able buffer error data.
7367 	 * Buffer allocation will take care of buffer alignment and other DMA
7368 	 * attributes.
7369 	 */
7370 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
7371 	if (bp == NULL) {
7372 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
7373 		    "sata_get_err_retrieval_pkt: "
7374 		    "cannot allocate buffer for error data", NULL);
7375 		return (SATA_FAILURE);
7376 	}
7377 	bp_mapin(bp); /* make data buffer accessible */
7378 
7379 	/* Operation modes are up to the caller */
7380 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
7381 
7382 	/* Synchronous mode, no callback - may be changed by the caller */
7383 	spkt->satapkt_comp = NULL;
7384 	spkt->satapkt_time = sata_default_pkt_time;
7385 
7386 	scmd = &spkt->satapkt_cmd;
7387 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
7388 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
7389 
7390 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
7391 
7392 	/*
7393 	 * Set-up acdb. Request Sense CDB (packet command content) is
7394 	 * not in DMA-able buffer. Its handling is HBA-specific (how
7395 	 * it is transfered into packet FIS).
7396 	 */
7397 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
7398 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
7399 	/* Following zeroing of pad bytes may not be necessary */
7400 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
7401 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
7402 
7403 	/*
7404 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
7405 	 * before accessing it. Handle is in usual place in translate struct.
7406 	 */
7407 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
7408 
7409 	/*
7410 	 * Preset request sense data to NO SENSE.
7411 	 * Here it is redundant, only for a symetry with scsi-originated
7412 	 * packets. It should not be used for anything but debugging.
7413 	 */
7414 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
7415 	sata_fixed_sense_data_preset(
7416 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
7417 
7418 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
7419 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
7420 
7421 	return (SATA_SUCCESS);
7422 }
7423 
7424 /*
7425  * Set-up ATAPI packet command.
7426  * Data transfer direction has to be set-up in sata_cmd structure prior to
7427  * calling this function.
7428  *
7429  * Returns void
7430  */
7431 
7432 static void
7433 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
7434 {
7435 	scmd->satacmd_addr_type = 0;		/* N/A */
7436 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
7437 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
7438 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
7439 	scmd->satacmd_lba_high_lsb =
7440 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
7441 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
7442 
7443 	/*
7444 	 * We want all data to be transfered via DMA.
7445 	 * But specify it only if drive supports DMA and DMA mode is
7446 	 * selected - some drives are sensitive about it.
7447 	 * Hopefully it wil work for all drives....
7448 	 */
7449 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
7450 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
7451 
7452 	/*
7453 	 * Features register requires special care for devices that use
7454 	 * Serial ATA bridge - they need an explicit specification of
7455 	 * the data transfer direction for Packet DMA commands.
7456 	 * Setting this bit is harmless if DMA is not used.
7457 	 *
7458 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
7459 	 * spec they follow.
7460 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
7461 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
7462 	 * ATA/ATAPI-7 support is explicitly indicated.
7463 	 */
7464 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
7465 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
7466 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
7467 		/*
7468 		 * Specification of major version is valid and version 7
7469 		 * is supported. It does automatically imply that all
7470 		 * spec features are supported. For now, we assume that
7471 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
7472 		 */
7473 		if ((sdinfo->satadrv_id.ai_dirdma &
7474 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
7475 			if (scmd->satacmd_flags.sata_data_direction ==
7476 			    SATA_DIR_READ)
7477 			scmd->satacmd_features_reg |=
7478 			    SATA_ATAPI_F_DATA_DIR_READ;
7479 		}
7480 	}
7481 }
7482 
7483 
7484 #ifdef SATA_DEBUG
7485 
7486 /* Display 18 bytes of Inquiry data */
7487 static void
7488 sata_show_inqry_data(uint8_t *buf)
7489 {
7490 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
7491 	uint8_t *p;
7492 
7493 	cmn_err(CE_NOTE, "Inquiry data:");
7494 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
7495 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
7496 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
7497 	cmn_err(CE_NOTE, "ATAPI transport version %d",
7498 	    SATA_ATAPI_TRANS_VERSION(inq));
7499 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
7500 	    inq->inq_rdf, inq->inq_aenc);
7501 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
7502 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
7503 	p = (uint8_t *)inq->inq_vid;
7504 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
7505 	    "%02x %02x %02x %02x",
7506 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
7507 	p = (uint8_t *)inq->inq_vid;
7508 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
7509 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
7510 
7511 	p = (uint8_t *)inq->inq_pid;
7512 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
7513 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
7514 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
7515 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
7516 	p = (uint8_t *)inq->inq_pid;
7517 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
7518 	    "%c %c %c %c %c %c %c %c",
7519 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
7520 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
7521 
7522 	p = (uint8_t *)inq->inq_revision;
7523 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
7524 	    p[0], p[1], p[2], p[3]);
7525 	p = (uint8_t *)inq->inq_revision;
7526 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
7527 	    p[0], p[1], p[2], p[3]);
7528 
7529 }
7530 
7531 
7532 static void
7533 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
7534 {
7535 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
7536 
7537 	if (scsi_pkt == NULL)
7538 		return;
7539 	if (count != 0) {
7540 		/* saving cdb */
7541 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
7542 		    SATA_ATAPI_MAX_CDB_LEN);
7543 		bcopy(scsi_pkt->pkt_cdbp,
7544 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
7545 	} else {
7546 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
7547 		    sts_sensedata,
7548 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
7549 		    SATA_ATAPI_MIN_RQSENSE_LEN);
7550 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
7551 		    scsi_pkt->pkt_reason;
7552 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
7553 		    spx->txlt_sata_pkt->satapkt_reason;
7554 
7555 		if (++sata_atapi_trace_index >= 64)
7556 			sata_atapi_trace_index = 0;
7557 	}
7558 }
7559 
7560 #endif
7561 
7562 /*
7563  * Fetch inquiry data from ATAPI device
7564  * Returns SATA_SUCCESS if operation was successfull, SATA_FAILURE otherwise.
7565  *
7566  * Note:
7567  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
7568  * where the caller expects to see the inquiry data.
7569  *
7570  */
7571 
7572 static int
7573 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
7574     sata_address_t *saddr, struct scsi_inquiry *inq)
7575 {
7576 	sata_pkt_txlate_t *spx;
7577 	sata_pkt_t *spkt;
7578 	struct buf *bp;
7579 	sata_drive_info_t *sdinfo;
7580 	sata_cmd_t *scmd;
7581 	int rval;
7582 	uint8_t *rqsp;
7583 #ifdef SATA_DEBUG
7584 	char msg_buf[MAXPATHLEN];
7585 #endif
7586 
7587 	ASSERT(sata_hba != NULL);
7588 
7589 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
7590 	spx->txlt_sata_hba_inst = sata_hba;
7591 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
7592 	spkt = sata_pkt_alloc(spx, NULL);
7593 	if (spkt == NULL) {
7594 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
7595 		return (SATA_FAILURE);
7596 	}
7597 	/* address is needed now */
7598 	spkt->satapkt_device.satadev_addr = *saddr;
7599 
7600 	/* scsi_inquiry size buffer */
7601 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
7602 	if (bp == NULL) {
7603 		sata_pkt_free(spx);
7604 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
7605 		SATA_LOG_D((sata_hba, CE_WARN,
7606 		    "sata_get_atapi_inquiry_data: "
7607 		    "cannot allocate data buffer"));
7608 		return (SATA_FAILURE);
7609 	}
7610 	bp_mapin(bp); /* make data buffer accessible */
7611 
7612 	scmd = &spkt->satapkt_cmd;
7613 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
7614 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
7615 
7616 	/* Use synchronous mode */
7617 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
7618 	spkt->satapkt_comp = NULL;
7619 	spkt->satapkt_time = sata_default_pkt_time;
7620 
7621 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
7622 
7623 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
7624 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
7625 
7626 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
7627 	sdinfo = sata_get_device_info(sata_hba,
7628 	    &spx->txlt_sata_pkt->satapkt_device);
7629 	if (sdinfo == NULL) {
7630 		/* we have to be carefull about the disapearing device */
7631 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
7632 		rval = SATA_FAILURE;
7633 		goto cleanup;
7634 	}
7635 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
7636 
7637 	/*
7638 	 * Set-up acdb. This works for atapi transport version 2 and later.
7639 	 */
7640 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
7641 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
7642 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
7643 	scmd->satacmd_acdb[1] = 0x00;
7644 	scmd->satacmd_acdb[2] = 0x00;
7645 	scmd->satacmd_acdb[3] = 0x00;
7646 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
7647 	scmd->satacmd_acdb[5] = 0x00;
7648 
7649 	sata_fixed_sense_data_preset(
7650 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
7651 
7652 	/* Transfer command to HBA */
7653 	if (sata_hba_start(spx, &rval) != 0) {
7654 		/* Pkt not accepted for execution */
7655 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
7656 		    "sata_get_atapi_inquiry_data: "
7657 		    "Packet not accepted for execution - ret: %02x", rval);
7658 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
7659 		rval = SATA_FAILURE;
7660 		goto cleanup;
7661 	}
7662 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
7663 
7664 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
7665 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
7666 		    "sata_get_atapi_inquiry_data: "
7667 		    "Packet completed successfully - ret: %02x", rval);
7668 		if (spx->txlt_buf_dma_handle != NULL) {
7669 			/*
7670 			 * Sync buffer. Handle is in usual place in translate
7671 			 * struct.
7672 			 */
7673 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
7674 			    DDI_DMA_SYNC_FORCPU);
7675 			ASSERT(rval == DDI_SUCCESS);
7676 		}
7677 		/*
7678 		 * Normal completion - copy data into caller's buffer
7679 		 */
7680 		bcopy(bp->b_un.b_addr, (uint8_t *)inq,
7681 		    sizeof (struct scsi_inquiry));
7682 #ifdef SATA_DEBUG
7683 		if (sata_debug_flags & SATA_DBG_ATAPI) {
7684 			sata_show_inqry_data((uint8_t *)inq);
7685 		}
7686 #endif
7687 		rval = SATA_SUCCESS;
7688 	} else {
7689 		/*
7690 		 * Something went wrong - analyze return - check rqsense data
7691 		 */
7692 		rval = SATA_FAILURE;
7693 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
7694 			/*
7695 			 * ARQ data hopefull show something other than NO SENSE
7696 			 */
7697 			rqsp = scmd->satacmd_rqsense;
7698 #ifdef SATA_DEBUG
7699 			if (sata_debug_flags & SATA_DBG_ATAPI) {
7700 				msg_buf[0] = '\0';
7701 				(void) snprintf(msg_buf, MAXPATHLEN,
7702 				    "ATAPI packet completion reason: %02x\n"
7703 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
7704 				    "          %02x %02x %02x %02x %02x %02x\n"
7705 				    "          %02x %02x %02x %02x %02x %02x",
7706 				    spkt->satapkt_reason,
7707 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
7708 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
7709 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
7710 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
7711 				    rqsp[16], rqsp[17]);
7712 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
7713 				    "%s", msg_buf);
7714 			}
7715 #endif
7716 		} else {
7717 			switch (spkt->satapkt_reason) {
7718 			case SATA_PKT_PORT_ERROR:
7719 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7720 				    "sata_get_atapi_inquiry_data: "
7721 				    "packet reason: port error", NULL);
7722 				break;
7723 
7724 			case SATA_PKT_TIMEOUT:
7725 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7726 				    "sata_get_atapi_inquiry_data: "
7727 				    "packet reason: timeout", NULL);
7728 				break;
7729 
7730 			case SATA_PKT_ABORTED:
7731 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7732 				    "sata_get_atapi_inquiry_data: "
7733 				    "packet reason: aborted", NULL);
7734 				break;
7735 
7736 			case SATA_PKT_RESET:
7737 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7738 				    "sata_get_atapi_inquiry_data: "
7739 				    "packet reason: reset\n", NULL);
7740 				break;
7741 			default:
7742 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
7743 				    "sata_get_atapi_inquiry_data: "
7744 				    "invalid packet reason: %02x\n",
7745 				    spkt->satapkt_reason);
7746 				break;
7747 			}
7748 		}
7749 	}
7750 cleanup:
7751 	sata_free_local_buffer(spx);
7752 	sata_pkt_free(spx);
7753 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
7754 	return (rval);
7755 }
7756 
7757 
7758 
7759 
7760 
7761 #if 0
7762 #ifdef SATA_DEBUG
7763 
7764 /*
7765  * Test ATAPI packet command.
7766  * Single threaded test: send packet command in synch mode, process completion
7767  *
7768  */
7769 static void
7770 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
7771 {
7772 	sata_pkt_txlate_t *spx;
7773 	sata_pkt_t *spkt;
7774 	struct buf *bp;
7775 	sata_device_t sata_device;
7776 	sata_drive_info_t *sdinfo;
7777 	sata_cmd_t *scmd;
7778 	int rval;
7779 	uint8_t *rqsp;
7780 
7781 	ASSERT(sata_hba_inst != NULL);
7782 	sata_device.satadev_addr.cport = cport;
7783 	sata_device.satadev_addr.pmport = 0;
7784 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
7785 	sata_device.satadev_rev = SATA_DEVICE_REV;
7786 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7787 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
7788 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7789 	if (sdinfo == NULL) {
7790 		sata_log(sata_hba_inst, CE_WARN,
7791 		    "sata_test_atapi_packet_command: "
7792 		    "no device info for cport %d",
7793 		    sata_device.satadev_addr.cport);
7794 		return;
7795 	}
7796 
7797 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
7798 	spx->txlt_sata_hba_inst = sata_hba_inst;
7799 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
7800 	spkt = sata_pkt_alloc(spx, NULL);
7801 	if (spkt == NULL) {
7802 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
7803 		return;
7804 	}
7805 	/* address is needed now */
7806 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
7807 
7808 	/* 1024k buffer */
7809 	bp = sata_alloc_local_buffer(spx, 1024);
7810 	if (bp == NULL) {
7811 		sata_pkt_free(spx);
7812 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
7813 		sata_log(sata_hba_inst, CE_WARN,
7814 		    "sata_test_atapi_packet_command: "
7815 		    "cannot allocate data buffer");
7816 		return;
7817 	}
7818 	bp_mapin(bp); /* make data buffer accessible */
7819 
7820 	scmd = &spkt->satapkt_cmd;
7821 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
7822 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
7823 
7824 	/* Use synchronous mode */
7825 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
7826 
7827 	/* Synchronous mode, no callback - may be changed by the caller */
7828 	spkt->satapkt_comp = NULL;
7829 	spkt->satapkt_time = sata_default_pkt_time;
7830 
7831 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
7832 
7833 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
7834 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
7835 
7836 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
7837 
7838 	/* Set-up acdb. */
7839 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
7840 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
7841 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
7842 	scmd->satacmd_acdb[1] = 0x00;
7843 	scmd->satacmd_acdb[2] = 0x00;
7844 	scmd->satacmd_acdb[3] = 0x00;
7845 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
7846 	scmd->satacmd_acdb[5] = 0x00;
7847 
7848 	sata_fixed_sense_data_preset(
7849 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
7850 
7851 	/* Transfer command to HBA */
7852 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7853 	if (sata_hba_start(spx, &rval) != 0) {
7854 		/* Pkt not accepted for execution */
7855 		sata_log(sata_hba_inst, CE_WARN,
7856 		    "sata_test_atapi_packet_command: "
7857 		    "Packet not accepted for execution - ret: %02x", rval);
7858 		mutex_exit(
7859 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7860 		goto cleanup;
7861 	}
7862 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
7863 
7864 	if (spx->txlt_buf_dma_handle != NULL) {
7865 		/*
7866 		 * Sync buffer. Handle is in usual place in translate struct.
7867 		 */
7868 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
7869 		    DDI_DMA_SYNC_FORCPU);
7870 		ASSERT(rval == DDI_SUCCESS);
7871 	}
7872 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
7873 		sata_log(sata_hba_inst, CE_WARN,
7874 		    "sata_test_atapi_packet_command: "
7875 		    "Packet completed successfully");
7876 		/*
7877 		 * Normal completion - show inquiry data
7878 		 */
7879 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
7880 	} else {
7881 		/*
7882 		 * Something went wrong - analyze return - check rqsense data
7883 		 */
7884 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
7885 			/*
7886 			 * ARQ data hopefull show something other than NO SENSE
7887 			 */
7888 			rqsp = scmd->satacmd_rqsense;
7889 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
7890 			    "ATAPI packet completion reason: %02x\n"
7891 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
7892 			    "          %02x %02x %02x %02x %02x %02x "
7893 			    "          %02x %02x %02x %02x %02x %02x\n",
7894 			    spkt->satapkt_reason,
7895 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
7896 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
7897 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
7898 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
7899 			    rqsp[16], rqsp[17]);
7900 		} else {
7901 			switch (spkt->satapkt_reason) {
7902 			case SATA_PKT_PORT_ERROR:
7903 				sata_log(sata_hba_inst, CE_WARN,
7904 				    "sata_test_atapi_packet_command: "
7905 				    "packet reason: port error\n");
7906 				break;
7907 
7908 			case SATA_PKT_TIMEOUT:
7909 				sata_log(sata_hba_inst, CE_WARN,
7910 				    "sata_test_atapi_packet_command: "
7911 				    "packet reason: timeout\n");
7912 				break;
7913 
7914 			case SATA_PKT_ABORTED:
7915 				sata_log(sata_hba_inst, CE_WARN,
7916 				    "sata_test_atapi_packet_command: "
7917 				    "packet reason: aborted\n");
7918 				break;
7919 
7920 			case SATA_PKT_RESET:
7921 				sata_log(sata_hba_inst, CE_WARN,
7922 				    "sata_test_atapi_packet_command: "
7923 				    "packet reason: reset\n");
7924 				break;
7925 			default:
7926 				sata_log(sata_hba_inst, CE_WARN,
7927 				    "sata_test_atapi_packet_command: "
7928 				    "invalid packet reason: %02x\n",
7929 				    spkt->satapkt_reason);
7930 				break;
7931 			}
7932 		}
7933 	}
7934 cleanup:
7935 	sata_free_local_buffer(spx);
7936 	sata_pkt_free(spx);
7937 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
7938 }
7939 
7940 #endif /* SATA_DEBUG */
7941 #endif /* 1 */
7942 
7943 
7944 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
7945 
7946 /*
7947  * Validate sata_tran info
7948  * SATA_FAILURE returns if structure is inconsistent or structure revision
7949  * does not match one used by the framework.
7950  *
7951  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
7952  * required function pointers.
7953  * Returns SATA_FAILURE otherwise.
7954  */
7955 static int
7956 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
7957 {
7958 	/*
7959 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
7960 	 * of the SATA interface.
7961 	 */
7962 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
7963 		sata_log(NULL, CE_WARN,
7964 		    "sata: invalid sata_hba_tran version %d for driver %s",
7965 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
7966 		return (SATA_FAILURE);
7967 	}
7968 
7969 	if (dip != sata_tran->sata_tran_hba_dip) {
7970 		SATA_LOG_D((NULL, CE_WARN,
7971 		    "sata: inconsistent sata_tran_hba_dip "
7972 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
7973 		return (SATA_FAILURE);
7974 	}
7975 
7976 	if (sata_tran->sata_tran_probe_port == NULL ||
7977 	    sata_tran->sata_tran_start == NULL ||
7978 	    sata_tran->sata_tran_abort == NULL ||
7979 	    sata_tran->sata_tran_reset_dport == NULL ||
7980 	    sata_tran->sata_tran_hotplug_ops == NULL ||
7981 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
7982 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
7983 	    NULL) {
7984 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
7985 		    "required functions"));
7986 	}
7987 	return (SATA_SUCCESS);
7988 }
7989 
7990 /*
7991  * Remove HBA instance from sata_hba_list.
7992  */
7993 static void
7994 sata_remove_hba_instance(dev_info_t *dip)
7995 {
7996 	sata_hba_inst_t	*sata_hba_inst;
7997 
7998 	mutex_enter(&sata_mutex);
7999 	for (sata_hba_inst = sata_hba_list;
8000 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
8001 	    sata_hba_inst = sata_hba_inst->satahba_next) {
8002 		if (sata_hba_inst->satahba_dip == dip)
8003 			break;
8004 	}
8005 
8006 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
8007 #ifdef SATA_DEBUG
8008 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
8009 		    "unknown HBA instance\n");
8010 #endif
8011 		ASSERT(FALSE);
8012 	}
8013 	if (sata_hba_inst == sata_hba_list) {
8014 		sata_hba_list = sata_hba_inst->satahba_next;
8015 		if (sata_hba_list) {
8016 			sata_hba_list->satahba_prev =
8017 			    (struct sata_hba_inst *)NULL;
8018 		}
8019 		if (sata_hba_inst == sata_hba_list_tail) {
8020 			sata_hba_list_tail = NULL;
8021 		}
8022 	} else if (sata_hba_inst == sata_hba_list_tail) {
8023 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
8024 		if (sata_hba_list_tail) {
8025 			sata_hba_list_tail->satahba_next =
8026 			    (struct sata_hba_inst *)NULL;
8027 		}
8028 	} else {
8029 		sata_hba_inst->satahba_prev->satahba_next =
8030 		    sata_hba_inst->satahba_next;
8031 		sata_hba_inst->satahba_next->satahba_prev =
8032 		    sata_hba_inst->satahba_prev;
8033 	}
8034 	mutex_exit(&sata_mutex);
8035 }
8036 
8037 
8038 
8039 
8040 
8041 /*
8042  * Probe all SATA ports of the specified HBA instance.
8043  * The assumption is that there are no target and attachment point minor nodes
8044  * created by the boot subsystems, so we do not need to prune device tree.
8045  *
8046  * This function is called only from sata_hba_attach(). It does not have to
8047  * be protected by controller mutex, because the hba_attached flag is not set
8048  * yet and no one would be touching this HBA instance other than this thread.
8049  * Determines if port is active and what type of the device is attached
8050  * (if any). Allocates necessary structures for each port.
8051  *
8052  * An AP (Attachement Point) node is created for each SATA device port even
8053  * when there is no device attached.
8054  */
8055 
8056 static 	void
8057 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
8058 {
8059 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
8060 	int			ncport, npmport;
8061 	sata_cport_info_t 	*cportinfo;
8062 	sata_drive_info_t	*drive;
8063 	sata_pmult_info_t	*pminfo;
8064 	sata_pmport_info_t 	*pmportinfo;
8065 	sata_device_t		sata_device;
8066 	int			rval;
8067 	dev_t			minor_number;
8068 	char			name[16];
8069 	clock_t			start_time, cur_time;
8070 
8071 	/*
8072 	 * Probe controller ports first, to find port status and
8073 	 * any port multiplier attached.
8074 	 */
8075 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
8076 		/* allocate cport structure */
8077 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
8078 		ASSERT(cportinfo != NULL);
8079 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
8080 
8081 		mutex_enter(&cportinfo->cport_mutex);
8082 
8083 		cportinfo->cport_addr.cport = ncport;
8084 		cportinfo->cport_addr.pmport = 0;
8085 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
8086 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
8087 		cportinfo->cport_state |= SATA_STATE_PROBING;
8088 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
8089 
8090 		/*
8091 		 * Regardless if a port is usable or not, create
8092 		 * an attachment point
8093 		 */
8094 		mutex_exit(&cportinfo->cport_mutex);
8095 		minor_number =
8096 		    SATA_MAKE_AP_MINOR(ddi_get_instance(dip), ncport, 0, 0);
8097 		(void) sprintf(name, "%d", ncport);
8098 		if (ddi_create_minor_node(dip, name, S_IFCHR,
8099 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
8100 		    DDI_SUCCESS) {
8101 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
8102 			    "cannot create SATA attachment point for port %d",
8103 			    ncport);
8104 		}
8105 
8106 		/* Probe port */
8107 		start_time = ddi_get_lbolt();
8108 	reprobe_cport:
8109 		sata_device.satadev_addr.cport = ncport;
8110 		sata_device.satadev_addr.pmport = 0;
8111 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
8112 		sata_device.satadev_rev = SATA_DEVICE_REV;
8113 
8114 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
8115 		    (dip, &sata_device);
8116 
8117 		mutex_enter(&cportinfo->cport_mutex);
8118 		sata_update_port_scr(&cportinfo->cport_scr, &sata_device);
8119 		if (rval != SATA_SUCCESS) {
8120 			/* Something went wrong? Fail the port */
8121 			cportinfo->cport_state = SATA_PSTATE_FAILED;
8122 			mutex_exit(&cportinfo->cport_mutex);
8123 			continue;
8124 		}
8125 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
8126 		cportinfo->cport_state |= SATA_STATE_PROBED;
8127 		cportinfo->cport_dev_type = sata_device.satadev_type;
8128 
8129 		cportinfo->cport_state |= SATA_STATE_READY;
8130 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
8131 			mutex_exit(&cportinfo->cport_mutex);
8132 			continue;
8133 		}
8134 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
8135 			/*
8136 			 * There is some device attached.
8137 			 * Allocate device info structure
8138 			 */
8139 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
8140 				mutex_exit(&cportinfo->cport_mutex);
8141 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
8142 				    kmem_zalloc(sizeof (sata_drive_info_t),
8143 				    KM_SLEEP);
8144 				mutex_enter(&cportinfo->cport_mutex);
8145 			}
8146 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
8147 			drive->satadrv_addr = cportinfo->cport_addr;
8148 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
8149 			drive->satadrv_type = cportinfo->cport_dev_type;
8150 			drive->satadrv_state = SATA_STATE_UNKNOWN;
8151 
8152 			mutex_exit(&cportinfo->cport_mutex);
8153 			if (sata_add_device(dip, sata_hba_inst, ncport, 0) !=
8154 			    SATA_SUCCESS) {
8155 				/*
8156 				 * Plugged device was not correctly identified.
8157 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
8158 				 */
8159 				cur_time = ddi_get_lbolt();
8160 				if ((cur_time - start_time) <
8161 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
8162 					/* sleep for a while */
8163 					delay(drv_usectohz(
8164 					    SATA_DEV_RETRY_DLY));
8165 					goto reprobe_cport;
8166 				}
8167 			}
8168 		} else {
8169 			mutex_exit(&cportinfo->cport_mutex);
8170 			ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
8171 			pminfo = kmem_zalloc(sizeof (sata_pmult_info_t),
8172 			    KM_SLEEP);
8173 			mutex_enter(&cportinfo->cport_mutex);
8174 			ASSERT(pminfo != NULL);
8175 			SATA_CPORTINFO_PMULT_INFO(cportinfo) = pminfo;
8176 			pminfo->pmult_addr.cport = cportinfo->cport_addr.cport;
8177 			pminfo->pmult_addr.pmport = SATA_PMULT_HOSTPORT;
8178 			pminfo->pmult_addr.qual = SATA_ADDR_PMPORT;
8179 			pminfo->pmult_num_dev_ports =
8180 			    sata_device.satadev_add_info;
8181 			mutex_init(&pminfo->pmult_mutex, NULL, MUTEX_DRIVER,
8182 			    NULL);
8183 			pminfo->pmult_state = SATA_STATE_PROBING;
8184 			mutex_exit(&cportinfo->cport_mutex);
8185 
8186 			/* Probe Port Multiplier ports */
8187 			for (npmport = 0;
8188 			    npmport < pminfo->pmult_num_dev_ports;
8189 			    npmport++) {
8190 				pmportinfo = kmem_zalloc(
8191 				    sizeof (sata_pmport_info_t), KM_SLEEP);
8192 				mutex_enter(&cportinfo->cport_mutex);
8193 				ASSERT(pmportinfo != NULL);
8194 				pmportinfo->pmport_addr.cport = ncport;
8195 				pmportinfo->pmport_addr.pmport = npmport;
8196 				pmportinfo->pmport_addr.qual =
8197 				    SATA_ADDR_PMPORT;
8198 				pminfo->pmult_dev_port[npmport] = pmportinfo;
8199 
8200 				mutex_init(&pmportinfo->pmport_mutex, NULL,
8201 				    MUTEX_DRIVER, NULL);
8202 
8203 				mutex_exit(&cportinfo->cport_mutex);
8204 
8205 				/* Create an attachment point */
8206 				minor_number = SATA_MAKE_AP_MINOR(
8207 				    ddi_get_instance(dip), ncport, npmport, 1);
8208 				(void) sprintf(name, "%d.%d", ncport, npmport);
8209 				if (ddi_create_minor_node(dip, name, S_IFCHR,
8210 				    minor_number, DDI_NT_SATA_ATTACHMENT_POINT,
8211 				    0) != DDI_SUCCESS) {
8212 					sata_log(sata_hba_inst, CE_WARN,
8213 					    "sata_hba_attach: "
8214 					    "cannot create SATA attachment "
8215 					    "point for port %d pmult port %d",
8216 					    ncport, npmport);
8217 				}
8218 
8219 				start_time = ddi_get_lbolt();
8220 			reprobe_pmport:
8221 				sata_device.satadev_addr.pmport = npmport;
8222 				sata_device.satadev_addr.qual =
8223 				    SATA_ADDR_PMPORT;
8224 
8225 				rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
8226 				    (dip, &sata_device);
8227 				mutex_enter(&cportinfo->cport_mutex);
8228 
8229 				/* sata_update_port_info() */
8230 				sata_update_port_scr(&pmportinfo->pmport_scr,
8231 				    &sata_device);
8232 
8233 				if (rval != SATA_SUCCESS) {
8234 					pmportinfo->pmport_state =
8235 					    SATA_PSTATE_FAILED;
8236 					mutex_exit(&cportinfo->cport_mutex);
8237 					continue;
8238 				}
8239 				pmportinfo->pmport_state &=
8240 				    ~SATA_STATE_PROBING;
8241 				pmportinfo->pmport_state |= SATA_STATE_PROBED;
8242 				pmportinfo->pmport_dev_type =
8243 				    sata_device.satadev_type;
8244 
8245 				pmportinfo->pmport_state |= SATA_STATE_READY;
8246 				if (pmportinfo->pmport_dev_type ==
8247 				    SATA_DTYPE_NONE) {
8248 					mutex_exit(&cportinfo->cport_mutex);
8249 					continue;
8250 				}
8251 				/* Port multipliers cannot be chained */
8252 				ASSERT(pmportinfo->pmport_dev_type !=
8253 				    SATA_DTYPE_PMULT);
8254 				/*
8255 				 * There is something attached to Port
8256 				 * Multiplier device port
8257 				 * Allocate device info structure
8258 				 */
8259 				if (pmportinfo->pmport_sata_drive == NULL) {
8260 					mutex_exit(&cportinfo->cport_mutex);
8261 					pmportinfo->pmport_sata_drive =
8262 					    kmem_zalloc(
8263 					    sizeof (sata_drive_info_t),
8264 					    KM_SLEEP);
8265 					mutex_enter(&cportinfo->cport_mutex);
8266 				}
8267 				drive = pmportinfo->pmport_sata_drive;
8268 				drive->satadrv_addr.cport =
8269 				    pmportinfo->pmport_addr.cport;
8270 				drive->satadrv_addr.pmport = npmport;
8271 				drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
8272 				drive->satadrv_type = pmportinfo->
8273 				    pmport_dev_type;
8274 				drive->satadrv_state = SATA_STATE_UNKNOWN;
8275 
8276 				mutex_exit(&cportinfo->cport_mutex);
8277 				if (sata_add_device(dip, sata_hba_inst, ncport,
8278 				    npmport) != SATA_SUCCESS) {
8279 					/*
8280 					 * Plugged device was not correctly
8281 					 * identified. Retry, within the
8282 					 * SATA_DEV_IDENTIFY_TIMEOUT
8283 					 */
8284 					cur_time = ddi_get_lbolt();
8285 					if ((cur_time - start_time) <
8286 					    drv_usectohz(
8287 					    SATA_DEV_IDENTIFY_TIMEOUT)) {
8288 						/* sleep for a while */
8289 						delay(drv_usectohz(
8290 						    SATA_DEV_RETRY_DLY));
8291 						goto reprobe_pmport;
8292 					}
8293 				}
8294 			}
8295 			pmportinfo->pmport_state =
8296 			    SATA_STATE_PROBED | SATA_STATE_READY;
8297 		}
8298 	}
8299 }
8300 
8301 /*
8302  * Add SATA device for specified HBA instance & port (SCSI target
8303  * device nodes).
8304  * This function is called (indirectly) only from sata_hba_attach().
8305  * A target node is created when there is a supported type device attached,
8306  * but may be removed if it cannot be put online.
8307  *
8308  * This function cannot be called from an interrupt context.
8309  *
8310  * ONLY DISK TARGET NODES ARE CREATED NOW
8311  *
8312  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
8313  * device identification failed - adding a device could be retried.
8314  *
8315  */
8316 static 	int
8317 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst, int cport,
8318     int pmport)
8319 {
8320 	sata_cport_info_t 	*cportinfo;
8321 	sata_pmult_info_t	*pminfo;
8322 	sata_pmport_info_t	*pmportinfo;
8323 	dev_info_t		*cdip;		/* child dip */
8324 	sata_device_t		sata_device;
8325 	int			rval;
8326 
8327 
8328 
8329 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
8330 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
8331 	mutex_enter(&cportinfo->cport_mutex);
8332 	/*
8333 	 * Some device is attached to a controller port.
8334 	 * We rely on controllers distinquishing between no-device,
8335 	 * attached port multiplier and other kind of attached device.
8336 	 * We need to get Identify Device data and determine
8337 	 * positively the dev type before trying to attach
8338 	 * the target driver.
8339 	 */
8340 	sata_device.satadev_rev = SATA_DEVICE_REV;
8341 	if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
8342 		/*
8343 		 * Not port multiplier.
8344 		 */
8345 		sata_device.satadev_addr = cportinfo->cport_addr;
8346 		sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
8347 		mutex_exit(&cportinfo->cport_mutex);
8348 
8349 		rval = sata_probe_device(sata_hba_inst, &sata_device);
8350 		if (rval != SATA_SUCCESS ||
8351 		    sata_device.satadev_type == SATA_DTYPE_UNKNOWN)
8352 			return (SATA_FAILURE);
8353 
8354 		mutex_enter(&cportinfo->cport_mutex);
8355 		sata_show_drive_info(sata_hba_inst,
8356 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
8357 
8358 		if ((sata_device.satadev_type & SATA_VALID_DEV_TYPE) == 0) {
8359 			/*
8360 			 * Could not determine device type or
8361 			 * a device is not supported.
8362 			 * Degrade this device to unknown.
8363 			 */
8364 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
8365 			mutex_exit(&cportinfo->cport_mutex);
8366 			return (SATA_SUCCESS);
8367 		}
8368 		cportinfo->cport_dev_type = sata_device.satadev_type;
8369 		cportinfo->cport_tgtnode_clean = B_TRUE;
8370 		mutex_exit(&cportinfo->cport_mutex);
8371 
8372 		/*
8373 		 * Initialize device to the desired state. Even if it
8374 		 * fails, the device will still attach but syslog
8375 		 * will show the warning.
8376 		 */
8377 		if (sata_initialize_device(sata_hba_inst,
8378 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
8379 			/* Retry */
8380 			rval = sata_initialize_device(sata_hba_inst,
8381 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
8382 
8383 			if (rval == SATA_RETRY)
8384 				sata_log(sata_hba_inst, CE_WARN,
8385 				    "SATA device at port %d - "
8386 				    "default device features could not be set."
8387 				    " Device may not operate as expected.",
8388 				    cportinfo->cport_addr.cport);
8389 		}
8390 
8391 		cdip = sata_create_target_node(pdip, sata_hba_inst,
8392 		    &sata_device.satadev_addr);
8393 		mutex_enter(&cportinfo->cport_mutex);
8394 		if (cdip == NULL) {
8395 			/*
8396 			 * Attaching target node failed.
8397 			 * We retain sata_drive_info structure...
8398 			 */
8399 			mutex_exit(&cportinfo->cport_mutex);
8400 			return (SATA_SUCCESS);
8401 		}
8402 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
8403 		    satadrv_state = SATA_STATE_READY;
8404 	} else {
8405 		/* This must be Port Multiplier type */
8406 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
8407 			SATA_LOG_D((sata_hba_inst, CE_WARN,
8408 			    "sata_add_device: "
8409 			    "unrecognized dev type %x",
8410 			    cportinfo->cport_dev_type));
8411 			mutex_exit(&cportinfo->cport_mutex);
8412 			return (SATA_SUCCESS);
8413 		}
8414 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
8415 		pmportinfo = pminfo->pmult_dev_port[pmport];
8416 		sata_device.satadev_addr = pmportinfo->pmport_addr;
8417 		sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
8418 		mutex_exit(&cportinfo->cport_mutex);
8419 
8420 		rval = sata_probe_device(sata_hba_inst, &sata_device);
8421 		if (rval != SATA_SUCCESS ||
8422 		    sata_device.satadev_type == SATA_DTYPE_UNKNOWN) {
8423 			return (SATA_FAILURE);
8424 		}
8425 		mutex_enter(&cportinfo->cport_mutex);
8426 		sata_show_drive_info(sata_hba_inst,
8427 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
8428 
8429 		if ((sata_device.satadev_type & SATA_VALID_DEV_TYPE) == 0) {
8430 			/*
8431 			 * Could not determine device type.
8432 			 * Degrade this device to unknown.
8433 			 */
8434 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
8435 			mutex_exit(&cportinfo->cport_mutex);
8436 			return (SATA_SUCCESS);
8437 		}
8438 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
8439 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
8440 		mutex_exit(&cportinfo->cport_mutex);
8441 
8442 		/*
8443 		 * Initialize device to the desired state.
8444 		 * Even if it fails, the device will still
8445 		 * attach but syslog will show the warning.
8446 		 */
8447 		if (sata_initialize_device(sata_hba_inst,
8448 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
8449 			/* Retry */
8450 			rval = sata_initialize_device(sata_hba_inst,
8451 			    pmportinfo->pmport_sata_drive);
8452 
8453 			if (rval == SATA_RETRY)
8454 				sata_log(sata_hba_inst, CE_WARN,
8455 				    "SATA device at port %d pmport %d - "
8456 				    "default device features could not be set."
8457 				    " Device may not operate as expected.",
8458 				    pmportinfo->pmport_addr.cport,
8459 				    pmportinfo->pmport_addr.pmport);
8460 		}
8461 		cdip = sata_create_target_node(pdip, sata_hba_inst,
8462 		    &sata_device.satadev_addr);
8463 		mutex_enter(&cportinfo->cport_mutex);
8464 		if (cdip == NULL) {
8465 			/*
8466 			 * Attaching target node failed.
8467 			 * We retain sata_drive_info structure...
8468 			 */
8469 			mutex_exit(&cportinfo->cport_mutex);
8470 			return (SATA_SUCCESS);
8471 		}
8472 		pmportinfo->pmport_sata_drive->satadrv_state |=
8473 		    SATA_STATE_READY;
8474 	}
8475 	mutex_exit(&cportinfo->cport_mutex);
8476 	return (SATA_SUCCESS);
8477 }
8478 
8479 
8480 
8481 /*
8482  * Create scsi target node for attached device, create node properties and
8483  * attach the node.
8484  * The node could be removed if the device onlining fails.
8485  *
8486  * A dev_info_t pointer is returned if operation is successful, NULL is
8487  * returned otherwise.
8488  *
8489  * No port multiplier support.
8490  */
8491 
8492 static dev_info_t *
8493 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
8494 			sata_address_t *sata_addr)
8495 {
8496 	dev_info_t *cdip = NULL;
8497 	int rval;
8498 	char *nname = NULL;
8499 	char **compatible = NULL;
8500 	int ncompatible;
8501 	struct scsi_inquiry inq;
8502 	sata_device_t sata_device;
8503 	sata_drive_info_t *sdinfo;
8504 	int target;
8505 	int i;
8506 
8507 	sata_device.satadev_rev = SATA_DEVICE_REV;
8508 	sata_device.satadev_addr = *sata_addr;
8509 
8510 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
8511 
8512 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
8513 
8514 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
8515 	    sata_addr->pmport, sata_addr->qual);
8516 
8517 	if (sdinfo == NULL) {
8518 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8519 		    sata_addr->cport)));
8520 		SATA_LOG_D((sata_hba_inst, CE_WARN,
8521 		    "sata_create_target_node: no sdinfo for target %x",
8522 		    target));
8523 		return (NULL);
8524 	}
8525 
8526 	/*
8527 	 * create or get scsi inquiry data, expected by
8528 	 * scsi_hba_nodename_compatible_get()
8529 	 * SATA hard disks get Identify Data translated into Inguiry Data.
8530 	 * ATAPI devices respond directly to Inquiry request.
8531 	 */
8532 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
8533 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
8534 		    (uint8_t *)&inq);
8535 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8536 		    sata_addr->cport)));
8537 	} else { /* Assume supported ATAPI device */
8538 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
8539 		    sata_addr->cport)));
8540 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
8541 		    &inq) == SATA_FAILURE)
8542 			return (NULL);
8543 		/*
8544 		 * Save supported ATAPI transport version
8545 		 */
8546 		sdinfo->satadrv_atapi_trans_ver =
8547 		    SATA_ATAPI_TRANS_VERSION(&inq);
8548 	}
8549 
8550 	/* determine the node name and compatible */
8551 	scsi_hba_nodename_compatible_get(&inq, NULL,
8552 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
8553 
8554 #ifdef SATA_DEBUG
8555 	if (sata_debug_flags & SATA_DBG_NODES) {
8556 		if (nname == NULL) {
8557 			cmn_err(CE_NOTE, "sata_create_target_node: "
8558 			    "cannot determine nodename for target %d\n",
8559 			    target);
8560 		} else {
8561 			cmn_err(CE_WARN, "sata_create_target_node: "
8562 			    "target %d nodename: %s\n", target, nname);
8563 		}
8564 		if (compatible == NULL) {
8565 			cmn_err(CE_WARN,
8566 			    "sata_create_target_node: no compatible name\n");
8567 		} else {
8568 			for (i = 0; i < ncompatible; i++) {
8569 				cmn_err(CE_WARN, "sata_create_target_node: "
8570 				    "compatible name: %s\n", compatible[i]);
8571 			}
8572 		}
8573 	}
8574 #endif
8575 
8576 	/* if nodename can't be determined, log error and exit */
8577 	if (nname == NULL) {
8578 		SATA_LOG_D((sata_hba_inst, CE_WARN,
8579 		    "sata_create_target_node: cannot determine nodename "
8580 		    "for target %d\n", target));
8581 		scsi_hba_nodename_compatible_free(nname, compatible);
8582 		return (NULL);
8583 	}
8584 	/*
8585 	 * Create scsi target node
8586 	 */
8587 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
8588 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
8589 	    "device-type", "scsi");
8590 
8591 	if (rval != DDI_PROP_SUCCESS) {
8592 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
8593 		    "updating device_type prop failed %d", rval));
8594 		goto fail;
8595 	}
8596 
8597 	/*
8598 	 * Create target node properties: target & lun
8599 	 */
8600 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
8601 	if (rval != DDI_PROP_SUCCESS) {
8602 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
8603 		    "updating target prop failed %d", rval));
8604 		goto fail;
8605 	}
8606 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
8607 	if (rval != DDI_PROP_SUCCESS) {
8608 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
8609 		    "updating target prop failed %d", rval));
8610 		goto fail;
8611 	}
8612 
8613 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
8614 		/*
8615 		 * Add "variant" property
8616 		 */
8617 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
8618 		    "variant", "atapi");
8619 		if (rval != DDI_PROP_SUCCESS) {
8620 			SATA_LOG_D((sata_hba_inst, CE_WARN,
8621 			    "sata_create_target_node: variant atapi "
8622 			    "property could not be created: %d", rval));
8623 			goto fail;
8624 		}
8625 	}
8626 	/* decorate the node with compatible */
8627 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
8628 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
8629 		SATA_LOG_D((sata_hba_inst, CE_WARN,
8630 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
8631 		    (void *)cdip));
8632 		goto fail;
8633 	}
8634 
8635 
8636 	/*
8637 	 * Now, try to attach the driver. If probing of the device fails,
8638 	 * the target node may be removed
8639 	 */
8640 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
8641 
8642 	scsi_hba_nodename_compatible_free(nname, compatible);
8643 
8644 	if (rval == NDI_SUCCESS)
8645 		return (cdip);
8646 
8647 	/* target node was removed - are we sure? */
8648 	return (NULL);
8649 
8650 fail:
8651 	scsi_hba_nodename_compatible_free(nname, compatible);
8652 	ddi_prop_remove_all(cdip);
8653 	rval = ndi_devi_free(cdip);
8654 	if (rval != NDI_SUCCESS) {
8655 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
8656 		    "node removal failed %d", rval));
8657 	}
8658 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
8659 	    "cannot create target node for SATA device at port %d",
8660 	    sata_addr->cport);
8661 	return (NULL);
8662 }
8663 
8664 
8665 
8666 /*
8667  * Re-probe sata port, check for a device and attach info
8668  * structures when necessary. Identify Device data is fetched, if possible.
8669  * Assumption: sata address is already validated.
8670  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
8671  * the presence of a device and its type.
8672  *
8673  * flag arg specifies that the function should try multiple times to identify
8674  * device type and to initialize it, or it should return immediately on failure.
8675  * SATA_DEV_IDENTIFY_RETRY - retry
8676  * SATA_DEV_IDENTIFY_NORETRY - no retry
8677  *
8678  * SATA_FAILURE is returned if one of the operations failed.
8679  *
8680  * This function cannot be called in interrupt context - it may sleep.
8681  *
8682  * NOte: Port multiplier is not supported yet, although there may be some
8683  * pieces of code referencing to it.
8684  */
8685 static int
8686 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
8687     int flag)
8688 {
8689 	sata_cport_info_t *cportinfo;
8690 	sata_drive_info_t *sdinfo, *osdinfo;
8691 	boolean_t init_device = B_FALSE;
8692 	int prev_device_type = SATA_DTYPE_NONE;
8693 	int prev_device_settings = 0;
8694 	int prev_device_state = 0;
8695 	clock_t start_time;
8696 	int retry = B_FALSE;
8697 	int rval_probe, rval_init;
8698 
8699 	/* We only care about host sata cport for now */
8700 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
8701 	    sata_device->satadev_addr.cport);
8702 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
8703 	if (osdinfo != NULL) {
8704 		/*
8705 		 * We are re-probing port with a previously attached device.
8706 		 * Save previous device type and settings.
8707 		 */
8708 		prev_device_type = cportinfo->cport_dev_type;
8709 		prev_device_settings = osdinfo->satadrv_settings;
8710 		prev_device_state = osdinfo->satadrv_state;
8711 	}
8712 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
8713 		start_time = ddi_get_lbolt();
8714 		retry = B_TRUE;
8715 	}
8716 retry_probe:
8717 
8718 	/* probe port */
8719 	mutex_enter(&cportinfo->cport_mutex);
8720 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
8721 	cportinfo->cport_state |= SATA_STATE_PROBING;
8722 	mutex_exit(&cportinfo->cport_mutex);
8723 
8724 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
8725 	    (SATA_DIP(sata_hba_inst), sata_device);
8726 
8727 	mutex_enter(&cportinfo->cport_mutex);
8728 	if (rval_probe != SATA_SUCCESS) {
8729 		cportinfo->cport_state = SATA_PSTATE_FAILED;
8730 		mutex_exit(&cportinfo->cport_mutex);
8731 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
8732 		    "SATA port %d probing failed",
8733 		    cportinfo->cport_addr.cport));
8734 		return (SATA_FAILURE);
8735 	}
8736 
8737 	/*
8738 	 * update sata port state and set device type
8739 	 */
8740 	sata_update_port_info(sata_hba_inst, sata_device);
8741 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
8742 
8743 	/*
8744 	 * Sanity check - Port is active? Is the link active?
8745 	 * Is there any device attached?
8746 	 */
8747 	if ((cportinfo->cport_state &
8748 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
8749 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
8750 	    SATA_PORT_DEVLINK_UP) {
8751 		/*
8752 		 * Port in non-usable state or no link active/no device.
8753 		 * Free info structure if necessary (direct attached drive
8754 		 * only, for now!
8755 		 */
8756 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
8757 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
8758 		/* Add here differentiation for device attached or not */
8759 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
8760 		mutex_exit(&cportinfo->cport_mutex);
8761 		if (sdinfo != NULL)
8762 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
8763 		return (SATA_SUCCESS);
8764 	}
8765 
8766 	cportinfo->cport_state |= SATA_STATE_READY;
8767 	cportinfo->cport_dev_type = sata_device->satadev_type;
8768 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
8769 
8770 	/*
8771 	 * If we are re-probing the port, there may be
8772 	 * sata_drive_info structure attached
8773 	 * (or sata_pm_info, if PMult is supported).
8774 	 */
8775 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
8776 		/*
8777 		 * There is no device, so remove device info structure,
8778 		 * if necessary.
8779 		 * Only direct attached drive is considered now, until
8780 		 * port multiplier is supported. If the previously
8781 		 * attached device was a port multiplier, we would need
8782 		 * to take care of devices attached beyond the port
8783 		 * multiplier.
8784 		 */
8785 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
8786 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
8787 		if (sdinfo != NULL) {
8788 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
8789 			sata_log(sata_hba_inst, CE_WARN,
8790 			    "SATA device detached "
8791 			    "from port %d", cportinfo->cport_addr.cport);
8792 		}
8793 		mutex_exit(&cportinfo->cport_mutex);
8794 		return (SATA_SUCCESS);
8795 	}
8796 
8797 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
8798 		if (sdinfo == NULL) {
8799 			/*
8800 			 * There is some device attached, but there is
8801 			 * no sata_drive_info structure - allocate one
8802 			 */
8803 			mutex_exit(&cportinfo->cport_mutex);
8804 			sdinfo = kmem_zalloc(
8805 			    sizeof (sata_drive_info_t), KM_SLEEP);
8806 			mutex_enter(&cportinfo->cport_mutex);
8807 			/*
8808 			 * Recheck, that the port state did not change when we
8809 			 * released mutex.
8810 			 */
8811 			if (cportinfo->cport_state & SATA_STATE_READY) {
8812 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
8813 				sdinfo->satadrv_addr = cportinfo->cport_addr;
8814 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
8815 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
8816 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
8817 			} else {
8818 				/*
8819 				 * Port is not in ready state, we
8820 				 * cannot attach a device.
8821 				 */
8822 				mutex_exit(&cportinfo->cport_mutex);
8823 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
8824 				return (SATA_SUCCESS);
8825 			}
8826 			/*
8827 			 * Since we are adding device, presumably new one,
8828 			 * indicate that it  should be initalized,
8829 			 * as well as some internal framework states).
8830 			 */
8831 			init_device = B_TRUE;
8832 		}
8833 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
8834 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
8835 	} else {
8836 		/*
8837 		 * The device is a port multiplier - not handled now.
8838 		 */
8839 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
8840 		mutex_exit(&cportinfo->cport_mutex);
8841 		return (SATA_SUCCESS);
8842 	}
8843 	mutex_exit(&cportinfo->cport_mutex);
8844 	/*
8845 	 * Figure out what kind of device we are really
8846 	 * dealing with. Failure of identifying device does not fail this
8847 	 * function.
8848 	 */
8849 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
8850 	rval_init = SATA_FAILURE;
8851 	mutex_enter(&cportinfo->cport_mutex);
8852 	if (rval_probe == SATA_SUCCESS) {
8853 		/*
8854 		 * If we are dealing with the same type of a device as before,
8855 		 * restore its settings flags.
8856 		 */
8857 		if (osdinfo != NULL &&
8858 		    sata_device->satadev_type == prev_device_type)
8859 			sdinfo->satadrv_settings = prev_device_settings;
8860 
8861 		mutex_exit(&cportinfo->cport_mutex);
8862 		rval_init = SATA_SUCCESS;
8863 		/* Set initial device features, if necessary */
8864 		if (init_device == B_TRUE) {
8865 			rval_init = sata_initialize_device(sata_hba_inst,
8866 			    sdinfo);
8867 		}
8868 		if (rval_init == SATA_SUCCESS)
8869 			return (rval_init);
8870 		/* else we will retry if retry was asked for */
8871 
8872 	} else {
8873 		/*
8874 		 * If there was some device info before we probe the device,
8875 		 * restore previous device setting, so we can retry from scratch
8876 		 * later. Providing, of course, that device has not disapear
8877 		 * during probing process.
8878 		 */
8879 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
8880 			if (osdinfo != NULL) {
8881 				cportinfo->cport_dev_type = prev_device_type;
8882 				sdinfo->satadrv_type = prev_device_type;
8883 				sdinfo->satadrv_state = prev_device_state;
8884 			}
8885 		} else {
8886 			/* device is gone */
8887 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
8888 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
8889 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
8890 			mutex_exit(&cportinfo->cport_mutex);
8891 			return (SATA_SUCCESS);
8892 		}
8893 		mutex_exit(&cportinfo->cport_mutex);
8894 	}
8895 
8896 	if (retry) {
8897 		clock_t cur_time = ddi_get_lbolt();
8898 		/*
8899 		 * A device was not successfully identified or initialized.
8900 		 * Track retry time for device identification.
8901 		 */
8902 		if ((cur_time - start_time) <
8903 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
8904 			/* sleep for a while */
8905 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
8906 			goto retry_probe;
8907 		}
8908 		/* else no more retries */
8909 		mutex_enter(&cportinfo->cport_mutex);
8910 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
8911 			if (rval_init == SATA_RETRY) {
8912 				/*
8913 				 * Setting drive features have failed, but
8914 				 * because the drive is still accessible,
8915 				 * keep it and emit a warning message.
8916 				 */
8917 				sata_log(sata_hba_inst, CE_WARN,
8918 				    "SATA device at port %d - desired "
8919 				    "drive features could not be set. "
8920 				    "Device may not operate as expected.",
8921 				    cportinfo->cport_addr.cport);
8922 			} else {
8923 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
8924 				    satadrv_state = SATA_DSTATE_FAILED;
8925 			}
8926 		}
8927 		mutex_exit(&cportinfo->cport_mutex);
8928 	}
8929 	return (SATA_SUCCESS);
8930 }
8931 
8932 /*
8933  * Initialize device
8934  * Specified device is initialized to a default state.
8935  *
8936  * Returns SATA_SUCCESS if all device features are set successfully,
8937  * SATA_RETRY if device is accessible but device features were not set
8938  * successfully, and SATA_FAILURE otherwise.
8939  */
8940 static int
8941 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
8942     sata_drive_info_t *sdinfo)
8943 {
8944 	int rval;
8945 
8946 	sata_save_drive_settings(sdinfo);
8947 
8948 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
8949 
8950 	sata_init_write_cache_mode(sdinfo);
8951 
8952 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
8953 
8954 	/* Determine current data transfer mode */
8955 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
8956 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
8957 	} else if ((sdinfo->satadrv_id.ai_validinfo &
8958 	    SATA_VALIDINFO_88) != 0 &&
8959 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
8960 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
8961 	} else if ((sdinfo->satadrv_id.ai_dworddma &
8962 	    SATA_MDMA_SEL_MASK) != 0) {
8963 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
8964 	} else
8965 		/* DMA supported, not no DMA transfer mode is selected !? */
8966 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
8967 
8968 	return (rval);
8969 }
8970 
8971 
8972 /*
8973  * Initialize write cache mode.
8974  *
8975  * The default write cache setting for SATA HDD is provided by sata_write_cache
8976  * static variable. ATAPI CD/DVDs devices have write cache default is
8977  * determined by sata_atapicdvd_write_cache static variable.
8978  * ATAPI tape devices have write cache default is determined by
8979  * sata_atapitape_write_cache static variable.
8980  * ATAPI disk devices have write cache default is determined by
8981  * sata_atapidisk_write_cache static variable.
8982  * 1 - enable
8983  * 0 - disable
8984  * any other value - current drive setting
8985  *
8986  * Although there is not reason to disable write cache on CD/DVD devices,
8987  * tape devices and ATAPI disk devices, the default setting control is provided
8988  * for the maximun flexibility.
8989  *
8990  * In the future, it may be overridden by the
8991  * disk-write-cache-enable property setting, if it is defined.
8992  * Returns SATA_SUCCESS if all device features are set successfully,
8993  * SATA_FAILURE otherwise.
8994  */
8995 static void
8996 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
8997 {
8998 	switch (sdinfo->satadrv_type) {
8999 	case SATA_DTYPE_ATADISK:
9000 		if (sata_write_cache == 1)
9001 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
9002 		else if (sata_write_cache == 0)
9003 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
9004 		/*
9005 		 * When sata_write_cache value is not 0 or 1,
9006 		 * a current setting of the drive's write cache is used.
9007 		 */
9008 		break;
9009 	case SATA_DTYPE_ATAPICD:
9010 		if (sata_atapicdvd_write_cache == 1)
9011 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
9012 		else if (sata_atapicdvd_write_cache == 0)
9013 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
9014 		/*
9015 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
9016 		 * a current setting of the drive's write cache is used.
9017 		 */
9018 		break;
9019 	case SATA_DTYPE_ATAPITAPE:
9020 		if (sata_atapitape_write_cache == 1)
9021 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
9022 		else if (sata_atapitape_write_cache == 0)
9023 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
9024 		/*
9025 		 * When sata_atapitape_write_cache value is not 0 or 1,
9026 		 * a current setting of the drive's write cache is used.
9027 		 */
9028 		break;
9029 	case SATA_DTYPE_ATAPIDISK:
9030 		if (sata_atapidisk_write_cache == 1)
9031 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
9032 		else if (sata_atapidisk_write_cache == 0)
9033 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
9034 		/*
9035 		 * When sata_atapidisk_write_cache value is not 0 or 1,
9036 		 * a current setting of the drive's write cache is used.
9037 		 */
9038 		break;
9039 	}
9040 }
9041 
9042 
9043 /*
9044  * Validate sata address.
9045  * Specified cport, pmport and qualifier has to match
9046  * passed sata_scsi configuration info.
9047  * The presence of an attached device is not verified.
9048  *
9049  * Returns 0 when address is valid, -1 otherwise.
9050  */
9051 static int
9052 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
9053 	int pmport, int qual)
9054 {
9055 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
9056 		goto invalid_address;
9057 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
9058 		goto invalid_address;
9059 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
9060 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
9061 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
9062 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
9063 		goto invalid_address;
9064 
9065 	return (0);
9066 
9067 invalid_address:
9068 	return (-1);
9069 
9070 }
9071 
9072 /*
9073  * Validate scsi address
9074  * SCSI target address is translated into SATA cport/pmport and compared
9075  * with a controller port/device configuration. LUN has to be 0.
9076  * Returns 0 if a scsi target refers to an attached device,
9077  * returns 1 if address is valid but device is not attached,
9078  * returns -1 if bad address or device is of an unsupported type.
9079  * Upon return sata_device argument is set.
9080  */
9081 static int
9082 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
9083 	struct scsi_address *ap, sata_device_t *sata_device)
9084 {
9085 	int cport, pmport, qual, rval;
9086 
9087 	rval = -1;	/* Invalid address */
9088 	if (ap->a_lun != 0)
9089 		goto out;
9090 
9091 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
9092 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
9093 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
9094 
9095 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
9096 		goto out;
9097 
9098 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
9099 	    0) {
9100 
9101 		sata_cport_info_t *cportinfo;
9102 		sata_pmult_info_t *pmultinfo;
9103 		sata_drive_info_t *sdinfo = NULL;
9104 
9105 		rval = 1;	/* Valid sata address */
9106 
9107 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
9108 		if (qual == SATA_ADDR_DCPORT) {
9109 			if (cportinfo == NULL ||
9110 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
9111 				goto out;
9112 
9113 			if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT ||
9114 			    (cportinfo->cport_dev_type &
9115 			    SATA_VALID_DEV_TYPE) == 0) {
9116 				rval = -1;
9117 				goto out;
9118 			}
9119 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
9120 
9121 		} else if (qual == SATA_ADDR_DPMPORT) {
9122 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
9123 			if (pmultinfo == NULL) {
9124 				rval = -1;
9125 				goto out;
9126 			}
9127 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
9128 			    NULL ||
9129 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
9130 			    pmport) == SATA_DTYPE_NONE)
9131 				goto out;
9132 
9133 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
9134 			    pmport);
9135 		} else {
9136 			rval = -1;
9137 			goto out;
9138 		}
9139 		if ((sdinfo == NULL) ||
9140 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
9141 			goto out;
9142 
9143 		sata_device->satadev_type = sdinfo->satadrv_type;
9144 		sata_device->satadev_addr.qual = qual;
9145 		sata_device->satadev_addr.cport = cport;
9146 		sata_device->satadev_addr.pmport = pmport;
9147 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
9148 		return (0);
9149 	}
9150 out:
9151 	if (rval == 1) {
9152 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
9153 		    "sata_validate_scsi_address: no valid target %x lun %x",
9154 		    ap->a_target, ap->a_lun);
9155 	}
9156 	return (rval);
9157 }
9158 
9159 /*
9160  * Find dip corresponding to passed device number
9161  *
9162  * Returns NULL if invalid device number is passed or device cannot be found,
9163  * Returns dip is device is found.
9164  */
9165 static dev_info_t *
9166 sata_devt_to_devinfo(dev_t dev)
9167 {
9168 	dev_info_t *dip;
9169 #ifndef __lock_lint
9170 	struct devnames *dnp;
9171 	major_t major = getmajor(dev);
9172 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
9173 
9174 	if (major >= devcnt)
9175 		return (NULL);
9176 
9177 	dnp = &devnamesp[major];
9178 	LOCK_DEV_OPS(&(dnp->dn_lock));
9179 	dip = dnp->dn_head;
9180 	while (dip && (ddi_get_instance(dip) != instance)) {
9181 		dip = ddi_get_next(dip);
9182 	}
9183 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
9184 #endif
9185 
9186 	return (dip);
9187 }
9188 
9189 
9190 /*
9191  * Probe device.
9192  * This function issues Identify Device command and initializes local
9193  * sata_drive_info structure if the device can be identified.
9194  * The device type is determined by examining Identify Device
9195  * command response.
9196  * If the sata_hba_inst has linked drive info structure for this
9197  * device address, the Identify Device data is stored into sata_drive_info
9198  * structure linked to the port info structure.
9199  *
9200  * sata_device has to refer to the valid sata port(s) for HBA described
9201  * by sata_hba_inst structure.
9202  *
9203  * Returns:
9204  *	SATA_SUCCESS if device type was successfully probed and port-linked
9205  *		drive info structure was updated;
9206  * 	SATA_FAILURE if there is no device, or device was not probed
9207  *		successully;
9208  *	SATA_RETRY if device probe can be retried later.
9209  * If a device cannot be identified, sata_device's dev_state and dev_type
9210  * fields are set to unknown.
9211  * There are no retries in this function. Any retries should be managed by
9212  * the caller.
9213  */
9214 
9215 
9216 static int
9217 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
9218 {
9219 	sata_drive_info_t *sdinfo;
9220 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
9221 	int rval;
9222 
9223 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
9224 	    sata_device->satadev_addr.cport) &
9225 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
9226 
9227 	sata_device->satadev_type = SATA_DTYPE_NONE;
9228 
9229 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
9230 	    sata_device->satadev_addr.cport)));
9231 
9232 	/* Get pointer to port-linked sata device info structure */
9233 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
9234 	if (sdinfo != NULL) {
9235 		sdinfo->satadrv_state &=
9236 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
9237 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
9238 	} else {
9239 		/* No device to probe */
9240 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9241 		    sata_device->satadev_addr.cport)));
9242 		sata_device->satadev_type = SATA_DTYPE_NONE;
9243 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
9244 		return (SATA_FAILURE);
9245 	}
9246 	/*
9247 	 * Need to issue both types of identify device command and
9248 	 * determine device type by examining retreived data/status.
9249 	 * First, ATA Identify Device.
9250 	 */
9251 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
9252 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
9253 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9254 	    sata_device->satadev_addr.cport)));
9255 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
9256 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
9257 	if (rval == SATA_RETRY) {
9258 		/* We may try to check for ATAPI device */
9259 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
9260 			/*
9261 			 * HBA supports ATAPI - try to issue Identify Packet
9262 			 * Device command.
9263 			 */
9264 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
9265 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
9266 		}
9267 	}
9268 	if (rval == SATA_SUCCESS) {
9269 		/*
9270 		 * Got something responding positively to ATA Identify Device
9271 		 * or to Identify Packet Device cmd.
9272 		 * Save last used device type.
9273 		 */
9274 		sata_device->satadev_type = new_sdinfo.satadrv_type;
9275 
9276 		/* save device info, if possible */
9277 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
9278 		    sata_device->satadev_addr.cport)));
9279 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
9280 		if (sdinfo == NULL) {
9281 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9282 			    sata_device->satadev_addr.cport)));
9283 			return (SATA_FAILURE);
9284 		}
9285 		/*
9286 		 * Copy drive info into the port-linked drive info structure.
9287 		 */
9288 		*sdinfo = new_sdinfo;
9289 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
9290 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
9291 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
9292 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
9293 			    sata_device->satadev_addr.cport) =
9294 			    sdinfo->satadrv_type;
9295 		else /* SATA_ADDR_DPMPORT */
9296 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
9297 			    sata_device->satadev_addr.cport,
9298 			    sata_device->satadev_addr.pmport) =
9299 			    sdinfo->satadrv_type;
9300 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9301 		    sata_device->satadev_addr.cport)));
9302 		return (SATA_SUCCESS);
9303 	}
9304 
9305 	/*
9306 	 * It may be SATA_RETRY or SATA_FAILURE return.
9307 	 * Looks like we cannot determine the device type at this time.
9308 	 */
9309 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
9310 	    sata_device->satadev_addr.cport)));
9311 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
9312 	if (sdinfo != NULL) {
9313 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
9314 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
9315 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
9316 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
9317 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
9318 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
9319 			    sata_device->satadev_addr.cport) =
9320 			    SATA_DTYPE_UNKNOWN;
9321 		else {
9322 			/* SATA_ADDR_DPMPORT */
9323 			if ((SATA_PMULT_INFO(sata_hba_inst,
9324 			    sata_device->satadev_addr.cport) != NULL) &&
9325 			    (SATA_PMPORT_INFO(sata_hba_inst,
9326 			    sata_device->satadev_addr.cport,
9327 			    sata_device->satadev_addr.pmport) != NULL))
9328 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
9329 				    sata_device->satadev_addr.cport,
9330 				    sata_device->satadev_addr.pmport) =
9331 				    SATA_DTYPE_UNKNOWN;
9332 		}
9333 	}
9334 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
9335 	    sata_device->satadev_addr.cport)));
9336 	return (rval);
9337 }
9338 
9339 
9340 /*
9341  * Get pointer to sata_drive_info structure.
9342  *
9343  * The sata_device has to contain address (cport, pmport and qualifier) for
9344  * specified sata_scsi structure.
9345  *
9346  * Returns NULL if device address is not valid for this HBA configuration.
9347  * Otherwise, returns a pointer to sata_drive_info structure.
9348  *
9349  * This function should be called with a port mutex held.
9350  */
9351 static sata_drive_info_t *
9352 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
9353     sata_device_t *sata_device)
9354 {
9355 	uint8_t cport = sata_device->satadev_addr.cport;
9356 	uint8_t pmport = sata_device->satadev_addr.pmport;
9357 	uint8_t qual = sata_device->satadev_addr.qual;
9358 
9359 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
9360 		return (NULL);
9361 
9362 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
9363 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
9364 		/* Port not probed yet */
9365 		return (NULL);
9366 
9367 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
9368 		return (NULL);
9369 
9370 	if (qual == SATA_ADDR_DCPORT) {
9371 		/* Request for a device on a controller port */
9372 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
9373 		    SATA_DTYPE_PMULT)
9374 			/* Port multiplier attached */
9375 			return (NULL);
9376 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
9377 	}
9378 	if (qual == SATA_ADDR_DPMPORT) {
9379 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
9380 		    SATA_DTYPE_PMULT)
9381 			return (NULL);
9382 
9383 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
9384 			return (NULL);
9385 
9386 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
9387 	}
9388 
9389 	/* we should not get here */
9390 	return (NULL);
9391 }
9392 
9393 
9394 /*
9395  * sata_identify_device.
9396  * Send Identify Device command to SATA HBA driver.
9397  * If command executes successfully, update sata_drive_info structure pointed
9398  * to by sdinfo argument, including Identify Device data.
9399  * If command fails, invalidate data in sata_drive_info.
9400  *
9401  * Cannot be called from interrupt level.
9402  *
9403  * Returns:
9404  * SATA_SUCCESS if the device was identified as a supported device,
9405  * SATA_RETRY if the device was not identified but could be retried,
9406  * SATA_FAILURE if the device was not identified and identify attempt
9407  *	should not be retried.
9408  */
9409 static int
9410 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
9411     sata_drive_info_t *sdinfo)
9412 {
9413 	uint16_t cfg_word;
9414 	int rval;
9415 
9416 	/* fetch device identify data */
9417 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
9418 	    sdinfo)) != SATA_SUCCESS)
9419 		goto fail_unknown;
9420 
9421 	cfg_word = sdinfo->satadrv_id.ai_config;
9422 
9423 	/* Set the correct device type */
9424 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
9425 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
9426 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
9427 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
9428 		case SATA_ATAPI_CDROM_DEV:
9429 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
9430 			break;
9431 		case SATA_ATAPI_SQACC_DEV:
9432 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
9433 			break;
9434 		case SATA_ATAPI_DIRACC_DEV:
9435 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
9436 			break;
9437 		default:
9438 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
9439 		}
9440 	} else {
9441 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
9442 	}
9443 
9444 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9445 		if (sdinfo->satadrv_capacity == 0) {
9446 			/* Non-LBA disk. Too bad... */
9447 			sata_log(sata_hba_inst, CE_WARN,
9448 			    "SATA disk device at port %d does not support LBA",
9449 			    sdinfo->satadrv_addr.cport);
9450 			rval = SATA_FAILURE;
9451 			goto fail_unknown;
9452 		}
9453 	}
9454 #if 0
9455 	/* Left for historical reason */
9456 	/*
9457 	 * Some initial version of SATA spec indicated that at least
9458 	 * UDMA mode 4 has to be supported. It is not metioned in
9459 	 * SerialATA 2.6, so this restriction is removed.
9460 	 */
9461 	/* Check for Ultra DMA modes 6 through 0 being supported */
9462 	for (i = 6; i >= 0; --i) {
9463 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
9464 			break;
9465 	}
9466 
9467 	/*
9468 	 * At least UDMA 4 mode has to be supported. If mode 4 or
9469 	 * higher are not supported by the device, fail this
9470 	 * device.
9471 	 */
9472 	if (i < 4) {
9473 		/* No required Ultra DMA mode supported */
9474 		sata_log(sata_hba_inst, CE_WARN,
9475 		    "SATA disk device at port %d does not support UDMA "
9476 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
9477 		SATA_LOG_D((sata_hba_inst, CE_WARN,
9478 		    "mode 4 or higher required, %d supported", i));
9479 		rval = SATA_FAILURE;
9480 		goto fail_unknown;
9481 	}
9482 #endif
9483 
9484 	/*
9485 	 * For Disk devices, if it doesn't support UDMA mode, we would
9486 	 * like to return failure directly.
9487 	 */
9488 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
9489 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
9490 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
9491 		sata_log(sata_hba_inst, CE_WARN,
9492 		    "SATA disk device at port %d does not support UDMA",
9493 		    sdinfo->satadrv_addr.cport);
9494 		rval = SATA_FAILURE;
9495 		goto fail_unknown;
9496 	}
9497 
9498 	return (SATA_SUCCESS);
9499 
9500 fail_unknown:
9501 	/* Invalidate sata_drive_info ? */
9502 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
9503 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
9504 	return (rval);
9505 }
9506 
9507 /*
9508  * Log/display device information
9509  */
9510 static void
9511 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
9512     sata_drive_info_t *sdinfo)
9513 {
9514 	int valid_version;
9515 	char msg_buf[MAXPATHLEN];
9516 	int i;
9517 
9518 	/* Show HBA path */
9519 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
9520 
9521 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
9522 
9523 	switch (sdinfo->satadrv_type) {
9524 	case SATA_DTYPE_ATADISK:
9525 		(void) sprintf(msg_buf, "SATA disk device at");
9526 		break;
9527 
9528 	case SATA_DTYPE_ATAPICD:
9529 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
9530 		break;
9531 
9532 	case SATA_DTYPE_ATAPITAPE:
9533 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
9534 		break;
9535 
9536 	case SATA_DTYPE_ATAPIDISK:
9537 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
9538 		break;
9539 
9540 	case SATA_DTYPE_UNKNOWN:
9541 		(void) sprintf(msg_buf,
9542 		    "Unsupported SATA device type (cfg 0x%x) at ",
9543 		    sdinfo->satadrv_id.ai_config);
9544 		break;
9545 	}
9546 
9547 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
9548 		cmn_err(CE_CONT, "?\t%s port %d\n",
9549 		    msg_buf, sdinfo->satadrv_addr.cport);
9550 	else
9551 		cmn_err(CE_CONT, "?\t%s port %d pmport %d\n",
9552 		    msg_buf, sdinfo->satadrv_addr.cport,
9553 		    sdinfo->satadrv_addr.pmport);
9554 
9555 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
9556 	    sizeof (sdinfo->satadrv_id.ai_model));
9557 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
9558 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
9559 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
9560 
9561 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
9562 	    sizeof (sdinfo->satadrv_id.ai_fw));
9563 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
9564 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
9565 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
9566 
9567 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
9568 	    sizeof (sdinfo->satadrv_id.ai_drvser));
9569 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
9570 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
9571 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9572 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
9573 	} else {
9574 		/*
9575 		 * Some drives do not implement serial number and may
9576 		 * violate the spec by providing spaces rather than zeros
9577 		 * in serial number field. Scan the buffer to detect it.
9578 		 */
9579 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
9580 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
9581 				break;
9582 		}
9583 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
9584 			cmn_err(CE_CONT, "?\tserial number - none\n");
9585 		} else {
9586 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
9587 		}
9588 	}
9589 
9590 #ifdef SATA_DEBUG
9591 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
9592 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
9593 		int i;
9594 		for (i = 14; i >= 2; i--) {
9595 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
9596 				valid_version = i;
9597 				break;
9598 			}
9599 		}
9600 		cmn_err(CE_CONT,
9601 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
9602 		    valid_version,
9603 		    sdinfo->satadrv_id.ai_majorversion,
9604 		    sdinfo->satadrv_id.ai_minorversion);
9605 	}
9606 #endif
9607 	/* Log some info */
9608 	cmn_err(CE_CONT, "?\tsupported features:\n");
9609 	msg_buf[0] = '\0';
9610 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9611 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
9612 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
9613 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
9614 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
9615 	}
9616 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
9617 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
9618 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
9619 		(void) strlcat(msg_buf, ", Native Command Queueing",
9620 		    MAXPATHLEN);
9621 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
9622 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
9623 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
9624 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
9625 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
9626 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
9627 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
9628 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
9629 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
9630 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
9631 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
9632 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
9633 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
9634 	if (sdinfo->satadrv_features_support &
9635 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
9636 		msg_buf[0] = '\0';
9637 		(void) snprintf(msg_buf, MAXPATHLEN,
9638 		    "Supported queue depth %d",
9639 		    sdinfo->satadrv_queue_depth);
9640 		if (!(sata_func_enable &
9641 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
9642 			(void) strlcat(msg_buf,
9643 			    " - queueing disabled globally", MAXPATHLEN);
9644 		else if (sdinfo->satadrv_queue_depth >
9645 		    sdinfo->satadrv_max_queue_depth) {
9646 			(void) snprintf(&msg_buf[strlen(msg_buf)],
9647 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
9648 			    (int)sdinfo->satadrv_max_queue_depth);
9649 		}
9650 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
9651 	}
9652 
9653 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9654 #ifdef __i386
9655 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
9656 		    sdinfo->satadrv_capacity);
9657 #else
9658 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
9659 		    sdinfo->satadrv_capacity);
9660 #endif
9661 		cmn_err(CE_CONT, "?%s", msg_buf);
9662 	}
9663 }
9664 
9665 
9666 /*
9667  * sata_save_drive_settings extracts current setting of the device and stores
9668  * it for future reference, in case the device setup would need to be restored
9669  * after the device reset.
9670  *
9671  * For all devices read ahead and write cache settings are saved, if the
9672  * device supports these features at all.
9673  * For ATAPI devices the Removable Media Status Notification setting is saved.
9674  */
9675 static void
9676 sata_save_drive_settings(sata_drive_info_t *sdinfo)
9677 {
9678 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
9679 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
9680 
9681 		/* Current setting of Read Ahead (and Read Cache) */
9682 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
9683 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
9684 		else
9685 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
9686 
9687 		/* Current setting of Write Cache */
9688 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
9689 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
9690 		else
9691 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
9692 	}
9693 
9694 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
9695 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
9696 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
9697 		else
9698 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
9699 	}
9700 }
9701 
9702 
9703 /*
9704  * sata_check_capacity function determines a disk capacity
9705  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
9706  *
9707  * NOTE: CHS mode is not supported! If a device does not support LBA,
9708  * this function is not called.
9709  *
9710  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
9711  */
9712 static uint64_t
9713 sata_check_capacity(sata_drive_info_t *sdinfo)
9714 {
9715 	uint64_t capacity = 0;
9716 	int i;
9717 
9718 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
9719 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
9720 		/* Capacity valid only for LBA-addressable disk devices */
9721 		return (0);
9722 
9723 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
9724 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
9725 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
9726 		/* LBA48 mode supported and enabled */
9727 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
9728 		    SATA_DEV_F_LBA28;
9729 		for (i = 3;  i >= 0;  --i) {
9730 			capacity <<= 16;
9731 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
9732 		}
9733 	} else {
9734 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
9735 		capacity <<= 16;
9736 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
9737 		if (capacity >= 0x1000000)
9738 			/* LBA28 mode */
9739 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
9740 	}
9741 	return (capacity);
9742 }
9743 
9744 
9745 /*
9746  * Allocate consistent buffer for DMA transfer
9747  *
9748  * Cannot be called from interrupt level or with mutex held - it may sleep.
9749  *
9750  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
9751  */
9752 static struct buf *
9753 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
9754 {
9755 	struct scsi_address ap;
9756 	struct buf *bp;
9757 	ddi_dma_attr_t	cur_dma_attr;
9758 
9759 	ASSERT(spx->txlt_sata_pkt != NULL);
9760 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
9761 	ap.a_target = SATA_TO_SCSI_TARGET(
9762 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
9763 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
9764 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
9765 	ap.a_lun = 0;
9766 
9767 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
9768 	    B_READ, SLEEP_FUNC, NULL);
9769 
9770 	if (bp != NULL) {
9771 		/* Allocate DMA resources for this buffer */
9772 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
9773 		/*
9774 		 * We use a local version of the dma_attr, to account
9775 		 * for a device addressing limitations.
9776 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
9777 		 * will cause dma attributes to be adjusted to a lowest
9778 		 * acceptable level.
9779 		 */
9780 		sata_adjust_dma_attr(NULL,
9781 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
9782 
9783 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
9784 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
9785 			scsi_free_consistent_buf(bp);
9786 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
9787 			bp = NULL;
9788 		}
9789 	}
9790 	return (bp);
9791 }
9792 
9793 /*
9794  * Release local buffer (consistent buffer for DMA transfer) allocated
9795  * via sata_alloc_local_buffer().
9796  */
9797 static void
9798 sata_free_local_buffer(sata_pkt_txlate_t *spx)
9799 {
9800 	ASSERT(spx->txlt_sata_pkt != NULL);
9801 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
9802 
9803 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
9804 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
9805 
9806 	sata_common_free_dma_rsrcs(spx);
9807 
9808 	/* Free buffer */
9809 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
9810 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
9811 }
9812 
9813 /*
9814  * Allocate sata_pkt
9815  * Pkt structure version and embedded strcutures version are initialized.
9816  * sata_pkt and sata_pkt_txlate structures are cross-linked.
9817  *
9818  * Since this may be called in interrupt context by sata_scsi_init_pkt,
9819  * callback argument determines if it can sleep or not.
9820  * Hence, it should not be called from interrupt context.
9821  *
9822  * If successful, non-NULL pointer to a sata pkt is returned.
9823  * Upon failure, NULL pointer is returned.
9824  */
9825 static sata_pkt_t *
9826 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
9827 {
9828 	sata_pkt_t *spkt;
9829 	int kmsflag;
9830 
9831 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
9832 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
9833 	if (spkt == NULL) {
9834 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9835 		    "sata_pkt_alloc: failed"));
9836 		return (NULL);
9837 	}
9838 	spkt->satapkt_rev = SATA_PKT_REV;
9839 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
9840 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
9841 	spkt->satapkt_framework_private = spx;
9842 	spx->txlt_sata_pkt = spkt;
9843 	return (spkt);
9844 }
9845 
9846 /*
9847  * Free sata pkt allocated via sata_pkt_alloc()
9848  */
9849 static void
9850 sata_pkt_free(sata_pkt_txlate_t *spx)
9851 {
9852 	ASSERT(spx->txlt_sata_pkt != NULL);
9853 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
9854 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
9855 	spx->txlt_sata_pkt = NULL;
9856 }
9857 
9858 
9859 /*
9860  * Adjust DMA attributes.
9861  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
9862  * from 8 bits to 16 bits, depending on a command being used.
9863  * Limiting max block count arbitrarily to 256 for all read/write
9864  * commands may affects performance, so check both the device and
9865  * controller capability before adjusting dma attributes.
9866  */
9867 void
9868 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
9869     ddi_dma_attr_t *adj_dma_attr)
9870 {
9871 	uint32_t count_max;
9872 
9873 	/* Copy original attributes */
9874 	*adj_dma_attr = *dma_attr;
9875 	/*
9876 	 * Things to consider: device addressing capability,
9877 	 * "excessive" controller DMA capabilities.
9878 	 * If a device is being probed/initialized, there are
9879 	 * no device info - use default limits then.
9880 	 */
9881 	if (sdinfo == NULL) {
9882 		count_max = dma_attr->dma_attr_granular * 0x100;
9883 		if (dma_attr->dma_attr_count_max > count_max)
9884 			adj_dma_attr->dma_attr_count_max = count_max;
9885 		if (dma_attr->dma_attr_maxxfer > count_max)
9886 			adj_dma_attr->dma_attr_maxxfer = count_max;
9887 		return;
9888 	}
9889 
9890 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
9891 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
9892 			/*
9893 			 * 16-bit sector count may be used - we rely on
9894 			 * the assumption that only read and write cmds
9895 			 * will request more than 256 sectors worth of data
9896 			 */
9897 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
9898 		} else {
9899 			/*
9900 			 * 8-bit sector count will be used - default limits
9901 			 * for dma attributes
9902 			 */
9903 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
9904 		}
9905 		/*
9906 		 * Adjust controler dma attributes, if necessary
9907 		 */
9908 		if (dma_attr->dma_attr_count_max > count_max)
9909 			adj_dma_attr->dma_attr_count_max = count_max;
9910 		if (dma_attr->dma_attr_maxxfer > count_max)
9911 			adj_dma_attr->dma_attr_maxxfer = count_max;
9912 	}
9913 }
9914 
9915 
9916 /*
9917  * Allocate DMA resources for the buffer
9918  * This function handles initial DMA resource allocation as well as
9919  * DMA window shift and may be called repeatedly for the same DMA window
9920  * until all DMA cookies in the DMA window are processed.
9921  * To guarantee that there is always a coherent set of cookies to process
9922  * by SATA HBA driver (observing alignment, device granularity, etc.),
9923  * the number of slots for DMA cookies is equal to lesser of  a number of
9924  * cookies in a DMA window and a max number of scatter/gather entries.
9925  *
9926  * Returns DDI_SUCCESS upon successful operation.
9927  * Return failure code of a failing command or DDI_FAILURE when
9928  * internal cleanup failed.
9929  */
9930 static int
9931 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
9932     int (*callback)(caddr_t), caddr_t arg,
9933     ddi_dma_attr_t *cur_dma_attr)
9934 {
9935 	int	rval;
9936 	off_t	offset;
9937 	size_t	size;
9938 	int	max_sg_len, req_len, i;
9939 	uint_t	dma_flags;
9940 	struct buf	*bp;
9941 	uint64_t	cur_txfer_len;
9942 
9943 
9944 	ASSERT(spx->txlt_sata_pkt != NULL);
9945 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
9946 	ASSERT(bp != NULL);
9947 
9948 
9949 	if (spx->txlt_buf_dma_handle == NULL) {
9950 		/*
9951 		 * No DMA resources allocated so far - this is a first call
9952 		 * for this sata pkt.
9953 		 */
9954 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
9955 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
9956 
9957 		if (rval != DDI_SUCCESS) {
9958 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9959 			    "sata_dma_buf_setup: no buf DMA resources %x",
9960 			    rval));
9961 			return (rval);
9962 		}
9963 
9964 		if (bp->b_flags & B_READ)
9965 			dma_flags = DDI_DMA_READ;
9966 		else
9967 			dma_flags = DDI_DMA_WRITE;
9968 
9969 		if (flags & PKT_CONSISTENT)
9970 			dma_flags |= DDI_DMA_CONSISTENT;
9971 
9972 		if (flags & PKT_DMA_PARTIAL)
9973 			dma_flags |= DDI_DMA_PARTIAL;
9974 
9975 		/*
9976 		 * Check buffer alignment and size against dma attributes
9977 		 * Consider dma_attr_align only. There may be requests
9978 		 * with the size lower than device granularity, but they
9979 		 * will not read/write from/to the device, so no adjustment
9980 		 * is necessary. The dma_attr_minxfer theoretically should
9981 		 * be considered, but no HBA driver is checking it.
9982 		 */
9983 		if (IS_P2ALIGNED(bp->b_un.b_addr,
9984 		    cur_dma_attr->dma_attr_align)) {
9985 			rval = ddi_dma_buf_bind_handle(
9986 			    spx->txlt_buf_dma_handle,
9987 			    bp, dma_flags, callback, arg,
9988 			    &spx->txlt_dma_cookie,
9989 			    &spx->txlt_curwin_num_dma_cookies);
9990 		} else { /* Buffer is not aligned */
9991 
9992 			int	(*ddicallback)(caddr_t);
9993 			size_t	bufsz;
9994 
9995 			/* Check id sleeping is allowed */
9996 			ddicallback = (callback == NULL_FUNC) ?
9997 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
9998 
9999 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
10000 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
10001 			    (void *)bp->b_un.b_addr, bp->b_bcount);
10002 
10003 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
10004 				/*
10005 				 * CPU will need to access data in the buffer
10006 				 * (for copying) so map it.
10007 				 */
10008 				bp_mapin(bp);
10009 
10010 			ASSERT(spx->txlt_tmp_buf == NULL);
10011 
10012 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
10013 			rval = ddi_dma_mem_alloc(
10014 			    spx->txlt_buf_dma_handle,
10015 			    bp->b_bcount,
10016 			    &sata_acc_attr,
10017 			    DDI_DMA_STREAMING,
10018 			    ddicallback, NULL,
10019 			    &spx->txlt_tmp_buf,
10020 			    &bufsz,
10021 			    &spx->txlt_tmp_buf_handle);
10022 
10023 			if (rval != DDI_SUCCESS) {
10024 				/* DMA mapping failed */
10025 				(void) ddi_dma_free_handle(
10026 				    &spx->txlt_buf_dma_handle);
10027 				spx->txlt_buf_dma_handle = NULL;
10028 #ifdef SATA_DEBUG
10029 				mbuffail_count++;
10030 #endif
10031 				SATADBG1(SATA_DBG_DMA_SETUP,
10032 				    spx->txlt_sata_hba_inst,
10033 				    "sata_dma_buf_setup: "
10034 				    "buf dma mem alloc failed %x\n", rval);
10035 				return (rval);
10036 			}
10037 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
10038 			    cur_dma_attr->dma_attr_align));
10039 
10040 #ifdef SATA_DEBUG
10041 			mbuf_count++;
10042 
10043 			if (bp->b_bcount != bufsz)
10044 				/*
10045 				 * This will require special handling, because
10046 				 * DMA cookies will be based on the temporary
10047 				 * buffer size, not the original buffer
10048 				 * b_bcount, so the residue may have to
10049 				 * be counted differently.
10050 				 */
10051 				SATADBG2(SATA_DBG_DMA_SETUP,
10052 				    spx->txlt_sata_hba_inst,
10053 				    "sata_dma_buf_setup: bp size %x != "
10054 				    "bufsz %x\n", bp->b_bcount, bufsz);
10055 #endif
10056 			if (dma_flags & DDI_DMA_WRITE) {
10057 				/*
10058 				 * Write operation - copy data into
10059 				 * an aligned temporary buffer. Buffer will be
10060 				 * synced for device by ddi_dma_addr_bind_handle
10061 				 */
10062 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
10063 				    bp->b_bcount);
10064 			}
10065 
10066 			rval = ddi_dma_addr_bind_handle(
10067 			    spx->txlt_buf_dma_handle,
10068 			    NULL,
10069 			    spx->txlt_tmp_buf,
10070 			    bufsz, dma_flags, ddicallback, 0,
10071 			    &spx->txlt_dma_cookie,
10072 			    &spx->txlt_curwin_num_dma_cookies);
10073 		}
10074 
10075 		switch (rval) {
10076 		case DDI_DMA_PARTIAL_MAP:
10077 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
10078 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
10079 			/*
10080 			 * Partial DMA mapping.
10081 			 * Retrieve number of DMA windows for this request.
10082 			 */
10083 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
10084 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
10085 				if (spx->txlt_tmp_buf != NULL) {
10086 					ddi_dma_mem_free(
10087 					    &spx->txlt_tmp_buf_handle);
10088 					spx->txlt_tmp_buf = NULL;
10089 				}
10090 				(void) ddi_dma_unbind_handle(
10091 				    spx->txlt_buf_dma_handle);
10092 				(void) ddi_dma_free_handle(
10093 				    &spx->txlt_buf_dma_handle);
10094 				spx->txlt_buf_dma_handle = NULL;
10095 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
10096 				    "sata_dma_buf_setup: numwin failed\n"));
10097 				return (DDI_FAILURE);
10098 			}
10099 			SATADBG2(SATA_DBG_DMA_SETUP,
10100 			    spx->txlt_sata_hba_inst,
10101 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
10102 			    spx->txlt_num_dma_win,
10103 			    spx->txlt_curwin_num_dma_cookies);
10104 			spx->txlt_cur_dma_win = 0;
10105 			break;
10106 
10107 		case DDI_DMA_MAPPED:
10108 			/* DMA fully mapped */
10109 			spx->txlt_num_dma_win = 1;
10110 			spx->txlt_cur_dma_win = 0;
10111 			SATADBG1(SATA_DBG_DMA_SETUP,
10112 			    spx->txlt_sata_hba_inst,
10113 			    "sata_dma_buf_setup: windows: 1 "
10114 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
10115 			break;
10116 
10117 		default:
10118 			/* DMA mapping failed */
10119 			if (spx->txlt_tmp_buf != NULL) {
10120 				ddi_dma_mem_free(
10121 				    &spx->txlt_tmp_buf_handle);
10122 				spx->txlt_tmp_buf = NULL;
10123 			}
10124 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
10125 			spx->txlt_buf_dma_handle = NULL;
10126 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
10127 			    "sata_dma_buf_setup: buf dma handle binding "
10128 			    "failed %x\n", rval));
10129 			return (rval);
10130 		}
10131 		spx->txlt_curwin_processed_dma_cookies = 0;
10132 		spx->txlt_dma_cookie_list = NULL;
10133 	} else {
10134 		/*
10135 		 * DMA setup is reused. Check if we need to process more
10136 		 * cookies in current window, or to get next window, if any.
10137 		 */
10138 
10139 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
10140 		    spx->txlt_curwin_num_dma_cookies);
10141 
10142 		if (spx->txlt_curwin_processed_dma_cookies ==
10143 		    spx->txlt_curwin_num_dma_cookies) {
10144 			/*
10145 			 * All cookies from current DMA window were processed.
10146 			 * Get next DMA window.
10147 			 */
10148 			spx->txlt_cur_dma_win++;
10149 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
10150 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
10151 				    spx->txlt_cur_dma_win, &offset, &size,
10152 				    &spx->txlt_dma_cookie,
10153 				    &spx->txlt_curwin_num_dma_cookies);
10154 				spx->txlt_curwin_processed_dma_cookies = 0;
10155 			} else {
10156 				/* No more windows! End of request! */
10157 				/* What to do? - panic for now */
10158 				ASSERT(spx->txlt_cur_dma_win >=
10159 				    spx->txlt_num_dma_win);
10160 
10161 				spx->txlt_curwin_num_dma_cookies = 0;
10162 				spx->txlt_curwin_processed_dma_cookies = 0;
10163 				spx->txlt_sata_pkt->
10164 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
10165 				return (DDI_SUCCESS);
10166 			}
10167 		}
10168 	}
10169 	/* There better be at least one DMA cookie outstanding */
10170 	ASSERT((spx->txlt_curwin_num_dma_cookies -
10171 	    spx->txlt_curwin_processed_dma_cookies) > 0);
10172 
10173 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
10174 		/* The default cookie slot was used in previous run */
10175 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
10176 		spx->txlt_dma_cookie_list = NULL;
10177 		spx->txlt_dma_cookie_list_len = 0;
10178 	}
10179 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
10180 		/*
10181 		 * Processing a new DMA window - set-up dma cookies list.
10182 		 * We may reuse previously allocated cookie array if it is
10183 		 * possible.
10184 		 */
10185 		if (spx->txlt_dma_cookie_list != NULL &&
10186 		    spx->txlt_dma_cookie_list_len <
10187 		    spx->txlt_curwin_num_dma_cookies) {
10188 			/*
10189 			 * New DMA window contains more cookies than
10190 			 * the previous one. We need larger cookie list - free
10191 			 * the old one.
10192 			 */
10193 			(void) kmem_free(spx->txlt_dma_cookie_list,
10194 			    spx->txlt_dma_cookie_list_len *
10195 			    sizeof (ddi_dma_cookie_t));
10196 			spx->txlt_dma_cookie_list = NULL;
10197 			spx->txlt_dma_cookie_list_len = 0;
10198 		}
10199 		if (spx->txlt_dma_cookie_list == NULL) {
10200 			/*
10201 			 * Calculate lesser of number of cookies in this
10202 			 * DMA window and number of s/g entries.
10203 			 */
10204 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
10205 			req_len = MIN(max_sg_len,
10206 			    spx->txlt_curwin_num_dma_cookies);
10207 
10208 			/* Allocate new dma cookie array if necessary */
10209 			if (req_len == 1) {
10210 				/* Only one cookie - no need for a list */
10211 				spx->txlt_dma_cookie_list =
10212 				    &spx->txlt_dma_cookie;
10213 				spx->txlt_dma_cookie_list_len = 1;
10214 			} else {
10215 				/*
10216 				 * More than one cookie - try to allocate space.
10217 				 */
10218 				spx->txlt_dma_cookie_list = kmem_zalloc(
10219 				    sizeof (ddi_dma_cookie_t) * req_len,
10220 				    callback == NULL_FUNC ? KM_NOSLEEP :
10221 				    KM_SLEEP);
10222 				if (spx->txlt_dma_cookie_list == NULL) {
10223 					SATADBG1(SATA_DBG_DMA_SETUP,
10224 					    spx->txlt_sata_hba_inst,
10225 					    "sata_dma_buf_setup: cookie list "
10226 					    "allocation failed\n", NULL);
10227 					/*
10228 					 * We could not allocate space for
10229 					 * neccessary number of dma cookies in
10230 					 * this window, so we fail this request.
10231 					 * Next invocation would try again to
10232 					 * allocate space for cookie list.
10233 					 * Note:Packet residue was not modified.
10234 					 */
10235 					return (DDI_DMA_NORESOURCES);
10236 				} else {
10237 					spx->txlt_dma_cookie_list_len = req_len;
10238 				}
10239 			}
10240 		}
10241 		/*
10242 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
10243 		 * First cookie was already fetched.
10244 		 */
10245 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
10246 		cur_txfer_len =
10247 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
10248 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
10249 		spx->txlt_curwin_processed_dma_cookies++;
10250 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
10251 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
10252 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
10253 			    &spx->txlt_dma_cookie_list[i]);
10254 			cur_txfer_len +=
10255 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
10256 			spx->txlt_curwin_processed_dma_cookies++;
10257 			spx->txlt_sata_pkt->
10258 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
10259 		}
10260 	} else {
10261 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
10262 		    "sata_dma_buf_setup: sliding within DMA window, "
10263 		    "cur cookie %d, total cookies %d\n",
10264 		    spx->txlt_curwin_processed_dma_cookies,
10265 		    spx->txlt_curwin_num_dma_cookies);
10266 
10267 		/*
10268 		 * Not all cookies from the current dma window were used because
10269 		 * of s/g limitation.
10270 		 * There is no need to re-size the list - it was set at
10271 		 * optimal size, or only default entry is used (s/g = 1).
10272 		 */
10273 		if (spx->txlt_dma_cookie_list == NULL) {
10274 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
10275 			spx->txlt_dma_cookie_list_len = 1;
10276 		}
10277 		/*
10278 		 * Since we are processing remaining cookies in a DMA window,
10279 		 * there may be less of them than the number of entries in the
10280 		 * current dma cookie list.
10281 		 */
10282 		req_len = MIN(spx->txlt_dma_cookie_list_len,
10283 		    (spx->txlt_curwin_num_dma_cookies -
10284 		    spx->txlt_curwin_processed_dma_cookies));
10285 
10286 		/* Fetch the next batch of cookies */
10287 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
10288 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
10289 			    &spx->txlt_dma_cookie_list[i]);
10290 			cur_txfer_len +=
10291 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
10292 			spx->txlt_sata_pkt->
10293 			    satapkt_cmd.satacmd_num_dma_cookies++;
10294 			spx->txlt_curwin_processed_dma_cookies++;
10295 		}
10296 	}
10297 
10298 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
10299 
10300 	/* Point sata_cmd to the cookie list */
10301 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
10302 	    &spx->txlt_dma_cookie_list[0];
10303 
10304 	/* Remember number of DMA cookies passed in sata packet */
10305 	spx->txlt_num_dma_cookies =
10306 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
10307 
10308 	ASSERT(cur_txfer_len != 0);
10309 	if (cur_txfer_len <= bp->b_bcount)
10310 		spx->txlt_total_residue -= cur_txfer_len;
10311 	else {
10312 		/*
10313 		 * Temporary DMA buffer has been padded by
10314 		 * ddi_dma_mem_alloc()!
10315 		 * This requires special handling, because DMA cookies are
10316 		 * based on the temporary buffer size, not the b_bcount,
10317 		 * and we have extra bytes to transfer - but the packet
10318 		 * residue has to stay correct because we will copy only
10319 		 * the requested number of bytes.
10320 		 */
10321 		spx->txlt_total_residue -= bp->b_bcount;
10322 	}
10323 
10324 	return (DDI_SUCCESS);
10325 }
10326 
10327 /*
10328  * Common routine for releasing DMA resources
10329  */
10330 static void
10331 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
10332 {
10333 	if (spx->txlt_buf_dma_handle != NULL) {
10334 		if (spx->txlt_tmp_buf != NULL)  {
10335 			/*
10336 			 * Intermediate DMA buffer was allocated.
10337 			 * Free allocated buffer and associated access handle.
10338 			 */
10339 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
10340 			spx->txlt_tmp_buf = NULL;
10341 		}
10342 		/*
10343 		 * Free DMA resources - cookies and handles
10344 		 */
10345 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
10346 		if (spx->txlt_dma_cookie_list != NULL) {
10347 			if (spx->txlt_dma_cookie_list !=
10348 			    &spx->txlt_dma_cookie) {
10349 				(void) kmem_free(spx->txlt_dma_cookie_list,
10350 				    spx->txlt_dma_cookie_list_len *
10351 				    sizeof (ddi_dma_cookie_t));
10352 				spx->txlt_dma_cookie_list = NULL;
10353 			}
10354 		}
10355 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
10356 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
10357 		spx->txlt_buf_dma_handle = NULL;
10358 	}
10359 }
10360 
10361 /*
10362  * Free DMA resources
10363  * Used by the HBA driver to release DMA resources that it does not use.
10364  *
10365  * Returns Void
10366  */
10367 void
10368 sata_free_dma_resources(sata_pkt_t *sata_pkt)
10369 {
10370 	sata_pkt_txlate_t *spx;
10371 
10372 	if (sata_pkt == NULL)
10373 		return;
10374 
10375 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
10376 
10377 	sata_common_free_dma_rsrcs(spx);
10378 }
10379 
10380 /*
10381  * Fetch Device Identify data.
10382  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
10383  * command to a device and get the device identify data.
10384  * The device_info structure has to be set to device type (for selecting proper
10385  * device identify command).
10386  *
10387  * Returns:
10388  * SATA_SUCCESS if cmd succeeded
10389  * SATA_RETRY if cmd was rejected and could be retried,
10390  * SATA_FAILURE if cmd failed and should not be retried (port error)
10391  *
10392  * Cannot be called in an interrupt context.
10393  */
10394 
10395 static int
10396 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
10397     sata_drive_info_t *sdinfo)
10398 {
10399 	struct buf *bp;
10400 	sata_pkt_t *spkt;
10401 	sata_cmd_t *scmd;
10402 	sata_pkt_txlate_t *spx;
10403 	int rval;
10404 
10405 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10406 	spx->txlt_sata_hba_inst = sata_hba_inst;
10407 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
10408 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
10409 	if (spkt == NULL) {
10410 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
10411 		return (SATA_RETRY); /* may retry later */
10412 	}
10413 	/* address is needed now */
10414 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10415 
10416 	/*
10417 	 * Allocate buffer for Identify Data return data
10418 	 */
10419 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
10420 	if (bp == NULL) {
10421 		sata_pkt_free(spx);
10422 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
10423 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10424 		    "sata_fetch_device_identify_data: "
10425 		    "cannot allocate buffer for ID"));
10426 		return (SATA_RETRY); /* may retry later */
10427 	}
10428 
10429 	/* Fill sata_pkt */
10430 	sdinfo->satadrv_state = SATA_STATE_PROBING;
10431 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10432 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10433 	/* Synchronous mode, no callback */
10434 	spkt->satapkt_comp = NULL;
10435 	/* Timeout 30s */
10436 	spkt->satapkt_time = sata_default_pkt_time;
10437 
10438 	scmd = &spkt->satapkt_cmd;
10439 	scmd->satacmd_bp = bp;
10440 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
10441 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10442 
10443 	/* Build Identify Device cmd in the sata_pkt */
10444 	scmd->satacmd_addr_type = 0;		/* N/A */
10445 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
10446 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
10447 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
10448 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
10449 	scmd->satacmd_features_reg = 0;		/* N/A */
10450 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
10451 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
10452 		/* Identify Packet Device cmd */
10453 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
10454 	} else {
10455 		/* Identify Device cmd - mandatory for all other devices */
10456 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
10457 	}
10458 
10459 	/* Send pkt to SATA HBA driver */
10460 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
10461 
10462 #ifdef SATA_INJECT_FAULTS
10463 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
10464 #endif
10465 
10466 	if (rval == SATA_TRAN_ACCEPTED &&
10467 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
10468 		if (spx->txlt_buf_dma_handle != NULL) {
10469 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
10470 			    DDI_DMA_SYNC_FORKERNEL);
10471 			ASSERT(rval == DDI_SUCCESS);
10472 		}
10473 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
10474 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
10475 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10476 			    "SATA disk device at port %d - "
10477 			    "partial Identify Data",
10478 			    sdinfo->satadrv_addr.cport));
10479 			rval = SATA_RETRY; /* may retry later */
10480 			goto fail;
10481 		}
10482 		/* Update sata_drive_info */
10483 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
10484 		    sizeof (sata_id_t));
10485 
10486 		sdinfo->satadrv_features_support = 0;
10487 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10488 			/*
10489 			 * Retrieve capacity (disks only) and addressing mode
10490 			 */
10491 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
10492 		} else {
10493 			/*
10494 			 * For ATAPI devices one would have to issue
10495 			 * Get Capacity cmd for media capacity. Not here.
10496 			 */
10497 			sdinfo->satadrv_capacity = 0;
10498 			/*
10499 			 * Check what cdb length is supported
10500 			 */
10501 			if ((sdinfo->satadrv_id.ai_config &
10502 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
10503 				sdinfo->satadrv_atapi_cdb_len = 16;
10504 			else
10505 				sdinfo->satadrv_atapi_cdb_len = 12;
10506 		}
10507 		/* Setup supported features flags */
10508 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
10509 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
10510 
10511 		/* Check for SATA GEN and NCQ support */
10512 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
10513 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
10514 			/* SATA compliance */
10515 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
10516 				sdinfo->satadrv_features_support |=
10517 				    SATA_DEV_F_NCQ;
10518 			if (sdinfo->satadrv_id.ai_satacap &
10519 			    (SATA_1_SPEED | SATA_2_SPEED)) {
10520 				if (sdinfo->satadrv_id.ai_satacap &
10521 				    SATA_2_SPEED)
10522 					sdinfo->satadrv_features_support |=
10523 					    SATA_DEV_F_SATA2;
10524 				if (sdinfo->satadrv_id.ai_satacap &
10525 				    SATA_1_SPEED)
10526 					sdinfo->satadrv_features_support |=
10527 					    SATA_DEV_F_SATA1;
10528 			} else {
10529 				sdinfo->satadrv_features_support |=
10530 				    SATA_DEV_F_SATA1;
10531 			}
10532 		}
10533 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
10534 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
10535 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
10536 
10537 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
10538 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
10539 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
10540 			++sdinfo->satadrv_queue_depth;
10541 			/* Adjust according to controller capabilities */
10542 			sdinfo->satadrv_max_queue_depth = MIN(
10543 			    sdinfo->satadrv_queue_depth,
10544 			    SATA_QDEPTH(sata_hba_inst));
10545 			/* Adjust according to global queue depth limit */
10546 			sdinfo->satadrv_max_queue_depth = MIN(
10547 			    sdinfo->satadrv_max_queue_depth,
10548 			    sata_current_max_qdepth);
10549 			if (sdinfo->satadrv_max_queue_depth == 0)
10550 				sdinfo->satadrv_max_queue_depth = 1;
10551 		} else
10552 			sdinfo->satadrv_max_queue_depth = 1;
10553 
10554 		rval = SATA_SUCCESS;
10555 	} else {
10556 		/*
10557 		 * Woops, no Identify Data.
10558 		 */
10559 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
10560 			rval = SATA_RETRY; /* may retry later */
10561 		} else if (rval == SATA_TRAN_ACCEPTED) {
10562 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
10563 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
10564 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
10565 			    spkt->satapkt_reason == SATA_PKT_RESET)
10566 				rval = SATA_RETRY; /* may retry later */
10567 			else
10568 				rval = SATA_FAILURE;
10569 		} else {
10570 			rval = SATA_FAILURE;
10571 		}
10572 	}
10573 fail:
10574 	/* Free allocated resources */
10575 	sata_free_local_buffer(spx);
10576 	sata_pkt_free(spx);
10577 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
10578 
10579 	return (rval);
10580 }
10581 
10582 
10583 /*
10584  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
10585  * UDMA mode is checked first, followed by MWDMA mode.
10586  * set correctly, so this function is setting it to the highest supported level.
10587  * Older SATA spec required that the device supports at least DMA 4 mode and
10588  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
10589  * restriction has been removed.
10590  *
10591  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
10592  * Returns SATA_FAILURE if proper DMA mode could not be selected.
10593  *
10594  * NOTE: This function should be called only if DMA mode is supported.
10595  */
10596 static int
10597 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
10598 {
10599 	sata_pkt_t *spkt;
10600 	sata_cmd_t *scmd;
10601 	sata_pkt_txlate_t *spx;
10602 	int mode;
10603 	uint8_t subcmd;
10604 	int rval = SATA_SUCCESS;
10605 
10606 	ASSERT(sdinfo != NULL);
10607 	ASSERT(sata_hba_inst != NULL);
10608 
10609 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
10610 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
10611 		/* Find highest Ultra DMA mode supported */
10612 		for (mode = 6; mode >= 0; --mode) {
10613 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
10614 				break;
10615 		}
10616 #if 0
10617 		/* Left for historical reasons */
10618 		/*
10619 		 * Some initial version of SATA spec indicated that at least
10620 		 * UDMA mode 4 has to be supported. It is not mentioned in
10621 		 * SerialATA 2.6, so this restriction is removed.
10622 		 */
10623 		if (mode < 4)
10624 			return (SATA_FAILURE);
10625 #endif
10626 
10627 		/*
10628 		 * We're still going to set DMA mode whatever is selected
10629 		 * by default
10630 		 *
10631 		 * We saw an old maxtor sata drive will select Ultra DMA and
10632 		 * Multi-Word DMA simultaneouly by default, which is going
10633 		 * to cause DMA command timed out, so we need to select DMA
10634 		 * mode even when it's already done by default
10635 		 */
10636 
10637 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
10638 
10639 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
10640 		/* Find highest MultiWord DMA mode supported */
10641 		for (mode = 2; mode >= 0; --mode) {
10642 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
10643 				break;
10644 		}
10645 
10646 		/*
10647 		 * We're still going to set DMA mode whatever is selected
10648 		 * by default
10649 		 *
10650 		 * We saw an old maxtor sata drive will select Ultra DMA and
10651 		 * Multi-Word DMA simultaneouly by default, which is going
10652 		 * to cause DMA command timed out, so we need to select DMA
10653 		 * mode even when it's already done by default
10654 		 */
10655 
10656 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
10657 	} else
10658 		return (SATA_SUCCESS);
10659 
10660 	/*
10661 	 * Set DMA mode via SET FEATURES COMMAND.
10662 	 * Prepare packet for SET FEATURES COMMAND.
10663 	 */
10664 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10665 	spx->txlt_sata_hba_inst = sata_hba_inst;
10666 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
10667 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
10668 	if (spkt == NULL) {
10669 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10670 		    "sata_set_dma_mode: could not set DMA mode %", mode));
10671 		rval = SATA_FAILURE;
10672 		goto done;
10673 	}
10674 	/* Fill sata_pkt */
10675 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10676 	/* Timeout 30s */
10677 	spkt->satapkt_time = sata_default_pkt_time;
10678 	/* Synchronous mode, no callback, interrupts */
10679 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10680 	spkt->satapkt_comp = NULL;
10681 	scmd = &spkt->satapkt_cmd;
10682 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
10683 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10684 	scmd->satacmd_addr_type = 0;
10685 	scmd->satacmd_device_reg = 0;
10686 	scmd->satacmd_status_reg = 0;
10687 	scmd->satacmd_error_reg = 0;
10688 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
10689 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
10690 	scmd->satacmd_sec_count_lsb = subcmd | mode;
10691 
10692 	/* Transfer command to HBA */
10693 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
10694 	    spkt) != SATA_TRAN_ACCEPTED ||
10695 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
10696 		/* Pkt execution failed */
10697 		rval = SATA_FAILURE;
10698 	}
10699 done:
10700 
10701 	/* Free allocated resources */
10702 	if (spkt != NULL)
10703 		sata_pkt_free(spx);
10704 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
10705 
10706 	return (rval);
10707 }
10708 
10709 
10710 /*
10711  * Set device caching mode.
10712  * One of the following operations should be specified:
10713  * SATAC_SF_ENABLE_READ_AHEAD
10714  * SATAC_SF_DISABLE_READ_AHEAD
10715  * SATAC_SF_ENABLE_WRITE_CACHE
10716  * SATAC_SF_DISABLE_WRITE_CACHE
10717  *
10718  * If operation fails, system log messgage is emitted.
10719  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
10720  * command was sent but did not succeed, and SATA_FAILURE otherwise.
10721  */
10722 
10723 static int
10724 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
10725     int cache_op)
10726 {
10727 	sata_pkt_t *spkt;
10728 	sata_cmd_t *scmd;
10729 	sata_pkt_txlate_t *spx;
10730 	int rval = SATA_SUCCESS;
10731 	int hba_rval;
10732 	char *infop;
10733 
10734 	ASSERT(sdinfo != NULL);
10735 	ASSERT(sata_hba_inst != NULL);
10736 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
10737 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
10738 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
10739 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
10740 
10741 
10742 	/* Prepare packet for SET FEATURES COMMAND */
10743 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10744 	spx->txlt_sata_hba_inst = sata_hba_inst;
10745 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
10746 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
10747 	if (spkt == NULL) {
10748 		rval = SATA_FAILURE;
10749 		goto failure;
10750 	}
10751 	/* Fill sata_pkt */
10752 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10753 	/* Timeout 30s */
10754 	spkt->satapkt_time = sata_default_pkt_time;
10755 	/* Synchronous mode, no callback, interrupts */
10756 	spkt->satapkt_op_mode =
10757 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10758 	spkt->satapkt_comp = NULL;
10759 	scmd = &spkt->satapkt_cmd;
10760 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
10761 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10762 	scmd->satacmd_addr_type = 0;
10763 	scmd->satacmd_device_reg = 0;
10764 	scmd->satacmd_status_reg = 0;
10765 	scmd->satacmd_error_reg = 0;
10766 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
10767 	scmd->satacmd_features_reg = cache_op;
10768 
10769 	/* Transfer command to HBA */
10770 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
10771 	    SATA_DIP(sata_hba_inst), spkt);
10772 
10773 #ifdef SATA_INJECT_FAULTS
10774 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
10775 #endif
10776 
10777 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
10778 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
10779 		/* Pkt execution failed */
10780 		switch (cache_op) {
10781 		case SATAC_SF_ENABLE_READ_AHEAD:
10782 			infop = "enabling read ahead failed";
10783 			break;
10784 		case SATAC_SF_DISABLE_READ_AHEAD:
10785 			infop = "disabling read ahead failed";
10786 			break;
10787 		case SATAC_SF_ENABLE_WRITE_CACHE:
10788 			infop = "enabling write cache failed";
10789 			break;
10790 		case SATAC_SF_DISABLE_WRITE_CACHE:
10791 			infop = "disabling write cache failed";
10792 			break;
10793 		}
10794 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
10795 		rval = SATA_RETRY;
10796 	}
10797 failure:
10798 	/* Free allocated resources */
10799 	if (spkt != NULL)
10800 		sata_pkt_free(spx);
10801 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
10802 	return (rval);
10803 }
10804 
10805 /*
10806  * Set Removable Media Status Notification (enable/disable)
10807  * state == 0 , disable
10808  * state != 0 , enable
10809  *
10810  * If operation fails, system log messgage is emitted.
10811  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
10812  */
10813 
10814 static int
10815 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
10816     int state)
10817 {
10818 	sata_pkt_t *spkt;
10819 	sata_cmd_t *scmd;
10820 	sata_pkt_txlate_t *spx;
10821 	int rval = SATA_SUCCESS;
10822 	char *infop;
10823 
10824 	ASSERT(sdinfo != NULL);
10825 	ASSERT(sata_hba_inst != NULL);
10826 
10827 	/* Prepare packet for SET FEATURES COMMAND */
10828 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10829 	spx->txlt_sata_hba_inst = sata_hba_inst;
10830 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
10831 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
10832 	if (spkt == NULL) {
10833 		rval = SATA_FAILURE;
10834 		goto failure;
10835 	}
10836 	/* Fill sata_pkt */
10837 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
10838 	/* Timeout 30s */
10839 	spkt->satapkt_time = sata_default_pkt_time;
10840 	/* Synchronous mode, no callback, interrupts */
10841 	spkt->satapkt_op_mode =
10842 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10843 	spkt->satapkt_comp = NULL;
10844 	scmd = &spkt->satapkt_cmd;
10845 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
10846 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10847 	scmd->satacmd_addr_type = 0;
10848 	scmd->satacmd_device_reg = 0;
10849 	scmd->satacmd_status_reg = 0;
10850 	scmd->satacmd_error_reg = 0;
10851 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
10852 	if (state == 0)
10853 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
10854 	else
10855 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
10856 
10857 	/* Transfer command to HBA */
10858 	if (((*SATA_START_FUNC(sata_hba_inst))(
10859 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
10860 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
10861 		/* Pkt execution failed */
10862 		if (state == 0)
10863 			infop = "disabling Removable Media Status "
10864 			    "Notification failed";
10865 		else
10866 			infop = "enabling Removable Media Status "
10867 			    "Notification failed";
10868 
10869 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
10870 		rval = SATA_FAILURE;
10871 	}
10872 failure:
10873 	/* Free allocated resources */
10874 	if (spkt != NULL)
10875 		sata_pkt_free(spx);
10876 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
10877 	return (rval);
10878 }
10879 
10880 
10881 /*
10882  * Update port SCR block
10883  */
10884 static void
10885 sata_update_port_scr(sata_port_scr_t *port_scr, sata_device_t *device)
10886 {
10887 	port_scr->sstatus = device->satadev_scr.sstatus;
10888 	port_scr->serror = device->satadev_scr.serror;
10889 	port_scr->scontrol = device->satadev_scr.scontrol;
10890 	port_scr->sactive = device->satadev_scr.sactive;
10891 	port_scr->snotific = device->satadev_scr.snotific;
10892 }
10893 
10894 /*
10895  * Update state and copy port ss* values from passed sata_device structure.
10896  * sata_address is validated - if not valid, nothing is changed in sata_scsi
10897  * configuration struct.
10898  *
10899  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
10900  * regardless of the state in device argument.
10901  *
10902  * Port mutex should be held while calling this function.
10903  */
10904 static void
10905 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
10906 	sata_device_t *sata_device)
10907 {
10908 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst,
10909 	    sata_device->satadev_addr.cport)));
10910 
10911 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
10912 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
10913 
10914 		sata_cport_info_t *cportinfo;
10915 
10916 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
10917 		    sata_device->satadev_addr.cport)
10918 			return;
10919 
10920 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
10921 		    sata_device->satadev_addr.cport);
10922 		sata_update_port_scr(&cportinfo->cport_scr, sata_device);
10923 
10924 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
10925 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
10926 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
10927 		cportinfo->cport_state |=
10928 		    sata_device->satadev_state & SATA_PSTATE_VALID;
10929 	} else {
10930 		sata_pmport_info_t *pmportinfo;
10931 
10932 		if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT) ||
10933 		    (sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
10934 		    SATA_NUM_PMPORTS(sata_hba_inst,
10935 		    sata_device->satadev_addr.cport) <
10936 		    sata_device->satadev_addr.pmport)
10937 			return;
10938 
10939 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
10940 		    sata_device->satadev_addr.cport,
10941 		    sata_device->satadev_addr.pmport);
10942 		sata_update_port_scr(&pmportinfo->pmport_scr, sata_device);
10943 
10944 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
10945 		pmportinfo->pmport_state &=
10946 		    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF |
10947 		    SATA_PSTATE_FAILED);
10948 		pmportinfo->pmport_state |=
10949 		    sata_device->satadev_state & SATA_PSTATE_VALID;
10950 	}
10951 }
10952 
10953 
10954 
10955 /*
10956  * Extract SATA port specification from an IOCTL argument.
10957  *
10958  * This function return the port the user land send us as is, unless it
10959  * cannot retrieve port spec, then -1 is returned.
10960  *
10961  * Note: Only cport  - no port multiplier port.
10962  */
10963 static int32_t
10964 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
10965 {
10966 	int32_t port;
10967 
10968 	/* Extract port number from nvpair in dca structure  */
10969 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
10970 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
10971 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
10972 		    port));
10973 		port = -1;
10974 	}
10975 
10976 	return (port);
10977 }
10978 
10979 /*
10980  * Get dev_info_t pointer to the device node pointed to by port argument.
10981  * NOTE: target argument is a value used in ioctls to identify
10982  * the AP - it is not a sata_address.
10983  * It is a combination of cport, pmport and address qualifier, encodded same
10984  * way as a scsi target number.
10985  * At this moment it carries only cport number.
10986  *
10987  * No PMult hotplug support.
10988  *
10989  * Returns dev_info_t pointer if target device was found, NULL otherwise.
10990  */
10991 
10992 static dev_info_t *
10993 sata_get_target_dip(dev_info_t *dip, int32_t port)
10994 {
10995 	dev_info_t	*cdip = NULL;
10996 	int		target, tgt;
10997 	int		ncport;
10998 	int 		circ;
10999 
11000 	ncport = port & SATA_CFGA_CPORT_MASK;
11001 	target = SATA_TO_SCSI_TARGET(ncport, 0, SATA_ADDR_DCPORT);
11002 
11003 	ndi_devi_enter(dip, &circ);
11004 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
11005 		dev_info_t *next = ddi_get_next_sibling(cdip);
11006 
11007 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
11008 		    DDI_PROP_DONTPASS, "target", -1);
11009 		if (tgt == -1) {
11010 			/*
11011 			 * This is actually an error condition, but not
11012 			 * a fatal one. Just continue the search.
11013 			 */
11014 			cdip = next;
11015 			continue;
11016 		}
11017 
11018 		if (tgt == target)
11019 			break;
11020 
11021 		cdip = next;
11022 	}
11023 	ndi_devi_exit(dip, circ);
11024 
11025 	return (cdip);
11026 }
11027 
11028 /*
11029  * Get dev_info_t pointer to the device node pointed to by port argument.
11030  * NOTE: target argument is a value used in ioctls to identify
11031  * the AP - it is not a sata_address.
11032  * It is a combination of cport, pmport and address qualifier, encoded same
11033  * way as a scsi target number.
11034  * At this moment it carries only cport number.
11035  *
11036  * No PMult hotplug support.
11037  *
11038  * Returns dev_info_t pointer if target device was found, NULL otherwise.
11039  */
11040 
11041 static dev_info_t *
11042 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
11043 {
11044 	dev_info_t	*cdip = NULL;
11045 	int		target, tgt;
11046 	int 		circ;
11047 
11048 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
11049 
11050 	ndi_devi_enter(dip, &circ);
11051 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
11052 		dev_info_t *next = ddi_get_next_sibling(cdip);
11053 
11054 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
11055 		    DDI_PROP_DONTPASS, "target", -1);
11056 		if (tgt == -1) {
11057 			/*
11058 			 * This is actually an error condition, but not
11059 			 * a fatal one. Just continue the search.
11060 			 */
11061 			cdip = next;
11062 			continue;
11063 		}
11064 
11065 		if (tgt == target)
11066 			break;
11067 
11068 		cdip = next;
11069 	}
11070 	ndi_devi_exit(dip, circ);
11071 
11072 	return (cdip);
11073 }
11074 
11075 /*
11076  * Process sata port disconnect request.
11077  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
11078  * before this request. Nevertheless, if a device is still configured,
11079  * we need to attempt to offline and unconfigure device.
11080  * Regardless of the unconfigure operation results the port is marked as
11081  * deactivated and no access to the attached device is possible.
11082  * If the target node remains because unconfigure operation failed, its state
11083  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
11084  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
11085  * the device and remove old target node.
11086  *
11087  * This function invokes sata_hba_inst->satahba_tran->
11088  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
11089  * If successful, the device structure (if any) attached to the specified port
11090  * is removed and state of the port marked appropriately.
11091  * Failure of the port_deactivate may keep port in the physically active state,
11092  * or may fail the port.
11093  *
11094  * NOTE: Port multiplier code is not completed nor tested.
11095  */
11096 
11097 static int
11098 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
11099     sata_device_t *sata_device)
11100 {
11101 	sata_drive_info_t *sdinfo = NULL;
11102 	sata_cport_info_t *cportinfo = NULL;
11103 	sata_pmport_info_t *pmportinfo = NULL;
11104 	sata_pmult_info_t *pmultinfo = NULL;
11105 	dev_info_t *tdip;
11106 	int cport, pmport, qual;
11107 	int rval = SATA_SUCCESS;
11108 	int rv = 0;
11109 
11110 	cport = sata_device->satadev_addr.cport;
11111 	pmport = sata_device->satadev_addr.pmport;
11112 	qual = sata_device->satadev_addr.qual;
11113 
11114 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
11115 
11116 	/*
11117 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
11118 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
11119 	 * Do the sanity check.
11120 	 */
11121 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
11122 		/* No physical port deactivation supported. */
11123 		return (EINVAL);
11124 	}
11125 
11126 	/* Check the current state of the port */
11127 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11128 	    (SATA_DIP(sata_hba_inst), sata_device);
11129 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11130 	sata_update_port_info(sata_hba_inst, sata_device);
11131 	if (rval != SATA_SUCCESS ||
11132 	    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
11133 		/* Device port status is unknown or it is in failed state */
11134 		if (qual == SATA_ADDR_PMPORT) {
11135 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
11136 			    SATA_PSTATE_FAILED;
11137 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
11138 			    "sata_hba_ioctl: connect: failed to deactivate "
11139 			    "SATA port %d", cport);
11140 		} else {
11141 			SATA_CPORT_STATE(sata_hba_inst, cport) =
11142 			    SATA_PSTATE_FAILED;
11143 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
11144 			    "sata_hba_ioctl: connect: failed to deactivate "
11145 			    "SATA port %d:%d", cport, pmport);
11146 		}
11147 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
11148 		    cport)->cport_mutex);
11149 		return (EIO);
11150 	}
11151 	/*
11152 	 * Set port's dev_state to not ready - this will disable
11153 	 * an access to a potentially attached device.
11154 	 */
11155 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11156 	if (qual == SATA_ADDR_PMPORT) {
11157 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11158 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
11159 			sdinfo = pmportinfo->pmport_sata_drive;
11160 			ASSERT(sdinfo != NULL);
11161 		}
11162 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
11163 	} else {
11164 		/* Assuming cport */
11165 
11166 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
11167 			if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
11168 				pmultinfo =
11169 				    cportinfo->cport_devp.cport_sata_pmult;
11170 				ASSERT(pmultinfo != NULL);
11171 			} else {
11172 				sdinfo = cportinfo->cport_devp.cport_sata_drive;
11173 			}
11174 		}
11175 		cportinfo->cport_state &= ~SATA_STATE_READY;
11176 	}
11177 	if (sdinfo != NULL) {
11178 		if ((sdinfo->satadrv_type & (SATA_VALID_DEV_TYPE)) != 0) {
11179 			/*
11180 			 * If a target node exists, try to offline
11181 			 * a device and remove target node.
11182 			 */
11183 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
11184 			    cport)->cport_mutex);
11185 			/* We are addressing attached device, not a port */
11186 			sata_device->satadev_addr.qual =
11187 			    sdinfo->satadrv_addr.qual;
11188 			tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11189 			    &sata_device->satadev_addr);
11190 			if (tdip != NULL && ndi_devi_offline(tdip,
11191 			    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11192 				/*
11193 				 * Problem
11194 				 * The target node remained attached.
11195 				 * This happens when the device file was open
11196 				 * or a node was waiting for resources.
11197 				 * Cannot do anything about it.
11198 				 */
11199 				if (qual == SATA_ADDR_CPORT) {
11200 					SATA_LOG_D((sata_hba_inst, CE_WARN,
11201 					    "sata_hba_ioctl: disconnect: could "
11202 					    "not unconfigure device before "
11203 					    "disconnecting the SATA port %d",
11204 					    cport));
11205 				} else {
11206 					SATA_LOG_D((sata_hba_inst, CE_WARN,
11207 					    "sata_hba_ioctl: disconnect: could "
11208 					    "not unconfigure device before "
11209 					    "disconnecting the SATA port %d:%d",
11210 					    cport, pmport));
11211 				}
11212 				/*
11213 				 * Set DEVICE REMOVED state in the target
11214 				 * node. It will prevent access to the device
11215 				 * even when a new device is attached, until
11216 				 * the old target node is released, removed and
11217 				 * recreated for a new  device.
11218 				 */
11219 				sata_set_device_removed(tdip);
11220 
11221 				/*
11222 				 * Instruct event daemon to try the target
11223 				 * node cleanup later.
11224 				 */
11225 				sata_set_target_node_cleanup(
11226 				    sata_hba_inst, &sata_device->satadev_addr);
11227 			}
11228 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11229 			    cport)->cport_mutex);
11230 		}
11231 
11232 		/* Remove and release sata_drive info structure. */
11233 		if (pmportinfo != NULL) {
11234 			SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport) =
11235 			    NULL;
11236 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11237 		} else {
11238 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11239 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11240 		}
11241 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
11242 	}
11243 #if 0
11244 	else if (pmultinfo != NULL) {
11245 		/*
11246 		 * Port Multiplier itself needs special handling.
11247 		 * All device ports need to be processed here!
11248 		 */
11249 	}
11250 #endif
11251 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11252 	/* Just ask HBA driver to deactivate port */
11253 	/*	sata_device->satadev_addr.qual = SATA_ADDR_DCPORT; */
11254 
11255 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
11256 	    (SATA_DIP(sata_hba_inst), sata_device);
11257 
11258 	/*
11259 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11260 	 * without the hint (to force listener to investivate the state).
11261 	 */
11262 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
11263 	    SE_NO_HINT);
11264 
11265 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11266 	sata_update_port_info(sata_hba_inst, sata_device);
11267 
11268 	if (rval != SATA_SUCCESS) {
11269 		/*
11270 		 * Port deactivation failure - do not
11271 		 * change port state unless the state
11272 		 * returned by HBA indicates a port failure.
11273 		 * NOTE: device structures were released, so devices now are
11274 		 * invisible! Port reset is needed to re-enumerate devices.
11275 		 */
11276 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11277 			if (pmportinfo != NULL)
11278 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
11279 			else
11280 				cportinfo->cport_state = SATA_PSTATE_FAILED;
11281 			rv = EIO;
11282 		}
11283 	} else {
11284 		/*
11285 		 * Deactivation succeded. From now on the sata framework
11286 		 * will not care what is happening to the device, until
11287 		 * the port is activated again.
11288 		 */
11289 		cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
11290 	}
11291 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11292 	return (rv);
11293 }
11294 
11295 
11296 
11297 /*
11298  * Process sata port connect request
11299  * The sata cfgadm pluging will invoke this operation only if port was found
11300  * in the disconnect state (failed state is also treated as the disconnected
11301  * state).
11302  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
11303  * sata_tran_hotplug_ops->sata_tran_port_activate().
11304  * If successful and a device is found attached to the port,
11305  * the initialization sequence is executed to attach a device structure to
11306  * a port structure. The state of the port and a device would be set
11307  * appropriately.
11308  * The device is not set in configured state (system-wise) by this operation.
11309  *
11310  * Note, that activating the port may generate link events,
11311  * so it is important that following processing and the
11312  * event processing does not interfere with each other!
11313  *
11314  * This operation may remove port failed state and will
11315  * try to make port active and in good standing.
11316  *
11317  * NOTE: Port multiplier code is not completed nor tested.
11318  */
11319 
11320 static int
11321 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
11322     sata_device_t *sata_device)
11323 {
11324 	int cport, pmport, qual;
11325 	int rv = 0;
11326 
11327 	cport = sata_device->satadev_addr.cport;
11328 	pmport = sata_device->satadev_addr.pmport;
11329 	qual = sata_device->satadev_addr.qual;
11330 
11331 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
11332 
11333 	/*
11334 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
11335 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
11336 	 * Perform sanity check now.
11337 	 */
11338 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
11339 		/* No physical port activation supported. */
11340 		return (EINVAL);
11341 	}
11342 
11343 	/* Just ask HBA driver to activate port */
11344 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
11345 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
11346 		/*
11347 		 * Port activation failure.
11348 		 */
11349 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11350 		    cport)->cport_mutex);
11351 		sata_update_port_info(sata_hba_inst, sata_device);
11352 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11353 			if (qual == SATA_ADDR_DCPORT) {
11354 				SATA_CPORT_STATE(sata_hba_inst, cport) =
11355 				    SATA_PSTATE_FAILED;
11356 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
11357 				    "sata_hba_ioctl: connect: failed to "
11358 				    "activate SATA port %d", cport);
11359 			} else { /* port multiplier device port */
11360 				SATA_PMPORT_STATE(sata_hba_inst, cport,
11361 				    pmport) = SATA_PSTATE_FAILED;
11362 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
11363 				    "sata_hba_ioctl: connect: failed to "
11364 				    "activate SATA port %d:%d", cport, pmport);
11365 
11366 			}
11367 		}
11368 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
11369 		    cport)->cport_mutex);
11370 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
11371 		    "sata_hba_ioctl: connect: failed to activate SATA "
11372 		    "port %d:%d", cport, pmport);
11373 		return (EIO);
11374 	}
11375 
11376 	/* Virgin port state - will be updated by the port re-probe. */
11377 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11378 	if (qual == SATA_ADDR_CPORT)
11379 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
11380 	else /* port multiplier device port */
11381 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
11382 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11383 
11384 	/*
11385 	 * Probe the port to find its state and attached device.
11386 	 */
11387 	if (sata_reprobe_port(sata_hba_inst, sata_device,
11388 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
11389 		rv = EIO;
11390 
11391 	/*
11392 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11393 	 * without the hint
11394 	 */
11395 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
11396 	    SE_NO_HINT);
11397 
11398 	/*
11399 	 * If there is a device attached to the port, emit
11400 	 * a message.
11401 	 */
11402 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
11403 
11404 		if (qual == SATA_ADDR_CPORT) {
11405 			sata_log(sata_hba_inst, CE_WARN,
11406 			    "SATA device detected at port %d", cport);
11407 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
11408 				/*
11409 				 * A device was not successfully identified
11410 				 */
11411 				sata_log(sata_hba_inst, CE_WARN,
11412 				    "Could not identify SATA "
11413 				    "device at port %d", cport);
11414 			}
11415 		} else { /* port multiplier device port */
11416 			sata_log(sata_hba_inst, CE_WARN,
11417 			    "SATA device detected at port %d:%d",
11418 			    cport, pmport);
11419 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
11420 				/*
11421 				 * A device was not successfully identified
11422 				 */
11423 				sata_log(sata_hba_inst, CE_WARN,
11424 				    "Could not identify SATA "
11425 				    "device at port %d:%d", cport, pmport);
11426 			}
11427 		}
11428 	}
11429 
11430 	return (rv);
11431 }
11432 
11433 
11434 /*
11435  * Process sata device unconfigure request.
11436  * The unconfigure operation uses generic nexus operation to
11437  * offline a device. It leaves a target device node attached.
11438  * and obviously sata_drive_info attached as well, because
11439  * from the hardware point of view nothing has changed.
11440  */
11441 static int
11442 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
11443     sata_device_t *sata_device)
11444 {
11445 	int rv = 0;
11446 	dev_info_t *tdip;
11447 
11448 	/* We are addressing attached device, not a port */
11449 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
11450 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
11451 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
11452 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
11453 
11454 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11455 	    &sata_device->satadev_addr)) != NULL) {
11456 
11457 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
11458 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11459 			    "sata_hba_ioctl: unconfigure: "
11460 			    "failed to unconfigure device at SATA port %d:%d",
11461 			    sata_device->satadev_addr.cport,
11462 			    sata_device->satadev_addr.pmport));
11463 			rv = EIO;
11464 		}
11465 		/*
11466 		 * The target node devi_state should be marked with
11467 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
11468 		 * This would be the indication for cfgadm that
11469 		 * the AP node occupant state is 'unconfigured'.
11470 		 */
11471 
11472 	} else {
11473 		/*
11474 		 * This would indicate a failure on the part of cfgadm
11475 		 * to detect correct state of the node prior to this
11476 		 * call - one cannot unconfigure non-existing device.
11477 		 */
11478 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11479 		    "sata_hba_ioctl: unconfigure: "
11480 		    "attempt to unconfigure non-existing device "
11481 		    "at SATA port %d:%d",
11482 		    sata_device->satadev_addr.cport,
11483 		    sata_device->satadev_addr.pmport));
11484 		rv = ENXIO;
11485 	}
11486 	return (rv);
11487 }
11488 
11489 /*
11490  * Process sata device configure request
11491  * If port is in a failed state, operation is aborted - one has to use
11492  * an explicit connect or port activate request to try to get a port into
11493  * non-failed mode. Port reset wil also work in such situation.
11494  * If the port is in disconnected (shutdown) state, the connect operation is
11495  * attempted prior to any other action.
11496  * When port is in the active state, there is a device attached and the target
11497  * node exists, a device was most likely offlined.
11498  * If target node does not exist, a new target node is created. In both cases
11499  * an attempt is made to online (configure) the device.
11500  *
11501  * NOTE: Port multiplier code is not completed nor tested.
11502  */
11503 static int
11504 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
11505     sata_device_t *sata_device)
11506 {
11507 	int cport, pmport, qual;
11508 	int rval;
11509 	boolean_t target = TRUE;
11510 	sata_cport_info_t *cportinfo;
11511 	sata_pmport_info_t *pmportinfo = NULL;
11512 	dev_info_t *tdip;
11513 	sata_drive_info_t *sdinfo;
11514 
11515 	cport = sata_device->satadev_addr.cport;
11516 	pmport = sata_device->satadev_addr.pmport;
11517 	qual = sata_device->satadev_addr.qual;
11518 
11519 	/* Get current port state */
11520 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11521 	    (SATA_DIP(sata_hba_inst), sata_device);
11522 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11523 	sata_update_port_info(sata_hba_inst, sata_device);
11524 
11525 	if (rval != SATA_SUCCESS ||
11526 	    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
11527 		/*
11528 		 * Obviously, device on a failed port is not visible
11529 		 */
11530 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11531 		return (ENXIO);
11532 	}
11533 
11534 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11535 	if (qual == SATA_ADDR_PMPORT)
11536 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11537 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11538 
11539 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
11540 		/* need to activate port */
11541 		target = FALSE;
11542 
11543 		/* Sanity check */
11544 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
11545 			return (ENXIO);
11546 
11547 		/* Just let HBA driver to activate port */
11548 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
11549 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
11550 			/*
11551 			 * Port activation failure - do not change port state
11552 			 * unless the state returned by HBA indicates a port
11553 			 * failure.
11554 			 */
11555 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11556 			    cport)->cport_mutex);
11557 			sata_update_port_info(sata_hba_inst, sata_device);
11558 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11559 				if (qual == SATA_ADDR_PMPORT)
11560 					pmportinfo->pmport_state =
11561 					    SATA_PSTATE_FAILED;
11562 				else
11563 					cportinfo->cport_state =
11564 					    SATA_PSTATE_FAILED;
11565 			}
11566 			mutex_exit(&SATA_CPORT_INFO(
11567 			    sata_hba_inst, cport)->cport_mutex);
11568 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11569 			    "sata_hba_ioctl: configure: "
11570 			    "failed to activate SATA port %d:%d",
11571 			    cport, pmport));
11572 			return (EIO);
11573 		}
11574 		/*
11575 		 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11576 		 * without the hint.
11577 		 */
11578 		sata_gen_sysevent(sata_hba_inst,
11579 		    &sata_device->satadev_addr, SE_NO_HINT);
11580 
11581 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11582 		    cport_mutex);
11583 		/* Virgin port state */
11584 		if (qual == SATA_ADDR_PMPORT)
11585 			pmportinfo->pmport_state = 0;
11586 		else
11587 			cportinfo->cport_state = 0;
11588 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11589 	}
11590 	/*
11591 	 * Always reprobe port, to get current device info.
11592 	 */
11593 	if (sata_reprobe_port(sata_hba_inst, sata_device,
11594 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
11595 		return (EIO);
11596 
11597 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == FALSE) {
11598 		if (qual == SATA_ADDR_PMPORT) {
11599 			/*
11600 			 * That's the transition from "inactive" port
11601 			 * to active one with device attached.
11602 			 */
11603 			sata_log(sata_hba_inst, CE_WARN,
11604 			    "SATA device detected at port %d:%d",
11605 			    cport, pmport);
11606 		} else {
11607 			/*
11608 			 * When PM is attached to the cport and cport is
11609 			 * activated, every PM device port needs to be reprobed.
11610 			 * We need to emit message for all devices detected
11611 			 * at port multiplier's device ports.
11612 			 * Add such code here.
11613 			 * For now, just inform about device attached to
11614 			 * cport.
11615 			 */
11616 			sata_log(sata_hba_inst, CE_WARN,
11617 			    "SATA device detected at port %d", cport);
11618 		}
11619 	}
11620 
11621 	/*
11622 	 * This is where real configuration operation starts.
11623 	 *
11624 	 * When PM is attached to the cport and cport is activated,
11625 	 * devices attached PM device ports may have to be configured
11626 	 * explicitly. This may change when port multiplier is supported.
11627 	 * For now, configure only disks and other valid target devices.
11628 	 */
11629 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
11630 		if (qual == SATA_ADDR_CPORT) {
11631 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
11632 				/*
11633 				 * A device was not successfully identified
11634 				 */
11635 				sata_log(sata_hba_inst, CE_WARN,
11636 				    "Could not identify SATA "
11637 				    "device at port %d", cport);
11638 			}
11639 		} else { /* port multiplier device port */
11640 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
11641 				/*
11642 				 * A device was not successfully identified
11643 				 */
11644 				sata_log(sata_hba_inst, CE_WARN,
11645 				    "Could not identify SATA "
11646 				    "device at port %d:%d", cport, pmport);
11647 			}
11648 		}
11649 		return (ENXIO);		/* No device to configure */
11650 	}
11651 
11652 	/*
11653 	 * Here we may have a device in reset condition,
11654 	 * but because we are just configuring it, there is
11655 	 * no need to process the reset other than just
11656 	 * to clear device reset condition in the HBA driver.
11657 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
11658 	 * cause a first command sent the HBA driver with the request
11659 	 * to clear device reset condition.
11660 	 */
11661 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11662 	if (qual == SATA_ADDR_PMPORT)
11663 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
11664 	else
11665 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
11666 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11667 	if (sdinfo == NULL) {
11668 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11669 		return (ENXIO);
11670 	}
11671 	if (sdinfo->satadrv_event_flags &
11672 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
11673 		sdinfo->satadrv_event_flags = 0;
11674 	}
11675 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
11676 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11677 
11678 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11679 	    &sata_device->satadev_addr)) != NULL) {
11680 		/*
11681 		 * Target node exists. Verify, that it belongs
11682 		 * to existing, attached device and not to
11683 		 * a removed device.
11684 		 */
11685 		if (sata_check_device_removed(tdip) == B_TRUE) {
11686 			if (qual == SATA_ADDR_DPMPORT)
11687 				sata_log(sata_hba_inst, CE_WARN,
11688 				    "SATA device at port %d cannot be "
11689 				    "configured. "
11690 				    "Application(s) accessing "
11691 				    "previously attached device "
11692 				    "have to release it before newly "
11693 				    "inserted device can be made accessible.",
11694 				    cport);
11695 			else
11696 				sata_log(sata_hba_inst, CE_WARN,
11697 				    "SATA device at port %d:%d cannot be"
11698 				    "configured. "
11699 				    "Application(s) accessing "
11700 				    "previously attached device "
11701 				    "have to release it before newly "
11702 				    "inserted device can be made accessible.",
11703 				    cport, pmport);
11704 			return (EIO);
11705 		}
11706 		/*
11707 		 * Device was not removed and re-inserted.
11708 		 * Try to online it.
11709 		 */
11710 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
11711 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11712 			    "sata_hba_ioctl: configure: "
11713 			    "onlining device at SATA port "
11714 			    "%d:%d failed", cport, pmport));
11715 			return (EIO);
11716 		}
11717 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11718 		    cport)->cport_mutex);
11719 
11720 		if (qual == SATA_ADDR_DPMPORT)
11721 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
11722 		else
11723 			cportinfo-> cport_tgtnode_clean = B_TRUE;
11724 
11725 		mutex_exit(&SATA_CPORT_INFO(
11726 		    sata_hba_inst, cport)->cport_mutex);
11727 	} else {
11728 		/*
11729 		 * No target node - need to create a new target node.
11730 		 */
11731 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11732 		    cport_mutex);
11733 		if (qual == SATA_ADDR_DPMPORT)
11734 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
11735 		else
11736 			cportinfo-> cport_tgtnode_clean = B_TRUE;
11737 
11738 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11739 		    cport_mutex);
11740 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
11741 		    sata_hba_inst, &sata_device->satadev_addr);
11742 		if (tdip == NULL) {
11743 			/* Configure operation failed */
11744 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11745 			    "sata_hba_ioctl: configure: "
11746 			    "configuring SATA device at port %d:%d "
11747 			    "failed", cport, pmport));
11748 			return (EIO);
11749 		}
11750 	}
11751 	return (0);
11752 }
11753 
11754 
11755 /*
11756  * Process ioctl deactivate port request.
11757  * Arbitrarily unconfigure attached device, if any.
11758  * Even if the unconfigure fails, proceed with the
11759  * port deactivation.
11760  *
11761  * NOTE: Port Multiplier code is not completed and tested.
11762  */
11763 
11764 static int
11765 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
11766     sata_device_t *sata_device)
11767 {
11768 	int cport, pmport, qual;
11769 	int rval, rv = 0;
11770 	sata_cport_info_t *cportinfo;
11771 	sata_pmport_info_t *pmportinfo = NULL;
11772 	dev_info_t *tdip;
11773 	sata_drive_info_t *sdinfo = NULL;
11774 
11775 	/* Sanity check */
11776 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
11777 		return (ENOTSUP);
11778 
11779 	cport = sata_device->satadev_addr.cport;
11780 	pmport = sata_device->satadev_addr.pmport;
11781 	qual = sata_device->satadev_addr.qual;
11782 
11783 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11784 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11785 	if (qual == SATA_ADDR_CPORT) {
11786 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
11787 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
11788 			/*
11789 			 * For now, assume that port multiplier is not
11790 			 * supported, i.e. deal only with valid devices
11791 			 */
11792 			if ((cportinfo->cport_dev_type &
11793 			    SATA_VALID_DEV_TYPE) != 0)
11794 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11795 			/*
11796 			 * If attached device is a port multiplier, we will
11797 			 * have to unconfigure all devices attached to the
11798 			 * port multiplier. Add this code here.
11799 			 */
11800 		}
11801 		cportinfo->cport_state &= ~SATA_STATE_READY;
11802 	} else {
11803 		/* Port multiplier device port */
11804 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11805 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
11806 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
11807 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
11808 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11809 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
11810 	}
11811 
11812 	if (sdinfo != NULL) {
11813 		/*
11814 		 * If a target node exists, try to offline a device and
11815 		 * to remove a target node.
11816 		 */
11817 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11818 		    cport_mutex);
11819 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11820 		    &sata_device->satadev_addr);
11821 		if (tdip != NULL) {
11822 			/* target node exist */
11823 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
11824 			    "sata_hba_ioctl: port deactivate: "
11825 			    "target node exists.", NULL);
11826 
11827 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
11828 			    NDI_SUCCESS) {
11829 				SATA_LOG_D((sata_hba_inst, CE_WARN,
11830 				    "sata_hba_ioctl: port deactivate: "
11831 				    "failed to unconfigure device at port "
11832 				    "%d:%d before deactivating the port",
11833 				    cport, pmport));
11834 				/*
11835 				 * Set DEVICE REMOVED state in the target
11836 				 * node. It will prevent an access to
11837 				 * the device even when a new device is
11838 				 * attached, until the old target node is
11839 				 * released, removed and recreated for a new
11840 				 * device.
11841 				 */
11842 				sata_set_device_removed(tdip);
11843 
11844 				/*
11845 				 * Instruct the event daemon to try the
11846 				 * target node cleanup later.
11847 				 */
11848 				sata_set_target_node_cleanup(sata_hba_inst,
11849 				    &sata_device->satadev_addr);
11850 			}
11851 		}
11852 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
11853 		    cport_mutex);
11854 		/*
11855 		 * In any case, remove and release sata_drive_info
11856 		 * structure.
11857 		 */
11858 		if (qual == SATA_ADDR_CPORT) {
11859 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11860 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11861 		} else { /* port multiplier device port */
11862 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11863 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11864 		}
11865 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
11866 	}
11867 	if (qual == SATA_ADDR_CPORT) {
11868 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
11869 		    SATA_STATE_PROBING);
11870 	} else { /* port multiplier device port */
11871 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
11872 		    SATA_STATE_PROBING);
11873 	}
11874 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11875 
11876 	/* Just let HBA driver to deactivate port */
11877 	sata_device->satadev_addr.qual = qual;
11878 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
11879 	    (SATA_DIP(sata_hba_inst), sata_device);
11880 
11881 	/*
11882 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
11883 	 * without the hint
11884 	 */
11885 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
11886 	    SE_NO_HINT);
11887 
11888 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11889 	sata_update_port_info(sata_hba_inst, sata_device);
11890 	if (qual == SATA_ADDR_CPORT) {
11891 		if (rval != SATA_SUCCESS) {
11892 			/*
11893 			 * Port deactivation failure - do not change port state
11894 			 * unless the state returned by HBA indicates a port
11895 			 * failure.
11896 			 */
11897 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11898 				SATA_CPORT_STATE(sata_hba_inst, cport) =
11899 				    SATA_PSTATE_FAILED;
11900 			}
11901 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11902 			    "sata_hba_ioctl: port deactivate: "
11903 			    "cannot deactivate SATA port %d", cport));
11904 			rv = EIO;
11905 		} else {
11906 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
11907 		}
11908 	} else {
11909 		if (rval != SATA_SUCCESS) {
11910 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11911 				SATA_PMPORT_STATE(sata_hba_inst, cport,
11912 				    pmport) = SATA_PSTATE_FAILED;
11913 			}
11914 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11915 			    "sata_hba_ioctl: port deactivate: "
11916 			    "cannot deactivate SATA port %d:%d",
11917 			    cport, pmport));
11918 			rv = EIO;
11919 		} else {
11920 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
11921 		}
11922 	}
11923 
11924 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11925 
11926 	return (rv);
11927 }
11928 
11929 /*
11930  * Process ioctl port activate request.
11931  *
11932  * NOTE: Port multiplier code is not completed nor tested.
11933  */
11934 static int
11935 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
11936     sata_device_t *sata_device)
11937 {
11938 	int cport, pmport, qual;
11939 	sata_cport_info_t *cportinfo;
11940 	sata_pmport_info_t *pmportinfo = NULL;
11941 	boolean_t dev_existed = TRUE;
11942 
11943 	/* Sanity check */
11944 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
11945 		return (ENOTSUP);
11946 
11947 	cport = sata_device->satadev_addr.cport;
11948 	pmport = sata_device->satadev_addr.pmport;
11949 	qual = sata_device->satadev_addr.qual;
11950 
11951 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11952 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11953 	if (qual == SATA_ADDR_PMPORT) {
11954 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11955 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
11956 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
11957 			dev_existed = FALSE;
11958 	} else { /* cport */
11959 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
11960 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
11961 			dev_existed = FALSE;
11962 	}
11963 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11964 
11965 	/* Just let HBA driver to activate port, if necessary */
11966 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
11967 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
11968 		/*
11969 		 * Port activation failure - do not change port state unless
11970 		 * the state returned by HBA indicates a port failure.
11971 		 */
11972 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
11973 		    cport)->cport_mutex);
11974 		sata_update_port_info(sata_hba_inst, sata_device);
11975 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
11976 			if (qual == SATA_ADDR_PMPORT)
11977 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
11978 			else
11979 				cportinfo->cport_state = SATA_PSTATE_FAILED;
11980 
11981 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
11982 			    cport)->cport_mutex);
11983 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11984 			    "sata_hba_ioctl: port activate: cannot activate "
11985 			    "SATA port %d:%d", cport, pmport));
11986 			return (EIO);
11987 		}
11988 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11989 	}
11990 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11991 	if (qual == SATA_ADDR_PMPORT)
11992 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
11993 	else
11994 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
11995 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
11996 
11997 	/*
11998 	 * Re-probe port to find its current state and possibly attached device.
11999 	 * Port re-probing may change the cportinfo device type if device is
12000 	 * found attached.
12001 	 * If port probing failed, the device type would be set to
12002 	 * SATA_DTYPE_NONE.
12003 	 */
12004 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
12005 	    SATA_DEV_IDENTIFY_RETRY);
12006 
12007 	/*
12008 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
12009 	 * without the hint.
12010 	 */
12011 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
12012 	    SE_NO_HINT);
12013 
12014 	if (dev_existed == FALSE) {
12015 		if (qual == SATA_ADDR_PMPORT &&
12016 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
12017 			/*
12018 			 * That's the transition from the "inactive" port state
12019 			 * or the active port without a device attached to the
12020 			 * active port state with a device attached.
12021 			 */
12022 			sata_log(sata_hba_inst, CE_WARN,
12023 			    "SATA device detected at port %d:%d",
12024 			    cport, pmport);
12025 		} else if (qual == SATA_ADDR_CPORT &&
12026 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
12027 			/*
12028 			 * That's the transition from the "inactive" port state
12029 			 * or the active port without a device attached to the
12030 			 * active port state with a device attached.
12031 			 */
12032 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
12033 				sata_log(sata_hba_inst, CE_WARN,
12034 				    "SATA device detected at port %d", cport);
12035 			} else {
12036 				sata_log(sata_hba_inst, CE_WARN,
12037 				    "SATA port multiplier detected at port %d",
12038 				    cport);
12039 				/*
12040 				 * Because the detected device is a port
12041 				 * multiplier, we need to reprobe every device
12042 				 * port on the port multiplier and show every
12043 				 * device found attached.
12044 				 * Add this code here.
12045 				 */
12046 			}
12047 		}
12048 	}
12049 	return (0);
12050 }
12051 
12052 
12053 
12054 /*
12055  * Process ioctl reset port request.
12056  *
12057  * NOTE: Port multiplier code is not completed nor tested.
12058  */
12059 static int
12060 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
12061     sata_device_t *sata_device)
12062 {
12063 	int cport, pmport, qual;
12064 	int rv = 0;
12065 
12066 	cport = sata_device->satadev_addr.cport;
12067 	pmport = sata_device->satadev_addr.pmport;
12068 	qual = sata_device->satadev_addr.qual;
12069 
12070 	/* Sanity check */
12071 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
12072 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12073 		    "sata_hba_ioctl: sata_hba_tran missing required "
12074 		    "function sata_tran_reset_dport"));
12075 		return (ENOTSUP);
12076 	}
12077 
12078 	/* Ask HBA to reset port */
12079 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
12080 	    sata_device) != SATA_SUCCESS) {
12081 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12082 		    "sata_hba_ioctl: reset port: failed %d:%d",
12083 		    cport, pmport));
12084 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
12085 		    cport_mutex);
12086 		sata_update_port_info(sata_hba_inst, sata_device);
12087 		if (qual == SATA_ADDR_CPORT)
12088 			SATA_CPORT_STATE(sata_hba_inst, cport) =
12089 			    SATA_PSTATE_FAILED;
12090 		else
12091 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
12092 			    SATA_PSTATE_FAILED;
12093 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
12094 		    cport_mutex);
12095 		rv = EIO;
12096 	}
12097 	/*
12098 	 * Beacuse the port was reset, it should be probed and
12099 	 * attached device reinitialized. At this point the
12100 	 * port state is unknown - it's state is HBA-specific.
12101 	 * Re-probe port to get its state.
12102 	 */
12103 	if (sata_reprobe_port(sata_hba_inst, sata_device,
12104 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
12105 		rv = EIO;
12106 	}
12107 	return (rv);
12108 }
12109 
12110 /*
12111  * Process ioctl reset device request.
12112  *
12113  * NOTE: Port multiplier code is not completed nor tested.
12114  */
12115 static int
12116 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
12117     sata_device_t *sata_device)
12118 {
12119 	sata_drive_info_t *sdinfo;
12120 	int cport, pmport;
12121 	int rv = 0;
12122 
12123 	/* Sanity check */
12124 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
12125 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12126 		    "sata_hba_ioctl: sata_hba_tran missing required "
12127 		    "function sata_tran_reset_dport"));
12128 		return (ENOTSUP);
12129 	}
12130 
12131 	cport = sata_device->satadev_addr.cport;
12132 	pmport = sata_device->satadev_addr.pmport;
12133 
12134 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
12135 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT) {
12136 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
12137 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
12138 		    sata_device->satadev_addr.cport);
12139 	} else { /* port multiplier */
12140 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
12141 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
12142 		    sata_device->satadev_addr.cport,
12143 		    sata_device->satadev_addr.pmport);
12144 	}
12145 	if (sdinfo == NULL) {
12146 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
12147 		return (EINVAL);
12148 	}
12149 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
12150 
12151 	/* Ask HBA to reset device */
12152 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
12153 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
12154 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12155 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
12156 		    cport, pmport));
12157 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
12158 		    cport_mutex);
12159 		sata_update_port_info(sata_hba_inst, sata_device);
12160 		/*
12161 		 * Device info structure remains attached. Another device reset
12162 		 * or port disconnect/connect and re-probing is
12163 		 * needed to change it's state
12164 		 */
12165 		sdinfo->satadrv_state &= ~SATA_STATE_READY;
12166 		sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
12167 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
12168 		rv = EIO;
12169 	}
12170 	/*
12171 	 * If attached device was a port multiplier, some extra processing
12172 	 * may be needed, to bring it back (if port re-probing did not handle
12173 	 * it). Add such code here.
12174 	 */
12175 	return (rv);
12176 }
12177 
12178 
12179 /*
12180  * Process ioctl reset all request.
12181  *
12182  * NOTE: Port multiplier code is not completed nor tested.
12183  */
12184 static int
12185 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
12186 {
12187 	sata_device_t sata_device;
12188 	int rv = 0;
12189 	int tcport;
12190 	int tpmport = 0;
12191 
12192 	sata_device.satadev_rev = SATA_DEVICE_REV;
12193 
12194 	/*
12195 	 * There is no protection here for configured devices.
12196 	 */
12197 	/* Sanity check */
12198 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
12199 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12200 		    "sata_hba_ioctl: sata_hba_tran missing required "
12201 		    "function sata_tran_reset_dport"));
12202 		return (ENOTSUP);
12203 	}
12204 
12205 	/*
12206 	 * Need to lock all ports, not just one.
12207 	 * If any port is locked by event processing, fail the whole operation.
12208 	 * One port is already locked, but for simplicity lock it again.
12209 	 */
12210 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
12211 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
12212 		    cport_mutex);
12213 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
12214 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
12215 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
12216 			    cport_mutex);
12217 			rv = EBUSY;
12218 			break;
12219 		} else {
12220 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
12221 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
12222 			/*
12223 			 * If there is a port multiplier attached, we may need
12224 			 * to lock its port as well. If so, add such code here.
12225 			 */
12226 		}
12227 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
12228 		    cport_mutex);
12229 	}
12230 
12231 	if (rv == 0) {
12232 		/*
12233 		 * All cports were successfully locked.
12234 		 * Reset main SATA controller only for now - no PMult.
12235 		 * Set the device address to port 0, to have a valid device
12236 		 * address.
12237 		 */
12238 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
12239 		sata_device.satadev_addr.cport = 0;
12240 		sata_device.satadev_addr.pmport = 0;
12241 
12242 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
12243 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
12244 			SATA_LOG_D((sata_hba_inst, CE_WARN,
12245 			    "sata_hba_ioctl: reset controller failed"));
12246 			return (EIO);
12247 		}
12248 		/*
12249 		 * Because ports were reset, port states are unknown.
12250 		 * They should be re-probed to get their state and
12251 		 * attached devices should be reinitialized.
12252 		 * Add code here to re-probe port multiplier device ports.
12253 		 */
12254 		for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst);
12255 		    tcport++) {
12256 			sata_device.satadev_addr.cport = tcport;
12257 			sata_device.satadev_addr.pmport = tpmport;
12258 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
12259 
12260 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
12261 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
12262 				rv = EIO;
12263 		}
12264 	}
12265 	/*
12266 	 * Unlock all ports
12267 	 */
12268 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
12269 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
12270 		    cport_mutex);
12271 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
12272 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
12273 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
12274 		    cport_mutex);
12275 	}
12276 
12277 	/*
12278 	 * This operation returns EFAULT if either reset
12279 	 * controller failed or a re-probing of any port failed.
12280 	 */
12281 	return (rv);
12282 }
12283 
12284 
12285 /*
12286  * Process ioctl port self test request.
12287  *
12288  * NOTE: Port multiplier code is not completed nor tested.
12289  */
12290 static int
12291 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
12292     sata_device_t *sata_device)
12293 {
12294 	int cport, pmport, qual;
12295 	int rv = 0;
12296 
12297 	/* Sanity check */
12298 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
12299 		return (ENOTSUP);
12300 
12301 	cport = sata_device->satadev_addr.cport;
12302 	pmport = sata_device->satadev_addr.pmport;
12303 	qual = sata_device->satadev_addr.qual;
12304 
12305 	/*
12306 	 * There is no protection here for a configured
12307 	 * device attached to this port.
12308 	 */
12309 
12310 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
12311 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
12312 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12313 		    "sata_hba_ioctl: port selftest: "
12314 		    "failed port %d:%d", cport, pmport));
12315 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
12316 		    cport_mutex);
12317 		sata_update_port_info(sata_hba_inst, sata_device);
12318 		if (qual == SATA_ADDR_CPORT)
12319 			SATA_CPORT_STATE(sata_hba_inst, cport) =
12320 			    SATA_PSTATE_FAILED;
12321 		else /* port ultiplier device port */
12322 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
12323 			    SATA_PSTATE_FAILED;
12324 
12325 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
12326 		    cport_mutex);
12327 		return (EIO);
12328 	}
12329 	/*
12330 	 * Beacuse the port was reset in the course of testing, it should be
12331 	 * re-probed and attached device state should be restored. At this
12332 	 * point the port state is unknown - it's state is HBA-specific.
12333 	 * Force port re-probing to get it into a known state.
12334 	 */
12335 	if (sata_reprobe_port(sata_hba_inst, sata_device,
12336 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
12337 		rv = EIO;
12338 	return (rv);
12339 }
12340 
12341 
12342 /*
12343  * sata_cfgadm_state:
12344  * Use the sata port state and state of the target node to figure out
12345  * the cfgadm_state.
12346  *
12347  * The port argument is a value with encoded cport,
12348  * pmport and address qualifier, in the same manner as a scsi target number.
12349  * SCSI_TO_SATA_CPORT macro extracts cport number,
12350  * SCSI_TO_SATA_PMPORT extracts pmport number and
12351  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
12352  *
12353  * For now, support is for cports only - no port multiplier device ports.
12354  */
12355 
12356 static void
12357 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
12358     devctl_ap_state_t *ap_state)
12359 {
12360 	uint16_t	cport;
12361 	int		port_state;
12362 	sata_drive_info_t *sdinfo;
12363 
12364 	/* Cport only */
12365 	cport = SCSI_TO_SATA_CPORT(port);
12366 
12367 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
12368 	if (port_state & SATA_PSTATE_SHUTDOWN ||
12369 	    port_state & SATA_PSTATE_FAILED) {
12370 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
12371 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
12372 		if (port_state & SATA_PSTATE_FAILED)
12373 			ap_state->ap_condition = AP_COND_FAILED;
12374 		else
12375 			ap_state->ap_condition = AP_COND_UNKNOWN;
12376 
12377 		return;
12378 	}
12379 
12380 	/* Need to check pmult device port here as well, when supported */
12381 
12382 	/* Port is enabled and ready */
12383 
12384 	switch (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport)) {
12385 	case SATA_DTYPE_NONE:
12386 	{
12387 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
12388 		ap_state->ap_condition = AP_COND_OK;
12389 		/* No device attached */
12390 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
12391 		break;
12392 	}
12393 	case SATA_DTYPE_UNKNOWN:
12394 	case SATA_DTYPE_PMULT:	/* Until PMult is supported */
12395 	case SATA_DTYPE_ATADISK:
12396 	case SATA_DTYPE_ATAPICD:
12397 	case SATA_DTYPE_ATAPITAPE:
12398 	case SATA_DTYPE_ATAPIDISK:
12399 	{
12400 		dev_info_t *tdip = NULL;
12401 		dev_info_t *dip = NULL;
12402 		int circ;
12403 
12404 		dip = SATA_DIP(sata_hba_inst);
12405 		tdip = sata_get_target_dip(dip, port);
12406 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
12407 		if (tdip != NULL) {
12408 			ndi_devi_enter(dip, &circ);
12409 			mutex_enter(&(DEVI(tdip)->devi_lock));
12410 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
12411 				/*
12412 				 * There could be the case where previously
12413 				 * configured and opened device was removed
12414 				 * and unknown device was plugged.
12415 				 * In such case we want to show a device, and
12416 				 * its configured or unconfigured state but
12417 				 * indicate unusable condition untill the
12418 				 * old target node is released and removed.
12419 				 */
12420 				ap_state->ap_condition = AP_COND_UNUSABLE;
12421 			} else {
12422 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
12423 				    cport));
12424 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
12425 				    cport);
12426 				if (sdinfo != NULL) {
12427 					if ((sdinfo->satadrv_state &
12428 					    SATA_DSTATE_FAILED) != 0)
12429 						ap_state->ap_condition =
12430 						    AP_COND_FAILED;
12431 					else
12432 						ap_state->ap_condition =
12433 						    AP_COND_OK;
12434 				} else {
12435 					ap_state->ap_condition =
12436 					    AP_COND_UNKNOWN;
12437 				}
12438 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
12439 				    cport));
12440 			}
12441 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
12442 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
12443 				ap_state->ap_ostate =
12444 				    AP_OSTATE_UNCONFIGURED;
12445 			} else {
12446 				ap_state->ap_ostate =
12447 				    AP_OSTATE_CONFIGURED;
12448 			}
12449 			mutex_exit(&(DEVI(tdip)->devi_lock));
12450 			ndi_devi_exit(dip, circ);
12451 		} else {
12452 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
12453 			ap_state->ap_condition = AP_COND_UNKNOWN;
12454 		}
12455 		break;
12456 	}
12457 	default:
12458 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
12459 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
12460 		ap_state->ap_condition = AP_COND_UNKNOWN;
12461 		/*
12462 		 * This is actually internal error condition (non fatal),
12463 		 * because we have already checked all defined device types.
12464 		 */
12465 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12466 		    "sata_cfgadm_state: Internal error: "
12467 		    "unknown device type"));
12468 		break;
12469 	}
12470 }
12471 
12472 
12473 /*
12474  * Process ioctl get device path request.
12475  *
12476  * NOTE: Port multiplier code is not completed nor tested.
12477  */
12478 static int
12479 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
12480     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12481 {
12482 	char path[MAXPATHLEN];
12483 	uint32_t size;
12484 	dev_info_t *tdip;
12485 
12486 	(void) strcpy(path, "/devices");
12487 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
12488 	    &sata_device->satadev_addr)) == NULL) {
12489 		/*
12490 		 * No such device. If this is a request for a size, do not
12491 		 * return EINVAL for non-existing target, because cfgadm
12492 		 * will then indicate a meaningless ioctl failure.
12493 		 * If this is a request for a path, indicate invalid
12494 		 * argument.
12495 		 */
12496 		if (ioc->get_size == 0)
12497 			return (EINVAL);
12498 	} else {
12499 		(void) ddi_pathname(tdip, path + strlen(path));
12500 	}
12501 	size = strlen(path) + 1;
12502 
12503 	if (ioc->get_size != 0) {
12504 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
12505 		    mode) != 0)
12506 			return (EFAULT);
12507 	} else {
12508 		if (ioc->bufsiz != size)
12509 			return (EINVAL);
12510 
12511 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
12512 		    mode) != 0)
12513 			return (EFAULT);
12514 	}
12515 	return (0);
12516 }
12517 
12518 /*
12519  * Process ioctl get attachment point type request.
12520  *
12521  * NOTE: Port multiplier code is not completed nor tested.
12522  */
12523 static	int
12524 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
12525     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12526 {
12527 	uint32_t	type_len;
12528 	const char	*ap_type;
12529 	int		dev_type;
12530 
12531 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
12532 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
12533 		    sata_device->satadev_addr.cport);
12534 	else /* pmport */
12535 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
12536 		    sata_device->satadev_addr.cport,
12537 		    sata_device->satadev_addr.pmport);
12538 
12539 	switch (dev_type) {
12540 	case SATA_DTYPE_NONE:
12541 		ap_type = "port";
12542 		break;
12543 
12544 	case SATA_DTYPE_ATADISK:
12545 	case SATA_DTYPE_ATAPIDISK:
12546 		ap_type = "disk";
12547 		break;
12548 
12549 	case SATA_DTYPE_ATAPICD:
12550 		ap_type = "cd/dvd";
12551 		break;
12552 
12553 	case SATA_DTYPE_ATAPITAPE:
12554 		ap_type = "tape";
12555 		break;
12556 
12557 	case SATA_DTYPE_PMULT:
12558 		ap_type = "pmult";
12559 		break;
12560 
12561 	case SATA_DTYPE_UNKNOWN:
12562 		ap_type = "unknown";
12563 		break;
12564 
12565 	default:
12566 		ap_type = "unsupported";
12567 		break;
12568 
12569 	} /* end of dev_type switch */
12570 
12571 	type_len = strlen(ap_type) + 1;
12572 
12573 	if (ioc->get_size) {
12574 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
12575 		    mode) != 0)
12576 			return (EFAULT);
12577 	} else {
12578 		if (ioc->bufsiz != type_len)
12579 			return (EINVAL);
12580 
12581 		if (ddi_copyout((void *)ap_type, ioc->buf,
12582 		    ioc->bufsiz, mode) != 0)
12583 			return (EFAULT);
12584 	}
12585 	return (0);
12586 
12587 }
12588 
12589 /*
12590  * Process ioctl get device model info request.
12591  * This operation should return to cfgadm the device model
12592  * information string
12593  *
12594  * NOTE: Port multiplier code is not completed nor tested.
12595  */
12596 static	int
12597 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
12598     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12599 {
12600 	sata_drive_info_t *sdinfo;
12601 	uint32_t info_len;
12602 	char ap_info[SATA_ID_MODEL_LEN + 1];
12603 
12604 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
12605 	    sata_device->satadev_addr.cport)->cport_mutex);
12606 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
12607 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
12608 		    sata_device->satadev_addr.cport);
12609 	else /* port multiplier */
12610 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
12611 		    sata_device->satadev_addr.cport,
12612 		    sata_device->satadev_addr.pmport);
12613 	if (sdinfo == NULL) {
12614 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12615 		    sata_device->satadev_addr.cport)->cport_mutex);
12616 		return (EINVAL);
12617 	}
12618 
12619 #ifdef	_LITTLE_ENDIAN
12620 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
12621 #else	/* _LITTLE_ENDIAN */
12622 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
12623 #endif	/* _LITTLE_ENDIAN */
12624 
12625 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12626 	    sata_device->satadev_addr.cport)->cport_mutex);
12627 
12628 	ap_info[SATA_ID_MODEL_LEN] = '\0';
12629 
12630 	info_len = strlen(ap_info) + 1;
12631 
12632 	if (ioc->get_size) {
12633 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
12634 		    mode) != 0)
12635 			return (EFAULT);
12636 	} else {
12637 		if (ioc->bufsiz < info_len)
12638 			return (EINVAL);
12639 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
12640 		    mode) != 0)
12641 			return (EFAULT);
12642 	}
12643 	return (0);
12644 }
12645 
12646 
12647 /*
12648  * Process ioctl get device firmware revision info request.
12649  * This operation should return to cfgadm the device firmware revision
12650  * information string
12651  *
12652  * NOTE: Port multiplier code is not completed nor tested.
12653  */
12654 static	int
12655 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
12656     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12657 {
12658 	sata_drive_info_t *sdinfo;
12659 	uint32_t info_len;
12660 	char ap_info[SATA_ID_FW_LEN + 1];
12661 
12662 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
12663 	    sata_device->satadev_addr.cport)->cport_mutex);
12664 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
12665 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
12666 		    sata_device->satadev_addr.cport);
12667 	else /* port multiplier */
12668 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
12669 		    sata_device->satadev_addr.cport,
12670 		    sata_device->satadev_addr.pmport);
12671 	if (sdinfo == NULL) {
12672 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12673 		    sata_device->satadev_addr.cport)->cport_mutex);
12674 		return (EINVAL);
12675 	}
12676 
12677 #ifdef	_LITTLE_ENDIAN
12678 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
12679 #else	/* _LITTLE_ENDIAN */
12680 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
12681 #endif	/* _LITTLE_ENDIAN */
12682 
12683 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12684 	    sata_device->satadev_addr.cport)->cport_mutex);
12685 
12686 	ap_info[SATA_ID_FW_LEN] = '\0';
12687 
12688 	info_len = strlen(ap_info) + 1;
12689 
12690 	if (ioc->get_size) {
12691 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
12692 		    mode) != 0)
12693 			return (EFAULT);
12694 	} else {
12695 		if (ioc->bufsiz < info_len)
12696 			return (EINVAL);
12697 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
12698 		    mode) != 0)
12699 			return (EFAULT);
12700 	}
12701 	return (0);
12702 }
12703 
12704 
12705 /*
12706  * Process ioctl get device serial number info request.
12707  * This operation should return to cfgadm the device serial number string.
12708  *
12709  * NOTE: Port multiplier code is not completed nor tested.
12710  */
12711 static	int
12712 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
12713     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
12714 {
12715 	sata_drive_info_t *sdinfo;
12716 	uint32_t info_len;
12717 	char ap_info[SATA_ID_SERIAL_LEN + 1];
12718 
12719 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
12720 	    sata_device->satadev_addr.cport)->cport_mutex);
12721 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
12722 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
12723 		    sata_device->satadev_addr.cport);
12724 	else /* port multiplier */
12725 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
12726 		    sata_device->satadev_addr.cport,
12727 		    sata_device->satadev_addr.pmport);
12728 	if (sdinfo == NULL) {
12729 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12730 		    sata_device->satadev_addr.cport)->cport_mutex);
12731 		return (EINVAL);
12732 	}
12733 
12734 #ifdef	_LITTLE_ENDIAN
12735 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
12736 #else	/* _LITTLE_ENDIAN */
12737 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
12738 #endif	/* _LITTLE_ENDIAN */
12739 
12740 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
12741 	    sata_device->satadev_addr.cport)->cport_mutex);
12742 
12743 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
12744 
12745 	info_len = strlen(ap_info) + 1;
12746 
12747 	if (ioc->get_size) {
12748 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
12749 		    mode) != 0)
12750 			return (EFAULT);
12751 	} else {
12752 		if (ioc->bufsiz < info_len)
12753 			return (EINVAL);
12754 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
12755 		    mode) != 0)
12756 			return (EFAULT);
12757 	}
12758 	return (0);
12759 }
12760 
12761 
12762 /*
12763  * Preset scsi extended sense data (to NO SENSE)
12764  * First 18 bytes of the sense data are preset to current valid sense
12765  * with a key NO SENSE data.
12766  *
12767  * Returns void
12768  */
12769 static void
12770 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
12771 {
12772 	sense->es_valid = 1;		/* Valid sense */
12773 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
12774 	sense->es_key = KEY_NO_SENSE;
12775 	sense->es_info_1 = 0;
12776 	sense->es_info_2 = 0;
12777 	sense->es_info_3 = 0;
12778 	sense->es_info_4 = 0;
12779 	sense->es_add_len = 10;	/* Additional length - replace with a def */
12780 	sense->es_cmd_info[0] = 0;
12781 	sense->es_cmd_info[1] = 0;
12782 	sense->es_cmd_info[2] = 0;
12783 	sense->es_cmd_info[3] = 0;
12784 	sense->es_add_code = 0;
12785 	sense->es_qual_code = 0;
12786 }
12787 
12788 /*
12789  * Register a legacy cmdk-style devid for the target (disk) device.
12790  *
12791  * Note: This function is called only when the HBA devinfo node has the
12792  * property "use-cmdk-devid-format" set. This property indicates that
12793  * devid compatible with old cmdk (target) driver is to be generated
12794  * for any target device attached to this controller. This will take
12795  * precedence over the devid generated by sd (target) driver.
12796  * This function is derived from cmdk_devid_setup() function in cmdk.c.
12797  */
12798 static void
12799 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
12800 {
12801 	char	*hwid;
12802 	int	modlen;
12803 	int	serlen;
12804 	int	rval;
12805 	ddi_devid_t	devid;
12806 
12807 	/*
12808 	 * device ID is a concatanation of model number, "=", serial number.
12809 	 */
12810 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
12811 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
12812 	    sizeof (sdinfo->satadrv_id.ai_model));
12813 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
12814 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
12815 	if (modlen == 0)
12816 		goto err;
12817 	hwid[modlen++] = '=';
12818 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
12819 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12820 	swab(&hwid[modlen], &hwid[modlen],
12821 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12822 	serlen = sata_check_modser(&hwid[modlen],
12823 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12824 	if (serlen == 0)
12825 		goto err;
12826 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
12827 
12828 	/* initialize/register devid */
12829 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
12830 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
12831 		rval = ddi_devid_register(dip, devid);
12832 		/*
12833 		 * Free up the allocated devid buffer.
12834 		 * NOTE: This doesn't mean unregistering devid.
12835 		 */
12836 		ddi_devid_free(devid);
12837 	}
12838 
12839 	if (rval != DDI_SUCCESS)
12840 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
12841 		    " on port %d", sdinfo->satadrv_addr.cport);
12842 err:
12843 	kmem_free(hwid, LEGACY_HWID_LEN);
12844 }
12845 
12846 /*
12847  * valid model/serial string must contain a non-zero non-space characters.
12848  * trim trailing spaces/NULLs.
12849  */
12850 static int
12851 sata_check_modser(char *buf, int buf_len)
12852 {
12853 	boolean_t ret;
12854 	char *s;
12855 	int i;
12856 	int tb;
12857 	char ch;
12858 
12859 	ret = B_FALSE;
12860 	s = buf;
12861 	for (i = 0; i < buf_len; i++) {
12862 		ch = *s++;
12863 		if (ch != ' ' && ch != '\0')
12864 			tb = i + 1;
12865 		if (ch != ' ' && ch != '\0' && ch != '0')
12866 			ret = B_TRUE;
12867 	}
12868 
12869 	if (ret == B_FALSE)
12870 		return (0); /* invalid string */
12871 
12872 	return (tb); /* return length */
12873 }
12874 
12875 /*
12876  * sata_set_drive_features function compares current device features setting
12877  * with the saved device features settings and, if there is a difference,
12878  * it restores device features setting to the previously saved state.
12879  * It also arbitrarily tries to select the highest supported DMA mode.
12880  * Device Identify or Identify Packet Device data has to be current.
12881  * At the moment read ahead and write cache are considered for all devices.
12882  * For atapi devices, Removable Media Status Notification is set in addition
12883  * to common features.
12884  *
12885  * This function cannot be called in the interrupt context (it may sleep).
12886  *
12887  * The input argument sdinfo should point to the drive info structure
12888  * to be updated after features are set. Note, that only
12889  * device (packet) identify data is updated, not the flags indicating the
12890  * supported features.
12891  *
12892  * Returns SATA_SUCCESS if successful or there was nothing to do.
12893  * Device Identify data in the drive info structure pointed to by the sdinfo
12894  * arguments is updated even when no features were set or changed.
12895  *
12896  * Returns SATA_FAILURE if device features could not be set or DMA mode
12897  * for a disk cannot be set and device identify data cannot be fetched.
12898  *
12899  * Returns SATA_RETRY if device features could not be set (other than disk
12900  * DMA mode) but the device identify data was fetched successfully.
12901  *
12902  * Note: This function may fail the port, making it inaccessible.
12903  * In such case the explicit port disconnect/connect or physical device
12904  * detach/attach is required to re-evaluate port state again.
12905  */
12906 
12907 static int
12908 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
12909     sata_drive_info_t *sdinfo, int restore)
12910 {
12911 	int rval = SATA_SUCCESS;
12912 	int rval_set;
12913 	sata_drive_info_t new_sdinfo;
12914 	char *finfo = "sata_set_drive_features: cannot";
12915 	char *finfox;
12916 	int cache_op;
12917 
12918 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
12919 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
12920 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
12921 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
12922 		/*
12923 		 * Cannot get device identification - caller may retry later
12924 		 */
12925 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
12926 		    "%s fetch device identify data\n", finfo);
12927 		return (SATA_FAILURE);
12928 	}
12929 	finfox = (restore != 0) ? " restore device features" :
12930 	    " initialize device features\n";
12931 
12932 	switch (sdinfo->satadrv_type) {
12933 	case SATA_DTYPE_ATADISK:
12934 		/* Arbitrarily set UDMA mode */
12935 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
12936 		    SATA_SUCCESS) {
12937 			SATA_LOG_D((sata_hba_inst, CE_WARN,
12938 			    "%s set UDMA mode\n", finfo));
12939 			return (SATA_FAILURE);
12940 		}
12941 		break;
12942 	case SATA_DTYPE_ATAPICD:
12943 	case SATA_DTYPE_ATAPITAPE:
12944 	case SATA_DTYPE_ATAPIDISK:
12945 		/*  Set Removable Media Status Notification, if necessary */
12946 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
12947 		    restore != 0) {
12948 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
12949 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
12950 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
12951 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
12952 				/* Current setting does not match saved one */
12953 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
12954 				    sdinfo->satadrv_settings &
12955 				    SATA_DEV_RMSN) != SATA_SUCCESS)
12956 					rval = SATA_FAILURE;
12957 			}
12958 		}
12959 		/*
12960 		 * We have to set Multiword DMA or UDMA, if it is supported, as
12961 		 * we want to use DMA transfer mode whenever possible.
12962 		 * Some devices require explicit setting of the DMA mode.
12963 		 */
12964 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
12965 			/* Set highest supported DMA mode */
12966 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
12967 			    SATA_SUCCESS) {
12968 				SATA_LOG_D((sata_hba_inst, CE_WARN,
12969 				    "%s set UDMA mode\n", finfo));
12970 				rval = SATA_FAILURE;
12971 			}
12972 		}
12973 		break;
12974 	}
12975 
12976 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
12977 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
12978 		/*
12979 		 * neither READ AHEAD nor WRITE CACHE is supported
12980 		 * - do nothing
12981 		 */
12982 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
12983 		    "settable features not supported\n", NULL);
12984 		goto update_sdinfo;
12985 	}
12986 
12987 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
12988 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
12989 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
12990 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
12991 		/*
12992 		 * both READ AHEAD and WRITE CACHE are enabled
12993 		 * - Nothing to do
12994 		 */
12995 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
12996 		    "no device features to set\n", NULL);
12997 		goto update_sdinfo;
12998 	}
12999 
13000 	cache_op = 0;
13001 
13002 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
13003 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
13004 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
13005 			/* Enable read ahead / read cache */
13006 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
13007 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
13008 			    "enabling read cache\n", NULL);
13009 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
13010 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
13011 			/* Disable read ahead  / read cache */
13012 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
13013 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
13014 			    "disabling read cache\n", NULL);
13015 		}
13016 
13017 		if (cache_op != 0) {
13018 			/* Try to set read cache mode */
13019 			rval_set = sata_set_cache_mode(sata_hba_inst,
13020 			    &new_sdinfo, cache_op);
13021 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
13022 				rval = rval_set;
13023 		}
13024 	}
13025 
13026 	cache_op = 0;
13027 
13028 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
13029 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
13030 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
13031 			/* Enable write cache */
13032 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
13033 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
13034 			    "enabling write cache\n", NULL);
13035 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
13036 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
13037 			/* Disable write cache */
13038 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
13039 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
13040 			    "disabling write cache\n", NULL);
13041 		}
13042 
13043 		if (cache_op != 0) {
13044 			/* Try to set write cache mode */
13045 			rval_set = sata_set_cache_mode(sata_hba_inst,
13046 			    &new_sdinfo, cache_op);
13047 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
13048 				rval = rval_set;
13049 		}
13050 	}
13051 	if (rval != SATA_SUCCESS)
13052 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13053 		    "%s %s", finfo, finfox));
13054 
13055 update_sdinfo:
13056 	/*
13057 	 * We need to fetch Device Identify data again
13058 	 */
13059 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
13060 		/*
13061 		 * Cannot get device identification - retry later
13062 		 */
13063 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13064 		    "%s re-fetch device identify data\n", finfo));
13065 		rval = SATA_FAILURE;
13066 	}
13067 	/* Copy device sata info. */
13068 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
13069 
13070 	return (rval);
13071 }
13072 
13073 
13074 /*
13075  *
13076  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
13077  * unable to determine.
13078  *
13079  * Cannot be called in an interrupt context.
13080  *
13081  * Called by sata_build_lsense_page_2f()
13082  */
13083 
13084 static int
13085 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
13086     sata_drive_info_t *sdinfo)
13087 {
13088 	sata_pkt_t *spkt;
13089 	sata_cmd_t *scmd;
13090 	sata_pkt_txlate_t *spx;
13091 	int rval;
13092 
13093 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13094 	spx->txlt_sata_hba_inst = sata_hba_inst;
13095 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13096 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13097 	if (spkt == NULL) {
13098 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13099 		return (-1);
13100 	}
13101 	/* address is needed now */
13102 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13103 
13104 
13105 	/* Fill sata_pkt */
13106 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13107 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13108 	/* Synchronous mode, no callback */
13109 	spkt->satapkt_comp = NULL;
13110 	/* Timeout 30s */
13111 	spkt->satapkt_time = sata_default_pkt_time;
13112 
13113 	scmd = &spkt->satapkt_cmd;
13114 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
13115 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13116 
13117 	/* Set up which registers need to be returned */
13118 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
13119 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
13120 
13121 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
13122 	scmd->satacmd_addr_type = 0;		/* N/A */
13123 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
13124 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
13125 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
13126 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
13127 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
13128 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13129 	scmd->satacmd_cmd_reg = SATAC_SMART;
13130 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13131 	    sdinfo->satadrv_addr.cport)));
13132 
13133 
13134 	/* Send pkt to SATA HBA driver */
13135 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13136 	    SATA_TRAN_ACCEPTED ||
13137 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13138 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13139 		    sdinfo->satadrv_addr.cport)));
13140 		/*
13141 		 * Whoops, no SMART RETURN STATUS
13142 		 */
13143 		rval = -1;
13144 	} else {
13145 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13146 		    sdinfo->satadrv_addr.cport)));
13147 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
13148 			rval = -1;
13149 			goto fail;
13150 		}
13151 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
13152 			rval = -1;
13153 			goto fail;
13154 		}
13155 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
13156 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
13157 			rval = 0;
13158 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
13159 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
13160 			rval = 1;
13161 		else {
13162 			rval = -1;
13163 			goto fail;
13164 		}
13165 	}
13166 fail:
13167 	/* Free allocated resources */
13168 	sata_pkt_free(spx);
13169 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13170 
13171 	return (rval);
13172 }
13173 
13174 /*
13175  *
13176  * Returns 0 if succeeded, -1 otherwise
13177  *
13178  * Cannot be called in an interrupt context.
13179  *
13180  */
13181 static int
13182 sata_fetch_smart_data(
13183 	sata_hba_inst_t *sata_hba_inst,
13184 	sata_drive_info_t *sdinfo,
13185 	struct smart_data *smart_data)
13186 {
13187 	sata_pkt_t *spkt;
13188 	sata_cmd_t *scmd;
13189 	sata_pkt_txlate_t *spx;
13190 	int rval;
13191 
13192 #if ! defined(lint)
13193 	ASSERT(sizeof (struct smart_data) == 512);
13194 #endif
13195 
13196 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13197 	spx->txlt_sata_hba_inst = sata_hba_inst;
13198 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13199 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13200 	if (spkt == NULL) {
13201 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13202 		return (-1);
13203 	}
13204 	/* address is needed now */
13205 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13206 
13207 
13208 	/* Fill sata_pkt */
13209 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13210 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13211 	/* Synchronous mode, no callback */
13212 	spkt->satapkt_comp = NULL;
13213 	/* Timeout 30s */
13214 	spkt->satapkt_time = sata_default_pkt_time;
13215 
13216 	scmd = &spkt->satapkt_cmd;
13217 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13218 
13219 	/*
13220 	 * Allocate buffer for SMART data
13221 	 */
13222 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
13223 	    sizeof (struct smart_data));
13224 	if (scmd->satacmd_bp == NULL) {
13225 		sata_pkt_free(spx);
13226 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13227 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13228 		    "sata_fetch_smart_data: "
13229 		    "cannot allocate buffer"));
13230 		return (-1);
13231 	}
13232 
13233 
13234 	/* Build SMART_READ_DATA cmd in the sata_pkt */
13235 	scmd->satacmd_addr_type = 0;		/* N/A */
13236 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
13237 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
13238 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
13239 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
13240 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
13241 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13242 	scmd->satacmd_cmd_reg = SATAC_SMART;
13243 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13244 	    sdinfo->satadrv_addr.cport)));
13245 
13246 	/* Send pkt to SATA HBA driver */
13247 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13248 	    SATA_TRAN_ACCEPTED ||
13249 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13250 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13251 		    sdinfo->satadrv_addr.cport)));
13252 		/*
13253 		 * Whoops, no SMART DATA available
13254 		 */
13255 		rval = -1;
13256 		goto fail;
13257 	} else {
13258 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13259 		    sdinfo->satadrv_addr.cport)));
13260 		if (spx->txlt_buf_dma_handle != NULL) {
13261 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13262 			    DDI_DMA_SYNC_FORKERNEL);
13263 			ASSERT(rval == DDI_SUCCESS);
13264 		}
13265 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
13266 		    sizeof (struct smart_data));
13267 	}
13268 
13269 fail:
13270 	/* Free allocated resources */
13271 	sata_free_local_buffer(spx);
13272 	sata_pkt_free(spx);
13273 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13274 
13275 	return (rval);
13276 }
13277 
13278 /*
13279  * Used by LOG SENSE page 0x10
13280  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
13281  * Note: cannot be called in the interrupt context.
13282  *
13283  * return 0 for success, -1 otherwise
13284  *
13285  */
13286 static int
13287 sata_ext_smart_selftest_read_log(
13288 	sata_hba_inst_t *sata_hba_inst,
13289 	sata_drive_info_t *sdinfo,
13290 	struct smart_ext_selftest_log *ext_selftest_log,
13291 	uint16_t block_num)
13292 {
13293 	sata_pkt_txlate_t *spx;
13294 	sata_pkt_t *spkt;
13295 	sata_cmd_t *scmd;
13296 	int rval;
13297 
13298 #if ! defined(lint)
13299 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
13300 #endif
13301 
13302 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13303 	spx->txlt_sata_hba_inst = sata_hba_inst;
13304 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13305 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13306 	if (spkt == NULL) {
13307 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13308 		return (-1);
13309 	}
13310 	/* address is needed now */
13311 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13312 
13313 
13314 	/* Fill sata_pkt */
13315 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13316 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13317 	/* Synchronous mode, no callback */
13318 	spkt->satapkt_comp = NULL;
13319 	/* Timeout 30s */
13320 	spkt->satapkt_time = sata_default_pkt_time;
13321 
13322 	scmd = &spkt->satapkt_cmd;
13323 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13324 
13325 	/*
13326 	 * Allocate buffer for SMART extended self-test log
13327 	 */
13328 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
13329 	    sizeof (struct smart_ext_selftest_log));
13330 	if (scmd->satacmd_bp == NULL) {
13331 		sata_pkt_free(spx);
13332 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13333 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13334 		    "sata_ext_smart_selftest_log: "
13335 		    "cannot allocate buffer"));
13336 		return (-1);
13337 	}
13338 
13339 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
13340 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
13341 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
13342 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
13343 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
13344 	scmd->satacmd_lba_low_msb = 0;
13345 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
13346 	scmd->satacmd_lba_mid_msb = block_num >> 8;
13347 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13348 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
13349 
13350 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13351 	    sdinfo->satadrv_addr.cport)));
13352 
13353 	/* Send pkt to SATA HBA driver */
13354 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13355 	    SATA_TRAN_ACCEPTED ||
13356 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13357 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13358 		    sdinfo->satadrv_addr.cport)));
13359 
13360 		/*
13361 		 * Whoops, no SMART selftest log info available
13362 		 */
13363 		rval = -1;
13364 		goto fail;
13365 	} else {
13366 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13367 		    sdinfo->satadrv_addr.cport)));
13368 
13369 		if (spx->txlt_buf_dma_handle != NULL) {
13370 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13371 			    DDI_DMA_SYNC_FORKERNEL);
13372 			ASSERT(rval == DDI_SUCCESS);
13373 		}
13374 		bcopy(scmd->satacmd_bp->b_un.b_addr,
13375 		    (uint8_t *)ext_selftest_log,
13376 		    sizeof (struct smart_ext_selftest_log));
13377 		rval = 0;
13378 	}
13379 
13380 fail:
13381 	/* Free allocated resources */
13382 	sata_free_local_buffer(spx);
13383 	sata_pkt_free(spx);
13384 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13385 
13386 	return (rval);
13387 }
13388 
13389 /*
13390  * Returns 0 for success, -1 otherwise
13391  *
13392  * SMART self-test log data is returned in buffer pointed to by selftest_log
13393  */
13394 static int
13395 sata_smart_selftest_log(
13396 	sata_hba_inst_t *sata_hba_inst,
13397 	sata_drive_info_t *sdinfo,
13398 	struct smart_selftest_log *selftest_log)
13399 {
13400 	sata_pkt_t *spkt;
13401 	sata_cmd_t *scmd;
13402 	sata_pkt_txlate_t *spx;
13403 	int rval;
13404 
13405 #if ! defined(lint)
13406 	ASSERT(sizeof (struct smart_selftest_log) == 512);
13407 #endif
13408 
13409 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13410 	spx->txlt_sata_hba_inst = sata_hba_inst;
13411 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13412 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13413 	if (spkt == NULL) {
13414 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13415 		return (-1);
13416 	}
13417 	/* address is needed now */
13418 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13419 
13420 
13421 	/* Fill sata_pkt */
13422 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13423 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13424 	/* Synchronous mode, no callback */
13425 	spkt->satapkt_comp = NULL;
13426 	/* Timeout 30s */
13427 	spkt->satapkt_time = sata_default_pkt_time;
13428 
13429 	scmd = &spkt->satapkt_cmd;
13430 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13431 
13432 	/*
13433 	 * Allocate buffer for SMART SELFTEST LOG
13434 	 */
13435 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
13436 	    sizeof (struct smart_selftest_log));
13437 	if (scmd->satacmd_bp == NULL) {
13438 		sata_pkt_free(spx);
13439 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13440 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13441 		    "sata_smart_selftest_log: "
13442 		    "cannot allocate buffer"));
13443 		return (-1);
13444 	}
13445 
13446 	/* Build SMART_READ_LOG cmd in the sata_pkt */
13447 	scmd->satacmd_addr_type = 0;		/* N/A */
13448 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
13449 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
13450 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
13451 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
13452 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
13453 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13454 	scmd->satacmd_cmd_reg = SATAC_SMART;
13455 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13456 	    sdinfo->satadrv_addr.cport)));
13457 
13458 	/* Send pkt to SATA HBA driver */
13459 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13460 	    SATA_TRAN_ACCEPTED ||
13461 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13462 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13463 		    sdinfo->satadrv_addr.cport)));
13464 		/*
13465 		 * Whoops, no SMART DATA available
13466 		 */
13467 		rval = -1;
13468 		goto fail;
13469 	} else {
13470 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13471 		    sdinfo->satadrv_addr.cport)));
13472 		if (spx->txlt_buf_dma_handle != NULL) {
13473 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13474 			    DDI_DMA_SYNC_FORKERNEL);
13475 			ASSERT(rval == DDI_SUCCESS);
13476 		}
13477 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
13478 		    sizeof (struct smart_selftest_log));
13479 		rval = 0;
13480 	}
13481 
13482 fail:
13483 	/* Free allocated resources */
13484 	sata_free_local_buffer(spx);
13485 	sata_pkt_free(spx);
13486 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13487 
13488 	return (rval);
13489 }
13490 
13491 
13492 /*
13493  * Returns 0 for success, -1 otherwise
13494  *
13495  * SMART READ LOG data is returned in buffer pointed to by smart_log
13496  */
13497 static int
13498 sata_smart_read_log(
13499 	sata_hba_inst_t *sata_hba_inst,
13500 	sata_drive_info_t *sdinfo,
13501 	uint8_t *smart_log,		/* where the data should be returned */
13502 	uint8_t which_log,		/* which log should be returned */
13503 	uint8_t log_size)		/* # of 512 bytes in log */
13504 {
13505 	sata_pkt_t *spkt;
13506 	sata_cmd_t *scmd;
13507 	sata_pkt_txlate_t *spx;
13508 	int rval;
13509 
13510 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13511 	spx->txlt_sata_hba_inst = sata_hba_inst;
13512 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13513 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13514 	if (spkt == NULL) {
13515 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13516 		return (-1);
13517 	}
13518 	/* address is needed now */
13519 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13520 
13521 
13522 	/* Fill sata_pkt */
13523 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13524 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13525 	/* Synchronous mode, no callback */
13526 	spkt->satapkt_comp = NULL;
13527 	/* Timeout 30s */
13528 	spkt->satapkt_time = sata_default_pkt_time;
13529 
13530 	scmd = &spkt->satapkt_cmd;
13531 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13532 
13533 	/*
13534 	 * Allocate buffer for SMART READ LOG
13535 	 */
13536 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
13537 	if (scmd->satacmd_bp == NULL) {
13538 		sata_pkt_free(spx);
13539 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13540 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13541 		    "sata_smart_read_log: " "cannot allocate buffer"));
13542 		return (-1);
13543 	}
13544 
13545 	/* Build SMART_READ_LOG cmd in the sata_pkt */
13546 	scmd->satacmd_addr_type = 0;		/* N/A */
13547 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
13548 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
13549 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
13550 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
13551 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
13552 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13553 	scmd->satacmd_cmd_reg = SATAC_SMART;
13554 
13555 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13556 	    sdinfo->satadrv_addr.cport)));
13557 
13558 	/* Send pkt to SATA HBA driver */
13559 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13560 	    SATA_TRAN_ACCEPTED ||
13561 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13562 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13563 		    sdinfo->satadrv_addr.cport)));
13564 
13565 		/*
13566 		 * Whoops, no SMART DATA available
13567 		 */
13568 		rval = -1;
13569 		goto fail;
13570 	} else {
13571 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13572 		    sdinfo->satadrv_addr.cport)));
13573 
13574 		if (spx->txlt_buf_dma_handle != NULL) {
13575 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13576 			    DDI_DMA_SYNC_FORKERNEL);
13577 			ASSERT(rval == DDI_SUCCESS);
13578 		}
13579 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
13580 		rval = 0;
13581 	}
13582 
13583 fail:
13584 	/* Free allocated resources */
13585 	sata_free_local_buffer(spx);
13586 	sata_pkt_free(spx);
13587 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13588 
13589 	return (rval);
13590 }
13591 
13592 /*
13593  * Used by LOG SENSE page 0x10
13594  *
13595  * return 0 for success, -1 otherwise
13596  *
13597  */
13598 static int
13599 sata_read_log_ext_directory(
13600 	sata_hba_inst_t *sata_hba_inst,
13601 	sata_drive_info_t *sdinfo,
13602 	struct read_log_ext_directory *logdir)
13603 {
13604 	sata_pkt_txlate_t *spx;
13605 	sata_pkt_t *spkt;
13606 	sata_cmd_t *scmd;
13607 	int rval;
13608 
13609 #if ! defined(lint)
13610 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
13611 #endif
13612 
13613 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13614 	spx->txlt_sata_hba_inst = sata_hba_inst;
13615 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13616 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13617 	if (spkt == NULL) {
13618 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13619 		return (-1);
13620 	}
13621 
13622 	/* Fill sata_pkt */
13623 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13624 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13625 	/* Synchronous mode, no callback */
13626 	spkt->satapkt_comp = NULL;
13627 	/* Timeout 30s */
13628 	spkt->satapkt_time = sata_default_pkt_time;
13629 
13630 	scmd = &spkt->satapkt_cmd;
13631 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13632 
13633 	/*
13634 	 * Allocate buffer for SMART READ LOG EXTENDED command
13635 	 */
13636 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
13637 	    sizeof (struct read_log_ext_directory));
13638 	if (scmd->satacmd_bp == NULL) {
13639 		sata_pkt_free(spx);
13640 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13641 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13642 		    "sata_read_log_ext_directory: "
13643 		    "cannot allocate buffer"));
13644 		return (-1);
13645 	}
13646 
13647 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
13648 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
13649 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
13650 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
13651 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
13652 	scmd->satacmd_lba_low_msb = 0;
13653 	scmd->satacmd_lba_mid_lsb = 0;
13654 	scmd->satacmd_lba_mid_msb = 0;
13655 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13656 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
13657 
13658 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
13659 	    sdinfo->satadrv_addr.cport)));
13660 
13661 	/* Send pkt to SATA HBA driver */
13662 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
13663 	    SATA_TRAN_ACCEPTED ||
13664 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13665 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13666 		    sdinfo->satadrv_addr.cport)));
13667 		/*
13668 		 * Whoops, no SMART selftest log info available
13669 		 */
13670 		rval = -1;
13671 		goto fail;
13672 	} else {
13673 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
13674 		    sdinfo->satadrv_addr.cport)));
13675 		if (spx->txlt_buf_dma_handle != NULL) {
13676 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13677 			    DDI_DMA_SYNC_FORKERNEL);
13678 			ASSERT(rval == DDI_SUCCESS);
13679 		}
13680 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
13681 		    sizeof (struct read_log_ext_directory));
13682 		rval = 0;
13683 	}
13684 
13685 fail:
13686 	/* Free allocated resources */
13687 	sata_free_local_buffer(spx);
13688 	sata_pkt_free(spx);
13689 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13690 
13691 	return (rval);
13692 }
13693 
13694 /*
13695  * Set up error retrieval sata command for NCQ command error data
13696  * recovery.
13697  *
13698  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
13699  * returns SATA_FAILURE otherwise.
13700  */
13701 static int
13702 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
13703 {
13704 #ifndef __lock_lint
13705 	_NOTE(ARGUNUSED(sdinfo))
13706 #endif
13707 
13708 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
13709 	sata_cmd_t *scmd;
13710 	struct buf *bp;
13711 
13712 	/* Operation modes are up to the caller */
13713 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13714 
13715 	/* Synchronous mode, no callback - may be changed by the caller */
13716 	spkt->satapkt_comp = NULL;
13717 	spkt->satapkt_time = sata_default_pkt_time;
13718 
13719 	scmd = &spkt->satapkt_cmd;
13720 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
13721 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13722 
13723 	/*
13724 	 * Allocate dma_able buffer error data.
13725 	 * Buffer allocation will take care of buffer alignment and other DMA
13726 	 * attributes.
13727 	 */
13728 	bp = sata_alloc_local_buffer(spx,
13729 	    sizeof (struct sata_ncq_error_recovery_page));
13730 	if (bp == NULL)
13731 		return (SATA_FAILURE);
13732 
13733 	bp_mapin(bp); /* make data buffer accessible */
13734 	scmd->satacmd_bp = bp;
13735 
13736 	/*
13737 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
13738 	 * before accessing it. Handle is in usual place in translate struct.
13739 	 */
13740 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
13741 
13742 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
13743 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
13744 
13745 	return (SATA_SUCCESS);
13746 }
13747 
13748 /*
13749  * sata_xlate_errors() is used to translate (S)ATA error
13750  * information to SCSI information returned in the SCSI
13751  * packet.
13752  */
13753 static void
13754 sata_xlate_errors(sata_pkt_txlate_t *spx)
13755 {
13756 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
13757 	struct scsi_extended_sense *sense;
13758 
13759 	scsipkt->pkt_reason = CMD_INCOMPLETE;
13760 	*scsipkt->pkt_scbp = STATUS_CHECK;
13761 	sense = sata_arq_sense(spx);
13762 
13763 	switch (spx->txlt_sata_pkt->satapkt_reason) {
13764 	case SATA_PKT_PORT_ERROR:
13765 		/*
13766 		 * We have no device data. Assume no data transfered.
13767 		 */
13768 		sense->es_key = KEY_HARDWARE_ERROR;
13769 		break;
13770 
13771 	case SATA_PKT_DEV_ERROR:
13772 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
13773 		    SATA_STATUS_ERR) {
13774 			/*
13775 			 * determine dev error reason from error
13776 			 * reg content
13777 			 */
13778 			sata_decode_device_error(spx, sense);
13779 			break;
13780 		}
13781 		/* No extended sense key - no info available */
13782 		break;
13783 
13784 	case SATA_PKT_TIMEOUT:
13785 		scsipkt->pkt_reason = CMD_TIMEOUT;
13786 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
13787 		/* No extended sense key */
13788 		break;
13789 
13790 	case SATA_PKT_ABORTED:
13791 		scsipkt->pkt_reason = CMD_ABORTED;
13792 		scsipkt->pkt_statistics |= STAT_ABORTED;
13793 		/* No extended sense key */
13794 		break;
13795 
13796 	case SATA_PKT_RESET:
13797 		/*
13798 		 * pkt aborted either by an explicit reset request from
13799 		 * a host, or due to error recovery
13800 		 */
13801 		scsipkt->pkt_reason = CMD_RESET;
13802 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
13803 		break;
13804 
13805 	default:
13806 		scsipkt->pkt_reason = CMD_TRAN_ERR;
13807 		break;
13808 	}
13809 }
13810 
13811 
13812 
13813 
13814 /*
13815  * Log sata message
13816  * dev pathname msg line preceeds the logged message.
13817  */
13818 
13819 static	void
13820 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
13821 {
13822 	char pathname[128];
13823 	dev_info_t *dip;
13824 	va_list ap;
13825 
13826 	mutex_enter(&sata_log_mutex);
13827 
13828 	va_start(ap, fmt);
13829 	(void) vsprintf(sata_log_buf, fmt, ap);
13830 	va_end(ap);
13831 
13832 	if (sata_hba_inst != NULL) {
13833 		dip = SATA_DIP(sata_hba_inst);
13834 		(void) ddi_pathname(dip, pathname);
13835 	} else {
13836 		pathname[0] = 0;
13837 	}
13838 	if (level == CE_CONT) {
13839 		if (sata_debug_flags == 0)
13840 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
13841 		else
13842 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
13843 	} else {
13844 		if (level != CE_NOTE) {
13845 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
13846 		} else if (sata_msg) {
13847 			cmn_err(level, "%s:\n %s", pathname,
13848 			    sata_log_buf);
13849 		}
13850 	}
13851 
13852 	mutex_exit(&sata_log_mutex);
13853 }
13854 
13855 
13856 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
13857 
13858 /*
13859  * Start or terminate the thread, depending on flag arg and current state
13860  */
13861 static void
13862 sata_event_thread_control(int startstop)
13863 {
13864 	static 	int sata_event_thread_terminating = 0;
13865 	static 	int sata_event_thread_starting = 0;
13866 	int i;
13867 
13868 	mutex_enter(&sata_event_mutex);
13869 
13870 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
13871 	    sata_event_thread_terminating == 1)) {
13872 		mutex_exit(&sata_event_mutex);
13873 		return;
13874 	}
13875 	if (startstop == 1 && sata_event_thread_starting == 1) {
13876 		mutex_exit(&sata_event_mutex);
13877 		return;
13878 	}
13879 	if (startstop == 1 && sata_event_thread_terminating == 1) {
13880 		sata_event_thread_starting = 1;
13881 		/* wait til terminate operation completes */
13882 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
13883 		while (sata_event_thread_terminating == 1) {
13884 			if (i-- <= 0) {
13885 				sata_event_thread_starting = 0;
13886 				mutex_exit(&sata_event_mutex);
13887 #ifdef SATA_DEBUG
13888 				cmn_err(CE_WARN, "sata_event_thread_control: "
13889 				    "timeout waiting for thread to terminate");
13890 #endif
13891 				return;
13892 			}
13893 			mutex_exit(&sata_event_mutex);
13894 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
13895 			mutex_enter(&sata_event_mutex);
13896 		}
13897 	}
13898 	if (startstop == 1) {
13899 		if (sata_event_thread == NULL) {
13900 			sata_event_thread = thread_create(NULL, 0,
13901 			    (void (*)())sata_event_daemon,
13902 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
13903 		}
13904 		sata_event_thread_starting = 0;
13905 		mutex_exit(&sata_event_mutex);
13906 		return;
13907 	}
13908 
13909 	/*
13910 	 * If we got here, thread may need to be terminated
13911 	 */
13912 	if (sata_event_thread != NULL) {
13913 		int i;
13914 		/* Signal event thread to go away */
13915 		sata_event_thread_terminating = 1;
13916 		sata_event_thread_terminate = 1;
13917 		cv_signal(&sata_event_cv);
13918 		/*
13919 		 * Wait til daemon terminates.
13920 		 */
13921 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
13922 		while (sata_event_thread_terminate == 1) {
13923 			mutex_exit(&sata_event_mutex);
13924 			if (i-- <= 0) {
13925 				/* Daemon did not go away !!! */
13926 #ifdef SATA_DEBUG
13927 				cmn_err(CE_WARN, "sata_event_thread_control: "
13928 				    "cannot terminate event daemon thread");
13929 #endif
13930 				mutex_enter(&sata_event_mutex);
13931 				break;
13932 			}
13933 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
13934 			mutex_enter(&sata_event_mutex);
13935 		}
13936 		sata_event_thread_terminating = 0;
13937 	}
13938 	ASSERT(sata_event_thread_terminating == 0);
13939 	ASSERT(sata_event_thread_starting == 0);
13940 	mutex_exit(&sata_event_mutex);
13941 }
13942 
13943 
13944 /*
13945  * SATA HBA event notification function.
13946  * Events reported by SATA HBA drivers per HBA instance relate to a change in
13947  * a port and/or device state or a controller itself.
13948  * Events for different addresses/addr types cannot be combined.
13949  * A warning message is generated for each event type.
13950  * Events are not processed by this function, so only the
13951  * event flag(s)is set for an affected entity and the event thread is
13952  * waken up. Event daemon thread processes all events.
13953  *
13954  * NOTE: Since more than one event may be reported at the same time, one
13955  * cannot determine a sequence of events when opposite event are reported, eg.
13956  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
13957  * is taking precedence over reported events, i.e. may cause ignoring some
13958  * events.
13959  */
13960 #define	SATA_EVENT_MAX_MSG_LENGTH	79
13961 
13962 void
13963 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
13964 {
13965 	sata_hba_inst_t *sata_hba_inst = NULL;
13966 	sata_address_t *saddr;
13967 	sata_drive_info_t *sdinfo;
13968 	sata_port_stats_t *pstats;
13969 	sata_cport_info_t *cportinfo;
13970 	sata_pmport_info_t *pmportinfo;
13971 	int cport, pmport;
13972 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
13973 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
13974 	char *lcp;
13975 	static char *err_msg_evnt_1 =
13976 	    "sata_hba_event_notify: invalid port event 0x%x ";
13977 	static char *err_msg_evnt_2 =
13978 	    "sata_hba_event_notify: invalid device event 0x%x ";
13979 	int linkevent;
13980 
13981 	/*
13982 	 * There is a possibility that an event will be generated on HBA
13983 	 * that has not completed attachment or is detaching. We still want
13984 	 * to process events until HBA is detached.
13985 	 */
13986 	mutex_enter(&sata_mutex);
13987 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
13988 	    sata_hba_inst = sata_hba_inst->satahba_next) {
13989 		if (SATA_DIP(sata_hba_inst) == dip)
13990 			if (sata_hba_inst->satahba_attached == 1)
13991 				break;
13992 	}
13993 	mutex_exit(&sata_mutex);
13994 	if (sata_hba_inst == NULL)
13995 		/* HBA not attached */
13996 		return;
13997 
13998 	ASSERT(sata_device != NULL);
13999 
14000 	/*
14001 	 * Validate address before - do not proceed with invalid address.
14002 	 */
14003 	saddr = &sata_device->satadev_addr;
14004 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
14005 		return;
14006 	if (saddr->qual == SATA_ADDR_PMPORT ||
14007 	    saddr->qual == SATA_ADDR_DPMPORT)
14008 		/* Port Multiplier not supported yet */
14009 		return;
14010 
14011 	cport = saddr->cport;
14012 	pmport = saddr->pmport;
14013 
14014 	buf1[0] = buf2[0] = '\0';
14015 
14016 	/*
14017 	 * If event relates to port or device, check port state.
14018 	 * Port has to be initialized, or we cannot accept an event.
14019 	 */
14020 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
14021 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) != 0) {
14022 		if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_DCPORT)) != 0) {
14023 			mutex_enter(&sata_hba_inst->satahba_mutex);
14024 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14025 			mutex_exit(&sata_hba_inst->satahba_mutex);
14026 			if (cportinfo == NULL || cportinfo->cport_state == 0)
14027 				return;
14028 		} else {
14029 			mutex_enter(&sata_hba_inst->satahba_mutex);
14030 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
14031 			    cport, pmport);
14032 			mutex_exit(&sata_hba_inst->satahba_mutex);
14033 			if (pmportinfo == NULL || pmportinfo->pmport_state == 0)
14034 				return;
14035 		}
14036 	}
14037 
14038 	/*
14039 	 * Events refer to devices, ports and controllers - each has
14040 	 * unique address. Events for different addresses cannot be combined.
14041 	 */
14042 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
14043 
14044 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
14045 
14046 		/* qualify this event(s) */
14047 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
14048 			/* Invalid event for the device port */
14049 			(void) sprintf(buf2, err_msg_evnt_1,
14050 			    event & SATA_EVNT_PORT_EVENTS);
14051 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
14052 			goto event_info;
14053 		}
14054 		if (saddr->qual == SATA_ADDR_CPORT) {
14055 			/* Controller's device port event */
14056 
14057 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
14058 			    cport_event_flags |=
14059 			    event & SATA_EVNT_PORT_EVENTS;
14060 			pstats =
14061 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
14062 			    cport_stats;
14063 		} else {
14064 			/* Port multiplier's device port event */
14065 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
14066 			    pmport_event_flags |=
14067 			    event & SATA_EVNT_PORT_EVENTS;
14068 			pstats =
14069 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
14070 			    pmport_stats;
14071 		}
14072 
14073 		/*
14074 		 * Add to statistics and log the message. We have to do it
14075 		 * here rather than in the event daemon, because there may be
14076 		 * multiple events occuring before they are processed.
14077 		 */
14078 		linkevent = event &
14079 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
14080 		if (linkevent) {
14081 			if (linkevent == (SATA_EVNT_LINK_LOST |
14082 			    SATA_EVNT_LINK_ESTABLISHED)) {
14083 				/* This is likely event combination */
14084 				(void) strlcat(buf1, "link lost/established, ",
14085 				    SATA_EVENT_MAX_MSG_LENGTH);
14086 
14087 				if (pstats->link_lost < 0xffffffffffffffffULL)
14088 					pstats->link_lost++;
14089 				if (pstats->link_established <
14090 				    0xffffffffffffffffULL)
14091 					pstats->link_established++;
14092 				linkevent = 0;
14093 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
14094 				(void) strlcat(buf1, "link lost, ",
14095 				    SATA_EVENT_MAX_MSG_LENGTH);
14096 
14097 				if (pstats->link_lost < 0xffffffffffffffffULL)
14098 					pstats->link_lost++;
14099 			} else {
14100 				(void) strlcat(buf1, "link established, ",
14101 				    SATA_EVENT_MAX_MSG_LENGTH);
14102 				if (pstats->link_established <
14103 				    0xffffffffffffffffULL)
14104 					pstats->link_established++;
14105 			}
14106 		}
14107 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
14108 			(void) strlcat(buf1, "device attached, ",
14109 			    SATA_EVENT_MAX_MSG_LENGTH);
14110 			if (pstats->device_attached < 0xffffffffffffffffULL)
14111 				pstats->device_attached++;
14112 		}
14113 		if (event & SATA_EVNT_DEVICE_DETACHED) {
14114 			(void) strlcat(buf1, "device detached, ",
14115 			    SATA_EVENT_MAX_MSG_LENGTH);
14116 			if (pstats->device_detached < 0xffffffffffffffffULL)
14117 				pstats->device_detached++;
14118 		}
14119 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
14120 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
14121 			    "port %d power level changed", cport);
14122 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
14123 				pstats->port_pwr_changed++;
14124 		}
14125 
14126 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
14127 			/* There should be no other events for this address */
14128 			(void) sprintf(buf2, err_msg_evnt_1,
14129 			    event & ~SATA_EVNT_PORT_EVENTS);
14130 		}
14131 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
14132 
14133 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
14134 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
14135 
14136 		/* qualify this event */
14137 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
14138 			/* Invalid event for a device */
14139 			(void) sprintf(buf2, err_msg_evnt_2,
14140 			    event & SATA_EVNT_DEVICE_RESET);
14141 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
14142 			goto event_info;
14143 		}
14144 		/* drive event */
14145 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
14146 		if (sdinfo != NULL) {
14147 			if (event & SATA_EVNT_DEVICE_RESET) {
14148 				(void) strlcat(buf1, "device reset, ",
14149 				    SATA_EVENT_MAX_MSG_LENGTH);
14150 				if (sdinfo->satadrv_stats.drive_reset <
14151 				    0xffffffffffffffffULL)
14152 					sdinfo->satadrv_stats.drive_reset++;
14153 				sdinfo->satadrv_event_flags |=
14154 				    SATA_EVNT_DEVICE_RESET;
14155 			}
14156 		}
14157 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
14158 			/* Invalid event for a device */
14159 			(void) sprintf(buf2, err_msg_evnt_2,
14160 			    event & ~SATA_EVNT_DRIVE_EVENTS);
14161 		}
14162 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
14163 	} else {
14164 		if (saddr->qual != SATA_ADDR_NULL) {
14165 			/* Wrong address qualifier */
14166 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14167 			    "sata_hba_event_notify: invalid address 0x%x",
14168 			    *(uint32_t *)saddr));
14169 			return;
14170 		}
14171 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
14172 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
14173 			/* Invalid event for the controller */
14174 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14175 			    "sata_hba_event_notify: invalid event 0x%x for "
14176 			    "controller",
14177 			    event & SATA_EVNT_CONTROLLER_EVENTS));
14178 			return;
14179 		}
14180 		buf1[0] = '\0';
14181 		/* This may be a frequent and not interesting event */
14182 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
14183 		    "controller power level changed\n", NULL);
14184 
14185 		mutex_enter(&sata_hba_inst->satahba_mutex);
14186 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
14187 		    0xffffffffffffffffULL)
14188 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
14189 
14190 		sata_hba_inst->satahba_event_flags |=
14191 		    SATA_EVNT_PWR_LEVEL_CHANGED;
14192 		mutex_exit(&sata_hba_inst->satahba_mutex);
14193 	}
14194 	/*
14195 	 * If we got here, there is something to do with this HBA
14196 	 * instance.
14197 	 */
14198 	mutex_enter(&sata_hba_inst->satahba_mutex);
14199 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
14200 	mutex_exit(&sata_hba_inst->satahba_mutex);
14201 	mutex_enter(&sata_mutex);
14202 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
14203 	mutex_exit(&sata_mutex);
14204 
14205 	/* Tickle event thread */
14206 	mutex_enter(&sata_event_mutex);
14207 	if (sata_event_thread_active == 0)
14208 		cv_signal(&sata_event_cv);
14209 	mutex_exit(&sata_event_mutex);
14210 
14211 event_info:
14212 	if (buf1[0] != '\0') {
14213 		lcp = strrchr(buf1, ',');
14214 		if (lcp != NULL)
14215 			*lcp = '\0';
14216 	}
14217 	if (saddr->qual == SATA_ADDR_CPORT ||
14218 	    saddr->qual == SATA_ADDR_DCPORT) {
14219 		if (buf1[0] != '\0') {
14220 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
14221 			    cport, buf1);
14222 		}
14223 		if (buf2[0] != '\0') {
14224 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
14225 			    cport, buf2);
14226 		}
14227 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
14228 	    saddr->qual == SATA_ADDR_DPMPORT) {
14229 		if (buf1[0] != '\0') {
14230 			sata_log(sata_hba_inst, CE_NOTE,
14231 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
14232 		}
14233 		if (buf2[0] != '\0') {
14234 			sata_log(sata_hba_inst, CE_NOTE,
14235 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
14236 		}
14237 	}
14238 }
14239 
14240 
14241 /*
14242  * Event processing thread.
14243  * Arg is a pointer to the sata_hba_list pointer.
14244  * It is not really needed, because sata_hba_list is global and static
14245  */
14246 static void
14247 sata_event_daemon(void *arg)
14248 {
14249 #ifndef __lock_lint
14250 	_NOTE(ARGUNUSED(arg))
14251 #endif
14252 	sata_hba_inst_t *sata_hba_inst;
14253 	clock_t lbolt;
14254 
14255 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
14256 	    "SATA event daemon started\n", NULL);
14257 loop:
14258 	/*
14259 	 * Process events here. Walk through all registered HBAs
14260 	 */
14261 	mutex_enter(&sata_mutex);
14262 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
14263 	    sata_hba_inst = sata_hba_inst->satahba_next) {
14264 		ASSERT(sata_hba_inst != NULL);
14265 		mutex_enter(&sata_hba_inst->satahba_mutex);
14266 		if (sata_hba_inst->satahba_attached == 0 ||
14267 		    (sata_hba_inst->satahba_event_flags &
14268 		    SATA_EVNT_SKIP) != 0) {
14269 			mutex_exit(&sata_hba_inst->satahba_mutex);
14270 			continue;
14271 		}
14272 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
14273 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
14274 			mutex_exit(&sata_hba_inst->satahba_mutex);
14275 			mutex_exit(&sata_mutex);
14276 			/* Got the controller with pending event */
14277 			sata_process_controller_events(sata_hba_inst);
14278 			/*
14279 			 * Since global mutex was released, there is a
14280 			 * possibility that HBA list has changed, so start
14281 			 * over from the top. Just processed controller
14282 			 * will be passed-over because of the SKIP flag.
14283 			 */
14284 			goto loop;
14285 		}
14286 		mutex_exit(&sata_hba_inst->satahba_mutex);
14287 	}
14288 	/* Clear SKIP flag in all controllers */
14289 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
14290 	    sata_hba_inst = sata_hba_inst->satahba_next) {
14291 		mutex_enter(&sata_hba_inst->satahba_mutex);
14292 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
14293 		mutex_exit(&sata_hba_inst->satahba_mutex);
14294 	}
14295 	mutex_exit(&sata_mutex);
14296 
14297 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
14298 	    "SATA EVENT DAEMON suspending itself", NULL);
14299 
14300 #ifdef SATA_DEBUG
14301 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
14302 		sata_log(sata_hba_inst, CE_WARN,
14303 		    "SATA EVENTS PROCESSING DISABLED\n");
14304 		thread_exit(); /* Daemon will not run again */
14305 	}
14306 #endif
14307 	mutex_enter(&sata_event_mutex);
14308 	sata_event_thread_active = 0;
14309 	mutex_exit(&sata_event_mutex);
14310 	/*
14311 	 * Go to sleep/suspend itself and wake up either because new event or
14312 	 * wait timeout. Exit if there is a termination request (driver
14313 	 * unload).
14314 	 */
14315 	do {
14316 		lbolt = ddi_get_lbolt();
14317 		lbolt += drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
14318 		mutex_enter(&sata_event_mutex);
14319 		(void) cv_timedwait(&sata_event_cv, &sata_event_mutex, lbolt);
14320 
14321 		if (sata_event_thread_active != 0) {
14322 			mutex_exit(&sata_event_mutex);
14323 			continue;
14324 		}
14325 
14326 		/* Check if it is time to go away */
14327 		if (sata_event_thread_terminate == 1) {
14328 			/*
14329 			 * It is up to the thread setting above flag to make
14330 			 * sure that this thread is not killed prematurely.
14331 			 */
14332 			sata_event_thread_terminate = 0;
14333 			sata_event_thread = NULL;
14334 			mutex_exit(&sata_event_mutex);
14335 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
14336 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
14337 			thread_exit();  { _NOTE(NOT_REACHED) }
14338 		}
14339 		mutex_exit(&sata_event_mutex);
14340 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
14341 
14342 	mutex_enter(&sata_event_mutex);
14343 	sata_event_thread_active = 1;
14344 	mutex_exit(&sata_event_mutex);
14345 
14346 	mutex_enter(&sata_mutex);
14347 	sata_event_pending &= ~SATA_EVNT_MAIN;
14348 	mutex_exit(&sata_mutex);
14349 
14350 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
14351 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
14352 
14353 	goto loop;
14354 }
14355 
14356 /*
14357  * Specific HBA instance event processing.
14358  *
14359  * NOTE: At the moment, device event processing is limited to hard disks
14360  * only.
14361  * cports only are supported - no pmports.
14362  */
14363 static void
14364 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
14365 {
14366 	int ncport;
14367 	uint32_t event_flags;
14368 	sata_address_t *saddr;
14369 	sata_cport_info_t *cportinfo;
14370 
14371 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
14372 	    "Processing controller %d event(s)",
14373 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
14374 
14375 	mutex_enter(&sata_hba_inst->satahba_mutex);
14376 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
14377 	event_flags = sata_hba_inst->satahba_event_flags;
14378 	mutex_exit(&sata_hba_inst->satahba_mutex);
14379 	/*
14380 	 * Process controller power change first
14381 	 * HERE
14382 	 */
14383 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
14384 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
14385 
14386 	/*
14387 	 * Search through ports/devices to identify affected port/device.
14388 	 * We may have to process events for more than one port/device.
14389 	 */
14390 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
14391 		/*
14392 		 * Not all ports may be processed in attach by the time we
14393 		 * get an event. Check if port info is initialized.
14394 		 */
14395 		mutex_enter(&sata_hba_inst->satahba_mutex);
14396 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
14397 		mutex_exit(&sata_hba_inst->satahba_mutex);
14398 		if (cportinfo == NULL || cportinfo->cport_state == NULL)
14399 			continue;
14400 
14401 		/* We have initialized controller port info */
14402 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
14403 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
14404 		    cport_event_flags;
14405 		/* Check if port was locked by IOCTL processing */
14406 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
14407 			/*
14408 			 * We ignore port events because port is busy
14409 			 * with AP control processing. Set again
14410 			 * controller and main event flag, so that
14411 			 * events may be processed by the next daemon
14412 			 * run.
14413 			 */
14414 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
14415 			mutex_enter(&sata_hba_inst->satahba_mutex);
14416 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
14417 			mutex_exit(&sata_hba_inst->satahba_mutex);
14418 			mutex_enter(&sata_mutex);
14419 			sata_event_pending |= SATA_EVNT_MAIN;
14420 			mutex_exit(&sata_mutex);
14421 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
14422 			    "Event processing postponed until "
14423 			    "AP control processing completes",
14424 			    NULL);
14425 			/* Check other ports */
14426 			continue;
14427 		} else {
14428 			/*
14429 			 * Set BSY flag so that AP control would not
14430 			 * interfere with events processing for
14431 			 * this port.
14432 			 */
14433 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
14434 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
14435 		}
14436 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
14437 
14438 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
14439 
14440 		if ((event_flags &
14441 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
14442 			/*
14443 			 * Got port event.
14444 			 * We need some hierarchy of event processing as they
14445 			 * are affecting each other:
14446 			 * 1. port failed
14447 			 * 2. device detached/attached
14448 			 * 3. link events - link events may trigger device
14449 			 *    detached or device attached events in some
14450 			 *    circumstances.
14451 			 * 4. port power level changed
14452 			 */
14453 			if (event_flags & SATA_EVNT_PORT_FAILED) {
14454 				sata_process_port_failed_event(sata_hba_inst,
14455 				    saddr);
14456 			}
14457 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
14458 				sata_process_device_detached(sata_hba_inst,
14459 				    saddr);
14460 			}
14461 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
14462 				sata_process_device_attached(sata_hba_inst,
14463 				    saddr);
14464 			}
14465 			if (event_flags &
14466 			    (SATA_EVNT_LINK_ESTABLISHED |
14467 			    SATA_EVNT_LINK_LOST)) {
14468 				sata_process_port_link_events(sata_hba_inst,
14469 				    saddr);
14470 			}
14471 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
14472 				sata_process_port_pwr_change(sata_hba_inst,
14473 				    saddr);
14474 			}
14475 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
14476 				sata_process_target_node_cleanup(
14477 				    sata_hba_inst, saddr);
14478 			}
14479 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
14480 				sata_process_device_autoonline(
14481 				    sata_hba_inst, saddr);
14482 			}
14483 		}
14484 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
14485 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
14486 		    SATA_DTYPE_NONE) &&
14487 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
14488 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
14489 			    satadrv_event_flags &
14490 			    (SATA_EVNT_DEVICE_RESET |
14491 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
14492 				/* Have device event */
14493 				sata_process_device_reset(sata_hba_inst,
14494 				    saddr);
14495 			}
14496 		}
14497 		/* Release PORT_BUSY flag */
14498 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
14499 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
14500 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
14501 
14502 	} /* End of loop through the controller SATA ports */
14503 }
14504 
14505 /*
14506  * Process HBA power level change reported by HBA driver.
14507  * Not implemented at this time - event is ignored.
14508  */
14509 static void
14510 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
14511 {
14512 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14513 	    "Processing controller power level change", NULL);
14514 
14515 	/* Ignoring it for now */
14516 	mutex_enter(&sata_hba_inst->satahba_mutex);
14517 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
14518 	mutex_exit(&sata_hba_inst->satahba_mutex);
14519 }
14520 
14521 /*
14522  * Process port power level change reported by HBA driver.
14523  * Not implemented at this time - event is ignored.
14524  */
14525 static void
14526 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
14527     sata_address_t *saddr)
14528 {
14529 	sata_cport_info_t *cportinfo;
14530 
14531 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14532 	    "Processing port power level change", NULL);
14533 
14534 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14535 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14536 	/* Reset event flag */
14537 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
14538 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14539 }
14540 
14541 /*
14542  * Process port failure reported by HBA driver.
14543  * cports support only - no pmports.
14544  */
14545 static void
14546 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
14547     sata_address_t *saddr)
14548 {
14549 	sata_cport_info_t *cportinfo;
14550 
14551 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14552 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14553 	/* Reset event flag first */
14554 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
14555 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
14556 	if ((cportinfo->cport_state &
14557 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
14558 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14559 		    cport_mutex);
14560 		return;
14561 	}
14562 	/* Fail the port */
14563 	cportinfo->cport_state = SATA_PSTATE_FAILED;
14564 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14565 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
14566 }
14567 
14568 /*
14569  * Device Reset Event processing.
14570  * The seqeunce is managed by 3 stage flags:
14571  * - reset event reported,
14572  * - reset event being processed,
14573  * - request to clear device reset state.
14574  *
14575  * NOTE: This function has to be entered with cport mutex held. It exits with
14576  * mutex held as well, but can release mutex during the processing.
14577  */
14578 static void
14579 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
14580     sata_address_t *saddr)
14581 {
14582 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
14583 	sata_drive_info_t *sdinfo;
14584 	sata_cport_info_t *cportinfo;
14585 	sata_device_t sata_device;
14586 	int rval_probe, rval_set;
14587 
14588 	/* We only care about host sata cport for now */
14589 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14590 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
14591 	/*
14592 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
14593 	 * state, ignore reset event.
14594 	 */
14595 	if (((cportinfo->cport_state &
14596 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
14597 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
14598 		sdinfo->satadrv_event_flags &=
14599 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
14600 		return;
14601 	}
14602 
14603 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
14604 	    SATA_VALID_DEV_TYPE) == 0) {
14605 		/*
14606 		 * This should not happen - coding error.
14607 		 * But we can recover, so do not panic, just clean up
14608 		 * and if in debug mode, log the message.
14609 		 */
14610 #ifdef SATA_DEBUG
14611 		sata_log(sata_hba_inst, CE_WARN,
14612 		    "sata_process_device_reset: "
14613 		    "Invalid device type with sdinfo!", NULL);
14614 #endif
14615 		sdinfo->satadrv_event_flags = 0;
14616 		return;
14617 	}
14618 
14619 #ifdef SATA_DEBUG
14620 	if ((sdinfo->satadrv_event_flags &
14621 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
14622 		/* Nothing to do */
14623 		/* Something is weird - why we are processing dev reset? */
14624 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14625 		    "No device reset event!!!!", NULL);
14626 
14627 		return;
14628 	}
14629 	if ((sdinfo->satadrv_event_flags &
14630 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
14631 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
14632 		/* Something is weird - new device reset event */
14633 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14634 		    "Overlapping device reset events!", NULL);
14635 	}
14636 #endif
14637 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14638 	    "Processing port %d device reset", saddr->cport);
14639 
14640 	/* Clear event flag */
14641 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
14642 
14643 	/* It seems that we always need to check the port state first */
14644 	sata_device.satadev_rev = SATA_DEVICE_REV;
14645 	sata_device.satadev_addr = *saddr;
14646 	/*
14647 	 * We have to exit mutex, because the HBA probe port function may
14648 	 * block on its own mutex.
14649 	 */
14650 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14651 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14652 	    (SATA_DIP(sata_hba_inst), &sata_device);
14653 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14654 	sata_update_port_info(sata_hba_inst, &sata_device);
14655 	if (rval_probe != SATA_SUCCESS) {
14656 		/* Something went wrong? Fail the port */
14657 		cportinfo->cport_state = SATA_PSTATE_FAILED;
14658 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
14659 		if (sdinfo != NULL)
14660 			sdinfo->satadrv_event_flags = 0;
14661 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14662 		    cport_mutex);
14663 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14664 		    "SATA port %d probing failed",
14665 		    saddr->cport));
14666 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14667 		    saddr->cport)->cport_mutex);
14668 		return;
14669 	}
14670 	if ((sata_device.satadev_scr.sstatus  &
14671 	    SATA_PORT_DEVLINK_UP_MASK) !=
14672 	    SATA_PORT_DEVLINK_UP ||
14673 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
14674 		/*
14675 		 * No device to process, anymore. Some other event processing
14676 		 * would or have already performed port info cleanup.
14677 		 * To be safe (HBA may need it), request clearing device
14678 		 * reset condition.
14679 		 */
14680 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
14681 		if (sdinfo != NULL) {
14682 			sdinfo->satadrv_event_flags &=
14683 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
14684 			sdinfo->satadrv_event_flags |=
14685 			    SATA_EVNT_CLEAR_DEVICE_RESET;
14686 		}
14687 		return;
14688 	}
14689 
14690 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
14691 	if (sdinfo == NULL) {
14692 		return;
14693 	}
14694 	if ((sdinfo->satadrv_event_flags &
14695 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
14696 		/*
14697 		 * Start tracking time for device feature restoration and
14698 		 * identification. Save current time (lbolt value).
14699 		 */
14700 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
14701 	}
14702 	/* Mark device reset processing as active */
14703 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
14704 
14705 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
14706 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14707 
14708 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
14709 
14710 	if (rval_set  != SATA_SUCCESS) {
14711 		/*
14712 		 * Restoring drive setting failed.
14713 		 * Probe the port first, to check if the port state has changed
14714 		 */
14715 		sata_device.satadev_rev = SATA_DEVICE_REV;
14716 		sata_device.satadev_addr = *saddr;
14717 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
14718 		/* probe port */
14719 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14720 		    (SATA_DIP(sata_hba_inst), &sata_device);
14721 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14722 		    cport_mutex);
14723 		if (rval_probe == SATA_SUCCESS &&
14724 		    (sata_device.satadev_state &
14725 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
14726 		    (sata_device.satadev_scr.sstatus  &
14727 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
14728 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
14729 			/*
14730 			 * We may retry this a bit later - in-process reset
14731 			 * condition should be already set.
14732 			 * Track retry time for device identification.
14733 			 */
14734 			if ((cportinfo->cport_dev_type &
14735 			    SATA_VALID_DEV_TYPE) != 0 &&
14736 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
14737 			    sdinfo->satadrv_reset_time != 0) {
14738 				clock_t cur_time = ddi_get_lbolt();
14739 				/*
14740 				 * If the retry time limit was not
14741 				 * exceeded, retry.
14742 				 */
14743 				if ((cur_time - sdinfo->satadrv_reset_time) <
14744 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
14745 					mutex_enter(
14746 					    &sata_hba_inst->satahba_mutex);
14747 					sata_hba_inst->satahba_event_flags |=
14748 					    SATA_EVNT_MAIN;
14749 					mutex_exit(
14750 					    &sata_hba_inst->satahba_mutex);
14751 					mutex_enter(&sata_mutex);
14752 					sata_event_pending |= SATA_EVNT_MAIN;
14753 					mutex_exit(&sata_mutex);
14754 					return;
14755 				}
14756 				if (rval_set == SATA_RETRY) {
14757 					/*
14758 					 * Setting drive features failed, but
14759 					 * the drive is still accessible,
14760 					 * so emit a warning message before
14761 					 * return.
14762 					 */
14763 					mutex_exit(&SATA_CPORT_INFO(
14764 					    sata_hba_inst,
14765 					    saddr->cport)->cport_mutex);
14766 					goto done;
14767 				}
14768 			}
14769 			/* Fail the drive */
14770 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
14771 
14772 			sata_log(sata_hba_inst, CE_WARN,
14773 			    "SATA device at port %d - device failed",
14774 			    saddr->cport);
14775 		}
14776 		/*
14777 		 * No point of retrying - device failed or some other event
14778 		 * processing or already did or will do port info cleanup.
14779 		 * To be safe (HBA may need it),
14780 		 * request clearing device reset condition.
14781 		 */
14782 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
14783 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
14784 		sdinfo->satadrv_reset_time = 0;
14785 		return;
14786 	}
14787 done:
14788 	/*
14789 	 * If setting of drive features failed, but the drive is still
14790 	 * accessible, emit a warning message.
14791 	 */
14792 	if (rval_set == SATA_RETRY) {
14793 		sata_log(sata_hba_inst, CE_WARN,
14794 		    "SATA device at port %d - desired setting could not be "
14795 		    "restored after reset. Device may not operate as expected.",
14796 		    saddr->cport);
14797 	}
14798 	/*
14799 	 * Raise the flag indicating that the next sata command could
14800 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
14801 	 * reset is reported.
14802 	 */
14803 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14804 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
14805 		sdinfo->satadrv_reset_time = 0;
14806 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
14807 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14808 			sdinfo->satadrv_event_flags &=
14809 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
14810 			sdinfo->satadrv_event_flags |=
14811 			    SATA_EVNT_CLEAR_DEVICE_RESET;
14812 		}
14813 	}
14814 }
14815 
14816 
14817 /*
14818  * Port Link Events processing.
14819  * Every link established event may involve device reset (due to
14820  * COMRESET signal, equivalent of the hard reset) so arbitrarily
14821  * set device reset event for an attached device (if any).
14822  * If the port is in SHUTDOWN or FAILED state, ignore link events.
14823  *
14824  * The link established event processing varies, depending on the state
14825  * of the target node, HBA hotplugging capabilities, state of the port.
14826  * If the link is not active, the link established event is ignored.
14827  * If HBA cannot detect device attachment and there is no target node,
14828  * the link established event triggers device attach event processing.
14829  * Else, link established event triggers device reset event processing.
14830  *
14831  * The link lost event processing varies, depending on a HBA hotplugging
14832  * capability and the state of the port (link active or not active).
14833  * If the link is active, the lost link event is ignored.
14834  * If HBA cannot detect device removal, the lost link event triggers
14835  * device detached event processing after link lost timeout.
14836  * Else, the event is ignored.
14837  *
14838  * NOTE: Only cports are processed for now, i.e. no port multiplier ports
14839  */
14840 static void
14841 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
14842     sata_address_t *saddr)
14843 {
14844 	sata_device_t sata_device;
14845 	sata_cport_info_t *cportinfo;
14846 	sata_drive_info_t *sdinfo;
14847 	uint32_t event_flags;
14848 	int rval;
14849 
14850 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14851 	    "Processing port %d link event(s)", saddr->cport);
14852 
14853 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
14854 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14855 	event_flags = cportinfo->cport_event_flags;
14856 
14857 	/* Reset event flags first */
14858 	cportinfo->cport_event_flags &=
14859 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
14860 
14861 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
14862 	if ((cportinfo->cport_state &
14863 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
14864 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14865 		    cport_mutex);
14866 		return;
14867 	}
14868 
14869 	/*
14870 	 * For the sanity sake get current port state.
14871 	 * Set device address only. Other sata_device fields should be
14872 	 * set by HBA driver.
14873 	 */
14874 	sata_device.satadev_rev = SATA_DEVICE_REV;
14875 	sata_device.satadev_addr = *saddr;
14876 	/*
14877 	 * We have to exit mutex, because the HBA probe port function may
14878 	 * block on its own mutex.
14879 	 */
14880 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14881 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14882 	    (SATA_DIP(sata_hba_inst), &sata_device);
14883 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
14884 	sata_update_port_info(sata_hba_inst, &sata_device);
14885 	if (rval != SATA_SUCCESS) {
14886 		/* Something went wrong? Fail the port */
14887 		cportinfo->cport_state = SATA_PSTATE_FAILED;
14888 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
14889 		    cport_mutex);
14890 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14891 		    "SATA port %d probing failed",
14892 		    saddr->cport));
14893 		/*
14894 		 * We may want to release device info structure, but
14895 		 * it is not necessary.
14896 		 */
14897 		return;
14898 	} else {
14899 		/* port probed successfully */
14900 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
14901 	}
14902 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
14903 
14904 		if ((sata_device.satadev_scr.sstatus &
14905 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
14906 			/* Ignore event */
14907 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14908 			    "Ignoring port %d link established event - "
14909 			    "link down",
14910 			    saddr->cport);
14911 			goto linklost;
14912 		}
14913 
14914 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14915 		    "Processing port %d link established event",
14916 		    saddr->cport);
14917 
14918 		/*
14919 		 * For the sanity sake check if a device is attached - check
14920 		 * return state of a port probing.
14921 		 */
14922 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
14923 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
14924 			/*
14925 			 * HBA port probe indicated that there is a device
14926 			 * attached. Check if the framework had device info
14927 			 * structure attached for this device.
14928 			 */
14929 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14930 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
14931 				    NULL);
14932 
14933 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14934 				if ((sdinfo->satadrv_type &
14935 				    SATA_VALID_DEV_TYPE) != 0) {
14936 					/*
14937 					 * Dev info structure is present.
14938 					 * If dev_type is set to known type in
14939 					 * the framework's drive info struct
14940 					 * then the device existed before and
14941 					 * the link was probably lost
14942 					 * momentarily - in such case
14943 					 * we may want to check device
14944 					 * identity.
14945 					 * Identity check is not supported now.
14946 					 *
14947 					 * Link established event
14948 					 * triggers device reset event.
14949 					 */
14950 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
14951 					    satadrv_event_flags |=
14952 					    SATA_EVNT_DEVICE_RESET;
14953 				}
14954 			} else if (cportinfo->cport_dev_type ==
14955 			    SATA_DTYPE_NONE) {
14956 				/*
14957 				 * We got new device attached! If HBA does not
14958 				 * generate device attached events, trigger it
14959 				 * here.
14960 				 */
14961 				if (!(SATA_FEATURES(sata_hba_inst) &
14962 				    SATA_CTLF_HOTPLUG)) {
14963 					cportinfo->cport_event_flags |=
14964 					    SATA_EVNT_DEVICE_ATTACHED;
14965 				}
14966 			}
14967 			/* Reset link lost timeout */
14968 			cportinfo->cport_link_lost_time = 0;
14969 		}
14970 	}
14971 linklost:
14972 	if (event_flags & SATA_EVNT_LINK_LOST) {
14973 		if ((sata_device.satadev_scr.sstatus &
14974 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
14975 			/* Ignore event */
14976 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14977 			    "Ignoring port %d link lost event - link is up",
14978 			    saddr->cport);
14979 			goto done;
14980 		}
14981 #ifdef SATA_DEBUG
14982 		if (cportinfo->cport_link_lost_time == 0) {
14983 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
14984 			    "Processing port %d link lost event",
14985 			    saddr->cport);
14986 		}
14987 #endif
14988 		/*
14989 		 * When HBA cannot generate device attached/detached events,
14990 		 * we need to track link lost time and eventually generate
14991 		 * device detach event.
14992 		 */
14993 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
14994 			/* We are tracking link lost time */
14995 			if (cportinfo->cport_link_lost_time == 0) {
14996 				/* save current time (lbolt value) */
14997 				cportinfo->cport_link_lost_time =
14998 				    ddi_get_lbolt();
14999 				/* just keep link lost event */
15000 				cportinfo->cport_event_flags |=
15001 				    SATA_EVNT_LINK_LOST;
15002 			} else {
15003 				clock_t cur_time = ddi_get_lbolt();
15004 				if ((cur_time -
15005 				    cportinfo->cport_link_lost_time) >=
15006 				    drv_usectohz(
15007 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
15008 					/* trigger device detach event */
15009 					cportinfo->cport_event_flags |=
15010 					    SATA_EVNT_DEVICE_DETACHED;
15011 					cportinfo->cport_link_lost_time = 0;
15012 					SATADBG1(SATA_DBG_EVENTS,
15013 					    sata_hba_inst,
15014 					    "Triggering port %d "
15015 					    "device detached event",
15016 					    saddr->cport);
15017 				} else {
15018 					/* keep link lost event */
15019 					cportinfo->cport_event_flags |=
15020 					    SATA_EVNT_LINK_LOST;
15021 				}
15022 			}
15023 		}
15024 		/*
15025 		 * We could change port state to disable/delay access to
15026 		 * the attached device until the link is recovered.
15027 		 */
15028 	}
15029 done:
15030 	event_flags = cportinfo->cport_event_flags;
15031 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15032 	if (event_flags != 0) {
15033 		mutex_enter(&sata_hba_inst->satahba_mutex);
15034 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
15035 		mutex_exit(&sata_hba_inst->satahba_mutex);
15036 		mutex_enter(&sata_mutex);
15037 		sata_event_pending |= SATA_EVNT_MAIN;
15038 		mutex_exit(&sata_mutex);
15039 	}
15040 }
15041 
15042 /*
15043  * Device Detached Event processing.
15044  * Port is probed to find if a device is really gone. If so,
15045  * the device info structure is detached from the SATA port info structure
15046  * and released.
15047  * Port status is updated.
15048  *
15049  * NOTE: Process cports event only, no port multiplier ports.
15050  */
15051 static void
15052 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
15053     sata_address_t *saddr)
15054 {
15055 	sata_cport_info_t *cportinfo;
15056 	sata_drive_info_t *sdevinfo;
15057 	sata_device_t sata_device;
15058 	dev_info_t *tdip;
15059 	int rval;
15060 
15061 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15062 	    "Processing port %d device detached", saddr->cport);
15063 
15064 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
15065 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15066 	/* Clear event flag */
15067 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
15068 
15069 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
15070 	if ((cportinfo->cport_state &
15071 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
15072 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15073 		    cport_mutex);
15074 		return;
15075 	}
15076 	/* For sanity, re-probe the port */
15077 	sata_device.satadev_rev = SATA_DEVICE_REV;
15078 	sata_device.satadev_addr = *saddr;
15079 
15080 	/*
15081 	 * We have to exit mutex, because the HBA probe port function may
15082 	 * block on its own mutex.
15083 	 */
15084 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15085 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
15086 	    (SATA_DIP(sata_hba_inst), &sata_device);
15087 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15088 	sata_update_port_info(sata_hba_inst, &sata_device);
15089 	if (rval != SATA_SUCCESS) {
15090 		/* Something went wrong? Fail the port */
15091 		cportinfo->cport_state = SATA_PSTATE_FAILED;
15092 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15093 		    cport_mutex);
15094 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15095 		    "SATA port %d probing failed",
15096 		    saddr->cport));
15097 		/*
15098 		 * We may want to release device info structure, but
15099 		 * it is not necessary.
15100 		 */
15101 		return;
15102 	} else {
15103 		/* port probed successfully */
15104 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
15105 	}
15106 	/*
15107 	 * Check if a device is still attached. For sanity, check also
15108 	 * link status - if no link, there is no device.
15109 	 */
15110 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
15111 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
15112 	    SATA_DTYPE_NONE) {
15113 		/*
15114 		 * Device is still attached - ignore detach event.
15115 		 */
15116 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15117 		    cport_mutex);
15118 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15119 		    "Ignoring detach - device still attached to port %d",
15120 		    sata_device.satadev_addr.cport);
15121 		return;
15122 	}
15123 	/*
15124 	 * We need to detach and release device info structure here
15125 	 */
15126 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
15127 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
15128 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
15129 		(void) kmem_free((void *)sdevinfo,
15130 		    sizeof (sata_drive_info_t));
15131 	}
15132 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
15133 	/*
15134 	 * Device cannot be reached anymore, even if the target node may be
15135 	 * still present.
15136 	 */
15137 
15138 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15139 	sata_log(sata_hba_inst, CE_WARN, "SATA device detached at port %d",
15140 	    sata_device.satadev_addr.cport);
15141 
15142 	/*
15143 	 * Try to offline a device and remove target node if it still exists
15144 	 */
15145 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport);
15146 	if (tdip != NULL) {
15147 		/*
15148 		 * Target node exists.  Unconfigure device then remove
15149 		 * the target node (one ndi operation).
15150 		 */
15151 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
15152 			/*
15153 			 * PROBLEM - no device, but target node remained
15154 			 * This happens when the file was open or node was
15155 			 * waiting for resources.
15156 			 */
15157 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15158 			    "sata_process_device_detached: "
15159 			    "Failed to remove target node for "
15160 			    "detached SATA device."));
15161 			/*
15162 			 * Set target node state to DEVI_DEVICE_REMOVED.
15163 			 * But re-check first that the node still exists.
15164 			 */
15165 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
15166 			    saddr->cport);
15167 			if (tdip != NULL) {
15168 				sata_set_device_removed(tdip);
15169 				/*
15170 				 * Instruct event daemon to retry the
15171 				 * cleanup later.
15172 				 */
15173 				sata_set_target_node_cleanup(sata_hba_inst,
15174 				    &sata_device.satadev_addr);
15175 			}
15176 		}
15177 	}
15178 	/*
15179 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
15180 	 * with the hint: SE_HINT_REMOVE
15181 	 */
15182 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
15183 }
15184 
15185 
15186 /*
15187  * Device Attached Event processing.
15188  * Port state is checked to verify that a device is really attached. If so,
15189  * the device info structure is created and attached to the SATA port info
15190  * structure.
15191  *
15192  * If attached device cannot be identified or set-up, the retry for the
15193  * attach processing is set-up. Subsequent daemon run would try again to
15194  * identify the device, until the time limit is reached
15195  * (SATA_DEV_IDENTIFY_TIMEOUT).
15196  *
15197  * This function cannot be called in interrupt context (it may sleep).
15198  *
15199  * NOTE: Process cports event only, no port multiplier ports.
15200  */
15201 static void
15202 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
15203     sata_address_t *saddr)
15204 {
15205 	sata_cport_info_t *cportinfo;
15206 	sata_drive_info_t *sdevinfo;
15207 	sata_device_t sata_device;
15208 	dev_info_t *tdip;
15209 	uint32_t event_flags;
15210 	int rval;
15211 
15212 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15213 	    "Processing port %d device attached", saddr->cport);
15214 
15215 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
15216 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15217 
15218 	/* Clear attach event flag first */
15219 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
15220 
15221 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
15222 	if ((cportinfo->cport_state &
15223 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
15224 		cportinfo->cport_dev_attach_time = 0;
15225 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15226 		    cport_mutex);
15227 		return;
15228 	}
15229 
15230 	/*
15231 	 * If the sata_drive_info structure is found attached to the port info,
15232 	 * despite the fact the device was removed and now it is re-attached,
15233 	 * the old drive info structure was not removed.
15234 	 * Arbitrarily release device info structure.
15235 	 */
15236 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
15237 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
15238 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
15239 		(void) kmem_free((void *)sdevinfo,
15240 		    sizeof (sata_drive_info_t));
15241 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15242 		    "Arbitrarily detaching old device info.", NULL);
15243 	}
15244 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
15245 
15246 	/* For sanity, re-probe the port */
15247 	sata_device.satadev_rev = SATA_DEVICE_REV;
15248 	sata_device.satadev_addr = *saddr;
15249 
15250 	/*
15251 	 * We have to exit mutex, because the HBA probe port function may
15252 	 * block on its own mutex.
15253 	 */
15254 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15255 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
15256 	    (SATA_DIP(sata_hba_inst), &sata_device);
15257 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15258 	sata_update_port_info(sata_hba_inst, &sata_device);
15259 	if (rval != SATA_SUCCESS) {
15260 		/* Something went wrong? Fail the port */
15261 		cportinfo->cport_state = SATA_PSTATE_FAILED;
15262 		cportinfo->cport_dev_attach_time = 0;
15263 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15264 		    cport_mutex);
15265 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15266 		    "SATA port %d probing failed",
15267 		    saddr->cport));
15268 		return;
15269 	} else {
15270 		/* port probed successfully */
15271 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
15272 	}
15273 	/*
15274 	 * Check if a device is still attached. For sanity, check also
15275 	 * link status - if no link, there is no device.
15276 	 */
15277 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
15278 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
15279 	    SATA_DTYPE_NONE) {
15280 		/*
15281 		 * No device - ignore attach event.
15282 		 */
15283 		cportinfo->cport_dev_attach_time = 0;
15284 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15285 		    cport_mutex);
15286 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15287 		    "Ignoring attach - no device connected to port %d",
15288 		    sata_device.satadev_addr.cport);
15289 		return;
15290 	}
15291 
15292 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15293 	/*
15294 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
15295 	 * with the hint: SE_HINT_INSERT
15296 	 */
15297 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
15298 
15299 	/*
15300 	 * Port reprobing will take care of the creation of the device
15301 	 * info structure and determination of the device type.
15302 	 */
15303 	sata_device.satadev_addr = *saddr;
15304 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
15305 	    SATA_DEV_IDENTIFY_NORETRY);
15306 
15307 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
15308 	    cport_mutex);
15309 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
15310 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
15311 		/* Some device is attached to the port */
15312 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
15313 			/*
15314 			 * A device was not successfully attached.
15315 			 * Track retry time for device identification.
15316 			 */
15317 			if (cportinfo->cport_dev_attach_time != 0) {
15318 				clock_t cur_time = ddi_get_lbolt();
15319 				/*
15320 				 * If the retry time limit was not exceeded,
15321 				 * reinstate attach event.
15322 				 */
15323 				if ((cur_time -
15324 				    cportinfo->cport_dev_attach_time) <
15325 				    drv_usectohz(
15326 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
15327 					/* OK, restore attach event */
15328 					cportinfo->cport_event_flags |=
15329 					    SATA_EVNT_DEVICE_ATTACHED;
15330 				} else {
15331 					/* Timeout - cannot identify device */
15332 					cportinfo->cport_dev_attach_time = 0;
15333 					sata_log(sata_hba_inst,
15334 					    CE_WARN,
15335 					    "Could not identify SATA device "
15336 					    "at port %d",
15337 					    saddr->cport);
15338 				}
15339 			} else {
15340 				/*
15341 				 * Start tracking time for device
15342 				 * identification.
15343 				 * Save current time (lbolt value).
15344 				 */
15345 				cportinfo->cport_dev_attach_time =
15346 				    ddi_get_lbolt();
15347 				/* Restore attach event */
15348 				cportinfo->cport_event_flags |=
15349 				    SATA_EVNT_DEVICE_ATTACHED;
15350 			}
15351 		} else {
15352 			/*
15353 			 * If device was successfully attached, the subsequent
15354 			 * action depends on a state of the
15355 			 * sata_auto_online variable. If it is set to zero.
15356 			 * an explicit 'configure' command will be needed to
15357 			 * configure it. If its value is non-zero, we will
15358 			 * attempt to online (configure) the device.
15359 			 * First, log the message indicating that a device
15360 			 * was attached.
15361 			 */
15362 			cportinfo->cport_dev_attach_time = 0;
15363 			sata_log(sata_hba_inst, CE_WARN,
15364 			    "SATA device detected at port %d", saddr->cport);
15365 
15366 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
15367 				sata_drive_info_t new_sdinfo;
15368 
15369 				/* Log device info data */
15370 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
15371 				    cportinfo));
15372 				sata_show_drive_info(sata_hba_inst,
15373 				    &new_sdinfo);
15374 			}
15375 
15376 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15377 			    saddr->cport)->cport_mutex);
15378 
15379 			/*
15380 			 * Make sure that there is no target node for that
15381 			 * device. If so, release it. It should not happen,
15382 			 * unless we had problem removing the node when
15383 			 * device was detached.
15384 			 */
15385 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
15386 			    saddr->cport);
15387 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15388 			    saddr->cport)->cport_mutex);
15389 			if (tdip != NULL) {
15390 
15391 #ifdef SATA_DEBUG
15392 				if ((cportinfo->cport_event_flags &
15393 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
15394 					sata_log(sata_hba_inst, CE_WARN,
15395 					    "sata_process_device_attached: "
15396 					    "old device target node exists!");
15397 #endif
15398 				/*
15399 				 * target node exists - try to unconfigure
15400 				 * device and remove the node.
15401 				 */
15402 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15403 				    saddr->cport)->cport_mutex);
15404 				rval = ndi_devi_offline(tdip,
15405 				    NDI_DEVI_REMOVE);
15406 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15407 				    saddr->cport)->cport_mutex);
15408 
15409 				if (rval == NDI_SUCCESS) {
15410 					cportinfo->cport_event_flags &=
15411 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
15412 					cportinfo->cport_tgtnode_clean = B_TRUE;
15413 				} else {
15414 					/*
15415 					 * PROBLEM - the target node remained
15416 					 * and it belongs to a previously
15417 					 * attached device.
15418 					 * This happens when the file was open
15419 					 * or the node was waiting for
15420 					 * resources at the time the
15421 					 * associated device was removed.
15422 					 * Instruct event daemon to retry the
15423 					 * cleanup later.
15424 					 */
15425 					sata_log(sata_hba_inst,
15426 					    CE_WARN,
15427 					    "Application(s) accessing "
15428 					    "previously attached SATA "
15429 					    "device have to release "
15430 					    "it before newly inserted "
15431 					    "device can be made accessible.",
15432 					    saddr->cport);
15433 					cportinfo->cport_event_flags |=
15434 					    SATA_EVNT_TARGET_NODE_CLEANUP;
15435 					cportinfo->cport_tgtnode_clean =
15436 					    B_FALSE;
15437 				}
15438 			}
15439 			if (sata_auto_online != 0) {
15440 				cportinfo->cport_event_flags |=
15441 				    SATA_EVNT_AUTOONLINE_DEVICE;
15442 			}
15443 
15444 		}
15445 	} else {
15446 		cportinfo->cport_dev_attach_time = 0;
15447 	}
15448 
15449 	event_flags = cportinfo->cport_event_flags;
15450 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15451 	if (event_flags != 0) {
15452 		mutex_enter(&sata_hba_inst->satahba_mutex);
15453 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
15454 		mutex_exit(&sata_hba_inst->satahba_mutex);
15455 		mutex_enter(&sata_mutex);
15456 		sata_event_pending |= SATA_EVNT_MAIN;
15457 		mutex_exit(&sata_mutex);
15458 	}
15459 }
15460 
15461 
15462 /*
15463  * Device Target Node Cleanup Event processing.
15464  * If the target node associated with a sata port device is in
15465  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
15466  * If the target node cannot be removed, the event flag is left intact,
15467  * so that event daemon may re-run this function later.
15468  *
15469  * This function cannot be called in interrupt context (it may sleep).
15470  *
15471  * NOTE: Processes cport events only, not port multiplier ports.
15472  */
15473 static void
15474 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
15475     sata_address_t *saddr)
15476 {
15477 	sata_cport_info_t *cportinfo;
15478 	dev_info_t *tdip;
15479 
15480 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15481 	    "Processing port %d device target node cleanup", saddr->cport);
15482 
15483 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
15484 
15485 	/*
15486 	 * Check if there is target node for that device and it is in the
15487 	 * DEVI_DEVICE_REMOVED state. If so, release it.
15488 	 */
15489 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport);
15490 	if (tdip != NULL) {
15491 		/*
15492 		 * target node exists - check if it is target node of
15493 		 * a removed device.
15494 		 */
15495 		if (sata_check_device_removed(tdip) == B_TRUE) {
15496 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15497 			    "sata_process_target_node_cleanup: "
15498 			    "old device target node exists!", NULL);
15499 			/*
15500 			 * Unconfigure and remove the target node
15501 			 */
15502 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
15503 			    NDI_SUCCESS) {
15504 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15505 				    saddr->cport)->cport_mutex);
15506 				cportinfo->cport_event_flags &=
15507 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
15508 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15509 				    saddr->cport)->cport_mutex);
15510 				return;
15511 			}
15512 			/*
15513 			 * Event daemon will retry the cleanup later.
15514 			 */
15515 			mutex_enter(&sata_hba_inst->satahba_mutex);
15516 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
15517 			mutex_exit(&sata_hba_inst->satahba_mutex);
15518 			mutex_enter(&sata_mutex);
15519 			sata_event_pending |= SATA_EVNT_MAIN;
15520 			mutex_exit(&sata_mutex);
15521 		}
15522 	} else {
15523 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15524 		    saddr->cport)->cport_mutex);
15525 		cportinfo->cport_event_flags &=
15526 		    ~SATA_EVNT_TARGET_NODE_CLEANUP;
15527 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15528 		    saddr->cport)->cport_mutex);
15529 	}
15530 }
15531 
15532 /*
15533  * Device AutoOnline Event processing.
15534  * If attached device is to be onlined, an attempt is made to online this
15535  * device, but only if there is no lingering (old) target node present.
15536  * If the device cannot be onlined, the event flag is left intact,
15537  * so that event daemon may re-run this function later.
15538  *
15539  * This function cannot be called in interrupt context (it may sleep).
15540  *
15541  * NOTE: Processes cport events only, not port multiplier ports.
15542  */
15543 static void
15544 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
15545     sata_address_t *saddr)
15546 {
15547 	sata_cport_info_t *cportinfo;
15548 	sata_drive_info_t *sdinfo;
15549 	sata_device_t sata_device;
15550 	dev_info_t *tdip;
15551 
15552 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15553 	    "Processing port %d attached device auto-onlining", saddr->cport);
15554 
15555 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
15556 
15557 	/*
15558 	 * Check if device is present and recognized. If not, reset event.
15559 	 */
15560 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15561 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
15562 		/* Nothing to online */
15563 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
15564 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15565 		    saddr->cport)->cport_mutex);
15566 		return;
15567 	}
15568 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15569 
15570 	/*
15571 	 * Check if there is target node for this device and if it is in the
15572 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
15573 	 * the event for later processing.
15574 	 */
15575 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport);
15576 	if (tdip != NULL) {
15577 		/*
15578 		 * target node exists - check if it is target node of
15579 		 * a removed device.
15580 		 */
15581 		if (sata_check_device_removed(tdip) == B_TRUE) {
15582 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
15583 			    "sata_process_device_autoonline: "
15584 			    "old device target node exists!", NULL);
15585 			/*
15586 			 * Event daemon will retry device onlining later.
15587 			 */
15588 			mutex_enter(&sata_hba_inst->satahba_mutex);
15589 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
15590 			mutex_exit(&sata_hba_inst->satahba_mutex);
15591 			mutex_enter(&sata_mutex);
15592 			sata_event_pending |= SATA_EVNT_MAIN;
15593 			mutex_exit(&sata_mutex);
15594 			return;
15595 		}
15596 		/*
15597 		 * If the target node is not in the 'removed" state, assume
15598 		 * that it belongs to this device. There is nothing more to do,
15599 		 * but reset the event.
15600 		 */
15601 	} else {
15602 
15603 		/*
15604 		 * Try to online the device
15605 		 * If there is any reset-related event, remove it. We are
15606 		 * configuring the device and no state restoring is needed.
15607 		 */
15608 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15609 		    saddr->cport)->cport_mutex);
15610 		sata_device.satadev_addr = *saddr;
15611 		if (saddr->qual == SATA_ADDR_CPORT)
15612 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
15613 		else
15614 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
15615 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
15616 		if (sdinfo != NULL) {
15617 			if (sdinfo->satadrv_event_flags &
15618 			    (SATA_EVNT_DEVICE_RESET |
15619 			    SATA_EVNT_INPROC_DEVICE_RESET))
15620 				sdinfo->satadrv_event_flags = 0;
15621 			sdinfo->satadrv_event_flags |=
15622 			    SATA_EVNT_CLEAR_DEVICE_RESET;
15623 
15624 			/* Need to create a new target node. */
15625 			cportinfo->cport_tgtnode_clean = B_TRUE;
15626 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15627 			    saddr->cport)->cport_mutex);
15628 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
15629 			    sata_hba_inst, &sata_device.satadev_addr);
15630 			if (tdip == NULL) {
15631 				/*
15632 				 * Configure (onlining) failed.
15633 				 * We will NOT retry
15634 				 */
15635 				SATA_LOG_D((sata_hba_inst, CE_WARN,
15636 				    "sata_process_device_autoonline: "
15637 				    "configuring SATA device at port %d failed",
15638 				    saddr->cport));
15639 			}
15640 		} else {
15641 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15642 			    saddr->cport)->cport_mutex);
15643 		}
15644 
15645 	}
15646 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15647 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
15648 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15649 	    saddr->cport)->cport_mutex);
15650 }
15651 
15652 
15653 static void
15654 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
15655     int hint)
15656 {
15657 	char ap[MAXPATHLEN];
15658 	nvlist_t *ev_attr_list = NULL;
15659 	int err;
15660 
15661 	/* Allocate and build sysevent attribute list */
15662 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
15663 	if (err != 0) {
15664 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15665 		    "sata_gen_sysevent: "
15666 		    "cannot allocate memory for sysevent attributes\n"));
15667 		return;
15668 	}
15669 	/* Add hint attribute */
15670 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
15671 	if (err != 0) {
15672 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15673 		    "sata_gen_sysevent: "
15674 		    "failed to add DR_HINT attr for sysevent"));
15675 		nvlist_free(ev_attr_list);
15676 		return;
15677 	}
15678 	/*
15679 	 * Add AP attribute.
15680 	 * Get controller pathname and convert it into AP pathname by adding
15681 	 * a target number.
15682 	 */
15683 	(void) snprintf(ap, MAXPATHLEN, "/devices");
15684 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
15685 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
15686 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
15687 
15688 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
15689 	if (err != 0) {
15690 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15691 		    "sata_gen_sysevent: "
15692 		    "failed to add DR_AP_ID attr for sysevent"));
15693 		nvlist_free(ev_attr_list);
15694 		return;
15695 	}
15696 
15697 	/* Generate/log sysevent */
15698 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
15699 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
15700 	if (err != DDI_SUCCESS) {
15701 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15702 		    "sata_gen_sysevent: "
15703 		    "cannot log sysevent, err code %x\n", err));
15704 	}
15705 
15706 	nvlist_free(ev_attr_list);
15707 }
15708 
15709 
15710 
15711 
15712 /*
15713  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
15714  */
15715 static void
15716 sata_set_device_removed(dev_info_t *tdip)
15717 {
15718 	int circ;
15719 
15720 	ASSERT(tdip != NULL);
15721 
15722 	ndi_devi_enter(tdip, &circ);
15723 	mutex_enter(&DEVI(tdip)->devi_lock);
15724 	DEVI_SET_DEVICE_REMOVED(tdip);
15725 	mutex_exit(&DEVI(tdip)->devi_lock);
15726 	ndi_devi_exit(tdip, circ);
15727 }
15728 
15729 
15730 /*
15731  * Set internal event instructing event daemon to try
15732  * to perform the target node cleanup.
15733  */
15734 static void
15735 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
15736     sata_address_t *saddr)
15737 {
15738 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15739 	SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
15740 	    SATA_EVNT_TARGET_NODE_CLEANUP;
15741 	SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_tgtnode_clean =
15742 	    B_FALSE;
15743 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
15744 	mutex_enter(&sata_hba_inst->satahba_mutex);
15745 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
15746 	mutex_exit(&sata_hba_inst->satahba_mutex);
15747 	mutex_enter(&sata_mutex);
15748 	sata_event_pending |= SATA_EVNT_MAIN;
15749 	mutex_exit(&sata_mutex);
15750 }
15751 
15752 
15753 /*
15754  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
15755  * i.e. check if the target node state indicates that it belongs to a removed
15756  * device.
15757  *
15758  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
15759  * B_FALSE otherwise.
15760  *
15761  * NOTE: No port multiplier support.
15762  */
15763 static boolean_t
15764 sata_check_device_removed(dev_info_t *tdip)
15765 {
15766 	ASSERT(tdip != NULL);
15767 
15768 	if (DEVI_IS_DEVICE_REMOVED(tdip))
15769 		return (B_TRUE);
15770 	else
15771 		return (B_FALSE);
15772 }
15773 
15774 /* ************************ FAULT INJECTTION **************************** */
15775 
15776 #ifdef SATA_INJECT_FAULTS
15777 
15778 static	uint32_t sata_fault_count = 0;
15779 static	uint32_t sata_fault_suspend_count = 0;
15780 
15781 /*
15782  * Inject sata pkt fault
15783  * It modifies returned values of the sata packet.
15784  * It returns immediately if:
15785  * pkt fault injection is not enabled (via sata_inject_fault,
15786  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
15787  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
15788  * pkt is not directed to specified fault controller/device
15789  * (sata_fault_ctrl_dev and sata_fault_device).
15790  * If fault controller is not specified, fault injection applies to all
15791  * controllers and devices.
15792  *
15793  * First argument is the pointer to the executed sata packet.
15794  * Second argument is a pointer to a value returned by the HBA tran_start
15795  * function.
15796  * Third argument specifies injected error. Injected sata packet faults
15797  * are the satapkt_reason values.
15798  * SATA_PKT_BUSY		-1	Not completed, busy
15799  * SATA_PKT_DEV_ERROR		1	Device reported error
15800  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
15801  * SATA_PKT_PORT_ERROR		3	Not completed, port error
15802  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
15803  * SATA_PKT_ABORTED		5	Aborted by request
15804  * SATA_PKT_TIMEOUT		6	Operation timeut
15805  * SATA_PKT_RESET		7	Aborted by reset request
15806  *
15807  * Additional global variables affecting the execution:
15808  *
15809  * sata_inject_fault_count variable specifies number of times in row the
15810  * error is injected. Value of -1 specifies permanent fault, ie. every time
15811  * the fault injection point is reached, the fault is injected and a pause
15812  * between fault injection specified by sata_inject_fault_pause_count is
15813  * ignored). Fault injection routine decrements sata_inject_fault_count
15814  * (if greater than zero) until it reaches 0. No fault is injected when
15815  * sata_inject_fault_count is 0 (zero).
15816  *
15817  * sata_inject_fault_pause_count variable specifies number of times a fault
15818  * injection is bypassed (pause between fault injections).
15819  * If set to 0, a fault is injected only a number of times specified by
15820  * sata_inject_fault_count.
15821  *
15822  * The fault counts are static, so for periodic errors they have to be manually
15823  * reset to start repetition sequence from scratch.
15824  * If the original value returned by the HBA tran_start function is not
15825  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
15826  * is injected (to avoid masking real problems);
15827  *
15828  * NOTE: In its current incarnation, this function should be invoked only for
15829  * commands executed in SYNCHRONOUS mode.
15830  */
15831 
15832 
15833 static	void
15834 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
15835 {
15836 
15837 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
15838 		return;
15839 
15840 	if (sata_inject_fault_count == 0)
15841 		return;
15842 
15843 	if (fault == 0)
15844 		return;
15845 
15846 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
15847 		return;
15848 
15849 	if (sata_fault_ctrl != NULL) {
15850 		sata_pkt_txlate_t *spx =
15851 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
15852 
15853 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
15854 		    spx->txlt_sata_hba_inst->satahba_dip)
15855 			return;
15856 
15857 		if (sata_fault_device.satadev_addr.cport !=
15858 		    spkt->satapkt_device.satadev_addr.cport ||
15859 		    sata_fault_device.satadev_addr.pmport !=
15860 		    spkt->satapkt_device.satadev_addr.pmport ||
15861 		    sata_fault_device.satadev_addr.qual !=
15862 		    spkt->satapkt_device.satadev_addr.qual)
15863 			return;
15864 	}
15865 
15866 	/* Modify pkt return parameters */
15867 	if (*rval != SATA_TRAN_ACCEPTED ||
15868 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
15869 		sata_fault_count = 0;
15870 		sata_fault_suspend_count = 0;
15871 		return;
15872 	}
15873 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
15874 		/* Pause in the injection */
15875 		sata_fault_suspend_count -= 1;
15876 		return;
15877 	}
15878 
15879 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
15880 		/*
15881 		 * Init inject fault cycle. If fault count is set to -1,
15882 		 * it is a permanent fault.
15883 		 */
15884 		if (sata_inject_fault_count != -1) {
15885 			sata_fault_count = sata_inject_fault_count;
15886 			sata_fault_suspend_count =
15887 			    sata_inject_fault_pause_count;
15888 			if (sata_fault_suspend_count == 0)
15889 				sata_inject_fault_count = 0;
15890 		}
15891 	}
15892 
15893 	if (sata_fault_count != 0)
15894 		sata_fault_count -= 1;
15895 
15896 	switch (fault) {
15897 	case SATA_PKT_BUSY:
15898 		*rval = SATA_TRAN_BUSY;
15899 		spkt->satapkt_reason = SATA_PKT_BUSY;
15900 		break;
15901 
15902 	case SATA_PKT_QUEUE_FULL:
15903 		*rval = SATA_TRAN_QUEUE_FULL;
15904 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
15905 		break;
15906 
15907 	case SATA_PKT_CMD_UNSUPPORTED:
15908 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
15909 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
15910 		break;
15911 
15912 	case SATA_PKT_PORT_ERROR:
15913 		/* This is "rejected" command */
15914 		*rval = SATA_TRAN_PORT_ERROR;
15915 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
15916 		/* Additional error setup could be done here - port state */
15917 		break;
15918 
15919 	case SATA_PKT_DEV_ERROR:
15920 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
15921 		/*
15922 		 * Additional error setup could be done here
15923 		 */
15924 		break;
15925 
15926 	case SATA_PKT_ABORTED:
15927 		spkt->satapkt_reason = SATA_PKT_ABORTED;
15928 		break;
15929 
15930 	case SATA_PKT_TIMEOUT:
15931 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
15932 		/* Additional error setup could be done here */
15933 		break;
15934 
15935 	case SATA_PKT_RESET:
15936 		spkt->satapkt_reason = SATA_PKT_RESET;
15937 		/*
15938 		 * Additional error setup could be done here - device reset
15939 		 */
15940 		break;
15941 
15942 	default:
15943 		break;
15944 	}
15945 }
15946 
15947 #endif
15948