xref: /titanic_44/usr/src/uts/common/io/sata/impl/sata.c (revision 3c112a2b34403220c06c3e2fcac403358cfba168)
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 (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
24  */
25 
26 
27 /*
28  * SATA Framework
29  * Generic SATA Host Adapter Implementation
30  */
31 
32 #include <sys/conf.h>
33 #include <sys/file.h>
34 #include <sys/ddi.h>
35 #include <sys/sunddi.h>
36 #include <sys/modctl.h>
37 #include <sys/cmn_err.h>
38 #include <sys/errno.h>
39 #include <sys/thread.h>
40 #include <sys/kstat.h>
41 #include <sys/note.h>
42 #include <sys/sysevent.h>
43 #include <sys/sysevent/eventdefs.h>
44 #include <sys/sysevent/dr.h>
45 #include <sys/taskq.h>
46 #include <sys/disp.h>
47 
48 #include <sys/sata/impl/sata.h>
49 #include <sys/sata/sata_hba.h>
50 #include <sys/sata/sata_defs.h>
51 #include <sys/sata/sata_cfgadm.h>
52 #include <sys/sata/sata_blacklist.h>
53 #include <sys/sata/sata_satl.h>
54 
55 #include <sys/scsi/impl/spc3_types.h>
56 
57 /*
58  * FMA header files
59  */
60 #include <sys/ddifm.h>
61 #include <sys/fm/protocol.h>
62 #include <sys/fm/util.h>
63 #include <sys/fm/io/ddi.h>
64 
65 /* Debug flags - defined in sata.h */
66 int	sata_debug_flags = 0;
67 int	sata_msg = 0;
68 
69 /*
70  * Flags enabling selected SATA HBA framework functionality
71  */
72 #define	SATA_ENABLE_QUEUING		1
73 #define	SATA_ENABLE_NCQ			2
74 #define	SATA_ENABLE_PROCESS_EVENTS	4
75 #define	SATA_ENABLE_PMULT_FBS		8 /* FIS-Based Switching */
76 int sata_func_enable =
77 	SATA_ENABLE_PROCESS_EVENTS | SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ;
78 
79 /*
80  * Global variable setting default maximum queue depth (NCQ or TCQ)
81  * Note:minimum queue depth is 1
82  */
83 int sata_max_queue_depth = SATA_MAX_QUEUE_DEPTH; /* max NCQ/TCQ queue depth */
84 
85 /*
86  * Currently used default NCQ/TCQ queue depth. It is set-up during the driver
87  * initialization, using value from sata_max_queue_depth
88  * It is adjusted to minimum supported by the controller and by the device,
89  * if queueing is enabled.
90  */
91 static	int sata_current_max_qdepth;
92 
93 /*
94  * Global variable determining the default behavior after device hotpluggin.
95  * If non-zero, the hotplugged device is onlined (if possible) without explicit
96  * IOCTL request (AP_CONFIGURE).
97  * If zero, hotplugged device is identified, but not onlined.
98  * Enabling (AP_CONNECT) device port with an attached device does not result
99  * in device onlining regardless of the flag setting
100  */
101 int sata_auto_online = 0;
102 
103 #ifdef SATA_DEBUG
104 
105 #define	SATA_LOG_D(args)	sata_log args
106 uint64_t mbuf_count = 0;
107 uint64_t mbuffail_count = 0;
108 
109 sata_atapi_cmd_t sata_atapi_trace[64];
110 uint32_t sata_atapi_trace_index = 0;
111 int sata_atapi_trace_save = 1;
112 static	void sata_save_atapi_trace(sata_pkt_txlate_t *, int);
113 #define	SATAATAPITRACE(spx, count)	if (sata_atapi_trace_save) \
114     sata_save_atapi_trace(spx, count);
115 
116 #else
117 #define	SATA_LOG_D(args)	sata_trace_log args
118 #define	SATAATAPITRACE(spx, count)
119 #endif
120 
121 #if 0
122 static void
123 sata_test_atapi_packet_command(sata_hba_inst_t *, int);
124 #endif
125 
126 #ifdef SATA_INJECT_FAULTS
127 
128 #define		SATA_INJECT_PKT_FAULT	1
129 uint32_t	sata_inject_fault = 0;
130 
131 uint32_t	sata_inject_fault_count = 0;
132 uint32_t	sata_inject_fault_pause_count = 0;
133 uint32_t	sata_fault_type = 0;
134 uint32_t	sata_fault_cmd = 0;
135 dev_info_t	*sata_fault_ctrl = NULL;
136 sata_device_t	sata_fault_device;
137 
138 static	void sata_inject_pkt_fault(sata_pkt_t *, int *, int);
139 
140 #endif
141 
142 #define	LEGACY_HWID_LEN	64	/* Model (40) + Serial (20) + pad */
143 
144 static char sata_rev_tag[] = {"1.46"};
145 
146 /*
147  * SATA cb_ops functions
148  */
149 static 	int sata_hba_open(dev_t *, int, int, cred_t *);
150 static 	int sata_hba_close(dev_t, int, int, cred_t *);
151 static 	int sata_hba_ioctl(dev_t, int, intptr_t, int, cred_t *,	int *);
152 
153 /*
154  * SCSA required entry points
155  */
156 static	int sata_scsi_tgt_init(dev_info_t *, dev_info_t *,
157     scsi_hba_tran_t *, struct scsi_device *);
158 static	int sata_scsi_tgt_probe(struct scsi_device *,
159     int (*callback)(void));
160 static void sata_scsi_tgt_free(dev_info_t *, dev_info_t *,
161     scsi_hba_tran_t *, struct scsi_device *);
162 static 	int sata_scsi_start(struct scsi_address *, struct scsi_pkt *);
163 static 	int sata_scsi_abort(struct scsi_address *, struct scsi_pkt *);
164 static 	int sata_scsi_reset(struct scsi_address *, int);
165 static 	int sata_scsi_getcap(struct scsi_address *, char *, int);
166 static 	int sata_scsi_setcap(struct scsi_address *, char *, int, int);
167 static 	struct scsi_pkt *sata_scsi_init_pkt(struct scsi_address *,
168     struct scsi_pkt *, struct buf *, int, int, int, int, int (*)(caddr_t),
169     caddr_t);
170 static 	void sata_scsi_destroy_pkt(struct scsi_address *, struct scsi_pkt *);
171 static 	void sata_scsi_dmafree(struct scsi_address *, struct scsi_pkt *);
172 static 	void sata_scsi_sync_pkt(struct scsi_address *, struct scsi_pkt *);
173 
174 /*
175  * SATA HBA interface functions are defined in sata_hba.h header file
176  */
177 
178 /* Event processing functions */
179 static	void sata_event_daemon(void *);
180 static	void sata_event_thread_control(int);
181 static	void sata_process_controller_events(sata_hba_inst_t *sata_hba_inst);
182 static	void sata_process_pmult_events(sata_hba_inst_t *, uint8_t);
183 static	void sata_process_device_reset(sata_hba_inst_t *, sata_address_t *);
184 static	void sata_process_pmdevice_reset(sata_hba_inst_t *, sata_address_t *);
185 static	void sata_process_port_failed_event(sata_hba_inst_t *,
186     sata_address_t *);
187 static	void sata_process_port_link_events(sata_hba_inst_t *,
188     sata_address_t *);
189 static	void sata_process_pmport_link_events(sata_hba_inst_t *,
190     sata_address_t *);
191 static	void sata_process_device_detached(sata_hba_inst_t *, sata_address_t *);
192 static	void sata_process_pmdevice_detached(sata_hba_inst_t *,
193     sata_address_t *);
194 static	void sata_process_device_attached(sata_hba_inst_t *, sata_address_t *);
195 static	void sata_process_pmdevice_attached(sata_hba_inst_t *,
196     sata_address_t *);
197 static	void sata_process_port_pwr_change(sata_hba_inst_t *, sata_address_t *);
198 static	void sata_process_cntrl_pwr_level_change(sata_hba_inst_t *);
199 static	void sata_process_target_node_cleanup(sata_hba_inst_t *,
200     sata_address_t *);
201 static	void sata_process_device_autoonline(sata_hba_inst_t *,
202     sata_address_t *saddr);
203 
204 /*
205  * Local translation functions
206  */
207 static	int sata_txlt_inquiry(sata_pkt_txlate_t *);
208 static	int sata_txlt_test_unit_ready(sata_pkt_txlate_t *);
209 static	int sata_txlt_start_stop_unit(sata_pkt_txlate_t *);
210 static	int sata_txlt_read_capacity(sata_pkt_txlate_t *);
211 static	int sata_txlt_read_capacity16(sata_pkt_txlate_t *);
212 static	int sata_txlt_request_sense(sata_pkt_txlate_t *);
213 static	int sata_txlt_read(sata_pkt_txlate_t *);
214 static	int sata_txlt_write(sata_pkt_txlate_t *);
215 static	int sata_txlt_log_sense(sata_pkt_txlate_t *);
216 static	int sata_txlt_log_select(sata_pkt_txlate_t *);
217 static	int sata_txlt_mode_sense(sata_pkt_txlate_t *);
218 static	int sata_txlt_mode_select(sata_pkt_txlate_t *);
219 static	int sata_txlt_ata_pass_thru(sata_pkt_txlate_t *);
220 static	int sata_txlt_synchronize_cache(sata_pkt_txlate_t *);
221 static	int sata_txlt_write_buffer(sata_pkt_txlate_t *);
222 static	int sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *);
223 
224 static	int sata_hba_start(sata_pkt_txlate_t *, int *);
225 static	int sata_txlt_invalid_command(sata_pkt_txlate_t *);
226 static	int sata_txlt_check_condition(sata_pkt_txlate_t *, uchar_t, uchar_t);
227 static	int sata_txlt_lba_out_of_range(sata_pkt_txlate_t *);
228 static	int sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *);
229 static	void sata_txlt_rw_completion(sata_pkt_t *);
230 static	void sata_txlt_nodata_cmd_completion(sata_pkt_t *);
231 static	void sata_txlt_apt_completion(sata_pkt_t *sata_pkt);
232 static	void sata_txlt_download_mcode_cmd_completion(sata_pkt_t *);
233 static	int sata_emul_rw_completion(sata_pkt_txlate_t *);
234 static	void sata_fill_ata_return_desc(sata_pkt_t *, uint8_t, uint8_t,
235     uint8_t);
236 static	struct scsi_extended_sense *sata_immediate_error_response(
237     sata_pkt_txlate_t *, int);
238 static	struct scsi_extended_sense *sata_arq_sense(sata_pkt_txlate_t *);
239 
240 static	int sata_txlt_atapi(sata_pkt_txlate_t *);
241 static	void sata_txlt_atapi_completion(sata_pkt_t *);
242 
243 /*
244  * Local functions for ioctl
245  */
246 static	int32_t sata_get_port_num(sata_hba_inst_t *,  struct devctl_iocdata *);
247 static	void sata_cfgadm_state(sata_hba_inst_t *, int32_t,
248     devctl_ap_state_t *);
249 static	dev_info_t *sata_get_target_dip(dev_info_t *, uint8_t, uint8_t);
250 static	dev_info_t *sata_get_scsi_target_dip(dev_info_t *, sata_address_t *);
251 static	dev_info_t *sata_devt_to_devinfo(dev_t);
252 static	int sata_ioctl_connect(sata_hba_inst_t *, sata_device_t *);
253 static	int sata_ioctl_disconnect(sata_hba_inst_t *, sata_device_t *);
254 static	int sata_ioctl_configure(sata_hba_inst_t *, sata_device_t *);
255 static	int sata_ioctl_unconfigure(sata_hba_inst_t *, sata_device_t *);
256 static	int sata_ioctl_activate(sata_hba_inst_t *, sata_device_t *);
257 static	int sata_ioctl_deactivate(sata_hba_inst_t *, sata_device_t *);
258 static	int sata_ioctl_reset_port(sata_hba_inst_t *, sata_device_t *);
259 static	int sata_ioctl_reset_device(sata_hba_inst_t *, sata_device_t *);
260 static	int sata_ioctl_reset_all(sata_hba_inst_t *);
261 static	int sata_ioctl_port_self_test(sata_hba_inst_t *, sata_device_t *);
262 static	int sata_ioctl_get_device_path(sata_hba_inst_t *, sata_device_t *,
263     sata_ioctl_data_t *, int mode);
264 static	int sata_ioctl_get_ap_type(sata_hba_inst_t *, sata_device_t *,
265     sata_ioctl_data_t *, int mode);
266 static	int sata_ioctl_get_model_info(sata_hba_inst_t *, sata_device_t *,
267     sata_ioctl_data_t *, int mode);
268 static	int sata_ioctl_get_revfirmware_info(sata_hba_inst_t *, sata_device_t *,
269     sata_ioctl_data_t *, int mode);
270 static	int sata_ioctl_get_serialnumber_info(sata_hba_inst_t *,
271     sata_device_t *, sata_ioctl_data_t *, int mode);
272 
273 /*
274  * Local functions
275  */
276 static 	void sata_remove_hba_instance(dev_info_t *);
277 static 	int sata_validate_sata_hba_tran(dev_info_t *, sata_hba_tran_t *);
278 static 	void sata_probe_ports(sata_hba_inst_t *);
279 static	void sata_probe_pmports(sata_hba_inst_t *, uint8_t);
280 static 	int sata_reprobe_port(sata_hba_inst_t *, sata_device_t *, int);
281 static 	int sata_reprobe_pmult(sata_hba_inst_t *, sata_device_t *, int);
282 static 	int sata_reprobe_pmport(sata_hba_inst_t *, sata_device_t *, int);
283 static	int sata_alloc_pmult(sata_hba_inst_t *, sata_device_t *);
284 static	void sata_free_pmult(sata_hba_inst_t *, sata_device_t *);
285 static 	int sata_add_device(dev_info_t *, sata_hba_inst_t *, sata_device_t *);
286 static	int sata_offline_device(sata_hba_inst_t *, sata_device_t *,
287     sata_drive_info_t *);
288 static 	dev_info_t *sata_create_target_node(dev_info_t *, sata_hba_inst_t *,
289     sata_address_t *);
290 static 	void sata_remove_target_node(sata_hba_inst_t *,
291     sata_address_t *);
292 static 	int sata_validate_scsi_address(sata_hba_inst_t *,
293     struct scsi_address *, sata_device_t *);
294 static 	int sata_validate_sata_address(sata_hba_inst_t *, int, int, int);
295 static	sata_pkt_t *sata_pkt_alloc(sata_pkt_txlate_t *, int (*)(caddr_t));
296 static	void sata_pkt_free(sata_pkt_txlate_t *);
297 static	int sata_dma_buf_setup(sata_pkt_txlate_t *, int, int (*)(caddr_t),
298     caddr_t, ddi_dma_attr_t *);
299 static	void sata_common_free_dma_rsrcs(sata_pkt_txlate_t *);
300 static	int sata_probe_device(sata_hba_inst_t *, sata_device_t *);
301 static	sata_drive_info_t *sata_get_device_info(sata_hba_inst_t *,
302     sata_device_t *);
303 static 	int sata_identify_device(sata_hba_inst_t *, sata_drive_info_t *);
304 static	void sata_reidentify_device(sata_pkt_txlate_t *);
305 static	struct buf *sata_alloc_local_buffer(sata_pkt_txlate_t *, int);
306 static 	void sata_free_local_buffer(sata_pkt_txlate_t *);
307 static 	uint64_t sata_check_capacity(sata_drive_info_t *);
308 void 	sata_adjust_dma_attr(sata_drive_info_t *, ddi_dma_attr_t *,
309     ddi_dma_attr_t *);
310 static 	int sata_fetch_device_identify_data(sata_hba_inst_t *,
311     sata_drive_info_t *);
312 static	void sata_update_port_info(sata_hba_inst_t *, sata_device_t *);
313 static	void sata_update_pmport_info(sata_hba_inst_t *, sata_device_t *);
314 static	void sata_update_port_scr(sata_port_scr_t *, sata_device_t *);
315 static	int sata_set_dma_mode(sata_hba_inst_t *, sata_drive_info_t *);
316 static	int sata_set_cache_mode(sata_hba_inst_t *, sata_drive_info_t *, int);
317 static	int sata_set_rmsn(sata_hba_inst_t *, sata_drive_info_t *, int);
318 static	int sata_set_drive_features(sata_hba_inst_t *,
319     sata_drive_info_t *, int flag);
320 static	void sata_init_write_cache_mode(sata_drive_info_t *sdinfo);
321 static	int sata_initialize_device(sata_hba_inst_t *, sata_drive_info_t *);
322 static	void sata_identdev_to_inquiry(sata_hba_inst_t *, sata_drive_info_t *,
323     uint8_t *);
324 static	int sata_get_atapi_inquiry_data(sata_hba_inst_t *, sata_address_t *,
325     struct scsi_inquiry *);
326 static	int sata_build_msense_page_1(sata_drive_info_t *, int, uint8_t *);
327 static	int sata_build_msense_page_8(sata_drive_info_t *, int, uint8_t *);
328 static	int sata_build_msense_page_1a(sata_drive_info_t *, int, uint8_t *);
329 static	int sata_build_msense_page_1c(sata_drive_info_t *, int, uint8_t *);
330 static	int sata_build_msense_page_30(sata_drive_info_t *, int, uint8_t *);
331 static	int sata_mode_select_page_8(sata_pkt_txlate_t *,
332     struct mode_cache_scsi3 *, int, int *, int *, int *);
333 static	int sata_mode_select_page_1a(sata_pkt_txlate_t *,
334     struct mode_info_power_cond *, int, int *, int *, int *);
335 static	int sata_mode_select_page_1c(sata_pkt_txlate_t *,
336     struct mode_info_excpt_page *, int, int *, int *, int *);
337 static	int sata_mode_select_page_30(sata_pkt_txlate_t *,
338     struct mode_acoustic_management *, int, int *, int *, int *);
339 
340 static	int sata_build_lsense_page_0(sata_drive_info_t *, uint8_t *);
341 static	int sata_build_lsense_page_10(sata_drive_info_t *, uint8_t *,
342     sata_hba_inst_t *);
343 static	int sata_build_lsense_page_2f(sata_drive_info_t *, uint8_t *,
344     sata_hba_inst_t *);
345 static	int sata_build_lsense_page_30(sata_drive_info_t *, uint8_t *,
346     sata_hba_inst_t *);
347 static	int sata_build_lsense_page_0e(sata_drive_info_t *, uint8_t *,
348     sata_pkt_txlate_t *);
349 
350 static	void sata_set_arq_data(sata_pkt_t *);
351 static	void sata_build_read_verify_cmd(sata_cmd_t *, uint16_t, uint64_t);
352 static	void sata_build_generic_cmd(sata_cmd_t *, uint8_t);
353 static	uint8_t sata_get_standby_timer(uint8_t *timer);
354 
355 static	void sata_save_drive_settings(sata_drive_info_t *);
356 static	void sata_show_drive_info(sata_hba_inst_t *, sata_drive_info_t *);
357 static	void sata_show_pmult_info(sata_hba_inst_t *, sata_device_t *);
358 static	void sata_log(sata_hba_inst_t *, uint_t, char *fmt, ...);
359 static	void sata_trace_log(sata_hba_inst_t *, uint_t, const char *fmt, ...);
360 static	int sata_fetch_smart_return_status(sata_hba_inst_t *,
361     sata_drive_info_t *);
362 static	int sata_fetch_smart_data(sata_hba_inst_t *, sata_drive_info_t *,
363     struct smart_data *);
364 static	int sata_smart_selftest_log(sata_hba_inst_t *,
365     sata_drive_info_t *,
366     struct smart_selftest_log *);
367 static	int sata_ext_smart_selftest_read_log(sata_hba_inst_t *,
368     sata_drive_info_t *, struct smart_ext_selftest_log *, uint16_t);
369 static	int sata_smart_read_log(sata_hba_inst_t *, sata_drive_info_t *,
370     uint8_t *, uint8_t, uint8_t);
371 static	int sata_read_log_ext_directory(sata_hba_inst_t *, sata_drive_info_t *,
372     struct read_log_ext_directory *);
373 static	void sata_gen_sysevent(sata_hba_inst_t *, sata_address_t *, int);
374 static	void sata_xlate_errors(sata_pkt_txlate_t *);
375 static	void sata_decode_device_error(sata_pkt_txlate_t *,
376     struct scsi_extended_sense *);
377 static	void sata_set_device_removed(dev_info_t *);
378 static	boolean_t sata_check_device_removed(dev_info_t *);
379 static	void sata_set_target_node_cleanup(sata_hba_inst_t *, sata_address_t *);
380 static	int sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *,
381     sata_drive_info_t *);
382 static	int sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *,
383     sata_drive_info_t *);
384 static	void sata_atapi_packet_cmd_setup(sata_cmd_t *, sata_drive_info_t *);
385 static	void sata_fixed_sense_data_preset(struct scsi_extended_sense *);
386 static  void sata_target_devid_register(dev_info_t *, sata_drive_info_t *);
387 static  int sata_check_modser(char *, int);
388 
389 /*
390  * FMA
391  */
392 static boolean_t sata_check_for_dma_error(dev_info_t *, sata_pkt_txlate_t *);
393 
394 
395 /*
396  * SATA Framework will ignore SATA HBA driver cb_ops structure and
397  * register following one with SCSA framework.
398  * Open & close are provided, so scsi framework will not use its own
399  */
400 static struct cb_ops sata_cb_ops = {
401 	sata_hba_open,			/* open */
402 	sata_hba_close,			/* close */
403 	nodev,				/* strategy */
404 	nodev,				/* print */
405 	nodev,				/* dump */
406 	nodev,				/* read */
407 	nodev,				/* write */
408 	sata_hba_ioctl,			/* ioctl */
409 	nodev,				/* devmap */
410 	nodev,				/* mmap */
411 	nodev,				/* segmap */
412 	nochpoll,			/* chpoll */
413 	ddi_prop_op,			/* cb_prop_op */
414 	0,				/* streamtab */
415 	D_NEW | D_MP,			/* cb_flag */
416 	CB_REV,				/* rev */
417 	nodev,				/* aread */
418 	nodev				/* awrite */
419 };
420 
421 
422 extern struct mod_ops mod_miscops;
423 extern uchar_t	scsi_cdb_size[];
424 
425 static struct modlmisc modlmisc = {
426 	&mod_miscops,			/* Type of module */
427 	"SATA Module"			/* module name */
428 };
429 
430 
431 static struct modlinkage modlinkage = {
432 	MODREV_1,
433 	(void *)&modlmisc,
434 	NULL
435 };
436 
437 /*
438  * Default sata pkt timeout. Used when a target driver scsi_pkt time is zero,
439  * i.e. when scsi_pkt has not timeout specified.
440  */
441 static int sata_default_pkt_time = 60;	/* 60 seconds */
442 
443 /*
444  * Intermediate buffer device access attributes - they are required,
445  * but not necessarily used.
446  */
447 static ddi_device_acc_attr_t sata_acc_attr = {
448 	DDI_DEVICE_ATTR_V0,
449 	DDI_STRUCTURE_LE_ACC,
450 	DDI_STRICTORDER_ACC
451 };
452 
453 
454 /*
455  * Mutexes protecting structures in multithreaded operations.
456  * Because events are relatively rare, a single global mutex protecting
457  * data structures should be sufficient. To increase performance, add
458  * separate mutex per each sata port and use global mutex only to protect
459  * common data structures.
460  */
461 static	kmutex_t sata_mutex;		/* protects sata_hba_list */
462 static	kmutex_t sata_log_mutex;	/* protects log */
463 
464 static 	char sata_log_buf[256];
465 
466 /*
467  * sata trace debug
468  */
469 static	sata_trace_rbuf_t *sata_debug_rbuf;
470 static	sata_trace_dmsg_t *sata_trace_dmsg_alloc(void);
471 static	void sata_trace_dmsg_free(void);
472 static	void sata_trace_rbuf_alloc(void);
473 static	void sata_trace_rbuf_free(void);
474 
475 int	dmsg_ring_size = DMSG_RING_SIZE;
476 
477 /* Default write cache setting for SATA hard disks */
478 int	sata_write_cache = 1;		/* enabled */
479 
480 /* Default write cache setting for SATA ATAPI CD/DVD */
481 int	sata_atapicdvd_write_cache = 1; /* enabled */
482 
483 /* Default write cache setting for SATA ATAPI tape */
484 int	sata_atapitape_write_cache = 1; /* enabled */
485 
486 /* Default write cache setting for SATA ATAPI disk */
487 int	sata_atapidisk_write_cache = 1;	/* enabled */
488 
489 /*
490  * Linked list of HBA instances
491  */
492 static 	sata_hba_inst_t *sata_hba_list = NULL;
493 static 	sata_hba_inst_t *sata_hba_list_tail = NULL;
494 /*
495  * Pointer to per-instance SATA HBA soft structure is stored in sata_hba_tran
496  * structure and in sata soft state.
497  */
498 
499 /*
500  * Event daemon related variables
501  */
502 static 	kmutex_t sata_event_mutex;
503 static 	kcondvar_t sata_event_cv;
504 static 	kthread_t *sata_event_thread = NULL;
505 static 	int sata_event_thread_terminate = 0;
506 static 	int sata_event_pending = 0;
507 static 	int sata_event_thread_active = 0;
508 extern 	pri_t minclsyspri;
509 
510 /*
511  * NCQ error recovery command
512  */
513 static const sata_cmd_t sata_rle_cmd = {
514 	SATA_CMD_REV,
515 	NULL,
516 	{
517 		SATA_DIR_READ
518 	},
519 	ATA_ADDR_LBA48,
520 	0,
521 	0,
522 	0,
523 	0,
524 	0,
525 	1,
526 	READ_LOG_EXT_NCQ_ERROR_RECOVERY,
527 	0,
528 	0,
529 	0,
530 	SATAC_READ_LOG_EXT,
531 	0,
532 	0,
533 	0,
534 };
535 
536 /*
537  * ATAPI error recovery CDB
538  */
539 static const uint8_t sata_rqsense_cdb[SATA_ATAPI_RQSENSE_CDB_LEN] = {
540 	SCMD_REQUEST_SENSE,
541 	0,			/* Only fixed RQ format is supported */
542 	0,
543 	0,
544 	SATA_ATAPI_MIN_RQSENSE_LEN, /* Less data may be returned */
545 	0
546 };
547 
548 
549 /* Warlock directives */
550 
551 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran))
552 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_device))
553 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_ops))
554 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_extended_sense))
555 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_arq_status))
556 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_attr))
557 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_cookie_t))
558 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", devctl_ap_state))
559 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_info::devi_state))
560 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_list))
561 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_list))
562 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_next))
563 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_prev))
564 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", \
565     sata_hba_inst::satahba_scsi_tran))
566 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_tran))
567 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_dip))
568 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_hba_inst::satahba_attached))
569 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_inst::satahba_dev_port))
570 _NOTE(MUTEX_PROTECTS_DATA(sata_hba_inst::satahba_mutex,
571     sata_hba_inst::satahba_event_flags))
572 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
573     sata_cport_info::cport_devp))
574 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_devp))
575 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_cport_info::cport_addr))
576 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
577     sata_cport_info::cport_dev_type))
578 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_dev_type))
579 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
580     sata_cport_info::cport_state))
581 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_state))
582 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
583     sata_pmport_info::pmport_state))
584 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_state))
585 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
586     sata_pmport_info::pmport_dev_type))
587 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_dev_type))
588 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
589     sata_pmport_info::pmport_sata_drive))
590 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
591     sata_pmport_info::pmport_tgtnode_clean))
592 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
593     sata_pmport_info::pmport_event_flags))
594 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_sata_drive))
595 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_dev_port))
596 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_num_dev_ports))
597 #ifdef SATA_DEBUG
598 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuf_count))
599 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuffail_count))
600 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace))
601 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace_index))
602 #endif
603 
604 /* End of warlock directives */
605 
606 /* ************** loadable module configuration functions ************** */
607 
608 int
609 _init()
610 {
611 	int rval;
612 
613 	mutex_init(&sata_mutex, NULL, MUTEX_DRIVER, NULL);
614 	mutex_init(&sata_event_mutex, NULL, MUTEX_DRIVER, NULL);
615 	mutex_init(&sata_log_mutex, NULL, MUTEX_DRIVER, NULL);
616 	cv_init(&sata_event_cv, NULL, CV_DRIVER, NULL);
617 	sata_trace_rbuf_alloc();
618 	if ((rval = mod_install(&modlinkage)) != 0) {
619 #ifdef SATA_DEBUG
620 		cmn_err(CE_WARN, "sata: _init: mod_install failed\n");
621 #endif
622 		sata_trace_rbuf_free();
623 		mutex_destroy(&sata_log_mutex);
624 		cv_destroy(&sata_event_cv);
625 		mutex_destroy(&sata_event_mutex);
626 		mutex_destroy(&sata_mutex);
627 	}
628 	return (rval);
629 }
630 
631 int
632 _fini()
633 {
634 	int rval;
635 
636 	if ((rval = mod_remove(&modlinkage)) != 0)
637 		return (rval);
638 
639 	sata_trace_rbuf_free();
640 	mutex_destroy(&sata_log_mutex);
641 	cv_destroy(&sata_event_cv);
642 	mutex_destroy(&sata_event_mutex);
643 	mutex_destroy(&sata_mutex);
644 	return (rval);
645 }
646 
647 int
648 _info(struct modinfo *modinfop)
649 {
650 	return (mod_info(&modlinkage, modinfop));
651 }
652 
653 
654 
655 /* ********************* SATA HBA entry points ********************* */
656 
657 
658 /*
659  * Called by SATA HBA from _init().
660  * Registers HBA driver instance/sata framework pair with scsi framework, by
661  * calling scsi_hba_init().
662  *
663  * SATA HBA driver cb_ops are ignored - SATA HBA framework cb_ops are used
664  * instead. SATA HBA framework cb_ops pointer overwrites SATA HBA driver
665  * cb_ops pointer in SATA HBA driver dev_ops structure.
666  * SATA HBA framework cb_ops supplies cb_open cb_close and cb_ioctl vectors.
667  *
668  * Return status of the scsi_hba_init() is returned to a calling SATA HBA
669  * driver.
670  */
671 int
672 sata_hba_init(struct modlinkage *modlp)
673 {
674 	int rval;
675 	struct dev_ops *hba_ops;
676 
677 	SATADBG1(SATA_DBG_HBA_IF, NULL,
678 	    "sata_hba_init: name %s \n",
679 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
680 	/*
681 	 * Fill-up cb_ops and dev_ops when necessary
682 	 */
683 	hba_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
684 	/*
685 	 * Provide pointer to SATA dev_ops
686 	 */
687 	hba_ops->devo_cb_ops = &sata_cb_ops;
688 
689 	/*
690 	 * Register SATA HBA with SCSI framework
691 	 */
692 	if ((rval = scsi_hba_init(modlp)) != 0) {
693 		SATADBG1(SATA_DBG_HBA_IF, NULL,
694 		    "sata_hba_init: scsi hba init failed\n", NULL);
695 		return (rval);
696 	}
697 
698 	return (0);
699 }
700 
701 
702 /* HBA attach stages */
703 #define	HBA_ATTACH_STAGE_SATA_HBA_INST	1
704 #define	HBA_ATTACH_STAGE_SCSI_ATTACHED	2
705 #define	HBA_ATTACH_STAGE_SETUP		4
706 #define	HBA_ATTACH_STAGE_LINKED		8
707 
708 
709 /*
710  *
711  * Called from SATA HBA driver's attach routine to attach an instance of
712  * the HBA.
713  *
714  * For DDI_ATTACH command:
715  * sata_hba_inst structure is allocated here and initialized with pointers to
716  * SATA framework implementation of required scsi tran functions.
717  * The scsi_tran's tran_hba_private field is used by SATA Framework to point
718  * to the soft structure (sata_hba_inst) allocated by SATA framework for
719  * SATA HBA instance related data.
720  * The scsi_tran's tran_hba_private field is used by SATA framework to
721  * store a pointer to per-HBA-instance of sata_hba_inst structure.
722  * The sata_hba_inst structure is cross-linked to scsi tran structure.
723  * Among other info, a pointer to sata_hba_tran structure is stored in
724  * sata_hba_inst. The sata_hba_inst structures for different HBA instances are
725  * linked together into the list, pointed to by sata_hba_list.
726  * On the first HBA instance attach the sata event thread is initialized.
727  * Attachment points are created for all SATA ports of the HBA being attached.
728  * All HBA instance's SATA ports are probed and type of plugged devices is
729  * determined. For each device of a supported type, a target node is created.
730  *
731  * DDI_SUCCESS is returned when attachment process is successful,
732  * DDI_FAILURE is returned otherwise.
733  *
734  * For DDI_RESUME command:
735  * Not implemented at this time (postponed until phase 2 of the development).
736  */
737 int
738 sata_hba_attach(dev_info_t *dip, sata_hba_tran_t *sata_tran,
739     ddi_attach_cmd_t cmd)
740 {
741 	sata_hba_inst_t	*sata_hba_inst;
742 	scsi_hba_tran_t *scsi_tran = NULL;
743 	int hba_attach_state = 0;
744 	char taskq_name[MAXPATHLEN];
745 
746 	SATADBG3(SATA_DBG_HBA_IF, NULL,
747 	    "sata_hba_attach: node %s (%s%d)\n",
748 	    ddi_node_name(dip), ddi_driver_name(dip),
749 	    ddi_get_instance(dip));
750 
751 	if (cmd == DDI_RESUME) {
752 		/*
753 		 * Postponed until phase 2 of the development
754 		 */
755 		return (DDI_FAILURE);
756 	}
757 
758 	if (cmd != DDI_ATTACH) {
759 		return (DDI_FAILURE);
760 	}
761 
762 	/* cmd == DDI_ATTACH */
763 
764 	if (sata_validate_sata_hba_tran(dip, sata_tran) != SATA_SUCCESS) {
765 		SATA_LOG_D((NULL, CE_WARN,
766 		    "sata_hba_attach: invalid sata_hba_tran"));
767 		return (DDI_FAILURE);
768 	}
769 	/*
770 	 * Allocate and initialize SCSI tran structure.
771 	 * SATA copy of tran_bus_config is provided to create port nodes.
772 	 */
773 	scsi_tran = scsi_hba_tran_alloc(dip, SCSI_HBA_CANSLEEP);
774 	if (scsi_tran == NULL)
775 		return (DDI_FAILURE);
776 	/*
777 	 * Allocate soft structure for SATA HBA instance.
778 	 * There is a separate softstate for each HBA instance.
779 	 */
780 	sata_hba_inst = kmem_zalloc(sizeof (struct sata_hba_inst), KM_SLEEP);
781 	ASSERT(sata_hba_inst != NULL); /* this should not fail */
782 	mutex_init(&sata_hba_inst->satahba_mutex, NULL, MUTEX_DRIVER, NULL);
783 	hba_attach_state |= HBA_ATTACH_STAGE_SATA_HBA_INST;
784 
785 	/*
786 	 * scsi_trans's tran_hba_private is used by SATA Framework to point to
787 	 * soft structure allocated by SATA framework for
788 	 * SATA HBA instance related data.
789 	 */
790 	scsi_tran->tran_hba_private	= sata_hba_inst;
791 	scsi_tran->tran_tgt_private	= NULL;
792 
793 	scsi_tran->tran_tgt_init	= sata_scsi_tgt_init;
794 	scsi_tran->tran_tgt_probe	= sata_scsi_tgt_probe;
795 	scsi_tran->tran_tgt_free	= sata_scsi_tgt_free;
796 
797 	scsi_tran->tran_start		= sata_scsi_start;
798 	scsi_tran->tran_reset		= sata_scsi_reset;
799 	scsi_tran->tran_abort		= sata_scsi_abort;
800 	scsi_tran->tran_getcap		= sata_scsi_getcap;
801 	scsi_tran->tran_setcap		= sata_scsi_setcap;
802 	scsi_tran->tran_init_pkt	= sata_scsi_init_pkt;
803 	scsi_tran->tran_destroy_pkt	= sata_scsi_destroy_pkt;
804 
805 	scsi_tran->tran_dmafree		= sata_scsi_dmafree;
806 	scsi_tran->tran_sync_pkt	= sata_scsi_sync_pkt;
807 
808 	scsi_tran->tran_reset_notify	= NULL;
809 	scsi_tran->tran_get_bus_addr	= NULL;
810 	scsi_tran->tran_quiesce		= NULL;
811 	scsi_tran->tran_unquiesce	= NULL;
812 	scsi_tran->tran_bus_reset	= NULL;
813 
814 	if (scsi_hba_attach_setup(dip, sata_tran->sata_tran_hba_dma_attr,
815 	    scsi_tran, 0) != DDI_SUCCESS) {
816 #ifdef SATA_DEBUG
817 		cmn_err(CE_WARN, "?SATA: %s%d hba scsi attach failed",
818 		    ddi_driver_name(dip), ddi_get_instance(dip));
819 #endif
820 		goto fail;
821 	}
822 	hba_attach_state |= HBA_ATTACH_STAGE_SCSI_ATTACHED;
823 
824 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "sata")) {
825 		if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
826 		    "sata", 1) != DDI_PROP_SUCCESS) {
827 			SATA_LOG_D((NULL, CE_WARN, "sata_hba_attach: "
828 			    "failed to create hba sata prop"));
829 			goto fail;
830 		}
831 	}
832 
833 	/*
834 	 * Save pointers in hba instance soft state.
835 	 */
836 	sata_hba_inst->satahba_scsi_tran = scsi_tran;
837 	sata_hba_inst->satahba_tran = sata_tran;
838 	sata_hba_inst->satahba_dip = dip;
839 
840 	/*
841 	 * Create a task queue to handle emulated commands completion
842 	 * Use node name, dash, instance number as the queue name.
843 	 */
844 	taskq_name[0] = '\0';
845 	(void) strlcat(taskq_name, DEVI(dip)->devi_node_name,
846 	    sizeof (taskq_name));
847 	(void) snprintf(taskq_name + strlen(taskq_name),
848 	    sizeof (taskq_name) - strlen(taskq_name),
849 	    "-%d", DEVI(dip)->devi_instance);
850 	sata_hba_inst->satahba_taskq = taskq_create(taskq_name, 1,
851 	    minclsyspri, 1, sata_tran->sata_tran_hba_num_cports * 4,
852 	    TASKQ_DYNAMIC);
853 
854 	hba_attach_state |= HBA_ATTACH_STAGE_SETUP;
855 
856 	/*
857 	 * Create events thread if not created yet.
858 	 */
859 	sata_event_thread_control(1);
860 
861 	/*
862 	 * Link this hba instance into the list.
863 	 */
864 	mutex_enter(&sata_mutex);
865 
866 	if (sata_hba_list == NULL) {
867 		/*
868 		 * The first instance of HBA is attached.
869 		 * Set current/active default maximum NCQ/TCQ queue depth for
870 		 * all SATA devices. It is done here and now, to eliminate the
871 		 * possibility of the dynamic, programatic modification of the
872 		 * queue depth via global (and public) sata_max_queue_depth
873 		 * variable (this would require special handling in HBA drivers)
874 		 */
875 		sata_current_max_qdepth = sata_max_queue_depth;
876 		if (sata_current_max_qdepth > 32)
877 			sata_current_max_qdepth = 32;
878 		else if (sata_current_max_qdepth < 1)
879 			sata_current_max_qdepth = 1;
880 	}
881 
882 	sata_hba_inst->satahba_next = NULL;
883 	sata_hba_inst->satahba_prev = sata_hba_list_tail;
884 	if (sata_hba_list == NULL) {
885 		sata_hba_list = sata_hba_inst;
886 	}
887 	if (sata_hba_list_tail != NULL) {
888 		sata_hba_list_tail->satahba_next = sata_hba_inst;
889 	}
890 	sata_hba_list_tail = sata_hba_inst;
891 	mutex_exit(&sata_mutex);
892 	hba_attach_state |= HBA_ATTACH_STAGE_LINKED;
893 
894 	/*
895 	 * Create SATA HBA devctl minor node for sata_hba_open, close, ioctl
896 	 * SATA HBA driver should not use its own open/close entry points.
897 	 *
898 	 * Make sure that instance number doesn't overflow
899 	 * when forming minor numbers.
900 	 */
901 	ASSERT(ddi_get_instance(dip) <= (L_MAXMIN >> INST_MINOR_SHIFT));
902 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
903 	    INST2DEVCTL(ddi_get_instance(dip)),
904 	    DDI_NT_SATA_NEXUS, 0) != DDI_SUCCESS) {
905 #ifdef SATA_DEBUG
906 		cmn_err(CE_WARN, "sata_hba_attach: "
907 		    "cannot create devctl minor node");
908 #endif
909 		goto fail;
910 	}
911 
912 
913 	/*
914 	 * Set-up kstats here, if necessary.
915 	 * (postponed until future phase of the development).
916 	 */
917 
918 	/*
919 	 * Indicate that HBA is attached. This will enable events processing
920 	 * for this HBA.
921 	 */
922 	sata_hba_inst->satahba_attached = 1;
923 	/*
924 	 * Probe controller ports. This operation will describe a current
925 	 * controller/port/multipliers/device configuration and will create
926 	 * attachment points.
927 	 * We may end-up with just a controller with no devices attached.
928 	 * For the ports with a supported device attached, device target nodes
929 	 * are created and devices are initialized.
930 	 */
931 	sata_probe_ports(sata_hba_inst);
932 
933 	return (DDI_SUCCESS);
934 
935 fail:
936 	if (hba_attach_state & HBA_ATTACH_STAGE_LINKED) {
937 		(void) sata_remove_hba_instance(dip);
938 		if (sata_hba_list == NULL)
939 			sata_event_thread_control(0);
940 	}
941 
942 	if (hba_attach_state & HBA_ATTACH_STAGE_SETUP) {
943 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
944 		taskq_destroy(sata_hba_inst->satahba_taskq);
945 	}
946 
947 	if (hba_attach_state & HBA_ATTACH_STAGE_SCSI_ATTACHED)
948 		(void) scsi_hba_detach(dip);
949 
950 	if (hba_attach_state & HBA_ATTACH_STAGE_SATA_HBA_INST) {
951 		mutex_destroy(&sata_hba_inst->satahba_mutex);
952 		kmem_free((void *)sata_hba_inst,
953 		    sizeof (struct sata_hba_inst));
954 		scsi_hba_tran_free(scsi_tran);
955 	}
956 
957 	sata_log(NULL, CE_WARN, "?SATA: %s%d hba attach failed",
958 	    ddi_driver_name(dip), ddi_get_instance(dip));
959 
960 	return (DDI_FAILURE);
961 }
962 
963 
964 /*
965  * Called by SATA HBA from to detach an instance of the driver.
966  *
967  * For DDI_DETACH command:
968  * Free local structures allocated for SATA HBA instance during
969  * sata_hba_attach processing.
970  *
971  * Returns DDI_SUCCESS when HBA was detached, DDI_FAILURE otherwise.
972  *
973  * For DDI_SUSPEND command:
974  * Not implemented at this time (postponed until phase 2 of the development)
975  * Returnd DDI_SUCCESS.
976  *
977  * When the last HBA instance is detached, the event daemon is terminated.
978  *
979  * NOTE: Port multiplier is supported.
980  */
981 int
982 sata_hba_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
983 {
984 	dev_info_t	*tdip;
985 	sata_hba_inst_t	*sata_hba_inst;
986 	scsi_hba_tran_t *scsi_hba_tran;
987 	sata_cport_info_t *cportinfo;
988 	sata_pmult_info_t *pminfo;
989 	sata_drive_info_t *sdinfo;
990 	sata_device_t	sdevice;
991 	int ncport, npmport;
992 
993 	SATADBG3(SATA_DBG_HBA_IF, NULL, "sata_hba_detach: node %s (%s%d)\n",
994 	    ddi_node_name(dip), ddi_driver_name(dip), ddi_get_instance(dip));
995 
996 	switch (cmd) {
997 	case DDI_DETACH:
998 
999 		if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1000 			return (DDI_FAILURE);
1001 
1002 		sata_hba_inst = scsi_hba_tran->tran_hba_private;
1003 		if (sata_hba_inst == NULL)
1004 			return (DDI_FAILURE);
1005 
1006 		if (scsi_hba_detach(dip) == DDI_FAILURE) {
1007 			sata_hba_inst->satahba_attached = 1;
1008 			return (DDI_FAILURE);
1009 		}
1010 
1011 		/*
1012 		 * Free all target nodes - at this point
1013 		 * devices should be at least offlined
1014 		 * otherwise scsi_hba_detach() should not be called.
1015 		 */
1016 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
1017 		    ncport++) {
1018 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
1019 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1020 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
1021 				if (sdinfo != NULL) {
1022 					tdip = sata_get_target_dip(dip,
1023 					    ncport, 0);
1024 					if (tdip != NULL) {
1025 						if (ndi_devi_offline(tdip,
1026 						    NDI_DEVI_REMOVE) !=
1027 						    NDI_SUCCESS) {
1028 							SATA_LOG_D((
1029 							    sata_hba_inst,
1030 							    CE_WARN,
1031 							    "sata_hba_detach: "
1032 							    "Target node not "
1033 							    "removed !"));
1034 							return (DDI_FAILURE);
1035 						}
1036 					}
1037 				}
1038 			} else { /* SATA_DTYPE_PMULT */
1039 				mutex_enter(&cportinfo->cport_mutex);
1040 				pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
1041 
1042 				if (pminfo == NULL) {
1043 					SATA_LOG_D((sata_hba_inst, CE_WARN,
1044 					    "sata_hba_detach: Port multiplier "
1045 					    "not ready yet!"));
1046 					mutex_exit(&cportinfo->cport_mutex);
1047 					return (DDI_FAILURE);
1048 				}
1049 
1050 				/*
1051 				 * Detach would fail if removal of any of the
1052 				 * target nodes is failed - albeit in that
1053 				 * case some of them may have been removed.
1054 				 */
1055 				for (npmport = 0; npmport < SATA_NUM_PMPORTS(
1056 				    sata_hba_inst, ncport); npmport++) {
1057 					tdip = sata_get_target_dip(dip, ncport,
1058 					    npmport);
1059 					if (tdip != NULL) {
1060 						if (ndi_devi_offline(tdip,
1061 						    NDI_DEVI_REMOVE) !=
1062 						    NDI_SUCCESS) {
1063 							SATA_LOG_D((
1064 							    sata_hba_inst,
1065 							    CE_WARN,
1066 							    "sata_hba_detach: "
1067 							    "Target node not "
1068 							    "removed !"));
1069 							mutex_exit(&cportinfo->
1070 							    cport_mutex);
1071 							return (DDI_FAILURE);
1072 						}
1073 					}
1074 				}
1075 				mutex_exit(&cportinfo->cport_mutex);
1076 			}
1077 		}
1078 		/*
1079 		 * Disable sata event daemon processing for this HBA
1080 		 */
1081 		sata_hba_inst->satahba_attached = 0;
1082 
1083 		/*
1084 		 * Remove event daemon thread, if it is last HBA instance.
1085 		 */
1086 
1087 		mutex_enter(&sata_mutex);
1088 		if (sata_hba_list->satahba_next == NULL) {
1089 			mutex_exit(&sata_mutex);
1090 			sata_event_thread_control(0);
1091 			mutex_enter(&sata_mutex);
1092 		}
1093 		mutex_exit(&sata_mutex);
1094 
1095 		/* Remove this HBA instance from the HBA list */
1096 		sata_remove_hba_instance(dip);
1097 
1098 		/*
1099 		 * At this point there should be no target nodes attached.
1100 		 * Detach and destroy device and port info structures.
1101 		 */
1102 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
1103 		    ncport++) {
1104 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
1105 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1106 				sdinfo =
1107 				    cportinfo->cport_devp.cport_sata_drive;
1108 				if (sdinfo != NULL) {
1109 					/* Release device structure */
1110 					kmem_free(sdinfo,
1111 					    sizeof (sata_drive_info_t));
1112 				}
1113 				/* Release cport info */
1114 				mutex_destroy(&cportinfo->cport_mutex);
1115 				kmem_free(cportinfo,
1116 				    sizeof (sata_cport_info_t));
1117 			} else { /* SATA_DTYPE_PMULT */
1118 				sdevice.satadev_addr.cport = (uint8_t)ncport;
1119 				sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
1120 				sata_free_pmult(sata_hba_inst, &sdevice);
1121 			}
1122 		}
1123 
1124 		scsi_hba_tran_free(sata_hba_inst->satahba_scsi_tran);
1125 
1126 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
1127 
1128 		taskq_destroy(sata_hba_inst->satahba_taskq);
1129 
1130 		mutex_destroy(&sata_hba_inst->satahba_mutex);
1131 		kmem_free((void *)sata_hba_inst,
1132 		    sizeof (struct sata_hba_inst));
1133 
1134 		return (DDI_SUCCESS);
1135 
1136 	case DDI_SUSPEND:
1137 		/*
1138 		 * Postponed until phase 2
1139 		 */
1140 		return (DDI_FAILURE);
1141 
1142 	default:
1143 		return (DDI_FAILURE);
1144 	}
1145 }
1146 
1147 
1148 /*
1149  * Called by an HBA drive from _fini() routine.
1150  * Unregisters SATA HBA instance/SATA framework pair from the scsi framework.
1151  */
1152 void
1153 sata_hba_fini(struct modlinkage *modlp)
1154 {
1155 	SATADBG1(SATA_DBG_HBA_IF, NULL,
1156 	    "sata_hba_fini: name %s\n",
1157 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
1158 
1159 	scsi_hba_fini(modlp);
1160 }
1161 
1162 
1163 /*
1164  * Default open and close routine for sata_hba framework.
1165  *
1166  */
1167 /*
1168  * Open devctl node.
1169  *
1170  * Returns:
1171  * 0 if node was open successfully, error code otherwise.
1172  *
1173  *
1174  */
1175 
1176 static int
1177 sata_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
1178 {
1179 #ifndef __lock_lint
1180 	_NOTE(ARGUNUSED(credp))
1181 #endif
1182 	int rv = 0;
1183 	dev_info_t *dip;
1184 	scsi_hba_tran_t *scsi_hba_tran;
1185 	sata_hba_inst_t	*sata_hba_inst;
1186 
1187 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_open: entered", NULL);
1188 
1189 	if (otyp != OTYP_CHR)
1190 		return (EINVAL);
1191 
1192 	dip = sata_devt_to_devinfo(*devp);
1193 	if (dip == NULL)
1194 		return (ENXIO);
1195 
1196 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1197 		return (ENXIO);
1198 
1199 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1200 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1201 		return (ENXIO);
1202 
1203 	mutex_enter(&sata_mutex);
1204 	if (flags & FEXCL) {
1205 		if (sata_hba_inst->satahba_open_flag != 0) {
1206 			rv = EBUSY;
1207 		} else {
1208 			sata_hba_inst->satahba_open_flag =
1209 			    SATA_DEVCTL_EXOPENED;
1210 		}
1211 	} else {
1212 		if (sata_hba_inst->satahba_open_flag == SATA_DEVCTL_EXOPENED) {
1213 			rv = EBUSY;
1214 		} else {
1215 			sata_hba_inst->satahba_open_flag =
1216 			    SATA_DEVCTL_SOPENED;
1217 		}
1218 	}
1219 	mutex_exit(&sata_mutex);
1220 
1221 	return (rv);
1222 }
1223 
1224 
1225 /*
1226  * Close devctl node.
1227  * Returns:
1228  * 0 if node was closed successfully, error code otherwise.
1229  *
1230  */
1231 
1232 static int
1233 sata_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
1234 {
1235 #ifndef __lock_lint
1236 	_NOTE(ARGUNUSED(credp))
1237 	_NOTE(ARGUNUSED(flag))
1238 #endif
1239 	dev_info_t *dip;
1240 	scsi_hba_tran_t *scsi_hba_tran;
1241 	sata_hba_inst_t	*sata_hba_inst;
1242 
1243 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_close: entered", NULL);
1244 
1245 	if (otyp != OTYP_CHR)
1246 		return (EINVAL);
1247 
1248 	dip = sata_devt_to_devinfo(dev);
1249 	if (dip == NULL)
1250 		return (ENXIO);
1251 
1252 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1253 		return (ENXIO);
1254 
1255 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1256 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1257 		return (ENXIO);
1258 
1259 	mutex_enter(&sata_mutex);
1260 	sata_hba_inst->satahba_open_flag = 0;
1261 	mutex_exit(&sata_mutex);
1262 	return (0);
1263 }
1264 
1265 
1266 
1267 /*
1268  * Standard IOCTL commands for SATA hotplugging.
1269  * Implemented DEVCTL_AP commands:
1270  * DEVCTL_AP_CONNECT
1271  * DEVCTL_AP_DISCONNECT
1272  * DEVCTL_AP_CONFIGURE
1273  * DEVCTL_UNCONFIGURE
1274  * DEVCTL_AP_CONTROL
1275  *
1276  * Commands passed to default ndi ioctl handler:
1277  * DEVCTL_DEVICE_GETSTATE
1278  * DEVCTL_DEVICE_ONLINE
1279  * DEVCTL_DEVICE_OFFLINE
1280  * DEVCTL_DEVICE_REMOVE
1281  * DEVCTL_DEVICE_INSERT
1282  * DEVCTL_BUS_GETSTATE
1283  *
1284  * All other cmds are passed to HBA if it provide ioctl handler, or failed
1285  * if not.
1286  *
1287  * Returns:
1288  * 0 if successful,
1289  * error code if operation failed.
1290  *
1291  * Port Multiplier support is supported now.
1292  *
1293  * NOTE: qual should be SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT
1294  */
1295 
1296 static int
1297 sata_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
1298     int *rvalp)
1299 {
1300 #ifndef __lock_lint
1301 	_NOTE(ARGUNUSED(credp))
1302 	_NOTE(ARGUNUSED(rvalp))
1303 #endif
1304 	int rv = 0;
1305 	int32_t	comp_port = -1;
1306 	dev_info_t *dip;
1307 	devctl_ap_state_t ap_state;
1308 	struct devctl_iocdata *dcp = NULL;
1309 	scsi_hba_tran_t *scsi_hba_tran;
1310 	sata_hba_inst_t *sata_hba_inst;
1311 	sata_device_t sata_device;
1312 	sata_cport_info_t *cportinfo;
1313 	int cport, pmport, qual;
1314 	int rval = SATA_SUCCESS;
1315 
1316 	dip = sata_devt_to_devinfo(dev);
1317 	if (dip == NULL)
1318 		return (ENXIO);
1319 
1320 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1321 		return (ENXIO);
1322 
1323 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1324 	if (sata_hba_inst == NULL)
1325 		return (ENXIO);
1326 
1327 	if (sata_hba_inst->satahba_tran == NULL)
1328 		return (ENXIO);
1329 
1330 	switch (cmd) {
1331 
1332 	case DEVCTL_DEVICE_GETSTATE:
1333 	case DEVCTL_DEVICE_ONLINE:
1334 	case DEVCTL_DEVICE_OFFLINE:
1335 	case DEVCTL_DEVICE_REMOVE:
1336 	case DEVCTL_BUS_GETSTATE:
1337 		/*
1338 		 * There may be more cases that we want to pass to default
1339 		 * handler rather than fail them.
1340 		 */
1341 		return (ndi_devctl_ioctl(dip, cmd, arg, mode, 0));
1342 	}
1343 
1344 	/* read devctl ioctl data */
1345 	if (cmd != DEVCTL_AP_CONTROL) {
1346 		if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS)
1347 			return (EFAULT);
1348 
1349 		if ((comp_port = sata_get_port_num(sata_hba_inst, dcp)) ==
1350 		    -1) {
1351 			if (dcp)
1352 				ndi_dc_freehdl(dcp);
1353 			return (EINVAL);
1354 		}
1355 
1356 		/*
1357 		 * According to SCSI_TO_SATA_ADDR_QUAL, qual should be either
1358 		 * SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT.
1359 		 */
1360 		cport = SCSI_TO_SATA_CPORT(comp_port);
1361 		pmport = SCSI_TO_SATA_PMPORT(comp_port);
1362 		qual = SCSI_TO_SATA_ADDR_QUAL(comp_port);
1363 
1364 		if (sata_validate_sata_address(sata_hba_inst, cport, pmport,
1365 		    qual) != 0) {
1366 			ndi_dc_freehdl(dcp);
1367 			return (EINVAL);
1368 		}
1369 
1370 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1371 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1372 		    cport_mutex);
1373 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1374 			/*
1375 			 * Cannot process ioctl request now. Come back later.
1376 			 */
1377 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1378 			    cport_mutex);
1379 			ndi_dc_freehdl(dcp);
1380 			return (EBUSY);
1381 		}
1382 		/* Block event processing for this port */
1383 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1384 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1385 
1386 		sata_device.satadev_addr.cport = cport;
1387 		sata_device.satadev_addr.pmport = pmport;
1388 		sata_device.satadev_addr.qual = qual;
1389 		sata_device.satadev_rev = SATA_DEVICE_REV;
1390 	}
1391 
1392 	switch (cmd) {
1393 
1394 	case DEVCTL_AP_DISCONNECT:
1395 
1396 		/*
1397 		 * Normally, cfgadm sata plugin will try to offline
1398 		 * (unconfigure) device before this request. Nevertheless,
1399 		 * if a device is still configured, we need to
1400 		 * attempt to offline and unconfigure device first, and we will
1401 		 * deactivate the port regardless of the unconfigure
1402 		 * operation results.
1403 		 *
1404 		 */
1405 		rv = sata_ioctl_disconnect(sata_hba_inst, &sata_device);
1406 
1407 		break;
1408 
1409 	case DEVCTL_AP_UNCONFIGURE:
1410 
1411 		/*
1412 		 * The unconfigure operation uses generic nexus operation to
1413 		 * offline a device. It leaves a target device node attached.
1414 		 * and obviously sata_drive_info attached as well, because
1415 		 * from the hardware point of view nothing has changed.
1416 		 */
1417 		rv = sata_ioctl_unconfigure(sata_hba_inst, &sata_device);
1418 		break;
1419 
1420 	case DEVCTL_AP_CONNECT:
1421 	{
1422 		/*
1423 		 * The sata cfgadm pluging will invoke this operation only if
1424 		 * port was found in the disconnect state (failed state
1425 		 * is also treated as the disconnected state).
1426 		 * If port activation is successful and a device is found
1427 		 * attached to the port, the initialization sequence is
1428 		 * executed to probe the port and attach
1429 		 * a device structure to a port structure. The device is not
1430 		 * set in configured state (system-wise) by this operation.
1431 		 */
1432 
1433 		rv = sata_ioctl_connect(sata_hba_inst, &sata_device);
1434 
1435 		break;
1436 	}
1437 
1438 	case DEVCTL_AP_CONFIGURE:
1439 	{
1440 		/*
1441 		 * A port may be in an active or shutdown state.
1442 		 * If port is in a failed state, operation is aborted.
1443 		 * If a port is in a shutdown state, sata_tran_port_activate()
1444 		 * is invoked prior to any other operation.
1445 		 *
1446 		 * Onlining the device involves creating a new target node.
1447 		 * If there is an old target node present (belonging to
1448 		 * previously removed device), the operation is aborted - the
1449 		 * old node has to be released and removed before configure
1450 		 * operation is attempted.
1451 		 */
1452 
1453 		rv = sata_ioctl_configure(sata_hba_inst, &sata_device);
1454 
1455 		break;
1456 	}
1457 
1458 	case DEVCTL_AP_GETSTATE:
1459 
1460 		sata_cfgadm_state(sata_hba_inst, comp_port, &ap_state);
1461 
1462 		ap_state.ap_last_change = (time_t)-1;
1463 		ap_state.ap_error_code = 0;
1464 		ap_state.ap_in_transition = 0;
1465 
1466 		/* Copy the return AP-state information to the user space */
1467 		if (ndi_dc_return_ap_state(&ap_state, dcp) != NDI_SUCCESS) {
1468 			rv = EFAULT;
1469 		}
1470 		break;
1471 
1472 	case DEVCTL_AP_CONTROL:
1473 	{
1474 		/*
1475 		 * Generic devctl for hardware specific functionality
1476 		 */
1477 		sata_ioctl_data_t	ioc;
1478 
1479 		ASSERT(dcp == NULL);
1480 
1481 		/* Copy in user ioctl data first */
1482 #ifdef _MULTI_DATAMODEL
1483 		if (ddi_model_convert_from(mode & FMODELS) ==
1484 		    DDI_MODEL_ILP32) {
1485 
1486 			sata_ioctl_data_32_t	ioc32;
1487 
1488 			if (ddi_copyin((void *)arg, (void *)&ioc32,
1489 			    sizeof (ioc32), mode) != 0) {
1490 				rv = EFAULT;
1491 				break;
1492 			}
1493 			ioc.cmd 	= (uint_t)ioc32.cmd;
1494 			ioc.port	= (uint_t)ioc32.port;
1495 			ioc.get_size	= (uint_t)ioc32.get_size;
1496 			ioc.buf		= (caddr_t)(uintptr_t)ioc32.buf;
1497 			ioc.bufsiz	= (uint_t)ioc32.bufsiz;
1498 			ioc.misc_arg	= (uint_t)ioc32.misc_arg;
1499 		} else
1500 #endif /* _MULTI_DATAMODEL */
1501 		if (ddi_copyin((void *)arg, (void *)&ioc, sizeof (ioc),
1502 		    mode) != 0) {
1503 			return (EFAULT);
1504 		}
1505 
1506 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
1507 		    "sata_hba_ioctl: DEVCTL_AP_CONTROL "
1508 		    "cmd 0x%x, port 0x%x", ioc.cmd, ioc.port);
1509 
1510 		/*
1511 		 * To avoid BE/LE and 32/64 issues, a get_size always returns
1512 		 * a 32-bit number.
1513 		 */
1514 		if (ioc.get_size != 0 && ioc.bufsiz != (sizeof (uint32_t))) {
1515 			return (EINVAL);
1516 		}
1517 		/* validate address */
1518 		cport = SCSI_TO_SATA_CPORT(ioc.port);
1519 		pmport = SCSI_TO_SATA_PMPORT(ioc.port);
1520 		qual = SCSI_TO_SATA_ADDR_QUAL(ioc.port);
1521 
1522 		SATADBG3(SATA_DBG_IOCTL_IF, sata_hba_inst,
1523 		    "sata_hba_ioctl: target port is %d:%d (%d)",
1524 		    cport, pmport, qual);
1525 
1526 		if (sata_validate_sata_address(sata_hba_inst, cport,
1527 		    pmport, qual) != 0)
1528 			return (EINVAL);
1529 
1530 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1531 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1532 		    cport_mutex);
1533 		/* Is the port locked by event processing daemon ? */
1534 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1535 			/*
1536 			 * Cannot process ioctl request now. Come back later
1537 			 */
1538 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1539 			    cport_mutex);
1540 			return (EBUSY);
1541 		}
1542 		/* Block event processing for this port */
1543 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1544 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1545 
1546 
1547 		sata_device.satadev_addr.cport = cport;
1548 		sata_device.satadev_addr.pmport = pmport;
1549 		sata_device.satadev_addr.qual = qual;
1550 		sata_device.satadev_rev = SATA_DEVICE_REV;
1551 
1552 		switch (ioc.cmd) {
1553 
1554 		case SATA_CFGA_RESET_PORT:
1555 			/*
1556 			 * There is no protection for configured device.
1557 			 */
1558 			rv = sata_ioctl_reset_port(sata_hba_inst, &sata_device);
1559 			break;
1560 
1561 		case SATA_CFGA_RESET_DEVICE:
1562 			/*
1563 			 * There is no protection for configured device.
1564 			 */
1565 			rv = sata_ioctl_reset_device(sata_hba_inst,
1566 			    &sata_device);
1567 			break;
1568 
1569 		case SATA_CFGA_RESET_ALL:
1570 			/*
1571 			 * There is no protection for configured devices.
1572 			 */
1573 			rv = sata_ioctl_reset_all(sata_hba_inst);
1574 			/*
1575 			 * We return here, because common return is for
1576 			 * a single port operation - we have already unlocked
1577 			 * all ports and no dc handle was allocated.
1578 			 */
1579 			return (rv);
1580 
1581 		case SATA_CFGA_PORT_DEACTIVATE:
1582 			/*
1583 			 * Arbitrarily unconfigure attached device, if any.
1584 			 * Even if the unconfigure fails, proceed with the
1585 			 * port deactivation.
1586 			 */
1587 			rv = sata_ioctl_deactivate(sata_hba_inst, &sata_device);
1588 
1589 			break;
1590 
1591 		case SATA_CFGA_PORT_ACTIVATE:
1592 
1593 			rv = sata_ioctl_activate(sata_hba_inst, &sata_device);
1594 			break;
1595 
1596 		case SATA_CFGA_PORT_SELF_TEST:
1597 
1598 			rv = sata_ioctl_port_self_test(sata_hba_inst,
1599 			    &sata_device);
1600 			break;
1601 
1602 		case SATA_CFGA_GET_DEVICE_PATH:
1603 
1604 			rv = sata_ioctl_get_device_path(sata_hba_inst,
1605 			    &sata_device, &ioc, mode);
1606 			break;
1607 
1608 		case SATA_CFGA_GET_AP_TYPE:
1609 
1610 			rv = sata_ioctl_get_ap_type(sata_hba_inst,
1611 			    &sata_device, &ioc, mode);
1612 			break;
1613 
1614 		case SATA_CFGA_GET_MODEL_INFO:
1615 
1616 			rv = sata_ioctl_get_model_info(sata_hba_inst,
1617 			    &sata_device, &ioc, mode);
1618 			break;
1619 
1620 		case SATA_CFGA_GET_REVFIRMWARE_INFO:
1621 
1622 			rv = sata_ioctl_get_revfirmware_info(sata_hba_inst,
1623 			    &sata_device, &ioc, mode);
1624 			break;
1625 
1626 		case SATA_CFGA_GET_SERIALNUMBER_INFO:
1627 
1628 			rv = sata_ioctl_get_serialnumber_info(sata_hba_inst,
1629 			    &sata_device, &ioc, mode);
1630 			break;
1631 
1632 		default:
1633 			rv = EINVAL;
1634 			break;
1635 
1636 		} /* End of DEVCTL_AP_CONTROL cmd switch */
1637 
1638 		break;
1639 	}
1640 
1641 	default:
1642 	{
1643 		/*
1644 		 * If we got here, we got an IOCTL that SATA HBA Framework
1645 		 * does not recognize. Pass ioctl to HBA driver, in case
1646 		 * it could process it.
1647 		 */
1648 		sata_hba_tran_t *sata_tran = sata_hba_inst->satahba_tran;
1649 		dev_info_t	*mydip = SATA_DIP(sata_hba_inst);
1650 
1651 		SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1652 		    "IOCTL 0x%2x not supported in SATA framework, "
1653 		    "passthrough to HBA", cmd);
1654 
1655 		if (sata_tran->sata_tran_ioctl == NULL) {
1656 			rv = EINVAL;
1657 			break;
1658 		}
1659 		rval = (*sata_tran->sata_tran_ioctl)(mydip, cmd, arg);
1660 		if (rval != 0) {
1661 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1662 			    "IOCTL 0x%2x failed in HBA", cmd);
1663 			rv = rval;
1664 		}
1665 		break;
1666 	}
1667 
1668 	} /* End of main IOCTL switch */
1669 
1670 	if (dcp) {
1671 		ndi_dc_freehdl(dcp);
1672 	}
1673 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1674 	cportinfo->cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
1675 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1676 
1677 	return (rv);
1678 }
1679 
1680 
1681 /*
1682  * Create error retrieval sata packet
1683  *
1684  * A sata packet is allocated and set-up to contain specified error retrieval
1685  * command and appropriate dma-able data buffer.
1686  * No association with any scsi packet is made and no callback routine is
1687  * specified.
1688  *
1689  * Returns a pointer to sata packet upon successful packet creation.
1690  * Returns NULL, if packet cannot be created.
1691  */
1692 sata_pkt_t *
1693 sata_get_error_retrieval_pkt(dev_info_t *dip, sata_device_t *sata_device,
1694     int pkt_type)
1695 {
1696 	sata_hba_inst_t	*sata_hba_inst;
1697 	sata_pkt_txlate_t *spx;
1698 	sata_pkt_t *spkt;
1699 	sata_drive_info_t *sdinfo;
1700 
1701 	mutex_enter(&sata_mutex);
1702 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1703 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1704 		if (SATA_DIP(sata_hba_inst) == dip)
1705 			break;
1706 	}
1707 	mutex_exit(&sata_mutex);
1708 	ASSERT(sata_hba_inst != NULL);
1709 
1710 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
1711 	if (sdinfo == NULL) {
1712 		sata_log(sata_hba_inst, CE_WARN,
1713 		    "sata: error recovery request for non-attached device at "
1714 		    "cport %d", sata_device->satadev_addr.cport);
1715 		return (NULL);
1716 	}
1717 
1718 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1719 	spx->txlt_sata_hba_inst = sata_hba_inst;
1720 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
1721 	spkt = sata_pkt_alloc(spx, NULL);
1722 	if (spkt == NULL) {
1723 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1724 		return (NULL);
1725 	}
1726 	/* address is needed now */
1727 	spkt->satapkt_device.satadev_addr = sata_device->satadev_addr;
1728 
1729 	switch (pkt_type) {
1730 	case SATA_ERR_RETR_PKT_TYPE_NCQ:
1731 		if (sata_ncq_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS) {
1732 			if (sata_check_for_dma_error(dip, spx)) {
1733 				ddi_fm_service_impact(dip,
1734 				    DDI_SERVICE_UNAFFECTED);
1735 				break;
1736 			}
1737 			return (spkt);
1738 		}
1739 		break;
1740 
1741 	case SATA_ERR_RETR_PKT_TYPE_ATAPI:
1742 		if (sata_atapi_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS) {
1743 			if (sata_check_for_dma_error(dip, spx)) {
1744 				ddi_fm_service_impact(dip,
1745 				    DDI_SERVICE_UNAFFECTED);
1746 				break;
1747 			}
1748 			return (spkt);
1749 		}
1750 		break;
1751 
1752 	default:
1753 		break;
1754 	}
1755 
1756 	sata_pkt_free(spx);
1757 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1758 	return (NULL);
1759 
1760 }
1761 
1762 
1763 /*
1764  * Free error retrieval sata packet
1765  *
1766  * Free sata packet and any associated resources allocated previously by
1767  * sata_get_error_retrieval_pkt().
1768  *
1769  * Void return.
1770  */
1771 void
1772 sata_free_error_retrieval_pkt(sata_pkt_t *sata_pkt)
1773 {
1774 	sata_pkt_txlate_t *spx =
1775 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1776 
1777 	ASSERT(sata_pkt != NULL);
1778 
1779 	sata_free_local_buffer(spx);
1780 	sata_pkt_free(spx);
1781 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1782 
1783 }
1784 
1785 /*
1786  * Create READ PORT MULTIPLIER and WRITE PORT MULTIPLIER sata packet
1787  *
1788  * No association with any scsi packet is made and no callback routine is
1789  * specified.
1790  *
1791  * Returns a pointer to sata packet upon successful packet creation.
1792  * Returns NULL, if packet cannot be created.
1793  *
1794  * NOTE: Input/Output value includes 64 bits accoring to SATA Spec 2.6,
1795  * only lower 32 bits are available currently.
1796  */
1797 sata_pkt_t *
1798 sata_get_rdwr_pmult_pkt(dev_info_t *dip, sata_device_t *sd,
1799     uint8_t regn, uint32_t regv, uint32_t type)
1800 {
1801 	sata_hba_inst_t	*sata_hba_inst;
1802 	sata_pkt_txlate_t *spx;
1803 	sata_pkt_t *spkt;
1804 	sata_cmd_t *scmd;
1805 
1806 	/* Only READ/WRITE commands are accepted. */
1807 	ASSERT(type == SATA_RDWR_PMULT_PKT_TYPE_READ ||
1808 	    type == SATA_RDWR_PMULT_PKT_TYPE_WRITE);
1809 
1810 	mutex_enter(&sata_mutex);
1811 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1812 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1813 		if (SATA_DIP(sata_hba_inst) == dip)
1814 			break;
1815 	}
1816 	mutex_exit(&sata_mutex);
1817 	ASSERT(sata_hba_inst != NULL);
1818 
1819 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1820 	spx->txlt_sata_hba_inst = sata_hba_inst;
1821 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
1822 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
1823 	if (spkt == NULL) {
1824 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1825 		return (NULL);
1826 	}
1827 
1828 	/*
1829 	 * NOTE: We need to send this command to the port multiplier,
1830 	 * that means send to SATA_PMULT_HOSTPORT(0xf) pmport
1831 	 *
1832 	 * sata_device contains the address of actual target device, and the
1833 	 * pmport number in the command comes from the sata_device structure.
1834 	 */
1835 	spkt->satapkt_device.satadev_addr = sd->satadev_addr;
1836 	spkt->satapkt_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
1837 	spkt->satapkt_device.satadev_addr.qual = SATA_ADDR_PMULT;
1838 
1839 	/* Fill sata_pkt */
1840 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_POLLING;
1841 	spkt->satapkt_comp = NULL; /* Synchronous mode, no callback */
1842 	spkt->satapkt_time = 10; /* Timeout 10s */
1843 
1844 	/* Build READ PORT MULTIPLIER cmd in the sata_pkt */
1845 	scmd = &spkt->satapkt_cmd;
1846 	scmd->satacmd_features_reg = regn & 0xff;
1847 	scmd->satacmd_features_reg_ext = (regn >> 8) & 0xff;
1848 	scmd->satacmd_device_reg = sd->satadev_addr.pmport;
1849 	scmd->satacmd_addr_type = 0;		/* N/A */
1850 
1851 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
1852 
1853 	if (type == SATA_RDWR_PMULT_PKT_TYPE_READ) {
1854 		scmd->satacmd_cmd_reg = SATAC_READ_PORTMULT;
1855 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
1856 		scmd->satacmd_flags.sata_special_regs = 1;
1857 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
1858 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
1859 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
1860 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
1861 	} else if (type == SATA_RDWR_PMULT_PKT_TYPE_WRITE) {
1862 		scmd->satacmd_cmd_reg = SATAC_WRITE_PORTMULT;
1863 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
1864 		scmd->satacmd_sec_count_lsb = regv & 0xff;
1865 		scmd->satacmd_lba_low_lsb = regv >> 8 & 0xff;
1866 		scmd->satacmd_lba_mid_lsb = regv >> 16 & 0xff;
1867 		scmd->satacmd_lba_high_lsb = regv >> 24 & 0xff;
1868 	}
1869 
1870 	return (spkt);
1871 }
1872 
1873 /*
1874  * Free sata packet and any associated resources allocated previously by
1875  * sata_get_rdwr_pmult_pkt().
1876  *
1877  * Void return.
1878  */
1879 void
1880 sata_free_rdwr_pmult_pkt(sata_pkt_t *sata_pkt)
1881 {
1882 	sata_pkt_txlate_t *spx =
1883 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1884 
1885 	/* Free allocated resources */
1886 	sata_pkt_free(spx);
1887 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1888 }
1889 
1890 /*
1891  * Register a port multiplier to framework.
1892  * 1) Store the GSCR values in the previous allocated pmult_info strctures.
1893  * 2) Search in the blacklist and update the number of the device ports of the
1894  * port multiplier.
1895  *
1896  * Void return.
1897  */
1898 void
1899 sata_register_pmult(dev_info_t *dip, sata_device_t *sd, sata_pmult_gscr_t *sg)
1900 {
1901 	sata_hba_inst_t *sata_hba_inst = NULL;
1902 	sata_pmult_info_t *pmultinfo;
1903 	sata_pmult_bl_t *blp;
1904 	int cport = sd->satadev_addr.cport;
1905 
1906 	mutex_enter(&sata_mutex);
1907 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1908 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1909 		if (SATA_DIP(sata_hba_inst) == dip)
1910 			if (sata_hba_inst->satahba_attached == 1)
1911 				break;
1912 	}
1913 	mutex_exit(&sata_mutex);
1914 	/* HBA not attached? */
1915 	if (sata_hba_inst == NULL)
1916 		return;
1917 
1918 	/* Number of pmports */
1919 	sd->satadev_add_info = sg->gscr2 & SATA_PMULT_PORTNUM_MASK;
1920 
1921 	/* Check the blacklist */
1922 	for (blp = sata_pmult_blacklist; blp->bl_gscr0; blp++) {
1923 		if (sg->gscr0 != blp->bl_gscr0 && blp->bl_gscr0)
1924 			continue;
1925 		if (sg->gscr1 != blp->bl_gscr1 && blp->bl_gscr1)
1926 			continue;
1927 		if (sg->gscr2 != blp->bl_gscr2 && blp->bl_gscr2)
1928 			continue;
1929 
1930 		cmn_err(CE_WARN, "!Port multiplier is on the blacklist.");
1931 		sd->satadev_add_info = blp->bl_flags;
1932 		break;
1933 	}
1934 
1935 	/* Register the port multiplier GSCR */
1936 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
1937 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
1938 	if (pmultinfo != NULL) {
1939 		pmultinfo->pmult_gscr = *sg;
1940 		pmultinfo->pmult_num_dev_ports =
1941 		    sd->satadev_add_info & SATA_PMULT_PORTNUM_MASK;
1942 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
1943 		    "Port multiplier registered at port %d", cport);
1944 	}
1945 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
1946 }
1947 
1948 /*
1949  * sata_name_child is for composing the name of the node
1950  * the format of the name is "target,0".
1951  */
1952 static int
1953 sata_name_child(dev_info_t *dip, char *name, int namelen)
1954 {
1955 	int target;
1956 
1957 	target = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1958 	    DDI_PROP_DONTPASS, "target", -1);
1959 	if (target == -1)
1960 		return (DDI_FAILURE);
1961 	(void) snprintf(name, namelen, "%x,0", target);
1962 	return (DDI_SUCCESS);
1963 }
1964 
1965 
1966 
1967 /* ****************** SCSA required entry points *********************** */
1968 
1969 /*
1970  * Implementation of scsi tran_tgt_init.
1971  * sata_scsi_tgt_init() initializes scsi_device structure
1972  *
1973  * If successful, DDI_SUCCESS is returned.
1974  * DDI_FAILURE is returned if addressed device does not exist
1975  */
1976 
1977 static int
1978 sata_scsi_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
1979     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
1980 {
1981 #ifndef __lock_lint
1982 	_NOTE(ARGUNUSED(hba_dip))
1983 	_NOTE(ARGUNUSED(tgt_dip))
1984 #endif
1985 	sata_device_t		sata_device;
1986 	sata_drive_info_t	*sdinfo;
1987 	struct sata_id		*sid;
1988 	sata_hba_inst_t		*sata_hba_inst;
1989 	char			model[SATA_ID_MODEL_LEN + 1];
1990 	char			fw[SATA_ID_FW_LEN + 1];
1991 	char			*vid, *pid;
1992 	int			i;
1993 
1994 	/*
1995 	 * Fail tran_tgt_init for .conf stub node
1996 	 */
1997 	if (ndi_dev_is_persistent_node(tgt_dip) == 0) {
1998 		(void) ndi_merge_node(tgt_dip, sata_name_child);
1999 		ddi_set_name_addr(tgt_dip, NULL);
2000 		return (DDI_FAILURE);
2001 	}
2002 
2003 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
2004 
2005 	/* Validate scsi device address */
2006 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
2007 	    &sata_device) != 0)
2008 		return (DDI_FAILURE);
2009 
2010 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2011 	    sata_device.satadev_addr.cport)));
2012 
2013 	/* sata_device now contains a valid sata address */
2014 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
2015 	if (sdinfo == NULL) {
2016 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2017 		    sata_device.satadev_addr.cport)));
2018 		return (DDI_FAILURE);
2019 	}
2020 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2021 	    sata_device.satadev_addr.cport)));
2022 
2023 	/*
2024 	 * Check if we need to create a legacy devid (i.e cmdk style) for
2025 	 * the target disks.
2026 	 *
2027 	 * HBA devinfo node will have the property "use-cmdk-devid-format"
2028 	 * if we need to create cmdk-style devid for all the disk devices
2029 	 * attached to this controller. This property may have been set
2030 	 * from HBA driver's .conf file or by the HBA driver in its
2031 	 * attach(9F) function.
2032 	 */
2033 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
2034 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
2035 	    "use-cmdk-devid-format", 0) == 1)) {
2036 		/* register a legacy devid for this target node */
2037 		sata_target_devid_register(tgt_dip, sdinfo);
2038 	}
2039 
2040 
2041 	/*
2042 	 * 'Identify Device Data' does not always fit in standard SCSI
2043 	 * INQUIRY data, so establish INQUIRY_* properties with full-form
2044 	 * of information.
2045 	 */
2046 	sid = &sdinfo->satadrv_id;
2047 #ifdef	_LITTLE_ENDIAN
2048 	swab(sid->ai_model, model, SATA_ID_MODEL_LEN);
2049 	swab(sid->ai_fw, fw, SATA_ID_FW_LEN);
2050 #else	/* _LITTLE_ENDIAN */
2051 	bcopy(sid->ai_model, model, SATA_ID_MODEL_LEN);
2052 	bcopy(sid->ai_fw, fw, SATA_ID_FW_LEN);
2053 #endif	/* _LITTLE_ENDIAN */
2054 	model[SATA_ID_MODEL_LEN] = 0;
2055 	fw[SATA_ID_FW_LEN] = 0;
2056 
2057 	/* split model into into vid/pid */
2058 	for (i = 0, pid = model; i < SATA_ID_MODEL_LEN; i++, pid++)
2059 		if ((*pid == ' ') || (*pid == '\t'))
2060 			break;
2061 	if (i < SATA_ID_MODEL_LEN) {
2062 		vid = model;
2063 		*pid++ = 0;		/* terminate vid, establish pid */
2064 	} else {
2065 		vid = NULL;		/* vid will stay "ATA     " */
2066 		pid = model;		/* model is all pid */
2067 	}
2068 
2069 	if (vid)
2070 		(void) scsi_device_prop_update_inqstring(sd, INQUIRY_VENDOR_ID,
2071 		    vid, strlen(vid));
2072 	if (pid)
2073 		(void) scsi_device_prop_update_inqstring(sd, INQUIRY_PRODUCT_ID,
2074 		    pid, strlen(pid));
2075 	(void) scsi_device_prop_update_inqstring(sd, INQUIRY_REVISION_ID,
2076 	    fw, strlen(fw));
2077 
2078 	return (DDI_SUCCESS);
2079 }
2080 
2081 /*
2082  * Implementation of scsi tran_tgt_probe.
2083  * Probe target, by calling default scsi routine scsi_hba_probe()
2084  */
2085 static int
2086 sata_scsi_tgt_probe(struct scsi_device *sd, int (*callback)(void))
2087 {
2088 	sata_hba_inst_t *sata_hba_inst =
2089 	    (sata_hba_inst_t *)(sd->sd_address.a_hba_tran->tran_hba_private);
2090 	int rval;
2091 	uint32_t pm_cap;
2092 
2093 	rval = scsi_hba_probe(sd, callback);
2094 	pm_cap = SATA_CAP_POWER_CONDITON | SATA_CAP_SMART_PAGE |
2095 	    SATA_CAP_LOG_SENSE;
2096 
2097 	if (rval == SCSIPROBE_EXISTS) {
2098 		/*
2099 		 * Set property "pm-capable" on the target device node, so that
2100 		 * the target driver will not try to fetch scsi cycle counters
2101 		 * before enabling device power-management.
2102 		 */
2103 		if ((ddi_prop_update_int(DDI_DEV_T_NONE, sd->sd_dev,
2104 		    "pm-capable", pm_cap)) != DDI_PROP_SUCCESS) {
2105 			sata_log(sata_hba_inst, CE_WARN,
2106 			    "SATA device at port %d: "
2107 			    "will not be power-managed ",
2108 			    SCSI_TO_SATA_CPORT(sd->sd_address.a_target));
2109 			SATA_LOG_D((sata_hba_inst, CE_WARN,
2110 			    "failure updating pm-capable property"));
2111 		}
2112 	}
2113 	return (rval);
2114 }
2115 
2116 /*
2117  * Implementation of scsi tran_tgt_free.
2118  * Release all resources allocated for scsi_device
2119  */
2120 static void
2121 sata_scsi_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
2122     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
2123 {
2124 #ifndef __lock_lint
2125 	_NOTE(ARGUNUSED(hba_dip))
2126 #endif
2127 	sata_device_t		sata_device;
2128 	sata_drive_info_t	*sdinfo;
2129 	sata_hba_inst_t		*sata_hba_inst;
2130 	ddi_devid_t		devid;
2131 
2132 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
2133 
2134 	/* Validate scsi device address */
2135 	/*
2136 	 * Note: tgt_free relates to the SCSA view of a device. If called, there
2137 	 * was a device at this address, so even if the sata framework internal
2138 	 * resources were alredy released because a device was detached,
2139 	 * this function should be executed as long as its actions do
2140 	 * not require the internal sata view of a device and the address
2141 	 * refers to a valid sata address.
2142 	 * Validating the address here means that we do not trust SCSA...
2143 	 */
2144 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
2145 	    &sata_device) == -1)
2146 		return;
2147 
2148 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2149 	    sata_device.satadev_addr.cport)));
2150 
2151 	/* sata_device now should contain a valid sata address */
2152 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
2153 	if (sdinfo == NULL) {
2154 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2155 		    sata_device.satadev_addr.cport)));
2156 		return;
2157 	}
2158 	/*
2159 	 * We did not allocate any resources in sata_scsi_tgt_init()
2160 	 * other than few properties.
2161 	 * Free them.
2162 	 */
2163 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2164 	    sata_device.satadev_addr.cport)));
2165 	(void) ndi_prop_remove(DDI_DEV_T_NONE, tgt_dip, "pm-capable");
2166 
2167 	/*
2168 	 * If devid was previously created but not freed up from
2169 	 * sd(7D) driver (i.e during detach(9F)) then do it here.
2170 	 */
2171 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
2172 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
2173 	    "use-cmdk-devid-format", 0) == 1) &&
2174 	    (ddi_devid_get(tgt_dip, &devid) == DDI_SUCCESS)) {
2175 		ddi_devid_unregister(tgt_dip);
2176 		ddi_devid_free(devid);
2177 	}
2178 }
2179 
2180 /*
2181  * Implementation of scsi tran_init_pkt
2182  * Upon successful return, scsi pkt buffer has DMA resources allocated.
2183  *
2184  * It seems that we should always allocate pkt, even if the address is
2185  * for non-existing device - just use some default for dma_attr.
2186  * The reason is that there is no way to communicate this to a caller here.
2187  * Subsequent call to sata_scsi_start may fail appropriately.
2188  * Simply returning NULL does not seem to discourage a target driver...
2189  *
2190  * Returns a pointer to initialized scsi_pkt, or NULL otherwise.
2191  */
2192 static struct scsi_pkt *
2193 sata_scsi_init_pkt(struct scsi_address *ap, struct scsi_pkt *pkt,
2194     struct buf *bp, int cmdlen, int statuslen, int tgtlen, int flags,
2195     int (*callback)(caddr_t), caddr_t arg)
2196 {
2197 	sata_hba_inst_t *sata_hba_inst =
2198 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2199 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
2200 	sata_device_t sata_device;
2201 	sata_drive_info_t *sdinfo;
2202 	sata_pkt_txlate_t *spx;
2203 	ddi_dma_attr_t cur_dma_attr;
2204 	int rval;
2205 	boolean_t new_pkt = B_TRUE;
2206 
2207 	ASSERT(ap->a_hba_tran->tran_hba_dip == dip);
2208 
2209 	/*
2210 	 * We need to translate the address, even if it could be
2211 	 * a bogus one, for a non-existing device
2212 	 */
2213 	sata_device.satadev_addr.qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
2214 	sata_device.satadev_addr.cport = SCSI_TO_SATA_CPORT(ap->a_target);
2215 	sata_device.satadev_addr.pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2216 	sata_device.satadev_rev = SATA_DEVICE_REV;
2217 
2218 	if (pkt == NULL) {
2219 		/*
2220 		 * Have to allocate a brand new scsi packet.
2221 		 * We need to operate with auto request sense enabled.
2222 		 */
2223 		pkt = scsi_hba_pkt_alloc(dip, ap, cmdlen,
2224 		    MAX(statuslen, SATA_MAX_SENSE_LEN),
2225 		    tgtlen, sizeof (sata_pkt_txlate_t), callback, arg);
2226 
2227 		if (pkt == NULL)
2228 			return (NULL);
2229 
2230 		/* Fill scsi packet structure */
2231 		pkt->pkt_comp		= (void (*)())NULL;
2232 		pkt->pkt_time		= 0;
2233 		pkt->pkt_resid		= 0;
2234 		pkt->pkt_statistics	= 0;
2235 		pkt->pkt_reason		= 0;
2236 
2237 		/*
2238 		 * pkt_hba_private will point to sata pkt txlate structure
2239 		 */
2240 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2241 		bzero(spx, sizeof (sata_pkt_txlate_t));
2242 
2243 		spx->txlt_scsi_pkt = pkt;
2244 		spx->txlt_sata_hba_inst = sata_hba_inst;
2245 
2246 		/* Allocate sata_pkt */
2247 		spx->txlt_sata_pkt = sata_pkt_alloc(spx, callback);
2248 		if (spx->txlt_sata_pkt == NULL) {
2249 			/* Could not allocate sata pkt */
2250 			scsi_hba_pkt_free(ap, pkt);
2251 			return (NULL);
2252 		}
2253 		/* Set sata address */
2254 		spx->txlt_sata_pkt->satapkt_device.satadev_addr =
2255 		    sata_device.satadev_addr;
2256 		spx->txlt_sata_pkt->satapkt_device.satadev_rev =
2257 		    sata_device.satadev_rev;
2258 
2259 		if ((bp == NULL) || (bp->b_bcount == 0))
2260 			return (pkt);
2261 
2262 		spx->txlt_total_residue = bp->b_bcount;
2263 	} else {
2264 		new_pkt = B_FALSE;
2265 		/*
2266 		 * Packet was preallocated/initialized by previous call
2267 		 */
2268 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2269 
2270 		if ((bp == NULL) || (bp->b_bcount == 0)) {
2271 			return (pkt);
2272 		}
2273 
2274 		/* Pkt is available already: spx->txlt_scsi_pkt == pkt; */
2275 	}
2276 
2277 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
2278 
2279 	/*
2280 	 * We use an adjusted version of the dma_attr, to account
2281 	 * for device addressing limitations.
2282 	 * sata_adjust_dma_attr() will handle sdinfo == NULL which may
2283 	 * happen when a device is not yet configured.
2284 	 */
2285 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2286 	    sata_device.satadev_addr.cport)));
2287 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
2288 	    &spx->txlt_sata_pkt->satapkt_device);
2289 	/* NULL sdinfo may be passsed to sata_adjust_dma_attr() */
2290 	sata_adjust_dma_attr(sdinfo,
2291 	    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
2292 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2293 	    sata_device.satadev_addr.cport)));
2294 	/*
2295 	 * Allocate necessary DMA resources for the packet's data buffer
2296 	 * NOTE:
2297 	 * In case of read/write commands, DMA resource allocation here is
2298 	 * based on the premise that the transfer length specified in
2299 	 * the read/write scsi cdb will match exactly DMA resources -
2300 	 * returning correct packet residue is crucial.
2301 	 */
2302 	if ((rval = sata_dma_buf_setup(spx, flags, callback, arg,
2303 	    &cur_dma_attr)) != DDI_SUCCESS) {
2304 		/*
2305 		 * If a DMA allocation request fails with
2306 		 * DDI_DMA_NOMAPPING, indicate the error by calling
2307 		 * bioerror(9F) with bp and an error code of EFAULT.
2308 		 * If a DMA allocation request fails with
2309 		 * DDI_DMA_TOOBIG, indicate the error by calling
2310 		 * bioerror(9F) with bp and an error code of EINVAL.
2311 		 * For DDI_DMA_NORESOURCES, we may have some of them allocated.
2312 		 * Request may be repeated later - there is no real error.
2313 		 */
2314 		switch (rval) {
2315 		case DDI_DMA_NORESOURCES:
2316 			bioerror(bp, 0);
2317 			break;
2318 		case DDI_DMA_NOMAPPING:
2319 		case DDI_DMA_BADATTR:
2320 			bioerror(bp, EFAULT);
2321 			break;
2322 		case DDI_DMA_TOOBIG:
2323 		default:
2324 			bioerror(bp, EINVAL);
2325 			break;
2326 		}
2327 		goto fail;
2328 	}
2329 
2330 	if (sata_check_for_dma_error(dip, spx)) {
2331 		ddi_fm_service_impact(dip, DDI_SERVICE_UNAFFECTED);
2332 		bioerror(bp, EFAULT);
2333 		goto fail;
2334 	}
2335 
2336 success:
2337 	/* Set number of bytes that are not yet accounted for */
2338 	pkt->pkt_resid = spx->txlt_total_residue;
2339 	ASSERT(pkt->pkt_resid >= 0);
2340 
2341 	return (pkt);
2342 
2343 fail:
2344 	if (new_pkt == B_TRUE) {
2345 		/*
2346 		 * Since this is a new packet, we can clean-up
2347 		 * everything
2348 		 */
2349 		sata_scsi_destroy_pkt(ap, pkt);
2350 	} else {
2351 		/*
2352 		 * This is a re-used packet. It will be target driver's
2353 		 * responsibility to eventually destroy it (which
2354 		 * will free allocated resources).
2355 		 * Here, we just "complete" the request, leaving
2356 		 * allocated resources intact, so the request may
2357 		 * be retried.
2358 		 */
2359 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2360 		sata_pkt_free(spx);
2361 	}
2362 	return (NULL);
2363 }
2364 
2365 /*
2366  * Implementation of scsi tran_start.
2367  * Translate scsi cmd into sata operation and return status.
2368  * ATAPI CDBs are passed to ATAPI devices - the device determines what commands
2369  * are supported.
2370  * For SATA hard disks, supported scsi commands:
2371  * SCMD_INQUIRY
2372  * SCMD_TEST_UNIT_READY
2373  * SCMD_START_STOP
2374  * SCMD_READ_CAPACITY
2375  * SCMD_SVC_ACTION_IN_G4 (READ CAPACITY (16))
2376  * SCMD_REQUEST_SENSE
2377  * SCMD_LOG_SENSE_G1
2378  * SCMD_LOG_SELECT_G1
2379  * SCMD_MODE_SENSE	(specific pages)
2380  * SCMD_MODE_SENSE_G1	(specific pages)
2381  * SCMD_MODE_SELECT	(specific pages)
2382  * SCMD_MODE_SELECT_G1	(specific pages)
2383  * SCMD_SYNCHRONIZE_CACHE
2384  * SCMD_SYNCHRONIZE_CACHE_G1
2385  * SCMD_READ
2386  * SCMD_READ_G1
2387  * SCMD_READ_G4
2388  * SCMD_READ_G5
2389  * SCMD_WRITE
2390  * SCMD_WRITE_BUFFER
2391  * SCMD_WRITE_G1
2392  * SCMD_WRITE_G4
2393  * SCMD_WRITE_G5
2394  * SCMD_SEEK		(noop)
2395  * SCMD_SDIAG
2396  *
2397  * All other commands are rejected as unsupported.
2398  *
2399  * Returns:
2400  * TRAN_ACCEPT if command was executed successfully or accepted by HBA driver
2401  * for execution. TRAN_ACCEPT may be returned also if device was removed but
2402  * a callback could be scheduled.
2403  * TRAN_BADPKT if cmd was directed to invalid address.
2404  * TRAN_FATAL_ERROR is command was rejected due to hardware error, including
2405  * some unspecified error. TRAN_FATAL_ERROR may be also returned if a device
2406  * was removed and there was no callback specified in scsi pkt.
2407  * TRAN_BUSY if command could not be executed becasue HBA driver or SATA
2408  * framework was busy performing some other operation(s).
2409  *
2410  */
2411 static int
2412 sata_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
2413 {
2414 	sata_hba_inst_t *sata_hba_inst =
2415 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2416 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2417 	sata_device_t *sdevice = &spx->txlt_sata_pkt->satapkt_device;
2418 	sata_drive_info_t *sdinfo;
2419 	struct buf *bp;
2420 	uint8_t cport, pmport;
2421 	boolean_t dev_gone = B_FALSE;
2422 	int rval;
2423 
2424 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2425 	    "sata_scsi_start: cmd 0x%02x\n", pkt->pkt_cdbp[0]);
2426 
2427 	ASSERT(spx != NULL &&
2428 	    spx->txlt_scsi_pkt == pkt && spx->txlt_sata_pkt != NULL);
2429 
2430 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
2431 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2432 
2433 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2434 
2435 	if (sdevice->satadev_addr.qual == SATA_ADDR_DCPORT) {
2436 		sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2437 		if (sdinfo == NULL ||
2438 		    SATA_CPORT_INFO(sata_hba_inst, cport)->
2439 		    cport_tgtnode_clean == B_FALSE ||
2440 		    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2441 			dev_gone = B_TRUE;
2442 		}
2443 	} else if (sdevice->satadev_addr.qual == SATA_ADDR_DPMPORT) {
2444 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
2445 		    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
2446 		    cport) == NULL) {
2447 			dev_gone = B_TRUE;
2448 		} else if (SATA_PMPORT_INFO(sata_hba_inst, cport,
2449 		    pmport) == NULL) {
2450 			dev_gone = B_TRUE;
2451 		} else {
2452 			mutex_enter(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2453 			    cport, pmport)));
2454 			sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2455 			if (sdinfo == NULL ||
2456 			    SATA_PMPORT_INFO(sata_hba_inst, cport, pmport)->
2457 			    pmport_tgtnode_clean == B_FALSE ||
2458 			    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2459 				dev_gone = B_TRUE;
2460 			}
2461 			mutex_exit(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2462 			    cport, pmport)));
2463 		}
2464 	}
2465 
2466 	if (dev_gone == B_TRUE) {
2467 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2468 		pkt->pkt_reason = CMD_DEV_GONE;
2469 		/*
2470 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
2471 		 * only in callback function (for normal requests) and
2472 		 * in the dump code path.
2473 		 * So, if the callback is available, we need to do
2474 		 * the callback rather than returning TRAN_FATAL_ERROR here.
2475 		 */
2476 		if (pkt->pkt_comp != NULL) {
2477 			/* scsi callback required */
2478 			if (servicing_interrupt()) {
2479 				if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2480 				    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2481 				    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
2482 				    NULL) {
2483 					return (TRAN_BUSY);
2484 				}
2485 			} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2486 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2487 			    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
2488 				/* Scheduling the callback failed */
2489 				return (TRAN_BUSY);
2490 			}
2491 			return (TRAN_ACCEPT);
2492 		}
2493 		/* No callback available */
2494 		return (TRAN_FATAL_ERROR);
2495 	}
2496 
2497 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
2498 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2499 		rval = sata_txlt_atapi(spx);
2500 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2501 		    "sata_scsi_start atapi: rval %d\n", rval);
2502 		return (rval);
2503 	}
2504 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2505 
2506 	/*
2507 	 * Checking for power state, if it was on
2508 	 * STOPPED state, then the drive is not capable
2509 	 * of processing media access command.  And
2510 	 * TEST_UNIT_READY, REQUEST_SENSE has special handling
2511 	 * in the function for different power state.
2512 	 */
2513 	if (((sdinfo->satadrv_power_level == SATA_POWER_STANDBY) ||
2514 	    (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)) &&
2515 	    (SATA_IS_MEDIUM_ACCESS_CMD(pkt->pkt_cdbp[0]))) {
2516 		return (sata_txlt_check_condition(spx, KEY_NOT_READY,
2517 		    SD_SCSI_ASC_LU_NOT_READY));
2518 	}
2519 
2520 	/* ATA Disk commands processing starts here */
2521 
2522 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2523 
2524 	switch (pkt->pkt_cdbp[0]) {
2525 
2526 	case SCMD_INQUIRY:
2527 		/* Mapped to identify device */
2528 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2529 			bp_mapin(bp);
2530 		rval = sata_txlt_inquiry(spx);
2531 		break;
2532 
2533 	case SCMD_TEST_UNIT_READY:
2534 		/*
2535 		 * SAT "SATA to ATA Translation" doc specifies translation
2536 		 * to ATA CHECK POWER MODE.
2537 		 */
2538 		rval = sata_txlt_test_unit_ready(spx);
2539 		break;
2540 
2541 	case SCMD_START_STOP:
2542 		/* Mapping depends on the command */
2543 		rval = sata_txlt_start_stop_unit(spx);
2544 		break;
2545 
2546 	case SCMD_READ_CAPACITY:
2547 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2548 			bp_mapin(bp);
2549 		rval = sata_txlt_read_capacity(spx);
2550 		break;
2551 
2552 	case SCMD_SVC_ACTION_IN_G4:		/* READ CAPACITY (16) */
2553 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2554 			bp_mapin(bp);
2555 		rval = sata_txlt_read_capacity16(spx);
2556 		break;
2557 
2558 	case SCMD_REQUEST_SENSE:
2559 		/*
2560 		 * Always No Sense, since we force ARQ
2561 		 */
2562 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2563 			bp_mapin(bp);
2564 		rval = sata_txlt_request_sense(spx);
2565 		break;
2566 
2567 	case SCMD_LOG_SENSE_G1:
2568 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2569 			bp_mapin(bp);
2570 		rval = sata_txlt_log_sense(spx);
2571 		break;
2572 
2573 	case SCMD_LOG_SELECT_G1:
2574 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2575 			bp_mapin(bp);
2576 		rval = sata_txlt_log_select(spx);
2577 		break;
2578 
2579 	case SCMD_MODE_SENSE:
2580 	case SCMD_MODE_SENSE_G1:
2581 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2582 			bp_mapin(bp);
2583 		rval = sata_txlt_mode_sense(spx);
2584 		break;
2585 
2586 
2587 	case SCMD_MODE_SELECT:
2588 	case SCMD_MODE_SELECT_G1:
2589 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2590 			bp_mapin(bp);
2591 		rval = sata_txlt_mode_select(spx);
2592 		break;
2593 
2594 	case SCMD_SYNCHRONIZE_CACHE:
2595 	case SCMD_SYNCHRONIZE_CACHE_G1:
2596 		rval = sata_txlt_synchronize_cache(spx);
2597 		break;
2598 
2599 	case SCMD_READ:
2600 	case SCMD_READ_G1:
2601 	case SCMD_READ_G4:
2602 	case SCMD_READ_G5:
2603 		rval = sata_txlt_read(spx);
2604 		break;
2605 	case SCMD_WRITE_BUFFER:
2606 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2607 			bp_mapin(bp);
2608 		rval = sata_txlt_write_buffer(spx);
2609 		break;
2610 
2611 	case SCMD_WRITE:
2612 	case SCMD_WRITE_G1:
2613 	case SCMD_WRITE_G4:
2614 	case SCMD_WRITE_G5:
2615 		rval = sata_txlt_write(spx);
2616 		break;
2617 
2618 	case SCMD_SEEK:
2619 		rval = sata_txlt_nodata_cmd_immediate(spx);
2620 		break;
2621 
2622 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
2623 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
2624 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2625 			bp_mapin(bp);
2626 		rval = sata_txlt_ata_pass_thru(spx);
2627 		break;
2628 
2629 		/* Other cases will be filed later */
2630 		/* postponed until phase 2 of the development */
2631 	default:
2632 		rval = sata_txlt_invalid_command(spx);
2633 		break;
2634 	}
2635 
2636 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2637 	    "sata_scsi_start: rval %d\n", rval);
2638 
2639 	return (rval);
2640 }
2641 
2642 /*
2643  * Implementation of scsi tran_abort.
2644  * Abort specific pkt or all packets.
2645  *
2646  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2647  *
2648  * May be called from an interrupt level.
2649  */
2650 static int
2651 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2652 {
2653 	sata_hba_inst_t *sata_hba_inst =
2654 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2655 	sata_device_t	sata_device;
2656 	sata_pkt_t	*sata_pkt;
2657 
2658 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2659 	    "sata_scsi_abort: %s at target: 0x%x\n",
2660 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2661 
2662 	/* Validate address */
2663 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2664 		/* Invalid address */
2665 		return (0);
2666 
2667 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2668 	    sata_device.satadev_addr.cport)));
2669 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2670 		/* invalid address */
2671 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2672 		    sata_device.satadev_addr.cport)));
2673 		return (0);
2674 	}
2675 	if (scsi_pkt == NULL) {
2676 		/*
2677 		 * Abort all packets.
2678 		 * Although we do not have specific packet, we still need
2679 		 * dummy packet structure to pass device address to HBA.
2680 		 * Allocate one, without sleeping. Fail if pkt cannot be
2681 		 * allocated.
2682 		 */
2683 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2684 		if (sata_pkt == NULL) {
2685 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2686 			    sata_device.satadev_addr.cport)));
2687 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2688 			    "could not allocate sata_pkt"));
2689 			return (0);
2690 		}
2691 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2692 		sata_pkt->satapkt_device = sata_device;
2693 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2694 	} else {
2695 		if (scsi_pkt->pkt_ha_private == NULL) {
2696 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2697 			    sata_device.satadev_addr.cport)));
2698 			return (0); /* Bad scsi pkt */
2699 		}
2700 		/* extract pointer to sata pkt */
2701 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2702 		    txlt_sata_pkt;
2703 	}
2704 
2705 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2706 	    sata_device.satadev_addr.cport)));
2707 	/* Send abort request to HBA */
2708 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2709 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2710 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2711 	    SATA_SUCCESS) {
2712 		if (scsi_pkt == NULL)
2713 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2714 		/* Success */
2715 		return (1);
2716 	}
2717 	/* Else, something did not go right */
2718 	if (scsi_pkt == NULL)
2719 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
2720 	/* Failure */
2721 	return (0);
2722 }
2723 
2724 
2725 /*
2726  * Implementation of scsi tran_reset.
2727  * RESET_ALL request is translated into port reset.
2728  * RESET_TARGET requests is translated into a device reset,
2729  * RESET_LUN request is accepted only for LUN 0 and translated into
2730  * device reset.
2731  * The target reset should cause all HBA active and queued packets to
2732  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
2733  * the return. HBA should report reset event for the device.
2734  *
2735  * Returns 1 upon success, 0 upon failure.
2736  */
2737 static int
2738 sata_scsi_reset(struct scsi_address *ap, int level)
2739 {
2740 	sata_hba_inst_t	*sata_hba_inst =
2741 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2742 	sata_device_t	sata_device;
2743 	int		val;
2744 
2745 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2746 	    "sata_scsi_reset: level %d target: 0x%x\n",
2747 	    level, ap->a_target);
2748 
2749 	/* Validate address */
2750 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
2751 	if (val == -1)
2752 		/* Invalid address */
2753 		return (0);
2754 
2755 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2756 	    sata_device.satadev_addr.cport)));
2757 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2758 		/* invalid address */
2759 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2760 		    sata_device.satadev_addr.cport)));
2761 		return (0);
2762 	}
2763 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2764 	    sata_device.satadev_addr.cport)));
2765 	if (level == RESET_ALL) {
2766 		/* port reset */
2767 		if (sata_device.satadev_addr.qual == SATA_ADDR_DCPORT)
2768 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2769 		else
2770 			sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
2771 
2772 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2773 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2774 			return (1);
2775 		else
2776 			return (0);
2777 
2778 	} else if (val == 0 &&
2779 	    (level == RESET_TARGET || level == RESET_LUN)) {
2780 		/* reset device (device attached) */
2781 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2782 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2783 			return (1);
2784 		else
2785 			return (0);
2786 	}
2787 	return (0);
2788 }
2789 
2790 
2791 /*
2792  * Implementation of scsi tran_getcap (get transport/device capabilities).
2793  * Supported capabilities for SATA hard disks:
2794  * auto-rqsense		(always supported)
2795  * tagged-qing		(supported if HBA supports it)
2796  * untagged-qing	(could be supported if disk supports it, but because
2797  *			 caching behavior allowing untagged queuing actually
2798  *			 results in reduced performance.  sd tries to throttle
2799  *			 back to only 3 outstanding commands, which may
2800  *			 work for real SCSI disks, but with read ahead
2801  *			 caching, having more than 1 outstanding command
2802  *			 results in cache thrashing.)
2803  * sector_size
2804  * dma_max
2805  * interconnect-type	(INTERCONNECT_SATA)
2806  *
2807  * Supported capabilities for ATAPI CD/DVD devices:
2808  * auto-rqsense		(always supported)
2809  * sector_size
2810  * dma_max
2811  * max-cdb-length
2812  * interconnect-type	(INTERCONNECT_SATA)
2813  *
2814  * Supported capabilities for ATAPI TAPE devices:
2815  * auto-rqsense		(always supported)
2816  * dma_max
2817  * max-cdb-length
2818  *
2819  * Supported capabilities for SATA ATAPI hard disks:
2820  * auto-rqsense		(always supported)
2821  * interconnect-type	(INTERCONNECT_SATA)
2822  * max-cdb-length
2823  *
2824  * Request for other capabilities is rejected as unsupported.
2825  *
2826  * Returns supported capability value, or -1 if capability is unsuppported or
2827  * the address is invalid - no device.
2828  */
2829 
2830 static int
2831 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
2832 {
2833 
2834 	sata_hba_inst_t 	*sata_hba_inst =
2835 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2836 	sata_device_t		sata_device;
2837 	sata_drive_info_t	*sdinfo;
2838 	ddi_dma_attr_t		adj_dma_attr;
2839 	int 			rval;
2840 
2841 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2842 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
2843 	    ap->a_target, cap);
2844 
2845 	/*
2846 	 * We want to process the capabilities on per port granularity.
2847 	 * So, we are specifically restricting ourselves to whom != 0
2848 	 * to exclude the controller wide handling.
2849 	 */
2850 	if (cap == NULL || whom == 0)
2851 		return (-1);
2852 
2853 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2854 		/* Invalid address */
2855 		return (-1);
2856 	}
2857 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2858 	    sata_device.satadev_addr.cport)));
2859 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
2860 	    NULL) {
2861 		/* invalid address */
2862 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2863 		    sata_device.satadev_addr.cport)));
2864 		return (-1);
2865 	}
2866 
2867 	switch (scsi_hba_lookup_capstr(cap)) {
2868 	case SCSI_CAP_ARQ:
2869 		rval = 1;		/* ARQ supported, turned on */
2870 		break;
2871 
2872 	case SCSI_CAP_SECTOR_SIZE:
2873 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
2874 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
2875 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
2876 			rval = SATA_ATAPI_SECTOR_SIZE;
2877 		else rval = -1;
2878 		break;
2879 
2880 	/*
2881 	 * untagged queuing cause a performance inversion because of
2882 	 * the way sd operates.  Because of this reason we do not
2883 	 * use it when available.
2884 	 */
2885 	case SCSI_CAP_UNTAGGED_QING:
2886 		if (sdinfo->satadrv_features_enabled &
2887 		    SATA_DEV_F_E_UNTAGGED_QING)
2888 			rval = 1;	/* Untagged queuing available */
2889 		else
2890 			rval = -1;	/* Untagged queuing not available */
2891 		break;
2892 
2893 	case SCSI_CAP_TAGGED_QING:
2894 		if ((sdinfo->satadrv_features_enabled &
2895 		    SATA_DEV_F_E_TAGGED_QING) &&
2896 		    (sdinfo->satadrv_max_queue_depth > 1))
2897 			rval = 1;	/* Tagged queuing available */
2898 		else
2899 			rval = -1;	/* Tagged queuing not available */
2900 		break;
2901 
2902 	case SCSI_CAP_DMA_MAX:
2903 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
2904 		    &adj_dma_attr);
2905 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
2906 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
2907 		break;
2908 
2909 	case SCSI_CAP_INTERCONNECT_TYPE:
2910 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
2911 		break;
2912 
2913 	case SCSI_CAP_CDB_LEN:
2914 		if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI)
2915 			rval = sdinfo->satadrv_atapi_cdb_len;
2916 		else
2917 			rval = -1;
2918 		break;
2919 
2920 	default:
2921 		rval = -1;
2922 		break;
2923 	}
2924 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2925 	    sata_device.satadev_addr.cport)));
2926 	return (rval);
2927 }
2928 
2929 /*
2930  * Implementation of scsi tran_setcap
2931  *
2932  * Only SCSI_CAP_UNTAGGED_QING and  SCSI_CAP_TAGGED_QING are changeable.
2933  *
2934  */
2935 static int
2936 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
2937 {
2938 	sata_hba_inst_t	*sata_hba_inst =
2939 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2940 	sata_device_t	sata_device;
2941 	sata_drive_info_t	*sdinfo;
2942 	int		rval;
2943 
2944 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2945 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
2946 
2947 	/*
2948 	 * We want to process the capabilities on per port granularity.
2949 	 * So, we are specifically restricting ourselves to whom != 0
2950 	 * to exclude the controller wide handling.
2951 	 */
2952 	if (cap == NULL || whom == 0) {
2953 		return (-1);
2954 	}
2955 
2956 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2957 		/* Invalid address */
2958 		return (-1);
2959 	}
2960 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2961 	    sata_device.satadev_addr.cport)));
2962 	if ((sdinfo = sata_get_device_info(sata_hba_inst,
2963 	    &sata_device)) == NULL) {
2964 		/* invalid address */
2965 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2966 		    sata_device.satadev_addr.cport)));
2967 		return (-1);
2968 	}
2969 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2970 	    sata_device.satadev_addr.cport)));
2971 
2972 	switch (scsi_hba_lookup_capstr(cap)) {
2973 	case SCSI_CAP_ARQ:
2974 	case SCSI_CAP_SECTOR_SIZE:
2975 	case SCSI_CAP_DMA_MAX:
2976 	case SCSI_CAP_INTERCONNECT_TYPE:
2977 		rval = 0;
2978 		break;
2979 	case SCSI_CAP_UNTAGGED_QING:
2980 		if (SATA_QDEPTH(sata_hba_inst) > 1) {
2981 			rval = 1;
2982 			if (value == 1) {
2983 				sdinfo->satadrv_features_enabled |=
2984 				    SATA_DEV_F_E_UNTAGGED_QING;
2985 			} else if (value == 0) {
2986 				sdinfo->satadrv_features_enabled &=
2987 				    ~SATA_DEV_F_E_UNTAGGED_QING;
2988 			} else {
2989 				rval = -1;
2990 			}
2991 		} else {
2992 			rval = 0;
2993 		}
2994 		break;
2995 	case SCSI_CAP_TAGGED_QING:
2996 		/* This can TCQ or NCQ */
2997 		if (sata_func_enable & SATA_ENABLE_QUEUING &&
2998 		    ((sdinfo->satadrv_features_support & SATA_DEV_F_TCQ &&
2999 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_QCMD) ||
3000 		    (sata_func_enable & SATA_ENABLE_NCQ &&
3001 		    sdinfo->satadrv_features_support & SATA_DEV_F_NCQ &&
3002 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_NCQ)) &&
3003 		    (sdinfo->satadrv_max_queue_depth > 1)) {
3004 			rval = 1;
3005 			if (value == 1) {
3006 				sdinfo->satadrv_features_enabled |=
3007 				    SATA_DEV_F_E_TAGGED_QING;
3008 			} else if (value == 0) {
3009 				sdinfo->satadrv_features_enabled &=
3010 				    ~SATA_DEV_F_E_TAGGED_QING;
3011 			} else {
3012 				rval = -1;
3013 			}
3014 		} else {
3015 			rval = 0;
3016 		}
3017 		break;
3018 	default:
3019 		rval = -1;
3020 		break;
3021 	}
3022 	return (rval);
3023 }
3024 
3025 /*
3026  * Implementations of scsi tran_destroy_pkt.
3027  * Free resources allocated by sata_scsi_init_pkt()
3028  */
3029 static void
3030 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3031 {
3032 	sata_pkt_txlate_t *spx;
3033 
3034 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3035 
3036 	sata_common_free_dma_rsrcs(spx);
3037 
3038 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
3039 	sata_pkt_free(spx);
3040 
3041 	scsi_hba_pkt_free(ap, pkt);
3042 }
3043 
3044 /*
3045  * Implementation of scsi tran_dmafree.
3046  * Free DMA resources allocated by sata_scsi_init_pkt()
3047  */
3048 
3049 static void
3050 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
3051 {
3052 #ifndef __lock_lint
3053 	_NOTE(ARGUNUSED(ap))
3054 #endif
3055 	sata_pkt_txlate_t *spx;
3056 
3057 	ASSERT(pkt != NULL);
3058 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3059 
3060 	sata_common_free_dma_rsrcs(spx);
3061 }
3062 
3063 /*
3064  * Implementation of scsi tran_sync_pkt.
3065  *
3066  * The assumption below is that pkt is unique - there is no need to check ap
3067  *
3068  * Synchronize DMA buffer and, if the intermediate buffer is used, copy data
3069  * into/from the real buffer.
3070  */
3071 static void
3072 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3073 {
3074 #ifndef __lock_lint
3075 	_NOTE(ARGUNUSED(ap))
3076 #endif
3077 	int rval;
3078 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3079 	struct buf *bp;
3080 	int direction;
3081 
3082 	ASSERT(spx != NULL);
3083 	if (spx->txlt_buf_dma_handle != NULL) {
3084 		direction = spx->txlt_sata_pkt->
3085 		    satapkt_cmd.satacmd_flags.sata_data_direction;
3086 		if (spx->txlt_sata_pkt != NULL &&
3087 		    direction != SATA_DIR_NODATA_XFER) {
3088 			if (spx->txlt_tmp_buf != NULL) {
3089 				/* Intermediate DMA buffer used */
3090 				bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3091 
3092 				if (direction & SATA_DIR_WRITE) {
3093 					bcopy(bp->b_un.b_addr,
3094 					    spx->txlt_tmp_buf, bp->b_bcount);
3095 				}
3096 			}
3097 			/* Sync the buffer for device or for CPU */
3098 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle,   0, 0,
3099 			    (direction & SATA_DIR_WRITE) ?
3100 			    DDI_DMA_SYNC_FORDEV :  DDI_DMA_SYNC_FORCPU);
3101 			ASSERT(rval == DDI_SUCCESS);
3102 			if (spx->txlt_tmp_buf != NULL &&
3103 			    !(direction & SATA_DIR_WRITE)) {
3104 				/* Intermediate DMA buffer used for read */
3105 				bcopy(spx->txlt_tmp_buf,
3106 				    bp->b_un.b_addr, bp->b_bcount);
3107 			}
3108 
3109 		}
3110 	}
3111 }
3112 
3113 
3114 
3115 /* *******************  SATA - SCSI Translation functions **************** */
3116 /*
3117  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
3118  * translation.
3119  */
3120 
3121 /*
3122  * Checks if a device exists and can be access and translates common
3123  * scsi_pkt data to sata_pkt data.
3124  *
3125  * Flag argument indicates that a non-read/write ATA command may be sent
3126  * to HBA in arbitrary SYNC mode to execute this packet.
3127  *
3128  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_CMPLT if device exists and
3129  * sata_pkt was set-up.
3130  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_DEV_GONE if device does not
3131  * exist and pkt_comp callback was scheduled.
3132  * Returns other TRAN_XXXXX values when error occured and command should be
3133  * rejected with the returned TRAN_XXXXX value.
3134  *
3135  * This function should be called with port mutex held.
3136  */
3137 static int
3138 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx, int *reason, int flag)
3139 {
3140 	sata_drive_info_t *sdinfo;
3141 	sata_device_t sata_device;
3142 	const struct sata_cmd_flags sata_initial_cmd_flags = {
3143 		SATA_DIR_NODATA_XFER,
3144 		/* all other values to 0/FALSE */
3145 	};
3146 	/*
3147 	 * Pkt_reason has to be set if the pkt_comp callback is invoked,
3148 	 * and that implies TRAN_ACCEPT return value. Any other returned value
3149 	 * indicates that the scsi packet was not accepted (the reason will not
3150 	 * be checked by the scsi target driver).
3151 	 * To make debugging easier, we set pkt_reason to know value here.
3152 	 * It may be changed later when different completion reason is
3153 	 * determined.
3154 	 */
3155 	spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
3156 	*reason = CMD_TRAN_ERR;
3157 
3158 	/* Validate address */
3159 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
3160 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
3161 
3162 	case -1:
3163 		/* Invalid address or invalid device type */
3164 		return (TRAN_BADPKT);
3165 	case 2:
3166 		/*
3167 		 * Valid address but device type is unknown - Chack if it is
3168 		 * in the reset state and therefore in an indeterminate state.
3169 		 */
3170 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3171 		    &spx->txlt_sata_pkt->satapkt_device);
3172 		if (sdinfo != NULL && (sdinfo->satadrv_event_flags &
3173 		    (SATA_EVNT_DEVICE_RESET |
3174 		    SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3175 			if (!ddi_in_panic()) {
3176 				spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3177 				*reason = CMD_INCOMPLETE;
3178 				SATADBG1(SATA_DBG_SCSI_IF,
3179 				    spx->txlt_sata_hba_inst,
3180 				    "sata_scsi_start: rejecting command "
3181 				    "because of device reset state\n", NULL);
3182 				return (TRAN_BUSY);
3183 			}
3184 		}
3185 		/* FALLTHROUGH */
3186 	case 1:
3187 		/* valid address but no valid device - it has disappeared */
3188 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
3189 		*reason = CMD_DEV_GONE;
3190 		/*
3191 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
3192 		 * only in callback function (for normal requests) and
3193 		 * in the dump code path.
3194 		 * So, if the callback is available, we need to do
3195 		 * the callback rather than returning TRAN_FATAL_ERROR here.
3196 		 */
3197 		if (spx->txlt_scsi_pkt->pkt_comp != NULL) {
3198 			/* scsi callback required */
3199 			if (servicing_interrupt()) {
3200 				if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3201 				    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3202 				    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
3203 				    NULL) {
3204 					return (TRAN_BUSY);
3205 				}
3206 			} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3207 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3208 			    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3209 				/* Scheduling the callback failed */
3210 				return (TRAN_BUSY);
3211 			}
3212 
3213 			return (TRAN_ACCEPT);
3214 		}
3215 		return (TRAN_FATAL_ERROR);
3216 	default:
3217 		/* all OK; pkt reason will be overwritten later */
3218 		break;
3219 	}
3220 	/*
3221 	 * If pkt is to be executed in polling mode and a command will not be
3222 	 * emulated in SATA module (requires sending a non-read/write ATA
3223 	 * command to HBA driver in arbitrary SYNC mode) and we are in the
3224 	 * interrupt context and not in the panic dump, then reject the packet
3225 	 * to avoid a possible interrupt stack overrun or hang caused by
3226 	 * a potentially blocked interrupt.
3227 	 */
3228 	if (((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0 || flag != 0) &&
3229 	    servicing_interrupt() && !ddi_in_panic()) {
3230 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
3231 		    "sata_scsi_start: rejecting synchronous command because "
3232 		    "of interrupt context\n", NULL);
3233 		return (TRAN_BUSY);
3234 	}
3235 
3236 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3237 	    &spx->txlt_sata_pkt->satapkt_device);
3238 
3239 	/*
3240 	 * If device is in reset condition, reject the packet with
3241 	 * TRAN_BUSY, unless:
3242 	 * 1. system is panicking (dumping)
3243 	 * In such case only one thread is running and there is no way to
3244 	 * process reset.
3245 	 * 2. cfgadm operation is is progress (internal APCTL lock is set)
3246 	 * Some cfgadm operations involve drive commands, so reset condition
3247 	 * needs to be ignored for IOCTL operations.
3248 	 */
3249 	if ((sdinfo->satadrv_event_flags &
3250 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3251 
3252 		if (!ddi_in_panic() &&
3253 		    ((SATA_CPORT_EVENT_FLAGS(spx->txlt_sata_hba_inst,
3254 		    sata_device.satadev_addr.cport) &
3255 		    SATA_APCTL_LOCK_PORT_BUSY) == 0)) {
3256 			spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3257 			*reason = CMD_INCOMPLETE;
3258 			SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3259 			    "sata_scsi_start: rejecting command because "
3260 			    "of device reset state\n", NULL);
3261 			return (TRAN_BUSY);
3262 		}
3263 	}
3264 
3265 	/*
3266 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
3267 	 * sata_scsi_pkt_init() because pkt init had to work also with
3268 	 * non-existing devices.
3269 	 * Now we know that the packet was set-up for a real device, so its
3270 	 * type is known.
3271 	 */
3272 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
3273 
3274 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
3275 	if ((SATA_CPORT_INFO(spx->txlt_sata_hba_inst,
3276 	    sata_device.satadev_addr.cport)->cport_event_flags &
3277 	    SATA_APCTL_LOCK_PORT_BUSY) != 0) {
3278 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3279 		    sata_ignore_dev_reset = B_TRUE;
3280 	}
3281 	/*
3282 	 * At this point the generic translation routine determined that the
3283 	 * scsi packet should be accepted. Packet completion reason may be
3284 	 * changed later when a different completion reason is determined.
3285 	 */
3286 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3287 	*reason = CMD_CMPLT;
3288 
3289 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3290 		/* Synchronous execution */
3291 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
3292 		    SATA_OPMODE_POLLING;
3293 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3294 		    sata_ignore_dev_reset = ddi_in_panic();
3295 	} else {
3296 		/* Asynchronous execution */
3297 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
3298 		    SATA_OPMODE_INTERRUPTS;
3299 	}
3300 	/* Convert queuing information */
3301 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
3302 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
3303 		    B_TRUE;
3304 	else if (spx->txlt_scsi_pkt->pkt_flags &
3305 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
3306 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
3307 		    B_TRUE;
3308 
3309 	/* Always limit pkt time */
3310 	if (spx->txlt_scsi_pkt->pkt_time == 0)
3311 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
3312 	else
3313 		/* Pass on scsi_pkt time */
3314 		spx->txlt_sata_pkt->satapkt_time =
3315 		    spx->txlt_scsi_pkt->pkt_time;
3316 
3317 	return (TRAN_ACCEPT);
3318 }
3319 
3320 
3321 /*
3322  * Translate ATA Identify Device data to SCSI Inquiry data.
3323  * This function may be called only for ATA devices.
3324  * This function should not be called for ATAPI devices - they
3325  * respond directly to SCSI Inquiry command.
3326  *
3327  * SATA Identify Device data has to be valid in sata_drive_info.
3328  * Buffer has to accomodate the inquiry length (36 bytes).
3329  *
3330  * This function should be called with a port mutex held.
3331  */
3332 static	void
3333 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
3334     sata_drive_info_t *sdinfo, uint8_t *buf)
3335 {
3336 
3337 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
3338 	struct sata_id *sid = &sdinfo->satadrv_id;
3339 
3340 	/* Start with a nice clean slate */
3341 	bzero((void *)inq, sizeof (struct scsi_inquiry));
3342 
3343 	/*
3344 	 * Rely on the dev_type for setting paripheral qualifier.
3345 	 * Assume that  DTYPE_RODIRECT applies to CD/DVD R/W devices.
3346 	 * It could be that DTYPE_OPTICAL could also qualify in the future.
3347 	 * ATAPI Inquiry may provide more data to the target driver.
3348 	 */
3349 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3350 	    DTYPE_DIRECT : DTYPE_RODIRECT; /* DTYPE_UNKNOWN; */
3351 
3352 	/* CFA type device is not a removable media device */
3353 	inq->inq_rmb = ((sid->ai_config != SATA_CFA_TYPE) &&
3354 	    (sid->ai_config & SATA_REM_MEDIA)) ? 1 : 0;
3355 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
3356 	inq->inq_iso = 0;	/* ISO version */
3357 	inq->inq_ecma = 0;	/* ECMA version */
3358 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
3359 	inq->inq_aenc = 0;	/* Async event notification cap. */
3360 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg - NO */
3361 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
3362 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
3363 	inq->inq_len = 31;	/* Additional length */
3364 	inq->inq_dualp = 0;	/* dual port device - NO */
3365 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
3366 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
3367 	inq->inq_linked = 0;	/* Supports linked commands - NO */
3368 				/*
3369 				 * Queuing support - controller has to
3370 				 * support some sort of command queuing.
3371 				 */
3372 	if (SATA_QDEPTH(sata_hba_inst) > 1)
3373 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
3374 	else
3375 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
3376 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
3377 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
3378 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
3379 
3380 #ifdef	_LITTLE_ENDIAN
3381 	/* Swap text fields to match SCSI format */
3382 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3383 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3384 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3385 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
3386 	else
3387 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
3388 #else	/* _LITTLE_ENDIAN */
3389 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3390 	bcopy(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3391 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3392 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
3393 	else
3394 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
3395 #endif	/* _LITTLE_ENDIAN */
3396 }
3397 
3398 
3399 /*
3400  * Scsi response set up for invalid command (command not supported)
3401  *
3402  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3403  */
3404 static int
3405 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
3406 {
3407 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3408 	struct scsi_extended_sense *sense;
3409 
3410 	scsipkt->pkt_reason = CMD_CMPLT;
3411 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3412 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3413 
3414 	*scsipkt->pkt_scbp = STATUS_CHECK;
3415 
3416 	sense = sata_arq_sense(spx);
3417 	sense->es_key = KEY_ILLEGAL_REQUEST;
3418 	sense->es_add_code = SD_SCSI_ASC_INVALID_COMMAND_CODE;
3419 
3420 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3421 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3422 
3423 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3424 	    scsipkt->pkt_comp != NULL) {
3425 		/* scsi callback required */
3426 		if (servicing_interrupt()) {
3427 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3428 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3429 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3430 				return (TRAN_BUSY);
3431 			}
3432 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3433 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3434 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3435 			/* Scheduling the callback failed */
3436 			return (TRAN_BUSY);
3437 		}
3438 	}
3439 	return (TRAN_ACCEPT);
3440 }
3441 
3442 /*
3443  * Scsi response set up for check condition with special sense key
3444  * and additional sense code.
3445  *
3446  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3447  */
3448 static int
3449 sata_txlt_check_condition(sata_pkt_txlate_t *spx, uchar_t key, uchar_t code)
3450 {
3451 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3452 	int cport = SATA_TXLT_CPORT(spx);
3453 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3454 	struct scsi_extended_sense *sense;
3455 
3456 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3457 	scsipkt->pkt_reason = CMD_CMPLT;
3458 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3459 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3460 
3461 	*scsipkt->pkt_scbp = STATUS_CHECK;
3462 
3463 	sense = sata_arq_sense(spx);
3464 	sense->es_key = key;
3465 	sense->es_add_code = code;
3466 
3467 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3468 
3469 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3470 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3471 
3472 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3473 	    scsipkt->pkt_comp != NULL) {
3474 		/* scsi callback required */
3475 		if (servicing_interrupt()) {
3476 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3477 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3478 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3479 				return (TRAN_BUSY);
3480 			}
3481 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3482 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3483 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3484 			/* Scheduling the callback failed */
3485 			return (TRAN_BUSY);
3486 		}
3487 	}
3488 	return (TRAN_ACCEPT);
3489 }
3490 
3491 /*
3492  * Scsi response setup for
3493  * emulated non-data command that requires no action/return data
3494  *
3495  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3496  */
3497 static	int
3498 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3499 {
3500 	int rval;
3501 	int reason;
3502 
3503 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3504 
3505 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3506 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3507 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3508 		return (rval);
3509 	}
3510 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3511 
3512 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3513 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3514 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3515 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3516 
3517 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3518 	    "Scsi_pkt completion reason %x\n",
3519 	    spx->txlt_scsi_pkt->pkt_reason);
3520 
3521 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3522 	    spx->txlt_scsi_pkt->pkt_comp != NULL) {
3523 		/* scsi callback required */
3524 		if (servicing_interrupt()) {
3525 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3526 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3527 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3528 				return (TRAN_BUSY);
3529 			}
3530 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3531 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3532 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3533 			/* Scheduling the callback failed */
3534 			return (TRAN_BUSY);
3535 		}
3536 	}
3537 	return (TRAN_ACCEPT);
3538 }
3539 
3540 
3541 /*
3542  * SATA translate command: Inquiry / Identify Device
3543  * Use cached Identify Device data for now, rather than issuing actual
3544  * Device Identify cmd request. If device is detached and re-attached,
3545  * asynchronous event processing should fetch and refresh Identify Device
3546  * data.
3547  * Two VPD pages are supported now:
3548  * Vital Product Data page
3549  * Unit Serial Number page
3550  *
3551  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3552  */
3553 
3554 #define	EVPD			1	/* Extended Vital Product Data flag */
3555 #define	CMDDT			2	/* Command Support Data - Obsolete */
3556 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VPD Pages Page Code */
3557 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3558 #define	INQUIRY_BDC_PAGE	0xB1	/* Block Device Characteristics Page */
3559 					/* Code */
3560 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3561 
3562 static int
3563 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3564 {
3565 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3566 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3567 	sata_drive_info_t *sdinfo;
3568 	struct scsi_extended_sense *sense;
3569 	int count;
3570 	uint8_t *p;
3571 	int i, j;
3572 	uint8_t page_buf[0xff]; /* Max length */
3573 	int rval, reason;
3574 	ushort_t rate;
3575 
3576 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3577 
3578 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3579 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3580 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3581 		return (rval);
3582 	}
3583 
3584 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3585 	    &spx->txlt_sata_pkt->satapkt_device);
3586 
3587 	ASSERT(sdinfo != NULL);
3588 
3589 	scsipkt->pkt_reason = CMD_CMPLT;
3590 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3591 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3592 
3593 	/* Reject not supported request */
3594 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3595 		*scsipkt->pkt_scbp = STATUS_CHECK;
3596 		sense = sata_arq_sense(spx);
3597 		sense->es_key = KEY_ILLEGAL_REQUEST;
3598 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3599 		goto done;
3600 	}
3601 
3602 	/* Valid Inquiry request */
3603 	*scsipkt->pkt_scbp = STATUS_GOOD;
3604 
3605 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3606 
3607 		/*
3608 		 * Because it is fully emulated command storing data
3609 		 * programatically in the specified buffer, release
3610 		 * preallocated DMA resources before storing data in the buffer,
3611 		 * so no unwanted DMA sync would take place.
3612 		 */
3613 		sata_scsi_dmafree(NULL, scsipkt);
3614 
3615 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3616 			/* Standard Inquiry Data request */
3617 			struct scsi_inquiry inq;
3618 			unsigned int bufsize;
3619 
3620 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3621 			    sdinfo, (uint8_t *)&inq);
3622 			/* Copy no more than requested */
3623 			count = MIN(bp->b_bcount,
3624 			    sizeof (struct scsi_inquiry));
3625 			bufsize = scsipkt->pkt_cdbp[4];
3626 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3627 			count = MIN(count, bufsize);
3628 			bcopy(&inq, bp->b_un.b_addr, count);
3629 
3630 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3631 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3632 			    bufsize - count : 0;
3633 		} else {
3634 			/*
3635 			 * peripheral_qualifier = 0;
3636 			 *
3637 			 * We are dealing only with HD and will be
3638 			 * dealing with CD/DVD devices soon
3639 			 */
3640 			uint8_t peripheral_device_type =
3641 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3642 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3643 
3644 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3645 			case INQUIRY_SUP_VPD_PAGE:
3646 				/*
3647 				 * Request for suported Vital Product Data
3648 				 * pages - assuming only 2 page codes
3649 				 * supported.
3650 				 */
3651 				page_buf[0] = peripheral_device_type;
3652 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3653 				page_buf[2] = 0;
3654 				page_buf[3] = 3; /* page length */
3655 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3656 				page_buf[5] = INQUIRY_USN_PAGE;
3657 				page_buf[6] = INQUIRY_BDC_PAGE;
3658 				/* Copy no more than requested */
3659 				count = MIN(bp->b_bcount, 7);
3660 				bcopy(page_buf, bp->b_un.b_addr, count);
3661 				break;
3662 
3663 			case INQUIRY_USN_PAGE:
3664 				/*
3665 				 * Request for Unit Serial Number page.
3666 				 * Set-up the page.
3667 				 */
3668 				page_buf[0] = peripheral_device_type;
3669 				page_buf[1] = INQUIRY_USN_PAGE;
3670 				page_buf[2] = 0;
3671 				/* remaining page length */
3672 				page_buf[3] = SATA_ID_SERIAL_LEN;
3673 
3674 				/*
3675 				 * Copy serial number from Identify Device data
3676 				 * words into the inquiry page and swap bytes
3677 				 * when necessary.
3678 				 */
3679 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3680 #ifdef	_LITTLE_ENDIAN
3681 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3682 #else
3683 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3684 #endif
3685 				/*
3686 				 * Least significant character of the serial
3687 				 * number shall appear as the last byte,
3688 				 * according to SBC-3 spec.
3689 				 * Count trailing spaces to determine the
3690 				 * necessary shift length.
3691 				 */
3692 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3693 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3694 					if (*(p - j) != '\0' &&
3695 					    *(p - j) != '\040')
3696 						break;
3697 				}
3698 
3699 				/*
3700 				 * Shift SN string right, so that the last
3701 				 * non-blank character would appear in last
3702 				 * byte of SN field in the page.
3703 				 * 'j' is the shift length.
3704 				 */
3705 				for (i = 0;
3706 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3707 				    i++, p--)
3708 					*p = *(p - j);
3709 
3710 				/*
3711 				 * Add leading spaces - same number as the
3712 				 * shift size
3713 				 */
3714 				for (; j > 0; j--)
3715 					page_buf[4 + j - 1] = '\040';
3716 
3717 				count = MIN(bp->b_bcount,
3718 				    SATA_ID_SERIAL_LEN + 4);
3719 				bcopy(page_buf, bp->b_un.b_addr, count);
3720 				break;
3721 
3722 			case INQUIRY_BDC_PAGE:
3723 				/*
3724 				 * Request for Block Device Characteristics
3725 				 * page.  Set-up the page.
3726 				 */
3727 				page_buf[0] = peripheral_device_type;
3728 				page_buf[1] = INQUIRY_BDC_PAGE;
3729 				page_buf[2] = 0;
3730 				/* remaining page length */
3731 				page_buf[3] = SATA_ID_BDC_LEN;
3732 
3733 				rate = sdinfo->satadrv_id.ai_medrotrate;
3734 				page_buf[4] = (rate >> 8) & 0xff;
3735 				page_buf[5] = rate & 0xff;
3736 				page_buf[6] = 0;
3737 				page_buf[7] = sdinfo->satadrv_id.
3738 				    ai_nomformfactor & 0xf;
3739 
3740 				count = MIN(bp->b_bcount,
3741 				    SATA_ID_BDC_LEN + 4);
3742 				bcopy(page_buf, bp->b_un.b_addr, count);
3743 				break;
3744 
3745 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3746 				/*
3747 				 * We may want to implement this page, when
3748 				 * identifiers are common for SATA devices
3749 				 * But not now.
3750 				 */
3751 				/*FALLTHROUGH*/
3752 
3753 			default:
3754 				/* Request for unsupported VPD page */
3755 				*scsipkt->pkt_scbp = STATUS_CHECK;
3756 				sense = sata_arq_sense(spx);
3757 				sense->es_key = KEY_ILLEGAL_REQUEST;
3758 				sense->es_add_code =
3759 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3760 				goto done;
3761 			}
3762 		}
3763 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3764 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3765 		    scsipkt->pkt_cdbp[4] - count : 0;
3766 	}
3767 done:
3768 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3769 
3770 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3771 	    "Scsi_pkt completion reason %x\n",
3772 	    scsipkt->pkt_reason);
3773 
3774 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3775 	    scsipkt->pkt_comp != NULL) {
3776 		/* scsi callback required */
3777 		if (servicing_interrupt()) {
3778 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3779 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3780 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3781 				return (TRAN_BUSY);
3782 			}
3783 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3784 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3785 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3786 			/* Scheduling the callback failed */
3787 			return (TRAN_BUSY);
3788 		}
3789 	}
3790 	return (TRAN_ACCEPT);
3791 }
3792 
3793 /*
3794  * SATA translate command: Request Sense.
3795  *
3796  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3797  * At the moment this is an emulated command (ATA version for SATA hard disks).
3798  * May be translated into Check Power Mode command in the future.
3799  *
3800  * Note: There is a mismatch between already implemented Informational
3801  * Exception Mode Select page 0x1C and this function.
3802  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3803  * NO SENSE and set additional sense code to the exception code - this is not
3804  * implemented here.
3805  */
3806 static int
3807 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3808 {
3809 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3810 	struct scsi_extended_sense sense;
3811 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3812 	sata_drive_info_t *sdinfo;
3813 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3814 	int rval, reason, power_state = 0;
3815 
3816 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3817 
3818 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3819 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3820 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3821 		return (rval);
3822 	}
3823 
3824 	scsipkt->pkt_reason = CMD_CMPLT;
3825 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3826 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3827 	*scsipkt->pkt_scbp = STATUS_GOOD;
3828 
3829 	/*
3830 	 * when CONTROL field's NACA bit == 1
3831 	 * return ILLEGAL_REQUEST
3832 	 */
3833 	if (scsipkt->pkt_cdbp[5] & CTL_BYTE_NACA_MASK) {
3834 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3835 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3836 		    SD_SCSI_ASC_CMD_SEQUENCE_ERR));
3837 	}
3838 
3839 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3840 	    &spx->txlt_sata_pkt->satapkt_device);
3841 	ASSERT(sdinfo != NULL);
3842 
3843 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3844 
3845 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3846 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3847 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3848 	if (sata_hba_start(spx, &rval) != 0) {
3849 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3850 		return (rval);
3851 	} else {
3852 		if (scmd->satacmd_error_reg != 0) {
3853 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3854 			return (sata_txlt_check_condition(spx, KEY_NO_SENSE,
3855 			    SD_SCSI_ASC_NO_ADD_SENSE));
3856 		}
3857 	}
3858 
3859 	switch (scmd->satacmd_sec_count_lsb) {
3860 	case SATA_PWRMODE_STANDBY: /* device in standby mode */
3861 		if (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)
3862 			power_state = SATA_POWER_STOPPED;
3863 		else {
3864 			power_state = SATA_POWER_STANDBY;
3865 			sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
3866 		}
3867 		break;
3868 	case SATA_PWRMODE_IDLE: /* device in idle mode */
3869 		power_state = SATA_POWER_IDLE;
3870 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
3871 		break;
3872 	case SATA_PWRMODE_ACTIVE: /* device in active or idle mode */
3873 	default:		  /* 0x40, 0x41 active mode */
3874 		if (sdinfo->satadrv_power_level == SATA_POWER_IDLE)
3875 			power_state = SATA_POWER_IDLE;
3876 		else {
3877 			power_state = SATA_POWER_ACTIVE;
3878 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3879 		}
3880 		break;
3881 	}
3882 
3883 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3884 
3885 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3886 		/*
3887 		 * Because it is fully emulated command storing data
3888 		 * programatically in the specified buffer, release
3889 		 * preallocated DMA resources before storing data in the buffer,
3890 		 * so no unwanted DMA sync would take place.
3891 		 */
3892 		int count = MIN(bp->b_bcount,
3893 		    sizeof (struct scsi_extended_sense));
3894 		sata_scsi_dmafree(NULL, scsipkt);
3895 		bzero(&sense, sizeof (struct scsi_extended_sense));
3896 		sense.es_valid = 0;	/* Valid LBA */
3897 		sense.es_class = 7;	/* Response code 0x70 - current err */
3898 		sense.es_key = KEY_NO_SENSE;
3899 		sense.es_add_len = 6;	/* Additional length */
3900 		/* Copy no more than requested */
3901 		bcopy(&sense, bp->b_un.b_addr, count);
3902 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3903 		scsipkt->pkt_resid = 0;
3904 		switch (power_state) {
3905 		case SATA_POWER_IDLE:
3906 		case SATA_POWER_STANDBY:
3907 			sense.es_add_code =
3908 			    SD_SCSI_ASC_LOW_POWER_CONDITION_ON;
3909 			break;
3910 		case SATA_POWER_STOPPED:
3911 			sense.es_add_code = SD_SCSI_ASC_NO_ADD_SENSE;
3912 			break;
3913 		case SATA_POWER_ACTIVE:
3914 		default:
3915 			break;
3916 		}
3917 	}
3918 
3919 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3920 	    "Scsi_pkt completion reason %x\n",
3921 	    scsipkt->pkt_reason);
3922 
3923 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3924 	    scsipkt->pkt_comp != NULL) {
3925 		/* scsi callback required */
3926 		if (servicing_interrupt()) {
3927 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3928 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3929 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3930 				return (TRAN_BUSY);
3931 			}
3932 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3933 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3934 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3935 			/* Scheduling the callback failed */
3936 			return (TRAN_BUSY);
3937 		}
3938 	}
3939 	return (TRAN_ACCEPT);
3940 }
3941 
3942 /*
3943  * SATA translate command: Test Unit Ready
3944  * (ATA version for SATA hard disks).
3945  * It is translated into the Check Power Mode command.
3946  *
3947  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3948  */
3949 static int
3950 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3951 {
3952 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3953 	struct scsi_extended_sense *sense;
3954 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3955 	sata_drive_info_t *sdinfo;
3956 	int power_state;
3957 	int rval, reason;
3958 
3959 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3960 
3961 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3962 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3963 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3964 		return (rval);
3965 	}
3966 
3967 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3968 	    &spx->txlt_sata_pkt->satapkt_device);
3969 	ASSERT(sdinfo != NULL);
3970 
3971 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3972 
3973 	/* send CHECK POWER MODE command */
3974 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3975 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3976 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3977 	if (sata_hba_start(spx, &rval) != 0) {
3978 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3979 		return (rval);
3980 	} else {
3981 		if (scmd->satacmd_error_reg != 0) {
3982 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3983 			return (sata_txlt_check_condition(spx, KEY_NOT_READY,
3984 			    SD_SCSI_ASC_LU_NOT_RESPONSE));
3985 		}
3986 	}
3987 
3988 	power_state = scmd->satacmd_sec_count_lsb;
3989 
3990 	/*
3991 	 * return NOT READY when device in STOPPED mode
3992 	 */
3993 	if (power_state == SATA_PWRMODE_STANDBY &&
3994 	    sdinfo->satadrv_power_level == SATA_POWER_STOPPED) {
3995 		*scsipkt->pkt_scbp = STATUS_CHECK;
3996 		sense = sata_arq_sense(spx);
3997 		sense->es_key = KEY_NOT_READY;
3998 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
3999 	} else {
4000 		/*
4001 		 * For other power mode, return GOOD status
4002 		 */
4003 		*scsipkt->pkt_scbp = STATUS_GOOD;
4004 	}
4005 
4006 	scsipkt->pkt_reason = CMD_CMPLT;
4007 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4008 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4009 
4010 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4011 
4012 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4013 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4014 
4015 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4016 	    scsipkt->pkt_comp != NULL) {
4017 		/* scsi callback required */
4018 		if (servicing_interrupt()) {
4019 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4020 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4021 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4022 				return (TRAN_BUSY);
4023 			}
4024 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4025 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4026 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4027 			/* Scheduling the callback failed */
4028 			return (TRAN_BUSY);
4029 		}
4030 	}
4031 
4032 	return (TRAN_ACCEPT);
4033 }
4034 
4035 /*
4036  * SATA translate command: Start Stop Unit
4037  * Translation depends on a command:
4038  *
4039  * Power condition bits will be supported
4040  * and the power level should be maintained by SATL,
4041  * When SATL received a command, it will check the
4042  * power level firstly, and return the status according
4043  * to SAT2 v2.6 and SAT-2 Standby Modifications
4044  *
4045  * SPC-4/SBC-3      SATL    ATA power condition  SATL      SPC/SBC
4046  * -----------------------------------------------------------------------
4047  * SSU_PC1 Active   <==>     ATA  Active         <==>     SSU:start_bit =1
4048  * SSU_PC2 Idle     <==>     ATA  Idle           <==>     N/A
4049  * SSU_PC3 Standby  <==>     ATA  Standby        <==>     N/A
4050  * SSU_PC4 Stopped  <==>     ATA  Standby        <==>     SSU:start_bit = 0
4051  *
4052  *	Unload Media / NOT SUPPORTED YET
4053  *	Load Media / NOT SUPPROTED YET
4054  *	Immediate bit / NOT SUPPORTED YET (deferred error)
4055  *
4056  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4057  * appropriate values in scsi_pkt fields.
4058  */
4059 static int
4060 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
4061 {
4062 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4063 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4064 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
4065 	int cport = SATA_TXLT_CPORT(spx);
4066 	int rval, reason;
4067 	sata_drive_info_t *sdinfo;
4068 	sata_id_t *sata_id;
4069 
4070 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4071 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
4072 
4073 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
4074 
4075 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4076 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4077 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4078 		return (rval);
4079 	}
4080 
4081 	if (scsipkt->pkt_cdbp[1] & START_STOP_IMMED_MASK) {
4082 		/* IMMED bit - not supported */
4083 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4084 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4085 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4086 	}
4087 
4088 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
4089 	spx->txlt_sata_pkt->satapkt_comp = NULL;
4090 
4091 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4092 	    &spx->txlt_sata_pkt->satapkt_device);
4093 	ASSERT(sdinfo != NULL);
4094 	sata_id = &sdinfo->satadrv_id;
4095 
4096 	switch ((scsipkt->pkt_cdbp[4] & START_STOP_POWER_COND_MASK) >> 4) {
4097 	case 0:
4098 		if (scsipkt->pkt_cdbp[4] & START_STOP_LOEJ_MASK) {
4099 			/* Load/Unload Media - invalid request */
4100 			goto err_out;
4101 		}
4102 		if (scsipkt->pkt_cdbp[4] & START_STOP_START_MASK) {
4103 			/* Start Unit */
4104 			sata_build_read_verify_cmd(scmd, 1, 5);
4105 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4106 			/* Transfer command to HBA */
4107 			if (sata_hba_start(spx, &rval) != 0) {
4108 				/* Pkt not accepted for execution */
4109 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4110 				return (rval);
4111 			} else {
4112 				if (scmd->satacmd_error_reg != 0) {
4113 					goto err_out;
4114 				}
4115 			}
4116 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4117 		} else {
4118 			/* Stop Unit */
4119 			sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4120 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4121 			if (sata_hba_start(spx, &rval) != 0) {
4122 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4123 				return (rval);
4124 			} else {
4125 				if (scmd->satacmd_error_reg != 0) {
4126 					goto err_out;
4127 				}
4128 			}
4129 			/* ata standby immediate command */
4130 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4131 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4132 			if (sata_hba_start(spx, &rval) != 0) {
4133 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4134 				return (rval);
4135 			} else {
4136 				if (scmd->satacmd_error_reg != 0) {
4137 					goto err_out;
4138 				}
4139 			}
4140 			sdinfo->satadrv_power_level = SATA_POWER_STOPPED;
4141 		}
4142 		break;
4143 	case 0x1:
4144 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4145 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4146 		if (sata_hba_start(spx, &rval) != 0) {
4147 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4148 			return (rval);
4149 		} else {
4150 			if (scmd->satacmd_error_reg != 0) {
4151 				goto err_out;
4152 			}
4153 		}
4154 		sata_build_read_verify_cmd(scmd, 1, 5);
4155 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4156 		/* Transfer command to HBA */
4157 		if (sata_hba_start(spx, &rval) != 0) {
4158 			/* Pkt not accepted for execution */
4159 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4160 			return (rval);
4161 		} else {
4162 			if (scmd->satacmd_error_reg != 0) {
4163 				goto err_out;
4164 			}
4165 		}
4166 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4167 		break;
4168 	case 0x2:
4169 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4170 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4171 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4172 			if (sata_hba_start(spx, &rval) != 0) {
4173 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4174 				return (rval);
4175 			} else {
4176 				if (scmd->satacmd_error_reg != 0) {
4177 					goto err_out;
4178 				}
4179 			}
4180 		}
4181 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4182 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4183 		if (sata_hba_start(spx, &rval) != 0) {
4184 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4185 			return (rval);
4186 		} else {
4187 			if (scmd->satacmd_error_reg != 0) {
4188 				goto err_out;
4189 			}
4190 		}
4191 		if ((scsipkt->pkt_cdbp[3] & START_STOP_MODIFIER_MASK)) {
4192 			/*
4193 			 *  POWER CONDITION MODIFIER bit set
4194 			 *  to 0x1 or larger it will be handled
4195 			 *  on the same way as bit = 0x1
4196 			 */
4197 			if (!(sata_id->ai_cmdset84 &
4198 			    SATA_IDLE_UNLOAD_SUPPORTED)) {
4199 				sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4200 				break;
4201 			}
4202 			sata_build_generic_cmd(scmd, SATAC_IDLE_IM);
4203 			scmd->satacmd_features_reg = 0x44;
4204 			scmd->satacmd_lba_low_lsb = 0x4c;
4205 			scmd->satacmd_lba_mid_lsb = 0x4e;
4206 			scmd->satacmd_lba_high_lsb = 0x55;
4207 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4208 			if (sata_hba_start(spx, &rval) != 0) {
4209 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4210 				return (rval);
4211 			} else {
4212 				if (scmd->satacmd_error_reg != 0) {
4213 					goto err_out;
4214 				}
4215 			}
4216 		}
4217 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4218 		break;
4219 	case 0x3:
4220 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4221 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4222 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4223 			if (sata_hba_start(spx, &rval) != 0) {
4224 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4225 				return (rval);
4226 			} else {
4227 				if (scmd->satacmd_error_reg != 0) {
4228 					goto err_out;
4229 				}
4230 			}
4231 		}
4232 		sata_build_generic_cmd(scmd, SATAC_STANDBY);
4233 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4234 		if (sata_hba_start(spx, &rval) != 0) {
4235 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4236 			return (rval);
4237 		} else {
4238 			if (scmd->satacmd_error_reg != 0) {
4239 				goto err_out;
4240 			}
4241 		}
4242 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4243 		break;
4244 	case 0x7:
4245 		sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4246 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4247 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4248 		if (sata_hba_start(spx, &rval) != 0) {
4249 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4250 			return (rval);
4251 		} else {
4252 			if (scmd->satacmd_error_reg != 0) {
4253 				goto err_out;
4254 			}
4255 		}
4256 		switch (scmd->satacmd_sec_count_lsb) {
4257 		case SATA_PWRMODE_STANDBY:
4258 			sata_build_generic_cmd(scmd, SATAC_STANDBY);
4259 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4260 			    sdinfo->satadrv_standby_timer);
4261 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4262 			if (sata_hba_start(spx, &rval) != 0) {
4263 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4264 				return (rval);
4265 			} else {
4266 				if (scmd->satacmd_error_reg != 0) {
4267 					goto err_out;
4268 				}
4269 			}
4270 			break;
4271 		case SATA_PWRMODE_IDLE:
4272 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4273 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4274 			    sdinfo->satadrv_standby_timer);
4275 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4276 			if (sata_hba_start(spx, &rval) != 0) {
4277 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4278 				return (rval);
4279 			} else {
4280 				if (scmd->satacmd_error_reg != 0) {
4281 					goto err_out;
4282 				}
4283 			}
4284 			break;
4285 		case SATA_PWRMODE_ACTIVE_SPINDOWN:
4286 		case SATA_PWRMODE_ACTIVE_SPINUP:
4287 		case SATA_PWRMODE_ACTIVE:
4288 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4289 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4290 			    sdinfo->satadrv_standby_timer);
4291 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4292 			if (sata_hba_start(spx, &rval) != 0) {
4293 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4294 				return (rval);
4295 			} else {
4296 				if (scmd->satacmd_error_reg != 0) {
4297 					goto err_out;
4298 				}
4299 			}
4300 			sata_build_read_verify_cmd(scmd, 1, 5);
4301 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4302 			if (sata_hba_start(spx, &rval) != 0) {
4303 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4304 				return (rval);
4305 			} else {
4306 				if (scmd->satacmd_error_reg != 0) {
4307 					goto err_out;
4308 				}
4309 			}
4310 			break;
4311 		default:
4312 			goto err_out;
4313 		}
4314 		break;
4315 	case 0xb:
4316 		if ((sata_get_standby_timer(sdinfo->satadrv_standby_timer) ==
4317 		    0) || (!(sata_id->ai_cap & SATA_STANDBYTIMER))) {
4318 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4319 			return (sata_txlt_check_condition(spx,
4320 			    KEY_ILLEGAL_REQUEST,
4321 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4322 		}
4323 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4324 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4325 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4326 			if (sata_hba_start(spx, &rval) != 0) {
4327 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4328 				return (rval);
4329 			} else {
4330 				if (scmd->satacmd_error_reg != 0) {
4331 					goto err_out;
4332 				}
4333 			}
4334 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4335 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4336 			if (sata_hba_start(spx, &rval) != 0) {
4337 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4338 				return (rval);
4339 			} else {
4340 				if (scmd->satacmd_error_reg != 0) {
4341 					goto err_out;
4342 				}
4343 			}
4344 		}
4345 		bzero(sdinfo->satadrv_standby_timer, sizeof (uchar_t) * 4);
4346 		break;
4347 	default:
4348 err_out:
4349 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4350 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4351 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4352 	}
4353 
4354 	/*
4355 	 * Since it was a synchronous command,
4356 	 * a callback function will be called directly.
4357 	 */
4358 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4359 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4360 	    "synchronous execution status %x\n",
4361 	    spx->txlt_sata_pkt->satapkt_reason);
4362 
4363 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4364 	    scsipkt->pkt_comp != NULL) {
4365 		sata_set_arq_data(spx->txlt_sata_pkt);
4366 		if (servicing_interrupt()) {
4367 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4368 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4369 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4370 				return (TRAN_BUSY);
4371 			}
4372 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4373 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4374 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4375 			/* Scheduling the callback failed */
4376 			return (TRAN_BUSY);
4377 		}
4378 	}
4379 	else
4380 
4381 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
4382 
4383 	return (TRAN_ACCEPT);
4384 
4385 }
4386 
4387 /*
4388  * SATA translate command:  Read Capacity.
4389  * Emulated command for SATA disks.
4390  * Capacity is retrieved from cached Idenifty Device data.
4391  * Identify Device data shows effective disk capacity, not the native
4392  * capacity, which may be limitted by Set Max Address command.
4393  * This is ATA version for SATA hard disks.
4394  *
4395  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4396  */
4397 static int
4398 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
4399 {
4400 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4401 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4402 	sata_drive_info_t *sdinfo;
4403 	uint64_t val;
4404 	uchar_t *rbuf;
4405 	int rval, reason;
4406 
4407 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4408 	    "sata_txlt_read_capacity: ", NULL);
4409 
4410 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4411 
4412 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4413 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4414 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4415 		return (rval);
4416 	}
4417 
4418 	scsipkt->pkt_reason = CMD_CMPLT;
4419 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4420 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4421 	*scsipkt->pkt_scbp = STATUS_GOOD;
4422 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4423 		/*
4424 		 * Because it is fully emulated command storing data
4425 		 * programatically in the specified buffer, release
4426 		 * preallocated DMA resources before storing data in the buffer,
4427 		 * so no unwanted DMA sync would take place.
4428 		 */
4429 		sata_scsi_dmafree(NULL, scsipkt);
4430 
4431 		sdinfo = sata_get_device_info(
4432 		    spx->txlt_sata_hba_inst,
4433 		    &spx->txlt_sata_pkt->satapkt_device);
4434 
4435 		/*
4436 		 * As per SBC-3, the "returned LBA" is either the highest
4437 		 * addressable LBA or 0xffffffff, whichever is smaller.
4438 		 */
4439 		val = MIN(sdinfo->satadrv_capacity - 1, UINT32_MAX);
4440 
4441 		rbuf = (uchar_t *)bp->b_un.b_addr;
4442 		/* Need to swap endians to match scsi format */
4443 		rbuf[0] = (val >> 24) & 0xff;
4444 		rbuf[1] = (val >> 16) & 0xff;
4445 		rbuf[2] = (val >> 8) & 0xff;
4446 		rbuf[3] = val & 0xff;
4447 		/* block size - always 512 bytes, for now */
4448 		rbuf[4] = 0;
4449 		rbuf[5] = 0;
4450 		rbuf[6] = 0x02;
4451 		rbuf[7] = 0;
4452 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4453 		scsipkt->pkt_resid = 0;
4454 
4455 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
4456 		    sdinfo->satadrv_capacity -1);
4457 	}
4458 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4459 	/*
4460 	 * If a callback was requested, do it now.
4461 	 */
4462 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4463 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4464 
4465 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4466 	    scsipkt->pkt_comp != NULL) {
4467 		/* scsi callback required */
4468 		if (servicing_interrupt()) {
4469 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4470 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4471 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4472 				return (TRAN_BUSY);
4473 			}
4474 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4475 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4476 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4477 			/* Scheduling the callback failed */
4478 			return (TRAN_BUSY);
4479 		}
4480 	}
4481 
4482 	return (TRAN_ACCEPT);
4483 }
4484 
4485 /*
4486  * SATA translate command:  Read Capacity (16).
4487  * Emulated command for SATA disks.
4488  * Info is retrieved from cached Identify Device data.
4489  * Implemented to SBC-3 (draft 21) and SAT-2 (final) specifications.
4490  *
4491  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4492  */
4493 static int
4494 sata_txlt_read_capacity16(sata_pkt_txlate_t *spx)
4495 {
4496 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4497 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4498 	sata_drive_info_t *sdinfo;
4499 	uint64_t val;
4500 	uint16_t l2p_exp;
4501 	uchar_t *rbuf;
4502 	int rval, reason;
4503 
4504 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4505 	    "sata_txlt_read_capacity: ", NULL);
4506 
4507 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4508 
4509 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4510 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4511 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4512 		return (rval);
4513 	}
4514 
4515 	scsipkt->pkt_reason = CMD_CMPLT;
4516 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4517 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4518 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4519 		/*
4520 		 * Because it is fully emulated command storing data
4521 		 * programatically in the specified buffer, release
4522 		 * preallocated DMA resources before storing data in the buffer,
4523 		 * so no unwanted DMA sync would take place.
4524 		 */
4525 		sata_scsi_dmafree(NULL, scsipkt);
4526 
4527 		/* Check SERVICE ACTION field */
4528 		if ((scsipkt->pkt_cdbp[1] & 0x1f) !=
4529 		    SSVC_ACTION_READ_CAPACITY_G4) {
4530 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4531 			return (sata_txlt_check_condition(spx,
4532 			    KEY_ILLEGAL_REQUEST,
4533 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4534 		}
4535 
4536 		/* Check LBA field */
4537 		if ((scsipkt->pkt_cdbp[2] != 0) ||
4538 		    (scsipkt->pkt_cdbp[3] != 0) ||
4539 		    (scsipkt->pkt_cdbp[4] != 0) ||
4540 		    (scsipkt->pkt_cdbp[5] != 0) ||
4541 		    (scsipkt->pkt_cdbp[6] != 0) ||
4542 		    (scsipkt->pkt_cdbp[7] != 0) ||
4543 		    (scsipkt->pkt_cdbp[8] != 0) ||
4544 		    (scsipkt->pkt_cdbp[9] != 0)) {
4545 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4546 			return (sata_txlt_check_condition(spx,
4547 			    KEY_ILLEGAL_REQUEST,
4548 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4549 		}
4550 
4551 		/* Check PMI bit */
4552 		if (scsipkt->pkt_cdbp[14] & 0x1) {
4553 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4554 			return (sata_txlt_check_condition(spx,
4555 			    KEY_ILLEGAL_REQUEST,
4556 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4557 		}
4558 
4559 		*scsipkt->pkt_scbp = STATUS_GOOD;
4560 
4561 		sdinfo = sata_get_device_info(
4562 		    spx->txlt_sata_hba_inst,
4563 		    &spx->txlt_sata_pkt->satapkt_device);
4564 
4565 		/* last logical block address */
4566 		val = MIN(sdinfo->satadrv_capacity - 1,
4567 		    SCSI_READ_CAPACITY16_MAX_LBA);
4568 
4569 		/* logical to physical block size exponent */
4570 		l2p_exp = 0;
4571 		if (sdinfo->satadrv_id.ai_phys_sect_sz & SATA_L2PS_CHECK_BIT) {
4572 			/* physical/logical sector size word is valid */
4573 
4574 			if (sdinfo->satadrv_id.ai_phys_sect_sz &
4575 			    SATA_L2PS_HAS_MULT) {
4576 				/* multiple logical sectors per phys sectors */
4577 				l2p_exp =
4578 				    sdinfo->satadrv_id.ai_phys_sect_sz &
4579 				    SATA_L2PS_EXP_MASK;
4580 			}
4581 		}
4582 
4583 		rbuf = (uchar_t *)bp->b_un.b_addr;
4584 		bzero(rbuf, bp->b_bcount);
4585 
4586 		/* returned logical block address */
4587 		rbuf[0] = (val >> 56) & 0xff;
4588 		rbuf[1] = (val >> 48) & 0xff;
4589 		rbuf[2] = (val >> 40) & 0xff;
4590 		rbuf[3] = (val >> 32) & 0xff;
4591 		rbuf[4] = (val >> 24) & 0xff;
4592 		rbuf[5] = (val >> 16) & 0xff;
4593 		rbuf[6] = (val >> 8) & 0xff;
4594 		rbuf[7] = val & 0xff;
4595 
4596 		/* logical block length in bytes = 512 (for now) */
4597 		/* rbuf[8] = 0; */
4598 		/* rbuf[9] = 0; */
4599 		rbuf[10] = 0x02;
4600 		/* rbuf[11] = 0; */
4601 
4602 		/* p_type, prot_en, unspecified by SAT-2 */
4603 		/* rbuf[12] = 0; */
4604 
4605 		/* p_i_exponent, undefined by SAT-2 */
4606 		/* logical blocks per physical block exponent */
4607 		rbuf[13] = l2p_exp;
4608 
4609 		/* tpe, tprz, undefined by SAT-2 */
4610 		/* lowest aligned logical block address = 0 (for now) */
4611 		/* rbuf[14] = 0; */
4612 		/* rbuf[15] = 0; */
4613 
4614 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4615 		scsipkt->pkt_resid = 0;
4616 
4617 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%llu\n",
4618 		    sdinfo->satadrv_capacity -1);
4619 	}
4620 
4621 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4622 
4623 	/*
4624 	 * If a callback was requested, do it now.
4625 	 */
4626 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4627 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4628 
4629 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4630 	    scsipkt->pkt_comp != NULL) {
4631 		/* scsi callback required */
4632 		if (servicing_interrupt()) {
4633 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4634 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4635 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4636 				return (TRAN_BUSY);
4637 			}
4638 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4639 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4640 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4641 			/* Scheduling the callback failed */
4642 			return (TRAN_BUSY);
4643 		}
4644 	}
4645 
4646 	return (TRAN_ACCEPT);
4647 }
4648 
4649 /*
4650  * SATA translate command: Mode Sense.
4651  * Translated into appropriate SATA command or emulated.
4652  * Saved Values Page Control (03) are not supported.
4653  *
4654  * NOTE: only caching mode sense page is currently implemented.
4655  *
4656  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4657  */
4658 
4659 #define	LLBAA	0x10	/* Long LBA Accepted */
4660 
4661 static int
4662 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4663 {
4664 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4665 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4666 	sata_drive_info_t *sdinfo;
4667 	sata_id_t *sata_id;
4668 	struct scsi_extended_sense *sense;
4669 	int 		len, bdlen, count, alc_len;
4670 	int		pc;	/* Page Control code */
4671 	uint8_t		*buf;	/* mode sense buffer */
4672 	int		rval, reason;
4673 
4674 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4675 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
4676 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4677 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4678 
4679 	if (servicing_interrupt()) {
4680 		buf = kmem_zalloc(1024, KM_NOSLEEP);
4681 		if (buf == NULL) {
4682 			return (TRAN_BUSY);
4683 		}
4684 	} else {
4685 		buf = kmem_zalloc(1024, KM_SLEEP);
4686 	}
4687 
4688 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4689 
4690 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4691 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4692 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4693 		kmem_free(buf, 1024);
4694 		return (rval);
4695 	}
4696 
4697 	scsipkt->pkt_reason = CMD_CMPLT;
4698 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4699 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4700 
4701 	pc = scsipkt->pkt_cdbp[2] >> 6;
4702 
4703 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4704 		/*
4705 		 * Because it is fully emulated command storing data
4706 		 * programatically in the specified buffer, release
4707 		 * preallocated DMA resources before storing data in the buffer,
4708 		 * so no unwanted DMA sync would take place.
4709 		 */
4710 		sata_scsi_dmafree(NULL, scsipkt);
4711 
4712 		len = 0;
4713 		bdlen = 0;
4714 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
4715 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
4716 			    (scsipkt->pkt_cdbp[1] & LLBAA))
4717 				bdlen = 16;
4718 			else
4719 				bdlen = 8;
4720 		}
4721 		/* Build mode parameter header */
4722 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4723 			/* 4-byte mode parameter header */
4724 			buf[len++] = 0;		/* mode data length */
4725 			buf[len++] = 0;		/* medium type */
4726 			buf[len++] = 0;		/* dev-specific param */
4727 			buf[len++] = bdlen;	/* Block Descriptor length */
4728 		} else {
4729 			/* 8-byte mode parameter header */
4730 			buf[len++] = 0;		/* mode data length */
4731 			buf[len++] = 0;
4732 			buf[len++] = 0;		/* medium type */
4733 			buf[len++] = 0;		/* dev-specific param */
4734 			if (bdlen == 16)
4735 				buf[len++] = 1;	/* long lba descriptor */
4736 			else
4737 				buf[len++] = 0;
4738 			buf[len++] = 0;
4739 			buf[len++] = 0;		/* Block Descriptor length */
4740 			buf[len++] = bdlen;
4741 		}
4742 
4743 		sdinfo = sata_get_device_info(
4744 		    spx->txlt_sata_hba_inst,
4745 		    &spx->txlt_sata_pkt->satapkt_device);
4746 
4747 		/* Build block descriptor only if not disabled (DBD) */
4748 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
4749 			/* Block descriptor - direct-access device format */
4750 			if (bdlen == 8) {
4751 				/* build regular block descriptor */
4752 				buf[len++] =
4753 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4754 				buf[len++] =
4755 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4756 				buf[len++] =
4757 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4758 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4759 				buf[len++] = 0; /* density code */
4760 				buf[len++] = 0;
4761 				if (sdinfo->satadrv_type ==
4762 				    SATA_DTYPE_ATADISK)
4763 					buf[len++] = 2;
4764 				else
4765 					/* ATAPI */
4766 					buf[len++] = 8;
4767 				buf[len++] = 0;
4768 			} else if (bdlen == 16) {
4769 				/* Long LBA Accepted */
4770 				/* build long lba block descriptor */
4771 #ifndef __lock_lint
4772 				buf[len++] =
4773 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
4774 				buf[len++] =
4775 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
4776 				buf[len++] =
4777 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
4778 				buf[len++] =
4779 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
4780 #endif
4781 				buf[len++] =
4782 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4783 				buf[len++] =
4784 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4785 				buf[len++] =
4786 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4787 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4788 				buf[len++] = 0;
4789 				buf[len++] = 0; /* density code */
4790 				buf[len++] = 0;
4791 				buf[len++] = 0;
4792 				if (sdinfo->satadrv_type ==
4793 				    SATA_DTYPE_ATADISK)
4794 					buf[len++] = 2;
4795 				else
4796 					/* ATAPI */
4797 					buf[len++] = 8;
4798 				buf[len++] = 0;
4799 			}
4800 		}
4801 
4802 		sata_id = &sdinfo->satadrv_id;
4803 
4804 		/*
4805 		 * Add requested pages.
4806 		 * Page 3 and 4 are obsolete and we are not supporting them.
4807 		 * We deal now with:
4808 		 * caching (read/write cache control).
4809 		 * We should eventually deal with following mode pages:
4810 		 * error recovery  (0x01),
4811 		 * power condition (0x1a),
4812 		 * exception control page (enables SMART) (0x1c),
4813 		 * enclosure management (ses),
4814 		 * protocol-specific port mode (port control).
4815 		 */
4816 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
4817 		case MODEPAGE_RW_ERRRECOV:
4818 			/* DAD_MODE_ERR_RECOV */
4819 			/* R/W recovery */
4820 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4821 			break;
4822 		case MODEPAGE_CACHING:
4823 			/* DAD_MODE_CACHE */
4824 			/* Reject not supported request for saved parameters */
4825 			if (pc == 3) {
4826 				*scsipkt->pkt_scbp = STATUS_CHECK;
4827 				sense = sata_arq_sense(spx);
4828 				sense->es_key = KEY_ILLEGAL_REQUEST;
4829 				sense->es_add_code =
4830 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
4831 				goto done;
4832 			}
4833 
4834 			/* caching */
4835 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4836 			break;
4837 		case MODEPAGE_INFO_EXCPT:
4838 			/* exception cntrl */
4839 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4840 				len += sata_build_msense_page_1c(sdinfo, pc,
4841 				    buf+len);
4842 			}
4843 			else
4844 				goto err;
4845 			break;
4846 		case MODEPAGE_POWER_COND:
4847 			/* DAD_MODE_POWER_COND */
4848 			/* power condition */
4849 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4850 			break;
4851 
4852 		case MODEPAGE_ACOUSTIC_MANAG:
4853 			/* acoustic management */
4854 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4855 			break;
4856 		case MODEPAGE_ALLPAGES:
4857 			/* all pages */
4858 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4859 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4860 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4861 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4862 				len += sata_build_msense_page_1c(sdinfo, pc,
4863 				    buf+len);
4864 			}
4865 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4866 			break;
4867 		default:
4868 		err:
4869 			/* Invalid request */
4870 			*scsipkt->pkt_scbp = STATUS_CHECK;
4871 			sense = sata_arq_sense(spx);
4872 			sense->es_key = KEY_ILLEGAL_REQUEST;
4873 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4874 			goto done;
4875 		}
4876 
4877 		/* fix total mode data length */
4878 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4879 			/* 4-byte mode parameter header */
4880 			buf[0] = len - 1;	/* mode data length */
4881 		} else {
4882 			buf[0] = (len -2) >> 8;
4883 			buf[1] = (len -2) & 0xff;
4884 		}
4885 
4886 
4887 		/* Check allocation length */
4888 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4889 			alc_len = scsipkt->pkt_cdbp[4];
4890 		} else {
4891 			alc_len = scsipkt->pkt_cdbp[7];
4892 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4893 		}
4894 		/*
4895 		 * We do not check for possible parameters truncation
4896 		 * (alc_len < len) assuming that the target driver works
4897 		 * correctly. Just avoiding overrun.
4898 		 * Copy no more than requested and possible, buffer-wise.
4899 		 */
4900 		count = MIN(alc_len, len);
4901 		count = MIN(bp->b_bcount, count);
4902 		bcopy(buf, bp->b_un.b_addr, count);
4903 
4904 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4905 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4906 	}
4907 	*scsipkt->pkt_scbp = STATUS_GOOD;
4908 done:
4909 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4910 	(void) kmem_free(buf, 1024);
4911 
4912 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4913 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4914 
4915 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4916 	    scsipkt->pkt_comp != NULL) {
4917 		/* scsi callback required */
4918 		if (servicing_interrupt()) {
4919 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4920 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4921 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4922 				return (TRAN_BUSY);
4923 			}
4924 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4925 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4926 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4927 			/* Scheduling the callback failed */
4928 			return (TRAN_BUSY);
4929 		}
4930 	}
4931 
4932 	return (TRAN_ACCEPT);
4933 }
4934 
4935 
4936 /*
4937  * SATA translate command: Mode Select.
4938  * Translated into appropriate SATA command or emulated.
4939  * Saving parameters is not supported.
4940  * Changing device capacity is not supported (although theoretically
4941  * possible by executing SET FEATURES/SET MAX ADDRESS)
4942  *
4943  * Assumption is that the target driver is working correctly.
4944  *
4945  * More than one SATA command may be executed to perform operations specified
4946  * by mode select pages. The first error terminates further execution.
4947  * Operations performed successully are not backed-up in such case.
4948  *
4949  * NOTE: Implemented pages:
4950  * - caching page
4951  * - informational exception page
4952  * - acoustic management page
4953  * - power condition page
4954  * Caching setup is remembered so it could be re-stored in case of
4955  * an unexpected device reset.
4956  *
4957  * Returns TRAN_XXXX.
4958  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
4959  */
4960 
4961 static int
4962 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
4963 {
4964 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4965 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4966 	struct scsi_extended_sense *sense;
4967 	int len, pagelen, count, pllen;
4968 	uint8_t *buf;	/* mode select buffer */
4969 	int rval, stat, reason;
4970 	uint_t nointr_flag;
4971 	int dmod = 0;
4972 
4973 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4974 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
4975 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4976 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4977 
4978 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4979 
4980 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4981 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4982 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4983 		return (rval);
4984 	}
4985 
4986 	rval = TRAN_ACCEPT;
4987 
4988 	scsipkt->pkt_reason = CMD_CMPLT;
4989 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4990 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4991 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
4992 
4993 	/* Reject not supported request */
4994 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
4995 		*scsipkt->pkt_scbp = STATUS_CHECK;
4996 		sense = sata_arq_sense(spx);
4997 		sense->es_key = KEY_ILLEGAL_REQUEST;
4998 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4999 		goto done;
5000 	}
5001 
5002 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
5003 		pllen = scsipkt->pkt_cdbp[4];
5004 	} else {
5005 		pllen = scsipkt->pkt_cdbp[7];
5006 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
5007 	}
5008 
5009 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
5010 
5011 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
5012 		buf = (uint8_t *)bp->b_un.b_addr;
5013 		count = MIN(bp->b_bcount, pllen);
5014 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5015 		scsipkt->pkt_resid = 0;
5016 		pllen = count;
5017 
5018 		/*
5019 		 * Check the header to skip the block descriptor(s) - we
5020 		 * do not support setting device capacity.
5021 		 * Existing macros do not recognize long LBA dscriptor,
5022 		 * hence manual calculation.
5023 		 */
5024 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
5025 			/* 6-bytes CMD, 4 bytes header */
5026 			if (count <= 4)
5027 				goto done;		/* header only */
5028 			len = buf[3] + 4;
5029 		} else {
5030 			/* 10-bytes CMD, 8 bytes header */
5031 			if (count <= 8)
5032 				goto done;		/* header only */
5033 			len = buf[6];
5034 			len = (len << 8) + buf[7] + 8;
5035 		}
5036 		if (len >= count)
5037 			goto done;	/* header + descriptor(s) only */
5038 
5039 		pllen -= len;		/* remaining data length */
5040 
5041 		/*
5042 		 * We may be executing SATA command and want to execute it
5043 		 * in SYNCH mode, regardless of scsi_pkt setting.
5044 		 * Save scsi_pkt setting and indicate SYNCH mode
5045 		 */
5046 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5047 		    scsipkt->pkt_comp != NULL) {
5048 			scsipkt->pkt_flags |= FLAG_NOINTR;
5049 		}
5050 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
5051 
5052 		/*
5053 		 * len is now the offset to a first mode select page
5054 		 * Process all pages
5055 		 */
5056 		while (pllen > 0) {
5057 			switch ((int)buf[len]) {
5058 			case MODEPAGE_CACHING:
5059 				/* No support for SP (saving) */
5060 				if (scsipkt->pkt_cdbp[1] & 0x01) {
5061 					*scsipkt->pkt_scbp = STATUS_CHECK;
5062 					sense = sata_arq_sense(spx);
5063 					sense->es_key = KEY_ILLEGAL_REQUEST;
5064 					sense->es_add_code =
5065 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5066 					goto done;
5067 				}
5068 				stat = sata_mode_select_page_8(spx,
5069 				    (struct mode_cache_scsi3 *)&buf[len],
5070 				    pllen, &pagelen, &rval, &dmod);
5071 				/*
5072 				 * The pagelen value indicates the number of
5073 				 * parameter bytes already processed.
5074 				 * The rval is the return value from
5075 				 * sata_tran_start().
5076 				 * The stat indicates the overall status of
5077 				 * the operation(s).
5078 				 */
5079 				if (stat != SATA_SUCCESS)
5080 					/*
5081 					 * Page processing did not succeed -
5082 					 * all error info is already set-up,
5083 					 * just return
5084 					 */
5085 					pllen = 0; /* this breaks the loop */
5086 				else {
5087 					len += pagelen;
5088 					pllen -= pagelen;
5089 				}
5090 				break;
5091 
5092 			case MODEPAGE_INFO_EXCPT:
5093 				stat = sata_mode_select_page_1c(spx,
5094 				    (struct mode_info_excpt_page *)&buf[len],
5095 				    pllen, &pagelen, &rval, &dmod);
5096 				/*
5097 				 * The pagelen value indicates the number of
5098 				 * parameter bytes already processed.
5099 				 * The rval is the return value from
5100 				 * sata_tran_start().
5101 				 * The stat indicates the overall status of
5102 				 * the operation(s).
5103 				 */
5104 				if (stat != SATA_SUCCESS)
5105 					/*
5106 					 * Page processing did not succeed -
5107 					 * all error info is already set-up,
5108 					 * just return
5109 					 */
5110 					pllen = 0; /* this breaks the loop */
5111 				else {
5112 					len += pagelen;
5113 					pllen -= pagelen;
5114 				}
5115 				break;
5116 
5117 			case MODEPAGE_ACOUSTIC_MANAG:
5118 				stat = sata_mode_select_page_30(spx,
5119 				    (struct mode_acoustic_management *)
5120 				    &buf[len], pllen, &pagelen, &rval, &dmod);
5121 				/*
5122 				 * The pagelen value indicates the number of
5123 				 * parameter bytes already processed.
5124 				 * The rval is the return value from
5125 				 * sata_tran_start().
5126 				 * The stat indicates the overall status of
5127 				 * the operation(s).
5128 				 */
5129 				if (stat != SATA_SUCCESS)
5130 					/*
5131 					 * Page processing did not succeed -
5132 					 * all error info is already set-up,
5133 					 * just return
5134 					 */
5135 					pllen = 0; /* this breaks the loop */
5136 				else {
5137 					len += pagelen;
5138 					pllen -= pagelen;
5139 				}
5140 
5141 				break;
5142 			case MODEPAGE_POWER_COND:
5143 				stat = sata_mode_select_page_1a(spx,
5144 				    (struct mode_info_power_cond *)&buf[len],
5145 				    pllen, &pagelen, &rval, &dmod);
5146 				/*
5147 				 * The pagelen value indicates the number of
5148 				 * parameter bytes already processed.
5149 				 * The rval is the return value from
5150 				 * sata_tran_start().
5151 				 * The stat indicates the overall status of
5152 				 * the operation(s).
5153 				 */
5154 				if (stat != SATA_SUCCESS)
5155 					/*
5156 					 * Page processing did not succeed -
5157 					 * all error info is already set-up,
5158 					 * just return
5159 					 */
5160 					pllen = 0; /* this breaks the loop */
5161 				else {
5162 					len += pagelen;
5163 					pllen -= pagelen;
5164 				}
5165 				break;
5166 			default:
5167 				*scsipkt->pkt_scbp = STATUS_CHECK;
5168 				sense = sata_arq_sense(spx);
5169 				sense->es_key = KEY_ILLEGAL_REQUEST;
5170 				sense->es_add_code =
5171 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
5172 				goto done;
5173 			}
5174 		}
5175 	}
5176 done:
5177 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5178 	/*
5179 	 * If device parameters were modified, fetch and store the new
5180 	 * Identify Device data. Since port mutex could have been released
5181 	 * for accessing HBA driver, we need to re-check device existence.
5182 	 */
5183 	if (dmod != 0) {
5184 		sata_drive_info_t new_sdinfo, *sdinfo;
5185 		int rv = 0;
5186 
5187 		/*
5188 		 * Following statement has to be changed if this function is
5189 		 * used for devices other than SATA hard disks.
5190 		 */
5191 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
5192 
5193 		new_sdinfo.satadrv_addr =
5194 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
5195 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
5196 		    &new_sdinfo);
5197 
5198 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5199 		/*
5200 		 * Since port mutex could have been released when
5201 		 * accessing HBA driver, we need to re-check that the
5202 		 * framework still holds the device info structure.
5203 		 */
5204 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5205 		    &spx->txlt_sata_pkt->satapkt_device);
5206 		if (sdinfo != NULL) {
5207 			/*
5208 			 * Device still has info structure in the
5209 			 * sata framework. Copy newly fetched info
5210 			 */
5211 			if (rv == 0) {
5212 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
5213 				sata_save_drive_settings(sdinfo);
5214 			} else {
5215 				/*
5216 				 * Could not fetch new data - invalidate
5217 				 * sata_drive_info. That makes device
5218 				 * unusable.
5219 				 */
5220 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
5221 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
5222 			}
5223 		}
5224 		if (rv != 0 || sdinfo == NULL) {
5225 			/*
5226 			 * This changes the overall mode select completion
5227 			 * reason to a failed one !!!!!
5228 			 */
5229 			*scsipkt->pkt_scbp = STATUS_CHECK;
5230 			sense = sata_arq_sense(spx);
5231 			scsipkt->pkt_reason = CMD_INCOMPLETE;
5232 			rval = TRAN_ACCEPT;
5233 		}
5234 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5235 	}
5236 	/* Restore the scsi pkt flags */
5237 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
5238 	scsipkt->pkt_flags |= nointr_flag;
5239 
5240 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5241 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5242 
5243 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5244 	    scsipkt->pkt_comp != NULL) {
5245 		/* scsi callback required */
5246 		if (servicing_interrupt()) {
5247 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5248 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5249 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
5250 				return (TRAN_BUSY);
5251 			}
5252 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5253 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5254 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
5255 			/* Scheduling the callback failed */
5256 			return (TRAN_BUSY);
5257 		}
5258 	}
5259 
5260 	return (rval);
5261 }
5262 
5263 /*
5264  * Translate command: ATA Pass Through
5265  * Incomplete implementation.  Only supports No-Data, PIO Data-In, and
5266  * PIO Data-Out protocols.  Also supports CK_COND bit.
5267  *
5268  * Mapping of the incoming CDB bytes to the outgoing satacmd bytes is
5269  * described in Table 111 of SAT-2 (Draft 9).
5270  */
5271 static  int
5272 sata_txlt_ata_pass_thru(sata_pkt_txlate_t *spx)
5273 {
5274 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5275 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5276 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5277 	int extend;
5278 	uint64_t lba;
5279 	uint16_t feature, sec_count;
5280 	int t_len, synch;
5281 	int rval, reason;
5282 
5283 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5284 
5285 	rval = sata_txlt_generic_pkt_info(spx, &reason, 1);
5286 	if ((rval != TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5287 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5288 		return (rval);
5289 	}
5290 
5291 	/* T_DIR bit */
5292 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_T_DIR)
5293 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5294 	else
5295 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5296 
5297 	/* MULTIPLE_COUNT field.  If non-zero, invalid command (for now). */
5298 	if (((scsipkt->pkt_cdbp[1] >> 5) & 0x7) != 0) {
5299 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5300 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5301 	}
5302 
5303 	/* OFFLINE field. If non-zero, invalid command (for now). */
5304 	if (((scsipkt->pkt_cdbp[2] >> 6) & 0x3) != 0) {
5305 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5306 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5307 	}
5308 
5309 	/* PROTOCOL field */
5310 	switch ((scsipkt->pkt_cdbp[1] >> 1) & 0xf) {
5311 	case SATL_APT_P_HW_RESET:
5312 	case SATL_APT_P_SRST:
5313 	case SATL_APT_P_DMA:
5314 	case SATL_APT_P_DMA_QUEUED:
5315 	case SATL_APT_P_DEV_DIAG:
5316 	case SATL_APT_P_DEV_RESET:
5317 	case SATL_APT_P_UDMA_IN:
5318 	case SATL_APT_P_UDMA_OUT:
5319 	case SATL_APT_P_FPDMA:
5320 	case SATL_APT_P_RET_RESP:
5321 		/* Not yet implemented */
5322 	default:
5323 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5324 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5325 
5326 	case SATL_APT_P_NON_DATA:
5327 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
5328 		break;
5329 
5330 	case SATL_APT_P_PIO_DATA_IN:
5331 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5332 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_WRITE) {
5333 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5334 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5335 		}
5336 
5337 		/* if there is a buffer, release its DMA resources */
5338 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5339 			sata_scsi_dmafree(NULL, scsipkt);
5340 		} else {
5341 			/* if there is no buffer, how do you PIO in? */
5342 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5343 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5344 		}
5345 
5346 		break;
5347 
5348 	case SATL_APT_P_PIO_DATA_OUT:
5349 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5350 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_READ) {
5351 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5352 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5353 		}
5354 
5355 		/* if there is a buffer, release its DMA resources */
5356 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5357 			sata_scsi_dmafree(NULL, scsipkt);
5358 		} else {
5359 			/* if there is no buffer, how do you PIO out? */
5360 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5361 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5362 		}
5363 
5364 		break;
5365 	}
5366 
5367 	/* Parse the ATA cmd fields, transfer some straight to the satacmd */
5368 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5369 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
5370 		feature = scsipkt->pkt_cdbp[3];
5371 
5372 		sec_count = scsipkt->pkt_cdbp[4];
5373 
5374 		lba = scsipkt->pkt_cdbp[8] & 0xf;
5375 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5376 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5377 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5378 
5379 		scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] & 0xf0;
5380 		scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[9];
5381 
5382 		break;
5383 
5384 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
5385 		if (scsipkt->pkt_cdbp[1] & SATL_APT_BM_EXTEND) {
5386 			extend = 1;
5387 
5388 			feature = scsipkt->pkt_cdbp[3];
5389 			feature = (feature << 8) | scsipkt->pkt_cdbp[4];
5390 
5391 			sec_count = scsipkt->pkt_cdbp[5];
5392 			sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[6];
5393 
5394 			lba = scsipkt->pkt_cdbp[11];
5395 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5396 			lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5397 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5398 			lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5399 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5400 
5401 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13];
5402 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5403 		} else {
5404 			feature = scsipkt->pkt_cdbp[3];
5405 
5406 			sec_count = scsipkt->pkt_cdbp[5];
5407 
5408 			lba = scsipkt->pkt_cdbp[13] & 0xf;
5409 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5410 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5411 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5412 
5413 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] &
5414 			    0xf0;
5415 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5416 		}
5417 
5418 		break;
5419 	}
5420 
5421 	/* CK_COND bit */
5422 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
5423 		if (extend) {
5424 			scmd->satacmd_flags.sata_copy_out_sec_count_msb = 1;
5425 			scmd->satacmd_flags.sata_copy_out_lba_low_msb = 1;
5426 			scmd->satacmd_flags.sata_copy_out_lba_mid_msb = 1;
5427 			scmd->satacmd_flags.sata_copy_out_lba_high_msb = 1;
5428 		}
5429 
5430 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
5431 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
5432 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
5433 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
5434 		scmd->satacmd_flags.sata_copy_out_device_reg = 1;
5435 		scmd->satacmd_flags.sata_copy_out_error_reg = 1;
5436 	}
5437 
5438 	/* Transfer remaining parsed ATA cmd values to the satacmd */
5439 	if (extend) {
5440 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5441 
5442 		scmd->satacmd_features_reg_ext = (feature >> 8) & 0xff;
5443 		scmd->satacmd_sec_count_msb = (sec_count >> 8) & 0xff;
5444 		scmd->satacmd_lba_low_msb = (lba >> 8) & 0xff;
5445 		scmd->satacmd_lba_mid_msb = (lba >> 8) & 0xff;
5446 		scmd->satacmd_lba_high_msb = lba >> 40;
5447 	} else {
5448 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5449 
5450 		scmd->satacmd_features_reg_ext = 0;
5451 		scmd->satacmd_sec_count_msb = 0;
5452 		scmd->satacmd_lba_low_msb = 0;
5453 		scmd->satacmd_lba_mid_msb = 0;
5454 		scmd->satacmd_lba_high_msb = 0;
5455 	}
5456 
5457 	scmd->satacmd_features_reg = feature & 0xff;
5458 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5459 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5460 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5461 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5462 
5463 	/* Determine transfer length */
5464 	switch (scsipkt->pkt_cdbp[2] & 0x3) {		/* T_LENGTH field */
5465 	case 1:
5466 		t_len = feature;
5467 		break;
5468 	case 2:
5469 		t_len = sec_count;
5470 		break;
5471 	default:
5472 		t_len = 0;
5473 		break;
5474 	}
5475 
5476 	/* Adjust transfer length for the Byte Block bit */
5477 	if ((scsipkt->pkt_cdbp[2] >> 2) & 1)
5478 		t_len *= SATA_DISK_SECTOR_SIZE;
5479 
5480 	/* Start processing command */
5481 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5482 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_apt_completion;
5483 		synch = FALSE;
5484 	} else {
5485 		synch = TRUE;
5486 	}
5487 
5488 	if (sata_hba_start(spx, &rval) != 0) {
5489 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5490 		return (rval);
5491 	}
5492 
5493 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5494 
5495 	if (synch) {
5496 		sata_txlt_apt_completion(spx->txlt_sata_pkt);
5497 	}
5498 
5499 	return (TRAN_ACCEPT);
5500 }
5501 
5502 /*
5503  * Translate command: Log Sense
5504  */
5505 static 	int
5506 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
5507 {
5508 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
5509 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5510 	sata_drive_info_t *sdinfo;
5511 	struct scsi_extended_sense *sense;
5512 	int 		len, count, alc_len;
5513 	int		pc;	/* Page Control code */
5514 	int		page_code;	/* Page code */
5515 	uint8_t		*buf;	/* log sense buffer */
5516 	int		rval, reason;
5517 #define	MAX_LOG_SENSE_PAGE_SIZE	512
5518 
5519 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5520 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
5521 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5522 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5523 
5524 	if (servicing_interrupt()) {
5525 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_NOSLEEP);
5526 		if (buf == NULL) {
5527 			return (TRAN_BUSY);
5528 		}
5529 	} else {
5530 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
5531 	}
5532 
5533 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5534 
5535 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5536 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5537 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5538 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5539 		return (rval);
5540 	}
5541 
5542 	scsipkt->pkt_reason = CMD_CMPLT;
5543 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5544 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5545 
5546 	pc = scsipkt->pkt_cdbp[2] >> 6;
5547 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
5548 
5549 	/* Reject not supported request for all but cumulative values */
5550 	switch (pc) {
5551 	case PC_CUMULATIVE_VALUES:
5552 		break;
5553 	default:
5554 		*scsipkt->pkt_scbp = STATUS_CHECK;
5555 		sense = sata_arq_sense(spx);
5556 		sense->es_key = KEY_ILLEGAL_REQUEST;
5557 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5558 		goto done;
5559 	}
5560 
5561 	switch (page_code) {
5562 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5563 	case PAGE_CODE_SELF_TEST_RESULTS:
5564 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
5565 	case PAGE_CODE_SMART_READ_DATA:
5566 	case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5567 		break;
5568 	default:
5569 		*scsipkt->pkt_scbp = STATUS_CHECK;
5570 		sense = sata_arq_sense(spx);
5571 		sense->es_key = KEY_ILLEGAL_REQUEST;
5572 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5573 		goto done;
5574 	}
5575 
5576 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
5577 		/*
5578 		 * Because log sense uses local buffers for data retrieval from
5579 		 * the devices and sets the data programatically in the
5580 		 * original specified buffer, release preallocated DMA
5581 		 * resources before storing data in the original buffer,
5582 		 * so no unwanted DMA sync would take place.
5583 		 */
5584 		sata_id_t *sata_id;
5585 
5586 		sata_scsi_dmafree(NULL, scsipkt);
5587 
5588 		len = 0;
5589 
5590 		/* Build log parameter header */
5591 		buf[len++] = page_code;	/* page code as in the CDB */
5592 		buf[len++] = 0;		/* reserved */
5593 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
5594 		buf[len++] = 0;		/* (LSB) */
5595 
5596 		sdinfo = sata_get_device_info(
5597 		    spx->txlt_sata_hba_inst,
5598 		    &spx->txlt_sata_pkt->satapkt_device);
5599 
5600 		/*
5601 		 * Add requested pages.
5602 		 */
5603 		switch (page_code) {
5604 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5605 			len = sata_build_lsense_page_0(sdinfo, buf + len);
5606 			break;
5607 		case PAGE_CODE_SELF_TEST_RESULTS:
5608 			sata_id = &sdinfo->satadrv_id;
5609 			if ((! (sata_id->ai_cmdset84 &
5610 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
5611 			    (! (sata_id->ai_features87 &
5612 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
5613 				*scsipkt->pkt_scbp = STATUS_CHECK;
5614 				sense = sata_arq_sense(spx);
5615 				sense->es_key = KEY_ILLEGAL_REQUEST;
5616 				sense->es_add_code =
5617 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5618 
5619 				goto done;
5620 			}
5621 			len = sata_build_lsense_page_10(sdinfo, buf + len,
5622 			    spx->txlt_sata_hba_inst);
5623 			break;
5624 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
5625 			sata_id = &sdinfo->satadrv_id;
5626 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5627 				*scsipkt->pkt_scbp = STATUS_CHECK;
5628 				sense = sata_arq_sense(spx);
5629 				sense->es_key = KEY_ILLEGAL_REQUEST;
5630 				sense->es_add_code =
5631 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5632 
5633 				goto done;
5634 			}
5635 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5636 				*scsipkt->pkt_scbp = STATUS_CHECK;
5637 				sense = sata_arq_sense(spx);
5638 				sense->es_key = KEY_ABORTED_COMMAND;
5639 				sense->es_add_code =
5640 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5641 				sense->es_qual_code =
5642 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5643 
5644 				goto done;
5645 			}
5646 
5647 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
5648 			    spx->txlt_sata_hba_inst);
5649 			break;
5650 		case PAGE_CODE_SMART_READ_DATA:
5651 			sata_id = &sdinfo->satadrv_id;
5652 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5653 				*scsipkt->pkt_scbp = STATUS_CHECK;
5654 				sense = sata_arq_sense(spx);
5655 				sense->es_key = KEY_ILLEGAL_REQUEST;
5656 				sense->es_add_code =
5657 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5658 
5659 				goto done;
5660 			}
5661 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5662 				*scsipkt->pkt_scbp = STATUS_CHECK;
5663 				sense = sata_arq_sense(spx);
5664 				sense->es_key = KEY_ABORTED_COMMAND;
5665 				sense->es_add_code =
5666 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5667 				sense->es_qual_code =
5668 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5669 
5670 				goto done;
5671 			}
5672 
5673 			/* This page doesn't include a page header */
5674 			len = sata_build_lsense_page_30(sdinfo, buf,
5675 			    spx->txlt_sata_hba_inst);
5676 			goto no_header;
5677 		case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5678 			sata_id = &sdinfo->satadrv_id;
5679 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5680 				*scsipkt->pkt_scbp = STATUS_CHECK;
5681 				sense = sata_arq_sense(spx);
5682 				sense->es_key = KEY_ILLEGAL_REQUEST;
5683 				sense->es_add_code =
5684 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5685 
5686 				goto done;
5687 			}
5688 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5689 				*scsipkt->pkt_scbp = STATUS_CHECK;
5690 				sense = sata_arq_sense(spx);
5691 				sense->es_key = KEY_ABORTED_COMMAND;
5692 				sense->es_add_code =
5693 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5694 				sense->es_qual_code =
5695 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5696 
5697 				goto done;
5698 			}
5699 			len = sata_build_lsense_page_0e(sdinfo, buf, spx);
5700 			goto no_header;
5701 		default:
5702 			/* Invalid request */
5703 			*scsipkt->pkt_scbp = STATUS_CHECK;
5704 			sense = sata_arq_sense(spx);
5705 			sense->es_key = KEY_ILLEGAL_REQUEST;
5706 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5707 			goto done;
5708 		}
5709 
5710 		/* set parameter log sense data length */
5711 		buf[2] = len >> 8;	/* log sense length (MSB) */
5712 		buf[3] = len & 0xff;	/* log sense length (LSB) */
5713 
5714 		len += SCSI_LOG_PAGE_HDR_LEN;
5715 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
5716 
5717 no_header:
5718 		/* Check allocation length */
5719 		alc_len = scsipkt->pkt_cdbp[7];
5720 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
5721 
5722 		/*
5723 		 * We do not check for possible parameters truncation
5724 		 * (alc_len < len) assuming that the target driver works
5725 		 * correctly. Just avoiding overrun.
5726 		 * Copy no more than requested and possible, buffer-wise.
5727 		 */
5728 		count = MIN(alc_len, len);
5729 		count = MIN(bp->b_bcount, count);
5730 		bcopy(buf, bp->b_un.b_addr, count);
5731 
5732 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5733 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
5734 	}
5735 	*scsipkt->pkt_scbp = STATUS_GOOD;
5736 done:
5737 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5738 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5739 
5740 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5741 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5742 
5743 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5744 	    scsipkt->pkt_comp != NULL) {
5745 		/* scsi callback required */
5746 		if (servicing_interrupt()) {
5747 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5748 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5749 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
5750 				return (TRAN_BUSY);
5751 			}
5752 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5753 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5754 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
5755 			/* Scheduling the callback failed */
5756 			return (TRAN_BUSY);
5757 		}
5758 	}
5759 
5760 	return (TRAN_ACCEPT);
5761 }
5762 
5763 /*
5764  * Translate command: Log Select
5765  * Not implemented at this time - returns invalid command response.
5766  */
5767 static	int
5768 sata_txlt_log_select(sata_pkt_txlate_t *spx)
5769 {
5770 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5771 	    "sata_txlt_log_select\n", NULL);
5772 
5773 	return (sata_txlt_invalid_command(spx));
5774 }
5775 
5776 
5777 /*
5778  * Translate command: Read (various types).
5779  * Translated into appropriate type of ATA READ command
5780  * for SATA hard disks.
5781  * Both the device capabilities and requested operation mode are
5782  * considered.
5783  *
5784  * Following scsi cdb fields are ignored:
5785  * rdprotect, dpo, fua, fua_nv, group_number.
5786  *
5787  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5788  * enable variable sata_func_enable), the capability of the controller and
5789  * capability of a device are checked and if both support queueing, read
5790  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
5791  * command rather than plain READ_XXX command.
5792  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5793  * both the controller and device suport such functionality, the read
5794  * request will be translated to READ_FPDMA_QUEUED command.
5795  * In both cases the maximum queue depth is derived as minimum of:
5796  * HBA capability,device capability and sata_max_queue_depth variable setting.
5797  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5798  * used to pass max queue depth value, and the maximum possible queue depth
5799  * is 32.
5800  *
5801  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5802  * appropriate values in scsi_pkt fields.
5803  */
5804 static int
5805 sata_txlt_read(sata_pkt_txlate_t *spx)
5806 {
5807 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5808 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5809 	sata_drive_info_t *sdinfo;
5810 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5811 	int cport = SATA_TXLT_CPORT(spx);
5812 	uint16_t sec_count;
5813 	uint64_t lba;
5814 	int rval, reason;
5815 	int synch;
5816 
5817 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5818 
5819 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
5820 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5821 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5822 		return (rval);
5823 	}
5824 
5825 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5826 	    &spx->txlt_sata_pkt->satapkt_device);
5827 
5828 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5829 	/*
5830 	 * Extract LBA and sector count from scsi CDB.
5831 	 */
5832 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5833 	case SCMD_READ:
5834 		/* 6-byte scsi read cmd : 0x08 */
5835 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5836 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5837 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5838 		sec_count = scsipkt->pkt_cdbp[4];
5839 		/* sec_count 0 will be interpreted as 256 by a device */
5840 		break;
5841 	case SCMD_READ_G1:
5842 		/* 10-bytes scsi read command : 0x28 */
5843 		lba = scsipkt->pkt_cdbp[2];
5844 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5845 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5846 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5847 		sec_count = scsipkt->pkt_cdbp[7];
5848 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5849 		break;
5850 	case SCMD_READ_G5:
5851 		/* 12-bytes scsi read command : 0xA8 */
5852 		lba = scsipkt->pkt_cdbp[2];
5853 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5854 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5855 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5856 		sec_count = scsipkt->pkt_cdbp[6];
5857 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5858 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5859 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5860 		break;
5861 	case SCMD_READ_G4:
5862 		/* 16-bytes scsi read command : 0x88 */
5863 		lba = scsipkt->pkt_cdbp[2];
5864 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5865 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5866 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5867 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5868 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5869 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5870 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5871 		sec_count = scsipkt->pkt_cdbp[10];
5872 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5873 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5874 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5875 		break;
5876 	default:
5877 		/* Unsupported command */
5878 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5879 		return (sata_txlt_invalid_command(spx));
5880 	}
5881 
5882 	/*
5883 	 * Check if specified address exceeds device capacity
5884 	 */
5885 	if ((lba >= sdinfo->satadrv_capacity) ||
5886 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5887 		/* LBA out of range */
5888 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5889 		return (sata_txlt_lba_out_of_range(spx));
5890 	}
5891 
5892 	/*
5893 	 * For zero-length transfer, emulate good completion of the command
5894 	 * (reasons for rejecting the command were already checked).
5895 	 * No DMA resources were allocated.
5896 	 */
5897 	if (spx->txlt_dma_cookie_list == NULL) {
5898 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5899 		return (sata_emul_rw_completion(spx));
5900 	}
5901 
5902 	/*
5903 	 * Build cmd block depending on the device capability and
5904 	 * requested operation mode.
5905 	 * Do not bother with non-dma mode - we are working only with
5906 	 * devices supporting DMA.
5907 	 */
5908 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5909 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5910 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
5911 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5912 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5913 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
5914 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5915 #ifndef __lock_lint
5916 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5917 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5918 		scmd->satacmd_lba_high_msb = lba >> 40;
5919 #endif
5920 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5921 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5922 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5923 	}
5924 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5925 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5926 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5927 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5928 	scmd->satacmd_features_reg = 0;
5929 	scmd->satacmd_status_reg = 0;
5930 	scmd->satacmd_error_reg = 0;
5931 
5932 	/*
5933 	 * Check if queueing commands should be used and switch
5934 	 * to appropriate command if possible
5935 	 */
5936 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5937 		boolean_t using_queuing;
5938 
5939 		/* Queuing supported by controller and device? */
5940 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5941 		    (sdinfo->satadrv_features_support &
5942 		    SATA_DEV_F_NCQ) &&
5943 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5944 		    SATA_CTLF_NCQ)) {
5945 			using_queuing = B_TRUE;
5946 
5947 			/* NCQ supported - use FPDMA READ */
5948 			scmd->satacmd_cmd_reg =
5949 			    SATAC_READ_FPDMA_QUEUED;
5950 			scmd->satacmd_features_reg_ext =
5951 			    scmd->satacmd_sec_count_msb;
5952 			scmd->satacmd_sec_count_msb = 0;
5953 		} else if ((sdinfo->satadrv_features_support &
5954 		    SATA_DEV_F_TCQ) &&
5955 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5956 		    SATA_CTLF_QCMD)) {
5957 			using_queuing = B_TRUE;
5958 
5959 			/* Legacy queueing */
5960 			if (sdinfo->satadrv_features_support &
5961 			    SATA_DEV_F_LBA48) {
5962 				scmd->satacmd_cmd_reg =
5963 				    SATAC_READ_DMA_QUEUED_EXT;
5964 				scmd->satacmd_features_reg_ext =
5965 				    scmd->satacmd_sec_count_msb;
5966 				scmd->satacmd_sec_count_msb = 0;
5967 			} else {
5968 				scmd->satacmd_cmd_reg =
5969 				    SATAC_READ_DMA_QUEUED;
5970 			}
5971 		} else	/* NCQ nor legacy queuing not supported */
5972 			using_queuing = B_FALSE;
5973 
5974 		/*
5975 		 * If queuing, the sector count goes in the features register
5976 		 * and the secount count will contain the tag.
5977 		 */
5978 		if (using_queuing) {
5979 			scmd->satacmd_features_reg =
5980 			    scmd->satacmd_sec_count_lsb;
5981 			scmd->satacmd_sec_count_lsb = 0;
5982 			scmd->satacmd_flags.sata_queued = B_TRUE;
5983 
5984 			/* Set-up maximum queue depth */
5985 			scmd->satacmd_flags.sata_max_queue_depth =
5986 			    sdinfo->satadrv_max_queue_depth - 1;
5987 		} else if (sdinfo->satadrv_features_enabled &
5988 		    SATA_DEV_F_E_UNTAGGED_QING) {
5989 			/*
5990 			 * Although NCQ/TCQ is not enabled, untagged queuing
5991 			 * may be still used.
5992 			 * Set-up the maximum untagged queue depth.
5993 			 * Use controller's queue depth from sata_hba_tran.
5994 			 * SATA HBA drivers may ignore this value and rely on
5995 			 * the internal limits.For drivers that do not
5996 			 * ignore untaged queue depth, limit the value to
5997 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5998 			 * largest value that can be passed via
5999 			 * satacmd_flags.sata_max_queue_depth.
6000 			 */
6001 			scmd->satacmd_flags.sata_max_queue_depth =
6002 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
6003 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
6004 
6005 		} else {
6006 			scmd->satacmd_flags.sata_max_queue_depth = 0;
6007 		}
6008 	} else
6009 		scmd->satacmd_flags.sata_max_queue_depth = 0;
6010 
6011 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
6012 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
6013 	    scmd->satacmd_cmd_reg, lba, sec_count);
6014 
6015 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6016 		/* Need callback function */
6017 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
6018 		synch = FALSE;
6019 	} else
6020 		synch = TRUE;
6021 
6022 	/* Transfer command to HBA */
6023 	if (sata_hba_start(spx, &rval) != 0) {
6024 		/* Pkt not accepted for execution */
6025 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6026 		return (rval);
6027 	}
6028 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6029 	/*
6030 	 * If execution is non-synchronous,
6031 	 * a callback function will handle potential errors, translate
6032 	 * the response and will do a callback to a target driver.
6033 	 * If it was synchronous, check execution status using the same
6034 	 * framework callback.
6035 	 */
6036 	if (synch) {
6037 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6038 		    "synchronous execution status %x\n",
6039 		    spx->txlt_sata_pkt->satapkt_reason);
6040 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
6041 	}
6042 	return (TRAN_ACCEPT);
6043 }
6044 
6045 
6046 /*
6047  * SATA translate command: Write (various types)
6048  * Translated into appropriate type of ATA WRITE command
6049  * for SATA hard disks.
6050  * Both the device capabilities and requested operation mode are
6051  * considered.
6052  *
6053  * Following scsi cdb fields are ignored:
6054  * rwprotect, dpo, fua, fua_nv, group_number.
6055  *
6056  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
6057  * enable variable sata_func_enable), the capability of the controller and
6058  * capability of a device are checked and if both support queueing, write
6059  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
6060  * command rather than plain WRITE_XXX command.
6061  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
6062  * both the controller and device suport such functionality, the write
6063  * request will be translated to WRITE_FPDMA_QUEUED command.
6064  * In both cases the maximum queue depth is derived as minimum of:
6065  * HBA capability,device capability and sata_max_queue_depth variable setting.
6066  * The value passed to HBA driver is decremented by 1, because only 5 bits are
6067  * used to pass max queue depth value, and the maximum possible queue depth
6068  * is 32.
6069  *
6070  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6071  * appropriate values in scsi_pkt fields.
6072  */
6073 static int
6074 sata_txlt_write(sata_pkt_txlate_t *spx)
6075 {
6076 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6077 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6078 	sata_drive_info_t *sdinfo;
6079 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6080 	int cport = SATA_TXLT_CPORT(spx);
6081 	uint16_t sec_count;
6082 	uint64_t lba;
6083 	int rval, reason;
6084 	int synch;
6085 
6086 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6087 
6088 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
6089 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6090 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6091 		return (rval);
6092 	}
6093 
6094 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6095 	    &spx->txlt_sata_pkt->satapkt_device);
6096 
6097 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
6098 	/*
6099 	 * Extract LBA and sector count from scsi CDB
6100 	 */
6101 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
6102 	case SCMD_WRITE:
6103 		/* 6-byte scsi read cmd : 0x0A */
6104 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
6105 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
6106 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6107 		sec_count = scsipkt->pkt_cdbp[4];
6108 		/* sec_count 0 will be interpreted as 256 by a device */
6109 		break;
6110 	case SCMD_WRITE_G1:
6111 		/* 10-bytes scsi write command : 0x2A */
6112 		lba = scsipkt->pkt_cdbp[2];
6113 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6114 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6115 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6116 		sec_count = scsipkt->pkt_cdbp[7];
6117 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
6118 		break;
6119 	case SCMD_WRITE_G5:
6120 		/* 12-bytes scsi read command : 0xAA */
6121 		lba = scsipkt->pkt_cdbp[2];
6122 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6123 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6124 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6125 		sec_count = scsipkt->pkt_cdbp[6];
6126 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
6127 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
6128 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
6129 		break;
6130 	case SCMD_WRITE_G4:
6131 		/* 16-bytes scsi write command : 0x8A */
6132 		lba = scsipkt->pkt_cdbp[2];
6133 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6134 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6135 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6136 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
6137 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
6138 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
6139 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
6140 		sec_count = scsipkt->pkt_cdbp[10];
6141 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
6142 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
6143 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
6144 		break;
6145 	default:
6146 		/* Unsupported command */
6147 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6148 		return (sata_txlt_invalid_command(spx));
6149 	}
6150 
6151 	/*
6152 	 * Check if specified address and length exceeds device capacity
6153 	 */
6154 	if ((lba >= sdinfo->satadrv_capacity) ||
6155 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
6156 		/* LBA out of range */
6157 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6158 		return (sata_txlt_lba_out_of_range(spx));
6159 	}
6160 
6161 	/*
6162 	 * For zero-length transfer, emulate good completion of the command
6163 	 * (reasons for rejecting the command were already checked).
6164 	 * No DMA resources were allocated.
6165 	 */
6166 	if (spx->txlt_dma_cookie_list == NULL) {
6167 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6168 		return (sata_emul_rw_completion(spx));
6169 	}
6170 
6171 	/*
6172 	 * Build cmd block depending on the device capability and
6173 	 * requested operation mode.
6174 	 * Do not bother with non-dma mode- we are working only with
6175 	 * devices supporting DMA.
6176 	 */
6177 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
6178 	scmd->satacmd_device_reg = SATA_ADH_LBA;
6179 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
6180 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
6181 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
6182 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
6183 		scmd->satacmd_sec_count_msb = sec_count >> 8;
6184 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
6185 #ifndef __lock_lint
6186 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
6187 		scmd->satacmd_lba_high_msb = lba >> 40;
6188 #endif
6189 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
6190 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
6191 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
6192 	}
6193 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
6194 	scmd->satacmd_lba_low_lsb = lba & 0xff;
6195 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
6196 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
6197 	scmd->satacmd_features_reg = 0;
6198 	scmd->satacmd_status_reg = 0;
6199 	scmd->satacmd_error_reg = 0;
6200 
6201 	/*
6202 	 * Check if queueing commands should be used and switch
6203 	 * to appropriate command if possible
6204 	 */
6205 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
6206 		boolean_t using_queuing;
6207 
6208 		/* Queuing supported by controller and device? */
6209 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
6210 		    (sdinfo->satadrv_features_support &
6211 		    SATA_DEV_F_NCQ) &&
6212 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6213 		    SATA_CTLF_NCQ)) {
6214 			using_queuing = B_TRUE;
6215 
6216 			/* NCQ supported - use FPDMA WRITE */
6217 			scmd->satacmd_cmd_reg =
6218 			    SATAC_WRITE_FPDMA_QUEUED;
6219 			scmd->satacmd_features_reg_ext =
6220 			    scmd->satacmd_sec_count_msb;
6221 			scmd->satacmd_sec_count_msb = 0;
6222 		} else if ((sdinfo->satadrv_features_support &
6223 		    SATA_DEV_F_TCQ) &&
6224 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6225 		    SATA_CTLF_QCMD)) {
6226 			using_queuing = B_TRUE;
6227 
6228 			/* Legacy queueing */
6229 			if (sdinfo->satadrv_features_support &
6230 			    SATA_DEV_F_LBA48) {
6231 				scmd->satacmd_cmd_reg =
6232 				    SATAC_WRITE_DMA_QUEUED_EXT;
6233 				scmd->satacmd_features_reg_ext =
6234 				    scmd->satacmd_sec_count_msb;
6235 				scmd->satacmd_sec_count_msb = 0;
6236 			} else {
6237 				scmd->satacmd_cmd_reg =
6238 				    SATAC_WRITE_DMA_QUEUED;
6239 			}
6240 		} else	/*  NCQ nor legacy queuing not supported */
6241 			using_queuing = B_FALSE;
6242 
6243 		if (using_queuing) {
6244 			scmd->satacmd_features_reg =
6245 			    scmd->satacmd_sec_count_lsb;
6246 			scmd->satacmd_sec_count_lsb = 0;
6247 			scmd->satacmd_flags.sata_queued = B_TRUE;
6248 			/* Set-up maximum queue depth */
6249 			scmd->satacmd_flags.sata_max_queue_depth =
6250 			    sdinfo->satadrv_max_queue_depth - 1;
6251 		} else if (sdinfo->satadrv_features_enabled &
6252 		    SATA_DEV_F_E_UNTAGGED_QING) {
6253 			/*
6254 			 * Although NCQ/TCQ is not enabled, untagged queuing
6255 			 * may be still used.
6256 			 * Set-up the maximum untagged queue depth.
6257 			 * Use controller's queue depth from sata_hba_tran.
6258 			 * SATA HBA drivers may ignore this value and rely on
6259 			 * the internal limits. For drivera that do not
6260 			 * ignore untaged queue depth, limit the value to
6261 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
6262 			 * largest value that can be passed via
6263 			 * satacmd_flags.sata_max_queue_depth.
6264 			 */
6265 			scmd->satacmd_flags.sata_max_queue_depth =
6266 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
6267 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
6268 
6269 		} else {
6270 			scmd->satacmd_flags.sata_max_queue_depth = 0;
6271 		}
6272 	} else
6273 		scmd->satacmd_flags.sata_max_queue_depth = 0;
6274 
6275 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6276 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
6277 	    scmd->satacmd_cmd_reg, lba, sec_count);
6278 
6279 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6280 		/* Need callback function */
6281 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
6282 		synch = FALSE;
6283 	} else
6284 		synch = TRUE;
6285 
6286 	/* Transfer command to HBA */
6287 	if (sata_hba_start(spx, &rval) != 0) {
6288 		/* Pkt not accepted for execution */
6289 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6290 		return (rval);
6291 	}
6292 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6293 
6294 	/*
6295 	 * If execution is non-synchronous,
6296 	 * a callback function will handle potential errors, translate
6297 	 * the response and will do a callback to a target driver.
6298 	 * If it was synchronous, check execution status using the same
6299 	 * framework callback.
6300 	 */
6301 	if (synch) {
6302 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6303 		    "synchronous execution status %x\n",
6304 		    spx->txlt_sata_pkt->satapkt_reason);
6305 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
6306 	}
6307 	return (TRAN_ACCEPT);
6308 }
6309 
6310 
6311 /*
6312  * Implements SCSI SBC WRITE BUFFER command download microcode option
6313  */
6314 static int
6315 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
6316 {
6317 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
6318 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
6319 
6320 	sata_hba_inst_t *sata_hba_inst = SATA_TXLT_HBA_INST(spx);
6321 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6322 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
6323 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6324 
6325 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6326 	struct scsi_extended_sense *sense;
6327 	int rval, mode, sector_count, reason;
6328 	int cport = SATA_TXLT_CPORT(spx);
6329 
6330 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
6331 
6332 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6333 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
6334 
6335 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6336 
6337 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6338 	    TRAN_ACCEPT) {
6339 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6340 		return (rval);
6341 	}
6342 
6343 	/* Use synchronous mode */
6344 	spx->txlt_sata_pkt->satapkt_op_mode
6345 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
6346 
6347 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
6348 
6349 	scsipkt->pkt_reason = CMD_CMPLT;
6350 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6351 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6352 
6353 	/*
6354 	 * The SCSI to ATA translation specification only calls
6355 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
6356 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
6357 	 * ATA 8 (draft) got rid of download microcode for temp
6358 	 * and it is even optional for ATA 7, so it may be aborted.
6359 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
6360 	 * it is not specified and the buffer offset for SCSI is a 16-bit
6361 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
6362 	 * sectors.  Thus the offset really doesn't buy us anything.
6363 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
6364 	 * is revised, this can be revisisted.
6365 	 */
6366 	/* Reject not supported request */
6367 	switch (mode) {
6368 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
6369 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
6370 		break;
6371 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
6372 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
6373 		break;
6374 	default:
6375 		goto bad_param;
6376 	}
6377 
6378 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
6379 
6380 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
6381 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
6382 		goto bad_param;
6383 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
6384 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
6385 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
6386 	scmd->satacmd_lba_mid_lsb = 0;
6387 	scmd->satacmd_lba_high_lsb = 0;
6388 	scmd->satacmd_device_reg = 0;
6389 	spx->txlt_sata_pkt->satapkt_comp = NULL;
6390 	scmd->satacmd_addr_type = 0;
6391 
6392 	/* Transfer command to HBA */
6393 	if (sata_hba_start(spx, &rval) != 0) {
6394 		/* Pkt not accepted for execution */
6395 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6396 		return (rval);
6397 	}
6398 
6399 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6400 
6401 	/* Then we need synchronous check the status of the disk */
6402 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6403 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6404 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6405 		scsipkt->pkt_reason = CMD_CMPLT;
6406 
6407 		/* Download commmand succeed, so probe and identify device */
6408 		sata_reidentify_device(spx);
6409 	} else {
6410 		/* Something went wrong, microcode download command failed */
6411 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6412 		*scsipkt->pkt_scbp = STATUS_CHECK;
6413 		sense = sata_arq_sense(spx);
6414 		switch (sata_pkt->satapkt_reason) {
6415 		case SATA_PKT_PORT_ERROR:
6416 			/*
6417 			 * We have no device data. Assume no data transfered.
6418 			 */
6419 			sense->es_key = KEY_HARDWARE_ERROR;
6420 			break;
6421 
6422 		case SATA_PKT_DEV_ERROR:
6423 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6424 			    SATA_STATUS_ERR) {
6425 				/*
6426 				 * determine dev error reason from error
6427 				 * reg content
6428 				 */
6429 				sata_decode_device_error(spx, sense);
6430 				break;
6431 			}
6432 			/* No extended sense key - no info available */
6433 			break;
6434 
6435 		case SATA_PKT_TIMEOUT:
6436 			scsipkt->pkt_reason = CMD_TIMEOUT;
6437 			scsipkt->pkt_statistics |=
6438 			    STAT_TIMEOUT | STAT_DEV_RESET;
6439 			/* No extended sense key ? */
6440 			break;
6441 
6442 		case SATA_PKT_ABORTED:
6443 			scsipkt->pkt_reason = CMD_ABORTED;
6444 			scsipkt->pkt_statistics |= STAT_ABORTED;
6445 			/* No extended sense key ? */
6446 			break;
6447 
6448 		case SATA_PKT_RESET:
6449 			/* pkt aborted by an explicit reset from a host */
6450 			scsipkt->pkt_reason = CMD_RESET;
6451 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6452 			break;
6453 
6454 		default:
6455 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6456 			    "sata_txlt_nodata_cmd_completion: "
6457 			    "invalid packet completion reason %d",
6458 			    sata_pkt->satapkt_reason));
6459 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6460 			break;
6461 		}
6462 
6463 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6464 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6465 
6466 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6467 			/* scsi callback required */
6468 			scsi_hba_pkt_comp(scsipkt);
6469 	}
6470 	return (TRAN_ACCEPT);
6471 
6472 bad_param:
6473 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6474 	*scsipkt->pkt_scbp = STATUS_CHECK;
6475 	sense = sata_arq_sense(spx);
6476 	sense->es_key = KEY_ILLEGAL_REQUEST;
6477 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6478 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6479 	    scsipkt->pkt_comp != NULL) {
6480 		/* scsi callback required */
6481 		if (servicing_interrupt()) {
6482 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6483 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6484 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6485 				return (TRAN_BUSY);
6486 			}
6487 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6488 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6489 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6490 			/* Scheduling the callback failed */
6491 			return (TRAN_BUSY);
6492 		}
6493 	}
6494 	return (rval);
6495 }
6496 
6497 /*
6498  * Re-identify device after doing a firmware download.
6499  */
6500 static void
6501 sata_reidentify_device(sata_pkt_txlate_t *spx)
6502 {
6503 #define	DOWNLOAD_WAIT_TIME_SECS	60
6504 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
6505 	int rval;
6506 	int retry_cnt;
6507 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6508 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6509 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
6510 	sata_drive_info_t *sdinfo;
6511 
6512 	/*
6513 	 * Before returning good status, probe device.
6514 	 * Device probing will get IDENTIFY DEVICE data, if possible.
6515 	 * The assumption is that the new microcode is applied by the
6516 	 * device. It is a caller responsibility to verify this.
6517 	 */
6518 	for (retry_cnt = 0;
6519 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
6520 	    retry_cnt++) {
6521 		rval = sata_probe_device(sata_hba_inst, &sata_device);
6522 
6523 		if (rval == SATA_SUCCESS) { /* Set default features */
6524 			sdinfo = sata_get_device_info(sata_hba_inst,
6525 			    &sata_device);
6526 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
6527 			    SATA_SUCCESS) {
6528 				/* retry */
6529 				rval = sata_initialize_device(sata_hba_inst,
6530 				    sdinfo);
6531 				if (rval == SATA_RETRY)
6532 					sata_log(sata_hba_inst, CE_WARN,
6533 					    "SATA device at port %d pmport %d -"
6534 					    " default device features could not"
6535 					    " be set. Device may not operate "
6536 					    "as expected.",
6537 					    sata_device.satadev_addr.cport,
6538 					    sata_device.satadev_addr.pmport);
6539 			}
6540 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6541 				scsi_hba_pkt_comp(scsipkt);
6542 			return;
6543 		} else if (rval == SATA_RETRY) {
6544 			delay(drv_usectohz(1000000 *
6545 			    DOWNLOAD_WAIT_INTERVAL_SECS));
6546 			continue;
6547 		} else	/* failed - no reason to retry */
6548 			break;
6549 	}
6550 
6551 	/*
6552 	 * Something went wrong, device probing failed.
6553 	 */
6554 	SATA_LOG_D((sata_hba_inst, CE_WARN,
6555 	    "Cannot probe device after downloading microcode\n"));
6556 
6557 	/* Reset device to force retrying the probe. */
6558 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
6559 	    (SATA_DIP(sata_hba_inst), &sata_device);
6560 
6561 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6562 		scsi_hba_pkt_comp(scsipkt);
6563 }
6564 
6565 
6566 /*
6567  * Translate command: Synchronize Cache.
6568  * Translates into Flush Cache command for SATA hard disks.
6569  *
6570  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6571  * appropriate values in scsi_pkt fields.
6572  */
6573 static 	int
6574 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
6575 {
6576 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6577 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6578 	int cport = SATA_TXLT_CPORT(spx);
6579 	int rval, reason;
6580 	int synch;
6581 
6582 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6583 
6584 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6585 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6586 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6587 		return (rval);
6588 	}
6589 
6590 	scmd->satacmd_addr_type = 0;
6591 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
6592 	scmd->satacmd_device_reg = 0;
6593 	scmd->satacmd_sec_count_lsb = 0;
6594 	scmd->satacmd_lba_low_lsb = 0;
6595 	scmd->satacmd_lba_mid_lsb = 0;
6596 	scmd->satacmd_lba_high_lsb = 0;
6597 	scmd->satacmd_features_reg = 0;
6598 	scmd->satacmd_status_reg = 0;
6599 	scmd->satacmd_error_reg = 0;
6600 
6601 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6602 	    "sata_txlt_synchronize_cache\n", NULL);
6603 
6604 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6605 		/* Need to set-up a callback function */
6606 		spx->txlt_sata_pkt->satapkt_comp =
6607 		    sata_txlt_nodata_cmd_completion;
6608 		synch = FALSE;
6609 	} else
6610 		synch = TRUE;
6611 
6612 	/* Transfer command to HBA */
6613 	if (sata_hba_start(spx, &rval) != 0) {
6614 		/* Pkt not accepted for execution */
6615 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6616 		return (rval);
6617 	}
6618 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6619 
6620 	/*
6621 	 * If execution non-synchronous, it had to be completed
6622 	 * a callback function will handle potential errors, translate
6623 	 * the response and will do a callback to a target driver.
6624 	 * If it was synchronous, check status, using the same
6625 	 * framework callback.
6626 	 */
6627 	if (synch) {
6628 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6629 		    "synchronous execution status %x\n",
6630 		    spx->txlt_sata_pkt->satapkt_reason);
6631 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
6632 	}
6633 	return (TRAN_ACCEPT);
6634 }
6635 
6636 
6637 /*
6638  * Send pkt to SATA HBA driver
6639  *
6640  * This function may be called only if the operation is requested by scsi_pkt,
6641  * i.e. scsi_pkt is not NULL.
6642  *
6643  * This function has to be called with cport mutex held. It does release
6644  * the mutex when it calls HBA driver sata_tran_start function and
6645  * re-acquires it afterwards.
6646  *
6647  * If return value is 0, pkt was accepted, -1 otherwise
6648  * rval is set to appropriate sata_scsi_start return value.
6649  *
6650  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
6651  * have called the sata_pkt callback function for this packet.
6652  *
6653  * The scsi callback has to be performed by the caller of this routine.
6654  */
6655 static int
6656 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
6657 {
6658 	int stat;
6659 	uint8_t cport = SATA_TXLT_CPORT(spx);
6660 	uint8_t pmport = SATA_TXLT_PMPORT(spx);
6661 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6662 	sata_drive_info_t *sdinfo;
6663 	sata_pmult_info_t *pminfo;
6664 	sata_pmport_info_t *pmportinfo = NULL;
6665 	sata_device_t *sata_device = NULL;
6666 	uint8_t cmd;
6667 	struct sata_cmd_flags cmd_flags;
6668 
6669 	ASSERT(spx->txlt_sata_pkt != NULL);
6670 
6671 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6672 
6673 	sdinfo = sata_get_device_info(sata_hba_inst,
6674 	    &spx->txlt_sata_pkt->satapkt_device);
6675 	ASSERT(sdinfo != NULL);
6676 
6677 	/* Clear device reset state? */
6678 	/* qual should be XXX_DPMPORT, but add XXX_PMPORT in case */
6679 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT ||
6680 	    sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT) {
6681 
6682 		/*
6683 		 * Get the pmult_info of the its parent port multiplier, all
6684 		 * sub-devices share a common device reset flags on in
6685 		 * pmult_info.
6686 		 */
6687 		pminfo = SATA_PMULT_INFO(sata_hba_inst, cport);
6688 		pmportinfo = pminfo->pmult_dev_port[pmport];
6689 		ASSERT(pminfo != NULL);
6690 		if (pminfo->pmult_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
6691 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6692 			    sata_clear_dev_reset = B_TRUE;
6693 			pminfo->pmult_event_flags &=
6694 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6695 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6696 			    "sata_hba_start: clearing device reset state"
6697 			    "on pmult.\n", NULL);
6698 		}
6699 	} else {
6700 		if (sdinfo->satadrv_event_flags &
6701 		    SATA_EVNT_CLEAR_DEVICE_RESET) {
6702 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6703 			    sata_clear_dev_reset = B_TRUE;
6704 			sdinfo->satadrv_event_flags &=
6705 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6706 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6707 			    "sata_hba_start: clearing device reset state\n",
6708 			    NULL);
6709 		}
6710 	}
6711 
6712 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
6713 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
6714 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
6715 
6716 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6717 
6718 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6719 	    "Sata cmd 0x%2x\n", cmd);
6720 
6721 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
6722 	    spx->txlt_sata_pkt);
6723 
6724 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6725 	/*
6726 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
6727 	 * with the sata callback, the sata_pkt could be already destroyed
6728 	 * by the time we check ther return status from the hba_start()
6729 	 * function, because sata_scsi_destroy_pkt() could have been already
6730 	 * called (perhaps in the interrupt context). So, in such case, there
6731 	 * should be no references to it. In other cases, sata_pkt still
6732 	 * exists.
6733 	 */
6734 	if (stat == SATA_TRAN_ACCEPTED) {
6735 		/*
6736 		 * pkt accepted for execution.
6737 		 * If it was executed synchronously, it is already completed
6738 		 * and pkt completion_reason indicates completion status.
6739 		 */
6740 		*rval = TRAN_ACCEPT;
6741 		return (0);
6742 	}
6743 
6744 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6745 	switch (stat) {
6746 	case SATA_TRAN_QUEUE_FULL:
6747 		/*
6748 		 * Controller detected queue full condition.
6749 		 */
6750 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
6751 		    "sata_hba_start: queue full\n", NULL);
6752 
6753 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6754 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
6755 
6756 		*rval = TRAN_BUSY;
6757 		break;
6758 
6759 	case SATA_TRAN_PORT_ERROR:
6760 		/*
6761 		 * Communication/link with device or general port error
6762 		 * detected before pkt execution begun.
6763 		 */
6764 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6765 		    SATA_ADDR_CPORT ||
6766 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6767 		    SATA_ADDR_DCPORT)
6768 			sata_log(sata_hba_inst, CE_CONT,
6769 			    "SATA port %d error",
6770 			    sata_device->satadev_addr.cport);
6771 		else
6772 			sata_log(sata_hba_inst, CE_CONT,
6773 			    "SATA port %d:%d error\n",
6774 			    sata_device->satadev_addr.cport,
6775 			    sata_device->satadev_addr.pmport);
6776 
6777 		/*
6778 		 * Update the port/device structure.
6779 		 * sata_pkt should be still valid. Since port error is
6780 		 * returned, sata_device content should reflect port
6781 		 * state - it means, that sata address have been changed,
6782 		 * because original packet's sata address refered to a device
6783 		 * attached to some port.
6784 		 */
6785 		if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT ||
6786 		    sata_device->satadev_addr.qual == SATA_ADDR_PMPORT) {
6787 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6788 			mutex_enter(&pmportinfo->pmport_mutex);
6789 			sata_update_pmport_info(sata_hba_inst, sata_device);
6790 			mutex_exit(&pmportinfo->pmport_mutex);
6791 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6792 		} else {
6793 			sata_update_port_info(sata_hba_inst, sata_device);
6794 		}
6795 
6796 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6797 		*rval = TRAN_FATAL_ERROR;
6798 		break;
6799 
6800 	case SATA_TRAN_CMD_UNSUPPORTED:
6801 		/*
6802 		 * Command rejected by HBA as unsupported. It was HBA driver
6803 		 * that rejected the command, command was not sent to
6804 		 * an attached device.
6805 		 */
6806 		if ((sdinfo != NULL) &&
6807 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
6808 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6809 			    "sat_hba_start: cmd 0x%2x rejected "
6810 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
6811 
6812 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6813 		(void) sata_txlt_invalid_command(spx);
6814 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6815 
6816 		*rval = TRAN_ACCEPT;
6817 		break;
6818 
6819 	case SATA_TRAN_BUSY:
6820 		/*
6821 		 * Command rejected by HBA because other operation prevents
6822 		 * accepting the packet, or device is in RESET condition.
6823 		 */
6824 		if (sdinfo != NULL) {
6825 			sdinfo->satadrv_state =
6826 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
6827 
6828 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
6829 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6830 				    "sata_hba_start: cmd 0x%2x rejected "
6831 				    "because of device reset condition\n",
6832 				    cmd);
6833 			} else {
6834 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6835 				    "sata_hba_start: cmd 0x%2x rejected "
6836 				    "with SATA_TRAN_BUSY status\n",
6837 				    cmd);
6838 			}
6839 		}
6840 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6841 		*rval = TRAN_BUSY;
6842 		break;
6843 
6844 	default:
6845 		/* Unrecognized HBA response */
6846 		SATA_LOG_D((sata_hba_inst, CE_WARN,
6847 		    "sata_hba_start: unrecognized HBA response "
6848 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
6849 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6850 		*rval = TRAN_FATAL_ERROR;
6851 		break;
6852 	}
6853 
6854 	/*
6855 	 * If we got here, the packet was rejected.
6856 	 * Check if we need to remember reset state clearing request
6857 	 */
6858 	if (cmd_flags.sata_clear_dev_reset) {
6859 		/*
6860 		 * Check if device is still configured - it may have
6861 		 * disapeared from the configuration
6862 		 */
6863 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6864 		if (sdinfo != NULL) {
6865 			/*
6866 			 * Restore the flag that requests clearing of
6867 			 * the device reset state,
6868 			 * so the next sata packet may carry it to HBA.
6869 			 */
6870 			if (sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT ||
6871 			    sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT) {
6872 				pminfo->pmult_event_flags |=
6873 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6874 			} else {
6875 				sdinfo->satadrv_event_flags |=
6876 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6877 			}
6878 		}
6879 	}
6880 	return (-1);
6881 }
6882 
6883 /*
6884  * Scsi response setup for invalid LBA
6885  *
6886  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
6887  */
6888 static int
6889 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
6890 {
6891 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6892 	struct scsi_extended_sense *sense;
6893 
6894 	scsipkt->pkt_reason = CMD_CMPLT;
6895 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6896 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6897 	*scsipkt->pkt_scbp = STATUS_CHECK;
6898 
6899 	*scsipkt->pkt_scbp = STATUS_CHECK;
6900 	sense = sata_arq_sense(spx);
6901 	sense->es_key = KEY_ILLEGAL_REQUEST;
6902 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
6903 
6904 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6905 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6906 
6907 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6908 	    scsipkt->pkt_comp != NULL) {
6909 		/* scsi callback required */
6910 		if (servicing_interrupt()) {
6911 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6912 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6913 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6914 				return (TRAN_BUSY);
6915 			}
6916 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6917 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6918 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6919 			/* Scheduling the callback failed */
6920 			return (TRAN_BUSY);
6921 		}
6922 	}
6923 	return (TRAN_ACCEPT);
6924 }
6925 
6926 
6927 /*
6928  * Analyze device status and error registers and translate them into
6929  * appropriate scsi sense codes.
6930  * NOTE: non-packet commands only for now
6931  */
6932 static void
6933 sata_decode_device_error(sata_pkt_txlate_t *spx,
6934     struct scsi_extended_sense *sense)
6935 {
6936 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
6937 
6938 	ASSERT(sense != NULL);
6939 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
6940 	    SATA_STATUS_ERR);
6941 
6942 
6943 	if (err_reg & SATA_ERROR_ICRC) {
6944 		sense->es_key = KEY_ABORTED_COMMAND;
6945 		sense->es_add_code = 0x08; /* Communication failure */
6946 		return;
6947 	}
6948 
6949 	if (err_reg & SATA_ERROR_UNC) {
6950 		sense->es_key = KEY_MEDIUM_ERROR;
6951 		/* Information bytes (LBA) need to be set by a caller */
6952 		return;
6953 	}
6954 
6955 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
6956 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
6957 		sense->es_key = KEY_UNIT_ATTENTION;
6958 		sense->es_add_code = 0x3a; /* No media present */
6959 		return;
6960 	}
6961 
6962 	if (err_reg & SATA_ERROR_IDNF) {
6963 		if (err_reg & SATA_ERROR_ABORT) {
6964 			sense->es_key = KEY_ABORTED_COMMAND;
6965 		} else {
6966 			sense->es_key = KEY_ILLEGAL_REQUEST;
6967 			sense->es_add_code = 0x21; /* LBA out of range */
6968 		}
6969 		return;
6970 	}
6971 
6972 	if (err_reg & SATA_ERROR_ABORT) {
6973 		ASSERT(spx->txlt_sata_pkt != NULL);
6974 		sense->es_key = KEY_ABORTED_COMMAND;
6975 		return;
6976 	}
6977 }
6978 
6979 /*
6980  * Extract error LBA from sata_pkt.satapkt_cmd register fields
6981  */
6982 static void
6983 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
6984 {
6985 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
6986 
6987 	*lba = 0;
6988 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
6989 		*lba = sata_cmd->satacmd_lba_high_msb;
6990 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
6991 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
6992 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
6993 		*lba = sata_cmd->satacmd_device_reg & 0xf;
6994 	}
6995 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
6996 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
6997 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
6998 }
6999 
7000 /*
7001  * This is fixed sense format - if LBA exceeds the info field size,
7002  * no valid info will be returned (valid bit in extended sense will
7003  * be set to 0).
7004  */
7005 static struct scsi_extended_sense *
7006 sata_arq_sense(sata_pkt_txlate_t *spx)
7007 {
7008 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7009 	struct scsi_arq_status *arqs;
7010 	struct scsi_extended_sense *sense;
7011 
7012 	/* Fill ARQ sense data */
7013 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7014 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
7015 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
7016 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
7017 	arqs->sts_rqpkt_reason = CMD_CMPLT;
7018 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7019 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7020 	arqs->sts_rqpkt_resid = 0;
7021 	sense = &arqs->sts_sensedata;
7022 	bzero(sense, sizeof (struct scsi_extended_sense));
7023 	sata_fixed_sense_data_preset(sense);
7024 	return (sense);
7025 }
7026 
7027 /*
7028  * ATA Pass Through support
7029  * Sets flags indicating that an invalid value was found in some
7030  * field in the command.  It could be something illegal according to
7031  * the SAT-2 spec or it could be a feature that is not (yet?)
7032  * supported.
7033  */
7034 static int
7035 sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *spx)
7036 {
7037 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7038 	struct scsi_extended_sense *sense = sata_arq_sense(spx);
7039 
7040 	scsipkt->pkt_reason = CMD_CMPLT;
7041 	*scsipkt->pkt_scbp = STATUS_CHECK;
7042 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7043 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7044 
7045 	sense = sata_arq_sense(spx);
7046 	sense->es_key = KEY_ILLEGAL_REQUEST;
7047 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7048 
7049 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
7050 	    scsipkt->pkt_comp != NULL) {
7051 		/* scsi callback required */
7052 		if (servicing_interrupt()) {
7053 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7054 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7055 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
7056 				return (TRAN_BUSY);
7057 			}
7058 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7059 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7060 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
7061 			/* Scheduling the callback failed */
7062 			return (TRAN_BUSY);
7063 		}
7064 	}
7065 
7066 	return (TRAN_ACCEPT);
7067 }
7068 
7069 /*
7070  * Emulated SATA Read/Write command completion for zero-length requests.
7071  * This request always succedes, so in synchronous mode it always returns
7072  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
7073  * callback cannot be scheduled.
7074  */
7075 static int
7076 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
7077 {
7078 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7079 
7080 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7081 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7082 	scsipkt->pkt_reason = CMD_CMPLT;
7083 	*scsipkt->pkt_scbp = STATUS_GOOD;
7084 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
7085 		/* scsi callback required - have to schedule it */
7086 		if (servicing_interrupt()) {
7087 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7088 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7089 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
7090 				return (TRAN_BUSY);
7091 			}
7092 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7093 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7094 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
7095 			/* Scheduling the callback failed */
7096 			return (TRAN_BUSY);
7097 		}
7098 	}
7099 	return (TRAN_ACCEPT);
7100 }
7101 
7102 
7103 /*
7104  * Translate completion status of SATA read/write commands into scsi response.
7105  * pkt completion_reason is checked to determine the completion status.
7106  * Do scsi callback if necessary.
7107  *
7108  * Note: this function may be called also for synchronously executed
7109  * commands.
7110  * This function may be used only if scsi_pkt is non-NULL.
7111  */
7112 static void
7113 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
7114 {
7115 	sata_pkt_txlate_t *spx =
7116 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7117 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7118 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7119 	struct scsi_extended_sense *sense;
7120 	uint64_t lba;
7121 	struct buf *bp;
7122 	int rval;
7123 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7124 		/* Normal completion */
7125 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7126 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
7127 		scsipkt->pkt_reason = CMD_CMPLT;
7128 		*scsipkt->pkt_scbp = STATUS_GOOD;
7129 		if (spx->txlt_tmp_buf != NULL) {
7130 			/* Temporary buffer was used */
7131 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7132 			if (bp->b_flags & B_READ) {
7133 				rval = ddi_dma_sync(
7134 				    spx->txlt_buf_dma_handle, 0, 0,
7135 				    DDI_DMA_SYNC_FORCPU);
7136 				ASSERT(rval == DDI_SUCCESS);
7137 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7138 				    bp->b_bcount);
7139 			}
7140 		}
7141 	} else {
7142 		/*
7143 		 * Something went wrong - analyze return
7144 		 */
7145 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7146 		    STATE_SENT_CMD | STATE_GOT_STATUS;
7147 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7148 		*scsipkt->pkt_scbp = STATUS_CHECK;
7149 		sense = sata_arq_sense(spx);
7150 		ASSERT(sense != NULL);
7151 
7152 		/*
7153 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
7154 		 * extract from device registers the failing LBA.
7155 		 */
7156 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
7157 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
7158 			    (scmd->satacmd_lba_mid_msb != 0 ||
7159 			    scmd->satacmd_lba_high_msb != 0)) {
7160 				/*
7161 				 * We have problem reporting this cmd LBA
7162 				 * in fixed sense data format, because of
7163 				 * the size of the scsi LBA fields.
7164 				 */
7165 				sense->es_valid = 0;
7166 			} else {
7167 				sata_extract_error_lba(spx, &lba);
7168 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
7169 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
7170 				sense->es_info_3 = (lba & 0xFF00) >> 8;
7171 				sense->es_info_4 = lba & 0xFF;
7172 			}
7173 		} else {
7174 			/* Invalid extended sense info */
7175 			sense->es_valid = 0;
7176 		}
7177 
7178 		switch (sata_pkt->satapkt_reason) {
7179 		case SATA_PKT_PORT_ERROR:
7180 			/* We may want to handle DEV GONE state as well */
7181 			/*
7182 			 * We have no device data. Assume no data transfered.
7183 			 */
7184 			sense->es_key = KEY_HARDWARE_ERROR;
7185 			break;
7186 
7187 		case SATA_PKT_DEV_ERROR:
7188 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7189 			    SATA_STATUS_ERR) {
7190 				/*
7191 				 * determine dev error reason from error
7192 				 * reg content
7193 				 */
7194 				sata_decode_device_error(spx, sense);
7195 				if (sense->es_key == KEY_MEDIUM_ERROR) {
7196 					switch (scmd->satacmd_cmd_reg) {
7197 					case SATAC_READ_DMA:
7198 					case SATAC_READ_DMA_EXT:
7199 					case SATAC_READ_DMA_QUEUED:
7200 					case SATAC_READ_DMA_QUEUED_EXT:
7201 					case SATAC_READ_FPDMA_QUEUED:
7202 						/* Unrecovered read error */
7203 						sense->es_add_code =
7204 						    SD_SCSI_ASC_UNREC_READ_ERR;
7205 						break;
7206 					case SATAC_WRITE_DMA:
7207 					case SATAC_WRITE_DMA_EXT:
7208 					case SATAC_WRITE_DMA_QUEUED:
7209 					case SATAC_WRITE_DMA_QUEUED_EXT:
7210 					case SATAC_WRITE_FPDMA_QUEUED:
7211 						/* Write error */
7212 						sense->es_add_code =
7213 						    SD_SCSI_ASC_WRITE_ERR;
7214 						break;
7215 					default:
7216 						/* Internal error */
7217 						SATA_LOG_D((
7218 						    spx->txlt_sata_hba_inst,
7219 						    CE_WARN,
7220 						    "sata_txlt_rw_completion :"
7221 						    "internal error - invalid "
7222 						    "command 0x%2x",
7223 						    scmd->satacmd_cmd_reg));
7224 						break;
7225 					}
7226 				}
7227 				break;
7228 			}
7229 			/* No extended sense key - no info available */
7230 			scsipkt->pkt_reason = CMD_INCOMPLETE;
7231 			break;
7232 
7233 		case SATA_PKT_TIMEOUT:
7234 			scsipkt->pkt_reason = CMD_TIMEOUT;
7235 			scsipkt->pkt_statistics |=
7236 			    STAT_TIMEOUT | STAT_DEV_RESET;
7237 			sense->es_key = KEY_ABORTED_COMMAND;
7238 			break;
7239 
7240 		case SATA_PKT_ABORTED:
7241 			scsipkt->pkt_reason = CMD_ABORTED;
7242 			scsipkt->pkt_statistics |= STAT_ABORTED;
7243 			sense->es_key = KEY_ABORTED_COMMAND;
7244 			break;
7245 
7246 		case SATA_PKT_RESET:
7247 			scsipkt->pkt_reason = CMD_RESET;
7248 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7249 			sense->es_key = KEY_ABORTED_COMMAND;
7250 			break;
7251 
7252 		default:
7253 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7254 			    "sata_txlt_rw_completion: "
7255 			    "invalid packet completion reason"));
7256 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7257 			break;
7258 		}
7259 	}
7260 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7261 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7262 
7263 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7264 		/* scsi callback required */
7265 		scsi_hba_pkt_comp(scsipkt);
7266 }
7267 
7268 
7269 /*
7270  * Translate completion status of non-data commands (i.e. commands returning
7271  * no data).
7272  * pkt completion_reason is checked to determine the completion status.
7273  * Do scsi callback if necessary (FLAG_NOINTR == 0)
7274  *
7275  * Note: this function may be called also for synchronously executed
7276  * commands.
7277  * This function may be used only if scsi_pkt is non-NULL.
7278  */
7279 
7280 static	void
7281 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
7282 {
7283 	sata_pkt_txlate_t *spx =
7284 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7285 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7286 
7287 	sata_set_arq_data(sata_pkt);
7288 
7289 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7290 		/* scsi callback required */
7291 		scsi_hba_pkt_comp(scsipkt);
7292 }
7293 
7294 /*
7295  * Completion handler for ATA Pass Through command
7296  */
7297 static void
7298 sata_txlt_apt_completion(sata_pkt_t *sata_pkt)
7299 {
7300 	sata_pkt_txlate_t *spx =
7301 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7302 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7303 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7304 	struct buf *bp;
7305 	uint8_t sense_key = 0, addl_sense_code = 0, addl_sense_qual = 0;
7306 
7307 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7308 		/* Normal completion */
7309 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7310 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
7311 		scsipkt->pkt_reason = CMD_CMPLT;
7312 		*scsipkt->pkt_scbp = STATUS_GOOD;
7313 
7314 		/*
7315 		 * If the command has CK_COND set
7316 		 */
7317 		if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
7318 			*scsipkt->pkt_scbp = STATUS_CHECK;
7319 			sata_fill_ata_return_desc(sata_pkt,
7320 			    KEY_RECOVERABLE_ERROR,
7321 			    SD_SCSI_ASC_ATP_INFO_AVAIL, 0);
7322 		}
7323 
7324 		if (spx->txlt_tmp_buf != NULL) {
7325 			/* Temporary buffer was used */
7326 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7327 			if (bp->b_flags & B_READ) {
7328 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7329 				    bp->b_bcount);
7330 			}
7331 		}
7332 	} else {
7333 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7334 		    STATE_SENT_CMD | STATE_GOT_STATUS;
7335 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7336 		*scsipkt->pkt_scbp = STATUS_CHECK;
7337 
7338 		/*
7339 		 * If DF or ERR was set, the HBA should have copied out the
7340 		 * status and error registers to the satacmd structure.
7341 		 */
7342 		if (scmd->satacmd_status_reg & SATA_STATUS_DF) {
7343 			sense_key = KEY_HARDWARE_ERROR;
7344 			addl_sense_code = SD_SCSI_ASC_INTERNAL_TARGET_FAILURE;
7345 			addl_sense_qual = 0;
7346 		} else if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
7347 			if (scmd->satacmd_error_reg & SATA_ERROR_NM) {
7348 				sense_key = KEY_NOT_READY;
7349 				addl_sense_code =
7350 				    SD_SCSI_ASC_MEDIUM_NOT_PRESENT;
7351 				addl_sense_qual = 0;
7352 			} else if (scmd->satacmd_error_reg & SATA_ERROR_UNC) {
7353 				sense_key = KEY_MEDIUM_ERROR;
7354 				addl_sense_code = SD_SCSI_ASC_UNREC_READ_ERR;
7355 				addl_sense_qual = 0;
7356 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ILI) {
7357 				sense_key = KEY_DATA_PROTECT;
7358 				addl_sense_code = SD_SCSI_ASC_WRITE_PROTECTED;
7359 				addl_sense_qual = 0;
7360 			} else if (scmd->satacmd_error_reg & SATA_ERROR_IDNF) {
7361 				sense_key = KEY_ILLEGAL_REQUEST;
7362 				addl_sense_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
7363 				addl_sense_qual = 0;
7364 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
7365 				sense_key = KEY_ABORTED_COMMAND;
7366 				addl_sense_code = SD_SCSI_ASC_NO_ADD_SENSE;
7367 				addl_sense_qual = 0;
7368 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MC) {
7369 				sense_key = KEY_UNIT_ATTENTION;
7370 				addl_sense_code =
7371 				    SD_SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED;
7372 				addl_sense_qual = 0;
7373 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MCR) {
7374 				sense_key = KEY_UNIT_ATTENTION;
7375 				addl_sense_code = SD_SCSI_ASC_OP_MEDIUM_REM_REQ;
7376 				addl_sense_qual = 0;
7377 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ICRC) {
7378 				sense_key = KEY_ABORTED_COMMAND;
7379 				addl_sense_code =
7380 				    SD_SCSI_ASC_INFO_UNIT_IUCRC_ERR;
7381 				addl_sense_qual = 0;
7382 			}
7383 		}
7384 
7385 		sata_fill_ata_return_desc(sata_pkt, sense_key, addl_sense_code,
7386 		    addl_sense_qual);
7387 	}
7388 
7389 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7390 		/* scsi callback required */
7391 		scsi_hba_pkt_comp(scsipkt);
7392 }
7393 
7394 /*
7395  * j
7396  */
7397 static void
7398 sata_fill_ata_return_desc(sata_pkt_t *sata_pkt, uint8_t sense_key,
7399     uint8_t addl_sense_code, uint8_t addl_sense_qual)
7400 {
7401 	sata_pkt_txlate_t *spx =
7402 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7403 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7404 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7405 	struct sata_apt_sense_data *apt_sd =
7406 	    (struct sata_apt_sense_data *)scsipkt->pkt_scbp;
7407 	struct scsi_descr_sense_hdr *sds = &(apt_sd->apt_sd_hdr);
7408 	struct scsi_ata_status_ret_sense_descr *ata_ret_desc =
7409 	    &(apt_sd->apt_sd_sense);
7410 	int extend = 0;
7411 
7412 	if ((scsipkt->pkt_cdbp[0] == SPC3_CMD_ATA_COMMAND_PASS_THROUGH16) &&
7413 	    (scsipkt->pkt_cdbp[2] & SATL_APT_BM_EXTEND))
7414 		extend = 1;
7415 
7416 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7417 
7418 	/* update the residual count */
7419 	*(uchar_t *)&apt_sd->apt_status = STATUS_CHECK;
7420 	*(uchar_t *)&apt_sd->apt_rqpkt_status = STATUS_GOOD;
7421 	apt_sd->apt_rqpkt_reason = CMD_CMPLT;
7422 	apt_sd->apt_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7423 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7424 	apt_sd->apt_rqpkt_resid = scsipkt->pkt_scblen -
7425 	    sizeof (struct sata_apt_sense_data);
7426 
7427 	/*
7428 	 * Fill in the Descriptor sense header
7429 	 */
7430 	bzero(sds, sizeof (struct scsi_descr_sense_hdr));
7431 	sds->ds_code = CODE_FMT_DESCR_CURRENT;
7432 	sds->ds_class = CLASS_EXTENDED_SENSE;
7433 	sds->ds_key = sense_key & 0xf;
7434 	sds->ds_add_code = addl_sense_code;
7435 	sds->ds_qual_code = addl_sense_qual;
7436 	sds->ds_addl_sense_length =
7437 	    sizeof (struct scsi_ata_status_ret_sense_descr);
7438 
7439 	/*
7440 	 * Fill in the ATA Return descriptor sense data
7441 	 */
7442 	bzero(ata_ret_desc, sizeof (struct scsi_ata_status_ret_sense_descr));
7443 	ata_ret_desc->ars_descr_type = DESCR_ATA_STATUS_RETURN;
7444 	ata_ret_desc->ars_addl_length = 0xc;
7445 	ata_ret_desc->ars_error = scmd->satacmd_error_reg;
7446 	ata_ret_desc->ars_sec_count_lsb = scmd->satacmd_sec_count_lsb;
7447 	ata_ret_desc->ars_lba_low_lsb = scmd->satacmd_lba_low_lsb;
7448 	ata_ret_desc->ars_lba_mid_lsb = scmd->satacmd_lba_mid_lsb;
7449 	ata_ret_desc->ars_lba_high_lsb = scmd->satacmd_lba_high_lsb;
7450 	ata_ret_desc->ars_device = scmd->satacmd_device_reg;
7451 	ata_ret_desc->ars_status = scmd->satacmd_status_reg;
7452 
7453 	if (extend == 1) {
7454 		ata_ret_desc->ars_extend = 1;
7455 		ata_ret_desc->ars_sec_count_msb = scmd->satacmd_sec_count_msb;
7456 		ata_ret_desc->ars_lba_low_msb = scmd->satacmd_lba_low_msb;
7457 		ata_ret_desc->ars_lba_mid_msb = scmd->satacmd_lba_mid_msb;
7458 		ata_ret_desc->ars_lba_high_msb = scmd->satacmd_lba_high_msb;
7459 	} else {
7460 		ata_ret_desc->ars_extend = 0;
7461 		ata_ret_desc->ars_sec_count_msb = 0;
7462 		ata_ret_desc->ars_lba_low_msb = 0;
7463 		ata_ret_desc->ars_lba_mid_msb = 0;
7464 		ata_ret_desc->ars_lba_high_msb = 0;
7465 	}
7466 }
7467 
7468 static	void
7469 sata_set_arq_data(sata_pkt_t *sata_pkt)
7470 {
7471 	sata_pkt_txlate_t *spx =
7472 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7473 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7474 	struct scsi_extended_sense *sense;
7475 
7476 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7477 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7478 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7479 		/* Normal completion */
7480 		scsipkt->pkt_reason = CMD_CMPLT;
7481 		*scsipkt->pkt_scbp = STATUS_GOOD;
7482 	} else {
7483 		/* Something went wrong */
7484 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7485 		*scsipkt->pkt_scbp = STATUS_CHECK;
7486 		sense = sata_arq_sense(spx);
7487 		switch (sata_pkt->satapkt_reason) {
7488 		case SATA_PKT_PORT_ERROR:
7489 			/*
7490 			 * We have no device data. Assume no data transfered.
7491 			 */
7492 			sense->es_key = KEY_HARDWARE_ERROR;
7493 			break;
7494 
7495 		case SATA_PKT_DEV_ERROR:
7496 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7497 			    SATA_STATUS_ERR) {
7498 				/*
7499 				 * determine dev error reason from error
7500 				 * reg content
7501 				 */
7502 				sata_decode_device_error(spx, sense);
7503 				break;
7504 			}
7505 			/* No extended sense key - no info available */
7506 			break;
7507 
7508 		case SATA_PKT_TIMEOUT:
7509 			scsipkt->pkt_reason = CMD_TIMEOUT;
7510 			scsipkt->pkt_statistics |=
7511 			    STAT_TIMEOUT | STAT_DEV_RESET;
7512 			/* No extended sense key ? */
7513 			break;
7514 
7515 		case SATA_PKT_ABORTED:
7516 			scsipkt->pkt_reason = CMD_ABORTED;
7517 			scsipkt->pkt_statistics |= STAT_ABORTED;
7518 			/* No extended sense key ? */
7519 			break;
7520 
7521 		case SATA_PKT_RESET:
7522 			/* pkt aborted by an explicit reset from a host */
7523 			scsipkt->pkt_reason = CMD_RESET;
7524 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7525 			break;
7526 
7527 		default:
7528 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7529 			    "sata_txlt_nodata_cmd_completion: "
7530 			    "invalid packet completion reason %d",
7531 			    sata_pkt->satapkt_reason));
7532 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7533 			break;
7534 		}
7535 
7536 	}
7537 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7538 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7539 }
7540 
7541 
7542 /*
7543  * Build Mode sense R/W recovery page
7544  * NOT IMPLEMENTED
7545  */
7546 
7547 static int
7548 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7549 {
7550 #ifndef __lock_lint
7551 	_NOTE(ARGUNUSED(sdinfo))
7552 	_NOTE(ARGUNUSED(pcntrl))
7553 	_NOTE(ARGUNUSED(buf))
7554 #endif
7555 	return (0);
7556 }
7557 
7558 /*
7559  * Build Mode sense caching page  -  scsi-3 implementation.
7560  * Page length distinguishes previous format from scsi-3 format.
7561  * buf must have space for 0x12 bytes.
7562  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
7563  *
7564  */
7565 static int
7566 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7567 {
7568 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
7569 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7570 
7571 	/*
7572 	 * Most of the fields are set to 0, being not supported and/or disabled
7573 	 */
7574 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
7575 
7576 	/* Saved paramters not supported */
7577 	if (pcntrl == 3)
7578 		return (0);
7579 	if (pcntrl == 0 || pcntrl == 2) {
7580 		/*
7581 		 * For now treat current and default parameters as same
7582 		 * That may have to change, if target driver will complain
7583 		 */
7584 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
7585 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7586 
7587 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
7588 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
7589 			page->dra = 1;		/* Read Ahead disabled */
7590 			page->rcd = 1;		/* Read Cache disabled */
7591 		}
7592 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
7593 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
7594 			page->wce = 1;		/* Write Cache enabled */
7595 	} else {
7596 		/* Changeable parameters */
7597 		page->mode_page.code = MODEPAGE_CACHING;
7598 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7599 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7600 			page->dra = 1;
7601 			page->rcd = 1;
7602 		}
7603 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
7604 			page->wce = 1;
7605 	}
7606 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7607 	    sizeof (struct mode_page));
7608 }
7609 
7610 /*
7611  * Build Mode sense exception cntrl page
7612  */
7613 static int
7614 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7615 {
7616 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
7617 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7618 
7619 	/*
7620 	 * Most of the fields are set to 0, being not supported and/or disabled
7621 	 */
7622 	bzero(buf, PAGELENGTH_INFO_EXCPT);
7623 
7624 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
7625 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
7626 
7627 	/* Indicate that this is page is saveable */
7628 	page->mode_page.ps = 1;
7629 
7630 	/*
7631 	 * We will return the same data for default, current and saved page.
7632 	 * The only changeable bit is dexcpt and that bit is required
7633 	 * by the ATA specification to be preserved across power cycles.
7634 	 */
7635 	if (pcntrl != 1) {
7636 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
7637 		page->mrie = MRIE_ONLY_ON_REQUEST;
7638 	}
7639 	else
7640 		page->dexcpt = 1;	/* Only changeable parameter */
7641 
7642 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page));
7643 }
7644 
7645 
7646 static int
7647 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7648 {
7649 	struct mode_acoustic_management *page =
7650 	    (struct mode_acoustic_management *)buf;
7651 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7652 
7653 	/*
7654 	 * Most of the fields are set to 0, being not supported and/or disabled
7655 	 */
7656 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
7657 
7658 	switch (pcntrl) {
7659 	case P_CNTRL_DEFAULT:
7660 		/*  default paramters not supported */
7661 		return (0);
7662 
7663 	case P_CNTRL_CURRENT:
7664 	case P_CNTRL_SAVED:
7665 		/* Saved and current are supported and are identical */
7666 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7667 		page->mode_page.length =
7668 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7669 		page->mode_page.ps = 1;
7670 
7671 		/* Word 83 indicates if feature is supported */
7672 		/* If feature is not supported */
7673 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
7674 			page->acoustic_manag_enable =
7675 			    ACOUSTIC_DISABLED;
7676 		} else {
7677 			page->acoustic_manag_enable =
7678 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
7679 			    != 0);
7680 			/* Word 94 inidicates the value */
7681 #ifdef	_LITTLE_ENDIAN
7682 			page->acoustic_manag_level =
7683 			    (uchar_t)sata_id->ai_acoustic;
7684 			page->vendor_recommended_value =
7685 			    sata_id->ai_acoustic >> 8;
7686 #else
7687 			page->acoustic_manag_level =
7688 			    sata_id->ai_acoustic >> 8;
7689 			page->vendor_recommended_value =
7690 			    (uchar_t)sata_id->ai_acoustic;
7691 #endif
7692 		}
7693 		break;
7694 
7695 	case P_CNTRL_CHANGEABLE:
7696 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7697 		page->mode_page.length =
7698 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7699 		page->mode_page.ps = 1;
7700 
7701 		/* Word 83 indicates if the feature is supported */
7702 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
7703 			page->acoustic_manag_enable =
7704 			    ACOUSTIC_ENABLED;
7705 			page->acoustic_manag_level = 0xff;
7706 		}
7707 		break;
7708 	}
7709 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7710 	    sizeof (struct mode_page));
7711 }
7712 
7713 
7714 /*
7715  * Build Mode sense power condition page.
7716  */
7717 static int
7718 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7719 {
7720 	struct mode_info_power_cond *page = (struct mode_info_power_cond *)buf;
7721 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7722 
7723 	/*
7724 	 * Most of the fields are set to 0, being not supported and/or disabled
7725 	 * power condition page length was 0x0a
7726 	 */
7727 	bzero(buf, sizeof (struct mode_info_power_cond));
7728 
7729 	if (pcntrl == P_CNTRL_DEFAULT) {
7730 		/*  default paramters not supported */
7731 		return (0);
7732 	}
7733 
7734 	page->mode_page.code = MODEPAGE_POWER_COND;
7735 	page->mode_page.length = sizeof (struct mode_info_power_cond);
7736 
7737 	if (sata_id->ai_cap && SATA_STANDBYTIMER) {
7738 		page->standby = 1;
7739 		bcopy(sdinfo->satadrv_standby_timer, page->standby_cond_timer,
7740 		    sizeof (uchar_t) * 4);
7741 	}
7742 
7743 	return (sizeof (struct mode_info_power_cond));
7744 }
7745 
7746 /*
7747  * Process mode select caching page 8 (scsi3 format only).
7748  * Read Ahead (same as read cache) and Write Cache may be turned on and off
7749  * if these features are supported by the device. If these features are not
7750  * supported, the command will be terminated with STATUS_CHECK.
7751  * This function fails only if the SET FEATURE command sent to
7752  * the device fails. The page format is not varified, assuming that the
7753  * target driver operates correctly - if parameters length is too short,
7754  * we just drop the page.
7755  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
7756  * setting have to be changed.
7757  * SET FEATURE command is executed synchronously, i.e. we wait here until
7758  * it is completed, regardless of the scsi pkt directives.
7759  *
7760  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
7761  * changing DRA will change RCD.
7762  *
7763  * More than one SATA command may be executed to perform operations specified
7764  * by mode select pages. The first error terminates further execution.
7765  * Operations performed successully are not backed-up in such case.
7766  *
7767  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7768  * If operation resulted in changing device setup, dmod flag should be set to
7769  * one (1). If parameters were not changed, dmod flag should be set to 0.
7770  * Upon return, if operation required sending command to the device, the rval
7771  * should be set to the value returned by sata_hba_start. If operation
7772  * did not require device access, rval should be set to TRAN_ACCEPT.
7773  * The pagelen should be set to the length of the page.
7774  *
7775  * This function has to be called with a port mutex held.
7776  *
7777  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7778  */
7779 int
7780 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
7781     int parmlen, int *pagelen, int *rval, int *dmod)
7782 {
7783 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7784 	sata_drive_info_t *sdinfo;
7785 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7786 	sata_id_t *sata_id;
7787 	struct scsi_extended_sense *sense;
7788 	int wce, dra;	/* Current settings */
7789 
7790 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7791 	    &spx->txlt_sata_pkt->satapkt_device);
7792 	sata_id = &sdinfo->satadrv_id;
7793 	*dmod = 0;
7794 
7795 	/* Verify parameters length. If too short, drop it */
7796 	if ((PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7797 	    sizeof (struct mode_page)) > parmlen) {
7798 		*scsipkt->pkt_scbp = STATUS_CHECK;
7799 		sense = sata_arq_sense(spx);
7800 		sense->es_key = KEY_ILLEGAL_REQUEST;
7801 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7802 		*pagelen = parmlen;
7803 		*rval = TRAN_ACCEPT;
7804 		return (SATA_FAILURE);
7805 	}
7806 
7807 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
7808 
7809 	/* Current setting of Read Ahead (and Read Cache) */
7810 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
7811 		dra = 0;	/* 0 == not disabled */
7812 	else
7813 		dra = 1;
7814 	/* Current setting of Write Cache */
7815 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
7816 		wce = 1;
7817 	else
7818 		wce = 0;
7819 
7820 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
7821 		/* nothing to do */
7822 		*rval = TRAN_ACCEPT;
7823 		return (SATA_SUCCESS);
7824 	}
7825 
7826 	/*
7827 	 * Need to flip some setting
7828 	 * Set-up Internal SET FEATURES command(s)
7829 	 */
7830 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7831 	scmd->satacmd_addr_type = 0;
7832 	scmd->satacmd_device_reg = 0;
7833 	scmd->satacmd_status_reg = 0;
7834 	scmd->satacmd_error_reg = 0;
7835 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7836 	if (page->dra != dra || page->rcd != dra) {
7837 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7838 			/* Need to flip read ahead setting */
7839 			if (dra == 0)
7840 				/* Disable read ahead / read cache */
7841 				scmd->satacmd_features_reg =
7842 				    SATAC_SF_DISABLE_READ_AHEAD;
7843 			else
7844 				/* Enable read ahead  / read cache */
7845 				scmd->satacmd_features_reg =
7846 				    SATAC_SF_ENABLE_READ_AHEAD;
7847 
7848 			/* Transfer command to HBA */
7849 			if (sata_hba_start(spx, rval) != 0)
7850 				/*
7851 				 * Pkt not accepted for execution.
7852 				 */
7853 				return (SATA_FAILURE);
7854 
7855 			*dmod = 1;
7856 
7857 			/* Now process return */
7858 			if (spx->txlt_sata_pkt->satapkt_reason !=
7859 			    SATA_PKT_COMPLETED) {
7860 				goto failure;	/* Terminate */
7861 			}
7862 		} else {
7863 			*scsipkt->pkt_scbp = STATUS_CHECK;
7864 			sense = sata_arq_sense(spx);
7865 			sense->es_key = KEY_ILLEGAL_REQUEST;
7866 			sense->es_add_code =
7867 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7868 			*pagelen = parmlen;
7869 			*rval = TRAN_ACCEPT;
7870 			return (SATA_FAILURE);
7871 		}
7872 	}
7873 
7874 	/* Note that the packet is not removed, so it could be re-used */
7875 	if (page->wce != wce) {
7876 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
7877 			/* Need to flip Write Cache setting */
7878 			if (page->wce == 1)
7879 				/* Enable write cache */
7880 				scmd->satacmd_features_reg =
7881 				    SATAC_SF_ENABLE_WRITE_CACHE;
7882 			else
7883 				/* Disable write cache */
7884 				scmd->satacmd_features_reg =
7885 				    SATAC_SF_DISABLE_WRITE_CACHE;
7886 
7887 			/* Transfer command to HBA */
7888 			if (sata_hba_start(spx, rval) != 0)
7889 				/*
7890 				 * Pkt not accepted for execution.
7891 				 */
7892 				return (SATA_FAILURE);
7893 
7894 			*dmod = 1;
7895 
7896 			/* Now process return */
7897 			if (spx->txlt_sata_pkt->satapkt_reason !=
7898 			    SATA_PKT_COMPLETED) {
7899 				goto failure;
7900 			}
7901 		} else {
7902 			*scsipkt->pkt_scbp = STATUS_CHECK;
7903 			sense = sata_arq_sense(spx);
7904 			sense->es_key = KEY_ILLEGAL_REQUEST;
7905 			sense->es_add_code =
7906 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7907 			*pagelen = parmlen;
7908 			*rval = TRAN_ACCEPT;
7909 			return (SATA_FAILURE);
7910 		}
7911 	}
7912 	return (SATA_SUCCESS);
7913 
7914 failure:
7915 	sata_xlate_errors(spx);
7916 
7917 	return (SATA_FAILURE);
7918 }
7919 
7920 /*
7921  * Process mode select informational exceptions control page 0x1c
7922  *
7923  * The only changeable bit is dexcpt (disable exceptions).
7924  * MRIE (method of reporting informational exceptions) must be
7925  * "only on request".
7926  * This page applies to informational exceptions that report
7927  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
7928  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
7929  * Informational exception conditions occur as the result of background scan
7930  * errors, background self-test errors, or vendor specific events within a
7931  * logical unit. An informational exception condition may occur asynchronous
7932  * to any commands.
7933  *
7934  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7935  * If operation resulted in changing device setup, dmod flag should be set to
7936  * one (1). If parameters were not changed, dmod flag should be set to 0.
7937  * Upon return, if operation required sending command to the device, the rval
7938  * should be set to the value returned by sata_hba_start. If operation
7939  * did not require device access, rval should be set to TRAN_ACCEPT.
7940  * The pagelen should be set to the length of the page.
7941  *
7942  * This function has to be called with a port mutex held.
7943  *
7944  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7945  *
7946  * Cannot be called in the interrupt context.
7947  */
7948 static	int
7949 sata_mode_select_page_1c(
7950 	sata_pkt_txlate_t *spx,
7951 	struct mode_info_excpt_page *page,
7952 	int parmlen,
7953 	int *pagelen,
7954 	int *rval,
7955 	int *dmod)
7956 {
7957 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7958 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7959 	sata_drive_info_t *sdinfo;
7960 	sata_id_t *sata_id;
7961 	struct scsi_extended_sense *sense;
7962 
7963 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7964 	    &spx->txlt_sata_pkt->satapkt_device);
7965 	sata_id = &sdinfo->satadrv_id;
7966 
7967 	*dmod = 0;
7968 
7969 	/* Verify parameters length. If too short, drop it */
7970 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) > parmlen) ||
7971 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
7972 		*scsipkt->pkt_scbp = STATUS_CHECK;
7973 		sense = sata_arq_sense(spx);
7974 		sense->es_key = KEY_ILLEGAL_REQUEST;
7975 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7976 		*pagelen = parmlen;
7977 		*rval = TRAN_ACCEPT;
7978 		return (SATA_FAILURE);
7979 	}
7980 
7981 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
7982 
7983 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
7984 		*scsipkt->pkt_scbp = STATUS_CHECK;
7985 		sense = sata_arq_sense(spx);
7986 		sense->es_key = KEY_ILLEGAL_REQUEST;
7987 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7988 		*pagelen = parmlen;
7989 		*rval = TRAN_ACCEPT;
7990 		return (SATA_FAILURE);
7991 	}
7992 
7993 	/* If already in the state requested, we are done */
7994 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
7995 		/* nothing to do */
7996 		*rval = TRAN_ACCEPT;
7997 		return (SATA_SUCCESS);
7998 	}
7999 
8000 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
8001 
8002 	/* Build SMART_ENABLE or SMART_DISABLE command */
8003 	scmd->satacmd_addr_type = 0;		/* N/A */
8004 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
8005 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
8006 	scmd->satacmd_features_reg = page->dexcpt ?
8007 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
8008 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
8009 	scmd->satacmd_cmd_reg = SATAC_SMART;
8010 
8011 	/* Transfer command to HBA */
8012 	if (sata_hba_start(spx, rval) != 0)
8013 		/*
8014 		 * Pkt not accepted for execution.
8015 		 */
8016 		return (SATA_FAILURE);
8017 
8018 	*dmod = 1;	/* At least may have been modified */
8019 
8020 	/* Now process return */
8021 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
8022 		return (SATA_SUCCESS);
8023 
8024 	/* Packet did not complete successfully */
8025 	sata_xlate_errors(spx);
8026 
8027 	return (SATA_FAILURE);
8028 }
8029 
8030 /*
8031  * Process mode select acoustic management control page 0x30
8032  *
8033  *
8034  * This function has to be called with a port mutex held.
8035  *
8036  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
8037  *
8038  * Cannot be called in the interrupt context.
8039  */
8040 int
8041 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
8042     mode_acoustic_management *page, int parmlen, int *pagelen,
8043     int *rval, int *dmod)
8044 {
8045 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8046 	sata_drive_info_t *sdinfo;
8047 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8048 	sata_id_t *sata_id;
8049 	struct scsi_extended_sense *sense;
8050 
8051 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
8052 	    &spx->txlt_sata_pkt->satapkt_device);
8053 	sata_id = &sdinfo->satadrv_id;
8054 	*dmod = 0;
8055 
8056 	/* If parmlen is too short or the feature is not supported, drop it */
8057 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
8058 	    sizeof (struct mode_page)) > parmlen) ||
8059 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
8060 		*scsipkt->pkt_scbp = STATUS_CHECK;
8061 		sense = sata_arq_sense(spx);
8062 		sense->es_key = KEY_ILLEGAL_REQUEST;
8063 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8064 		*pagelen = parmlen;
8065 		*rval = TRAN_ACCEPT;
8066 		return (SATA_FAILURE);
8067 	}
8068 
8069 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
8070 	    sizeof (struct mode_page);
8071 
8072 	/*
8073 	 * We can enable and disable acoustice management and
8074 	 * set the acoustic management level.
8075 	 */
8076 
8077 	/*
8078 	 * Set-up Internal SET FEATURES command(s)
8079 	 */
8080 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
8081 	scmd->satacmd_addr_type = 0;
8082 	scmd->satacmd_device_reg = 0;
8083 	scmd->satacmd_status_reg = 0;
8084 	scmd->satacmd_error_reg = 0;
8085 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
8086 	if (page->acoustic_manag_enable) {
8087 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
8088 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
8089 	} else {	/* disabling acoustic management */
8090 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
8091 	}
8092 
8093 	/* Transfer command to HBA */
8094 	if (sata_hba_start(spx, rval) != 0)
8095 		/*
8096 		 * Pkt not accepted for execution.
8097 		 */
8098 		return (SATA_FAILURE);
8099 
8100 	/* Now process return */
8101 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
8102 		sata_xlate_errors(spx);
8103 		return (SATA_FAILURE);
8104 	}
8105 
8106 	*dmod = 1;
8107 
8108 	return (SATA_SUCCESS);
8109 }
8110 
8111 /*
8112  * Process mode select power condition page 0x1a
8113  *
8114  * This function has to be called with a port mutex held.
8115  *
8116  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
8117  *
8118  * Cannot be called in the interrupt context.
8119  */
8120 int
8121 sata_mode_select_page_1a(sata_pkt_txlate_t *spx, struct
8122     mode_info_power_cond *page, int parmlen, int *pagelen,
8123     int *rval, int *dmod)
8124 {
8125 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8126 	sata_drive_info_t *sdinfo;
8127 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8128 	sata_id_t *sata_id;
8129 	struct scsi_extended_sense *sense;
8130 	uint8_t ata_count;
8131 	int i, len;
8132 
8133 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
8134 	    &spx->txlt_sata_pkt->satapkt_device);
8135 	sata_id = &sdinfo->satadrv_id;
8136 	*dmod = 0;
8137 
8138 	len = sizeof (struct mode_info_power_cond);
8139 	len += sizeof (struct mode_page);
8140 
8141 	/* If parmlen is too short or the feature is not supported, drop it */
8142 	if ((len < parmlen) || (page->idle == 1) ||
8143 	    (!(sata_id->ai_cap && SATA_STANDBYTIMER) && page->standby == 1)) {
8144 		*scsipkt->pkt_scbp = STATUS_CHECK;
8145 		sense = sata_arq_sense(spx);
8146 		sense->es_key = KEY_ILLEGAL_REQUEST;
8147 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8148 		*pagelen = parmlen;
8149 		*rval = TRAN_ACCEPT;
8150 		return (SATA_FAILURE);
8151 	}
8152 
8153 	*pagelen = len;
8154 
8155 	/*
8156 	 * Set-up Internal STANDBY command(s)
8157 	 */
8158 	if (page->standby == 0)
8159 		goto out;
8160 
8161 	ata_count = sata_get_standby_timer(page->standby_cond_timer);
8162 
8163 	scmd->satacmd_addr_type = 0;
8164 	scmd->satacmd_sec_count_lsb = ata_count;
8165 	scmd->satacmd_lba_low_lsb = 0;
8166 	scmd->satacmd_lba_mid_lsb = 0;
8167 	scmd->satacmd_lba_high_lsb = 0;
8168 	scmd->satacmd_features_reg = 0;
8169 	scmd->satacmd_device_reg = 0;
8170 	scmd->satacmd_status_reg = 0;
8171 	scmd->satacmd_cmd_reg = SATAC_STANDBY;
8172 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8173 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
8174 
8175 	/* Transfer command to HBA */
8176 	if (sata_hba_start(spx, rval) != 0) {
8177 		return (SATA_FAILURE);
8178 	} else {
8179 		if ((scmd->satacmd_error_reg != 0) ||
8180 		    (spx->txlt_sata_pkt->satapkt_reason !=
8181 		    SATA_PKT_COMPLETED)) {
8182 			sata_xlate_errors(spx);
8183 			return (SATA_FAILURE);
8184 		}
8185 	}
8186 
8187 	for (i = 0; i < 4; i++) {
8188 		sdinfo->satadrv_standby_timer[i] = page->standby_cond_timer[i];
8189 	}
8190 out:
8191 	*dmod = 1;
8192 	return (SATA_SUCCESS);
8193 }
8194 
8195 /*
8196  * sata_build_lsense_page0() is used to create the
8197  * SCSI LOG SENSE page 0 (supported log pages)
8198  *
8199  * Currently supported pages are 0, 0x10, 0x2f, 0x30 and 0x0e
8200  * (supported log pages, self-test results, informational exceptions
8201  * Sun vendor specific ATA SMART data, and start stop cycle counter).
8202  *
8203  * Takes a sata_drive_info t * and the address of a buffer
8204  * in which to create the page information.
8205  *
8206  * Returns the number of bytes valid in the buffer.
8207  */
8208 static	int
8209 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
8210 {
8211 	struct log_parameter *lpp = (struct log_parameter *)buf;
8212 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
8213 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
8214 	sata_id_t *sata_id = &sdinfo->satadrv_id;
8215 
8216 	lpp->param_code[0] = 0;
8217 	lpp->param_code[1] = 0;
8218 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8219 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
8220 
8221 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
8222 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
8223 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
8224 			++num_pages_supported;
8225 		}
8226 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
8227 		++num_pages_supported;
8228 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
8229 		++num_pages_supported;
8230 		*page_ptr++ = PAGE_CODE_START_STOP_CYCLE_COUNTER;
8231 		++num_pages_supported;
8232 	}
8233 
8234 	lpp->param_len = num_pages_supported;
8235 
8236 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
8237 	    num_pages_supported);
8238 }
8239 
8240 /*
8241  * sata_build_lsense_page_10() is used to create the
8242  * SCSI LOG SENSE page 0x10 (self-test results)
8243  *
8244  * Takes a sata_drive_info t * and the address of a buffer
8245  * in which to create the page information as well as a sata_hba_inst_t *.
8246  *
8247  * Returns the number of bytes valid in the buffer.
8248  *
8249  * Note: Self test and SMART data is accessible in device log pages.
8250  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
8251  * of data can be transferred by a single command), or by the General Purpose
8252  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
8253  * - approximately 33MB - can be transferred by a single command.
8254  * The SCT Command response (either error or command) is the same for both
8255  * the SMART and GPL methods of issuing commands.
8256  * This function uses READ LOG EXT command when drive supports LBA48, and
8257  * SMART READ command otherwise.
8258  *
8259  * Since above commands are executed in a synchronous mode, this function
8260  * should not be called in an interrupt context.
8261  */
8262 static	int
8263 sata_build_lsense_page_10(
8264 	sata_drive_info_t *sdinfo,
8265 	uint8_t *buf,
8266 	sata_hba_inst_t *sata_hba_inst)
8267 {
8268 	struct log_parameter *lpp = (struct log_parameter *)buf;
8269 	int rval;
8270 
8271 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
8272 		struct smart_ext_selftest_log *ext_selftest_log;
8273 
8274 		ext_selftest_log = kmem_zalloc(
8275 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
8276 
8277 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
8278 		    ext_selftest_log, 0);
8279 		if (rval == 0) {
8280 			int index, start_index;
8281 			struct smart_ext_selftest_log_entry *entry;
8282 			static const struct smart_ext_selftest_log_entry empty =
8283 			    {0};
8284 			uint16_t block_num;
8285 			int count;
8286 			boolean_t only_one_block = B_FALSE;
8287 
8288 			index = ext_selftest_log->
8289 			    smart_ext_selftest_log_index[0];
8290 			index |= ext_selftest_log->
8291 			    smart_ext_selftest_log_index[1] << 8;
8292 			if (index == 0)
8293 				goto out;
8294 
8295 			--index;	/* Correct for 0 origin */
8296 			start_index = index;	/* remember where we started */
8297 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8298 			if (block_num != 0) {
8299 				rval = sata_ext_smart_selftest_read_log(
8300 				    sata_hba_inst, sdinfo, ext_selftest_log,
8301 				    block_num);
8302 				if (rval != 0)
8303 					goto out;
8304 			}
8305 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8306 			entry =
8307 			    &ext_selftest_log->
8308 			    smart_ext_selftest_log_entries[index];
8309 
8310 			for (count = 1;
8311 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8312 			    ++count) {
8313 				uint8_t status;
8314 				uint8_t code;
8315 				uint8_t sense_key;
8316 				uint8_t add_sense_code;
8317 				uint8_t add_sense_code_qual;
8318 
8319 				/* If this is an unused entry, we are done */
8320 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
8321 					/* Broken firmware on some disks */
8322 					if (index + 1 ==
8323 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
8324 						--entry;
8325 						--index;
8326 						if (bcmp(entry, &empty,
8327 						    sizeof (empty)) == 0)
8328 							goto out;
8329 					} else
8330 						goto out;
8331 				}
8332 
8333 				if (only_one_block &&
8334 				    start_index == index)
8335 					goto out;
8336 
8337 				lpp->param_code[0] = 0;
8338 				lpp->param_code[1] = count;
8339 				lpp->param_ctrl_flags =
8340 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8341 				lpp->param_len =
8342 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8343 
8344 				status = entry->smart_ext_selftest_log_status;
8345 				status >>= 4;
8346 				switch (status) {
8347 				case 0:
8348 				default:
8349 					sense_key = KEY_NO_SENSE;
8350 					add_sense_code =
8351 					    SD_SCSI_ASC_NO_ADD_SENSE;
8352 					add_sense_code_qual = 0;
8353 					break;
8354 				case 1:
8355 					sense_key = KEY_ABORTED_COMMAND;
8356 					add_sense_code =
8357 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8358 					add_sense_code_qual = SCSI_COMPONENT_81;
8359 					break;
8360 				case 2:
8361 					sense_key = KEY_ABORTED_COMMAND;
8362 					add_sense_code =
8363 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8364 					add_sense_code_qual = SCSI_COMPONENT_82;
8365 					break;
8366 				case 3:
8367 					sense_key = KEY_ABORTED_COMMAND;
8368 					add_sense_code =
8369 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8370 					add_sense_code_qual = SCSI_COMPONENT_83;
8371 					break;
8372 				case 4:
8373 					sense_key = KEY_HARDWARE_ERROR;
8374 					add_sense_code =
8375 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8376 					add_sense_code_qual = SCSI_COMPONENT_84;
8377 					break;
8378 				case 5:
8379 					sense_key = KEY_HARDWARE_ERROR;
8380 					add_sense_code =
8381 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8382 					add_sense_code_qual = SCSI_COMPONENT_85;
8383 					break;
8384 				case 6:
8385 					sense_key = KEY_HARDWARE_ERROR;
8386 					add_sense_code =
8387 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8388 					add_sense_code_qual = SCSI_COMPONENT_86;
8389 					break;
8390 				case 7:
8391 					sense_key = KEY_MEDIUM_ERROR;
8392 					add_sense_code =
8393 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8394 					add_sense_code_qual = SCSI_COMPONENT_87;
8395 					break;
8396 				case 8:
8397 					sense_key = KEY_HARDWARE_ERROR;
8398 					add_sense_code =
8399 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8400 					add_sense_code_qual = SCSI_COMPONENT_88;
8401 					break;
8402 				}
8403 				code = 0;	/* unspecified */
8404 				status |= (code << 4);
8405 				lpp->param_values[0] = status;
8406 				lpp->param_values[1] = 0; /* unspecified */
8407 				lpp->param_values[2] = entry->
8408 				    smart_ext_selftest_log_timestamp[1];
8409 				lpp->param_values[3] = entry->
8410 				    smart_ext_selftest_log_timestamp[0];
8411 				if (status != 0) {
8412 					lpp->param_values[4] = 0;
8413 					lpp->param_values[5] = 0;
8414 					lpp->param_values[6] = entry->
8415 					    smart_ext_selftest_log_failing_lba
8416 					    [5];
8417 					lpp->param_values[7] = entry->
8418 					    smart_ext_selftest_log_failing_lba
8419 					    [4];
8420 					lpp->param_values[8] = entry->
8421 					    smart_ext_selftest_log_failing_lba
8422 					    [3];
8423 					lpp->param_values[9] = entry->
8424 					    smart_ext_selftest_log_failing_lba
8425 					    [2];
8426 					lpp->param_values[10] = entry->
8427 					    smart_ext_selftest_log_failing_lba
8428 					    [1];
8429 					lpp->param_values[11] = entry->
8430 					    smart_ext_selftest_log_failing_lba
8431 					    [0];
8432 				} else {	/* No bad block address */
8433 					lpp->param_values[4] = 0xff;
8434 					lpp->param_values[5] = 0xff;
8435 					lpp->param_values[6] = 0xff;
8436 					lpp->param_values[7] = 0xff;
8437 					lpp->param_values[8] = 0xff;
8438 					lpp->param_values[9] = 0xff;
8439 					lpp->param_values[10] = 0xff;
8440 					lpp->param_values[11] = 0xff;
8441 				}
8442 
8443 				lpp->param_values[12] = sense_key;
8444 				lpp->param_values[13] = add_sense_code;
8445 				lpp->param_values[14] = add_sense_code_qual;
8446 				lpp->param_values[15] = 0; /* undefined */
8447 
8448 				lpp = (struct log_parameter *)
8449 				    (((uint8_t *)lpp) +
8450 				    SCSI_LOG_PARAM_HDR_LEN +
8451 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8452 
8453 				--index;	/* Back up to previous entry */
8454 				if (index < 0) {
8455 					if (block_num > 0) {
8456 						--block_num;
8457 					} else {
8458 						struct read_log_ext_directory
8459 						    logdir;
8460 
8461 						rval =
8462 						    sata_read_log_ext_directory(
8463 						    sata_hba_inst, sdinfo,
8464 						    &logdir);
8465 						if (rval == -1)
8466 							goto out;
8467 						if ((logdir.read_log_ext_vers
8468 						    [0] == 0) &&
8469 						    (logdir.read_log_ext_vers
8470 						    [1] == 0))
8471 							goto out;
8472 						block_num =
8473 						    logdir.read_log_ext_nblks
8474 						    [EXT_SMART_SELFTEST_LOG_PAGE
8475 						    - 1][0];
8476 						block_num |= logdir.
8477 						    read_log_ext_nblks
8478 						    [EXT_SMART_SELFTEST_LOG_PAGE
8479 						    - 1][1] << 8;
8480 						--block_num;
8481 						only_one_block =
8482 						    (block_num == 0);
8483 					}
8484 					rval = sata_ext_smart_selftest_read_log(
8485 					    sata_hba_inst, sdinfo,
8486 					    ext_selftest_log, block_num);
8487 					if (rval != 0)
8488 						goto out;
8489 
8490 					index =
8491 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
8492 					    1;
8493 				}
8494 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8495 				entry = &ext_selftest_log->
8496 				    smart_ext_selftest_log_entries[index];
8497 			}
8498 		}
8499 out:
8500 		kmem_free(ext_selftest_log,
8501 		    sizeof (struct smart_ext_selftest_log));
8502 	} else {
8503 		struct smart_selftest_log *selftest_log;
8504 
8505 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
8506 		    KM_SLEEP);
8507 
8508 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
8509 		    selftest_log);
8510 
8511 		if (rval == 0) {
8512 			int index;
8513 			int count;
8514 			struct smart_selftest_log_entry *entry;
8515 			static const struct smart_selftest_log_entry empty =
8516 			    { 0 };
8517 
8518 			index = selftest_log->smart_selftest_log_index;
8519 			if (index == 0)
8520 				goto done;
8521 			--index;	/* Correct for 0 origin */
8522 			entry = &selftest_log->
8523 			    smart_selftest_log_entries[index];
8524 			for (count = 1;
8525 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8526 			    ++count) {
8527 				uint8_t status;
8528 				uint8_t code;
8529 				uint8_t sense_key;
8530 				uint8_t add_sense_code;
8531 				uint8_t add_sense_code_qual;
8532 
8533 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
8534 					goto done;
8535 
8536 				lpp->param_code[0] = 0;
8537 				lpp->param_code[1] = count;
8538 				lpp->param_ctrl_flags =
8539 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8540 				lpp->param_len =
8541 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8542 
8543 				status = entry->smart_selftest_log_status;
8544 				status >>= 4;
8545 				switch (status) {
8546 				case 0:
8547 				default:
8548 					sense_key = KEY_NO_SENSE;
8549 					add_sense_code =
8550 					    SD_SCSI_ASC_NO_ADD_SENSE;
8551 					break;
8552 				case 1:
8553 					sense_key = KEY_ABORTED_COMMAND;
8554 					add_sense_code =
8555 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8556 					add_sense_code_qual = SCSI_COMPONENT_81;
8557 					break;
8558 				case 2:
8559 					sense_key = KEY_ABORTED_COMMAND;
8560 					add_sense_code =
8561 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8562 					add_sense_code_qual = SCSI_COMPONENT_82;
8563 					break;
8564 				case 3:
8565 					sense_key = KEY_ABORTED_COMMAND;
8566 					add_sense_code =
8567 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8568 					add_sense_code_qual = SCSI_COMPONENT_83;
8569 					break;
8570 				case 4:
8571 					sense_key = KEY_HARDWARE_ERROR;
8572 					add_sense_code =
8573 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8574 					add_sense_code_qual = SCSI_COMPONENT_84;
8575 					break;
8576 				case 5:
8577 					sense_key = KEY_HARDWARE_ERROR;
8578 					add_sense_code =
8579 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8580 					add_sense_code_qual = SCSI_COMPONENT_85;
8581 					break;
8582 				case 6:
8583 					sense_key = KEY_HARDWARE_ERROR;
8584 					add_sense_code =
8585 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8586 					add_sense_code_qual = SCSI_COMPONENT_86;
8587 					break;
8588 				case 7:
8589 					sense_key = KEY_MEDIUM_ERROR;
8590 					add_sense_code =
8591 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8592 					add_sense_code_qual = SCSI_COMPONENT_87;
8593 					break;
8594 				case 8:
8595 					sense_key = KEY_HARDWARE_ERROR;
8596 					add_sense_code =
8597 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8598 					add_sense_code_qual = SCSI_COMPONENT_88;
8599 					break;
8600 				}
8601 				code = 0;	/* unspecified */
8602 				status |= (code << 4);
8603 				lpp->param_values[0] = status;
8604 				lpp->param_values[1] = 0; /* unspecified */
8605 				lpp->param_values[2] = entry->
8606 				    smart_selftest_log_timestamp[1];
8607 				lpp->param_values[3] = entry->
8608 				    smart_selftest_log_timestamp[0];
8609 				if (status != 0) {
8610 					lpp->param_values[4] = 0;
8611 					lpp->param_values[5] = 0;
8612 					lpp->param_values[6] = 0;
8613 					lpp->param_values[7] = 0;
8614 					lpp->param_values[8] = entry->
8615 					    smart_selftest_log_failing_lba[3];
8616 					lpp->param_values[9] = entry->
8617 					    smart_selftest_log_failing_lba[2];
8618 					lpp->param_values[10] = entry->
8619 					    smart_selftest_log_failing_lba[1];
8620 					lpp->param_values[11] = entry->
8621 					    smart_selftest_log_failing_lba[0];
8622 				} else {	/* No block address */
8623 					lpp->param_values[4] = 0xff;
8624 					lpp->param_values[5] = 0xff;
8625 					lpp->param_values[6] = 0xff;
8626 					lpp->param_values[7] = 0xff;
8627 					lpp->param_values[8] = 0xff;
8628 					lpp->param_values[9] = 0xff;
8629 					lpp->param_values[10] = 0xff;
8630 					lpp->param_values[11] = 0xff;
8631 				}
8632 				lpp->param_values[12] = sense_key;
8633 				lpp->param_values[13] = add_sense_code;
8634 				lpp->param_values[14] = add_sense_code_qual;
8635 				lpp->param_values[15] = 0; /* undefined */
8636 
8637 				lpp = (struct log_parameter *)
8638 				    (((uint8_t *)lpp) +
8639 				    SCSI_LOG_PARAM_HDR_LEN +
8640 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8641 				--index;	/* back up to previous entry */
8642 				if (index < 0) {
8643 					index =
8644 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
8645 				}
8646 				entry = &selftest_log->
8647 				    smart_selftest_log_entries[index];
8648 			}
8649 		}
8650 done:
8651 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
8652 	}
8653 
8654 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
8655 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
8656 }
8657 
8658 /*
8659  * sata_build_lsense_page_2f() is used to create the
8660  * SCSI LOG SENSE page 0x2f (informational exceptions)
8661  *
8662  * Takes a sata_drive_info t * and the address of a buffer
8663  * in which to create the page information as well as a sata_hba_inst_t *.
8664  *
8665  * Returns the number of bytes valid in the buffer.
8666  *
8667  * Because it invokes function(s) that send synchronously executed command
8668  * to the HBA, it cannot be called in the interrupt context.
8669  */
8670 static	int
8671 sata_build_lsense_page_2f(
8672 	sata_drive_info_t *sdinfo,
8673 	uint8_t *buf,
8674 	sata_hba_inst_t *sata_hba_inst)
8675 {
8676 	struct log_parameter *lpp = (struct log_parameter *)buf;
8677 	int rval;
8678 	uint8_t *smart_data;
8679 	uint8_t temp;
8680 	sata_id_t *sata_id;
8681 #define	SMART_NO_TEMP	0xff
8682 
8683 	lpp->param_code[0] = 0;
8684 	lpp->param_code[1] = 0;
8685 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8686 
8687 	/* Now get the SMART status w.r.t. threshold exceeded */
8688 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
8689 	switch (rval) {
8690 	case 1:
8691 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
8692 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
8693 		break;
8694 	case 0:
8695 	case -1:	/* failed to get data */
8696 		lpp->param_values[0] = 0;	/* No failure predicted */
8697 		lpp->param_values[1] = 0;
8698 		break;
8699 #if defined(SATA_DEBUG)
8700 	default:
8701 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
8702 		/* NOTREACHED */
8703 #endif
8704 	}
8705 
8706 	sata_id = &sdinfo->satadrv_id;
8707 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
8708 		temp = SMART_NO_TEMP;
8709 	else {
8710 		/* Now get the temperature */
8711 		smart_data = kmem_zalloc(512, KM_SLEEP);
8712 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
8713 		    SCT_STATUS_LOG_PAGE, 1);
8714 		if (rval == -1)
8715 			temp = SMART_NO_TEMP;
8716 		else {
8717 			temp = smart_data[200];
8718 			if (temp & 0x80) {
8719 				if (temp & 0x7f)
8720 					temp = 0;
8721 				else
8722 					temp = SMART_NO_TEMP;
8723 			}
8724 		}
8725 		kmem_free(smart_data, 512);
8726 	}
8727 
8728 	lpp->param_values[2] = temp;	/* most recent temperature */
8729 	lpp->param_values[3] = 0;	/* required vendor specific byte */
8730 
8731 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
8732 
8733 
8734 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
8735 }
8736 
8737 /*
8738  * sata_build_lsense_page_30() is used to create the
8739  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
8740  *
8741  * Takes a sata_drive_info t * and the address of a buffer
8742  * in which to create the page information as well as a sata_hba_inst_t *.
8743  *
8744  * Returns the number of bytes valid in the buffer.
8745  */
8746 static int
8747 sata_build_lsense_page_30(
8748 	sata_drive_info_t *sdinfo,
8749 	uint8_t *buf,
8750 	sata_hba_inst_t *sata_hba_inst)
8751 {
8752 	struct smart_data *smart_data = (struct smart_data *)buf;
8753 	int rval;
8754 
8755 	/* Now do the SMART READ DATA */
8756 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
8757 	if (rval == -1)
8758 		return (0);
8759 
8760 	return (sizeof (struct smart_data));
8761 }
8762 
8763 /*
8764  * sata_build_lsense_page_0e() is used to create the
8765  * SCSI LOG SENSE page 0e (start-stop cycle counter page)
8766  *
8767  * Date of Manufacture (0x0001)
8768  *	YEAR = "0000"
8769  *	WEEK = "00"
8770  * Accounting Date (0x0002)
8771  *	6 ASCII space character(20h)
8772  * Specified cycle count over device lifetime
8773  *	VALUE - THRESH - the delta between max and min;
8774  * Accumulated start-stop cycles
8775  *	VALUE - WORST - the accumulated cycles;
8776  *
8777  * ID FLAG THRESH VALUE WORST RAW on start/stop counter attribute
8778  *
8779  * Takes a sata_drive_info t * and the address of a buffer
8780  * in which to create the page information as well as a sata_hba_inst_t *.
8781  *
8782  * Returns the number of bytes valid in the buffer.
8783  */
8784 static	int
8785 sata_build_lsense_page_0e(sata_drive_info_t *sdinfo, uint8_t *buf,
8786 	sata_pkt_txlate_t *spx)
8787 {
8788 	struct start_stop_cycle_counter_log *log_page;
8789 	int i, rval, index;
8790 	uint8_t smart_data[512], id, value, worst, thresh;
8791 	uint32_t max_count, cycles;
8792 
8793 	/* Now do the SMART READ DATA */
8794 	rval = sata_fetch_smart_data(spx->txlt_sata_hba_inst, sdinfo,
8795 	    (struct smart_data *)smart_data);
8796 	if (rval == -1)
8797 		return (0);
8798 	for (i = 0, id = 0; i < SMART_START_STOP_COUNT_ID * 2; i++) {
8799 		index = (i * 12) + 2;
8800 		id = smart_data[index];
8801 		if (id != SMART_START_STOP_COUNT_ID)
8802 			continue;
8803 		else {
8804 			thresh = smart_data[index + 2];
8805 			value = smart_data[index + 3];
8806 			worst = smart_data[index + 4];
8807 			break;
8808 		}
8809 	}
8810 	if (id != SMART_START_STOP_COUNT_ID)
8811 		return (0);
8812 	max_count = value - thresh;
8813 	cycles = value - worst;
8814 
8815 	log_page = (struct start_stop_cycle_counter_log *)buf;
8816 	bzero(log_page, sizeof (struct start_stop_cycle_counter_log));
8817 	log_page->code = 0x0e;
8818 	log_page->page_len_low = 0x24;
8819 
8820 	log_page->manufactor_date_low = 0x1;
8821 	log_page->param_1.fmt_link = 0x1; /* 01b */
8822 	log_page->param_len_1 = 0x06;
8823 	for (i = 0; i < 4; i++) {
8824 		log_page->year_manu[i] = 0x30;
8825 		if (i < 2)
8826 			log_page->week_manu[i] = 0x30;
8827 	}
8828 
8829 	log_page->account_date_low = 0x02;
8830 	log_page->param_2.fmt_link = 0x01; /* 01b */
8831 	log_page->param_len_2 = 0x06;
8832 	for (i = 0; i < 4; i++) {
8833 		log_page->year_account[i] = 0x20;
8834 		if (i < 2)
8835 			log_page->week_account[i] = 0x20;
8836 	}
8837 
8838 	log_page->lifetime_code_low = 0x03;
8839 	log_page->param_3.fmt_link = 0x03; /* 11b */
8840 	log_page->param_len_3 = 0x04;
8841 	/* VALUE - THRESH - the delta between max and min */
8842 	log_page->cycle_code_low = 0x04;
8843 	log_page->param_4.fmt_link = 0x03; /* 11b */
8844 	log_page->param_len_4 = 0x04;
8845 	/* WORST - THRESH - the distance from 'now' to min */
8846 
8847 	for (i = 0; i < 4; i++) {
8848 		log_page->cycle_lifetime[i] =
8849 		    (max_count >> (8 * (3 - i))) & 0xff;
8850 		log_page->cycle_accumulated[i] =
8851 		    (cycles >> (8 * (3 - i))) & 0xff;
8852 	}
8853 
8854 	return (sizeof (struct start_stop_cycle_counter_log));
8855 }
8856 
8857 /*
8858  * This function was used for build a ATA read verify sector command
8859  */
8860 static void
8861 sata_build_read_verify_cmd(sata_cmd_t *scmd, uint16_t sec, uint64_t lba)
8862 {
8863 	scmd->satacmd_cmd_reg = SATAC_RDVER;
8864 	scmd->satacmd_addr_type = ATA_ADDR_LBA28;
8865 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8866 
8867 	scmd->satacmd_sec_count_lsb = sec & 0xff;
8868 	scmd->satacmd_lba_low_lsb = lba & 0xff;
8869 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
8870 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
8871 	scmd->satacmd_device_reg = (SATA_ADH_LBA | (lba >> 24) & 0xf);
8872 	scmd->satacmd_features_reg = 0;
8873 	scmd->satacmd_status_reg = 0;
8874 	scmd->satacmd_error_reg = 0;
8875 }
8876 
8877 /*
8878  * This function was used for building an ATA
8879  * command, and only command register need to
8880  * be defined, other register will be zero or na.
8881  */
8882 static void
8883 sata_build_generic_cmd(sata_cmd_t *scmd, uint8_t cmd)
8884 {
8885 	scmd->satacmd_addr_type = 0;
8886 	scmd->satacmd_cmd_reg = cmd;
8887 	scmd->satacmd_device_reg = 0;
8888 	scmd->satacmd_sec_count_lsb = 0;
8889 	scmd->satacmd_lba_low_lsb = 0;
8890 	scmd->satacmd_lba_mid_lsb = 0;
8891 	scmd->satacmd_lba_high_lsb = 0;
8892 	scmd->satacmd_features_reg = 0;
8893 	scmd->satacmd_status_reg = 0;
8894 	scmd->satacmd_error_reg = 0;
8895 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8896 }
8897 
8898 /*
8899  * This function was used for changing the standby
8900  * timer format from SCSI to ATA.
8901  */
8902 static uint8_t
8903 sata_get_standby_timer(uint8_t *timer)
8904 {
8905 	uint32_t i = 0, count = 0;
8906 	uint8_t ata_count;
8907 
8908 	for (i = 0; i < 4; i++) {
8909 		count = count << 8 | timer[i];
8910 	}
8911 
8912 	if (count == 0)
8913 		return (0);
8914 
8915 	if (count >= 1 && count <= 12000)
8916 		ata_count = (count -1) / 50 + 1;
8917 	else if (count > 12000 && count <= 12600)
8918 		ata_count = 0xfc;
8919 	else if (count > 12601 && count <= 12750)
8920 		ata_count = 0xff;
8921 	else if (count > 12750 && count <= 17999)
8922 		ata_count = 0xf1;
8923 	else if (count > 18000 && count <= 198000)
8924 		ata_count = count / 18000 + 240;
8925 	else
8926 		ata_count = 0xfd;
8927 	return (ata_count);
8928 }
8929 
8930 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
8931 
8932 /*
8933  * Start command for ATAPI device.
8934  * This function processes scsi_pkt requests.
8935  * Now CD/DVD, tape and ATAPI disk devices are supported.
8936  * Most commands are packet without any translation into Packet Command.
8937  * Some may be trapped and executed as SATA commands (not clear which one).
8938  *
8939  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
8940  * execution).
8941  * Returns other TRAN_XXXX codes if command is not accepted or completed
8942  * (see return values for sata_hba_start()).
8943  *
8944  * Note:
8945  * Inquiry cdb format differs between transport version 2 and 3.
8946  * However, the transport version 3 devices that were checked did not adhere
8947  * to the specification (ignored MSB of the allocation length). Therefore,
8948  * the transport version is not checked, but Inquiry allocation length is
8949  * truncated to 255 bytes if the original allocation length set-up by the
8950  * target driver is greater than 255 bytes.
8951  */
8952 static int
8953 sata_txlt_atapi(sata_pkt_txlate_t *spx)
8954 {
8955 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8956 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8957 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8958 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
8959 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
8960 	    &spx->txlt_sata_pkt->satapkt_device);
8961 	int cport = SATA_TXLT_CPORT(spx);
8962 	int cdblen;
8963 	int rval, reason;
8964 	int synch;
8965 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
8966 
8967 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
8968 
8969 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
8970 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
8971 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8972 		return (rval);
8973 	}
8974 
8975 	/*
8976 	 * ATAPI device executes some ATA commands in addition to those
8977 	 * commands sent via PACKET command. These ATA commands may be
8978 	 * executed by the regular SATA translation functions. None needs
8979 	 * to be captured now.
8980 	 *
8981 	 * Commands sent via PACKET command include:
8982 	 *	MMC command set for ATAPI CD/DVD device
8983 	 *	SSC command set for ATAPI TAPE device
8984 	 *	SBC command set for ATAPI disk device
8985 	 *
8986 	 */
8987 
8988 	/* Check the size of cdb */
8989 
8990 	switch (GETGROUP(cdbp)) {
8991 	case CDB_GROUPID_3:   /* Reserved, per SPC-4 */
8992 		/*
8993 		 * opcodes 0x7e and 0x7f identify variable-length CDBs and
8994 		 * therefore require special handling.  Return failure, for now.
8995 		 */
8996 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8997 		return (TRAN_BADPKT);
8998 
8999 	case CDB_GROUPID_6:   /* Vendor-specific, per SPC-4 */
9000 	case CDB_GROUPID_7:   /* Vendor-specific, per SPC-4 */
9001 		/* obtain length from the scsi_pkt */
9002 		cdblen = scsipkt->pkt_cdblen;
9003 		break;
9004 
9005 	default:
9006 		/* CDB's length is statically known, per SPC-4 */
9007 		cdblen = scsi_cdb_size[GETGROUP(cdbp)];
9008 		break;
9009 	}
9010 
9011 	if (cdblen <= 0 || cdblen > sdinfo->satadrv_atapi_cdb_len) {
9012 		sata_log(NULL, CE_WARN,
9013 		    "sata: invalid ATAPI cdb length %d",
9014 		    cdblen);
9015 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9016 		return (TRAN_BADPKT);
9017 	}
9018 
9019 	SATAATAPITRACE(spx, cdblen);
9020 
9021 	/*
9022 	 * For non-read/write commands we need to
9023 	 * map buffer
9024 	 */
9025 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
9026 	case SCMD_READ:
9027 	case SCMD_READ_G1:
9028 	case SCMD_READ_G5:
9029 	case SCMD_READ_G4:
9030 	case SCMD_WRITE:
9031 	case SCMD_WRITE_G1:
9032 	case SCMD_WRITE_G5:
9033 	case SCMD_WRITE_G4:
9034 		break;
9035 	default:
9036 		if (bp != NULL) {
9037 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
9038 				bp_mapin(bp);
9039 		}
9040 		break;
9041 	}
9042 	/*
9043 	 * scmd->satacmd_flags.sata_data_direction default -
9044 	 * SATA_DIR_NODATA_XFER - is set by
9045 	 * sata_txlt_generic_pkt_info().
9046 	 */
9047 	if (scmd->satacmd_bp) {
9048 		if (scmd->satacmd_bp->b_flags & B_READ) {
9049 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9050 		} else {
9051 			scmd->satacmd_flags.sata_data_direction =
9052 			    SATA_DIR_WRITE;
9053 		}
9054 	}
9055 
9056 	/*
9057 	 * Set up ATAPI packet command.
9058 	 */
9059 
9060 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9061 
9062 	/* Copy cdb into sata_cmd */
9063 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9064 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9065 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
9066 
9067 	/* See note in the command header */
9068 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
9069 		if (scmd->satacmd_acdb[3] != 0)
9070 			scmd->satacmd_acdb[4] = 255;
9071 	}
9072 
9073 #ifdef SATA_DEBUG
9074 	if (sata_debug_flags & SATA_DBG_ATAPI) {
9075 		uint8_t *p = scmd->satacmd_acdb;
9076 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
9077 
9078 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
9079 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
9080 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
9081 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9082 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9083 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
9084 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
9085 	}
9086 #endif
9087 
9088 	/*
9089 	 * Preset request sense data to NO SENSE.
9090 	 * If there is no way to get error information via Request Sense,
9091 	 * the packet request sense data would not have to be modified by HBA,
9092 	 * but it could be returned as is.
9093 	 */
9094 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
9095 	sata_fixed_sense_data_preset(
9096 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9097 
9098 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
9099 		/* Need callback function */
9100 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
9101 		synch = FALSE;
9102 	} else
9103 		synch = TRUE;
9104 
9105 	/* Transfer command to HBA */
9106 	if (sata_hba_start(spx, &rval) != 0) {
9107 		/* Pkt not accepted for execution */
9108 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
9109 		return (rval);
9110 	}
9111 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
9112 	/*
9113 	 * If execution is non-synchronous,
9114 	 * a callback function will handle potential errors, translate
9115 	 * the response and will do a callback to a target driver.
9116 	 * If it was synchronous, use the same framework callback to check
9117 	 * an execution status.
9118 	 */
9119 	if (synch) {
9120 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
9121 		    "synchronous execution status %x\n",
9122 		    spx->txlt_sata_pkt->satapkt_reason);
9123 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
9124 	}
9125 	return (TRAN_ACCEPT);
9126 }
9127 
9128 
9129 /*
9130  * ATAPI Packet command completion.
9131  *
9132  * Failure of the command passed via Packet command are considered device
9133  * error. SATA HBA driver would have to retrieve error data (via Request
9134  * Sense command delivered via error retrieval sata packet) and copy it
9135  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
9136  */
9137 static void
9138 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
9139 {
9140 	sata_pkt_txlate_t *spx =
9141 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
9142 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
9143 	struct scsi_extended_sense *sense;
9144 	struct buf *bp;
9145 	int rval;
9146 
9147 #ifdef SATA_DEBUG
9148 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
9149 #endif
9150 
9151 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
9152 	    STATE_SENT_CMD | STATE_GOT_STATUS;
9153 
9154 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
9155 		/* Normal completion */
9156 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
9157 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
9158 		scsipkt->pkt_reason = CMD_CMPLT;
9159 		*scsipkt->pkt_scbp = STATUS_GOOD;
9160 		if (spx->txlt_tmp_buf != NULL) {
9161 			/* Temporary buffer was used */
9162 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
9163 			if (bp->b_flags & B_READ) {
9164 				rval = ddi_dma_sync(
9165 				    spx->txlt_buf_dma_handle, 0, 0,
9166 				    DDI_DMA_SYNC_FORCPU);
9167 				ASSERT(rval == DDI_SUCCESS);
9168 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
9169 				    bp->b_bcount);
9170 			}
9171 		}
9172 	} else {
9173 		/*
9174 		 * Something went wrong - analyze return
9175 		 */
9176 		*scsipkt->pkt_scbp = STATUS_CHECK;
9177 		sense = sata_arq_sense(spx);
9178 
9179 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9180 			/*
9181 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
9182 			 * Under this condition ERR bit is set for ATA command,
9183 			 * and CHK bit set for ATAPI command.
9184 			 *
9185 			 * Please check st_intr & sdintr about how pkt_reason
9186 			 * is used.
9187 			 */
9188 			scsipkt->pkt_reason = CMD_CMPLT;
9189 
9190 			/*
9191 			 * We may not have ARQ data if there was a double
9192 			 * error. But sense data in sata packet was pre-set
9193 			 * with NO SENSE so it is valid even if HBA could
9194 			 * not retrieve a real sense data.
9195 			 * Just copy this sense data into scsi pkt sense area.
9196 			 */
9197 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
9198 			    SATA_ATAPI_MIN_RQSENSE_LEN);
9199 #ifdef SATA_DEBUG
9200 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
9201 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9202 				    "sata_txlt_atapi_completion: %02x\n"
9203 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
9204 				    "          %02x %02x %02x %02x %02x %02x "
9205 				    "          %02x %02x %02x %02x %02x %02x\n",
9206 				    scsipkt->pkt_reason,
9207 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9208 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9209 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9210 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9211 				    rqsp[16], rqsp[17]);
9212 			}
9213 #endif
9214 		} else {
9215 			switch (sata_pkt->satapkt_reason) {
9216 			case SATA_PKT_PORT_ERROR:
9217 				/*
9218 				 * We have no device data.
9219 				 */
9220 				scsipkt->pkt_reason = CMD_INCOMPLETE;
9221 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
9222 				    STATE_GOT_TARGET | STATE_SENT_CMD |
9223 				    STATE_GOT_STATUS);
9224 				sense->es_key = KEY_HARDWARE_ERROR;
9225 				break;
9226 
9227 			case SATA_PKT_TIMEOUT:
9228 				scsipkt->pkt_reason = CMD_TIMEOUT;
9229 				scsipkt->pkt_statistics |=
9230 				    STAT_TIMEOUT | STAT_DEV_RESET;
9231 				/*
9232 				 * Need to check if HARDWARE_ERROR/
9233 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
9234 				 * appropriate.
9235 				 */
9236 				break;
9237 
9238 			case SATA_PKT_ABORTED:
9239 				scsipkt->pkt_reason = CMD_ABORTED;
9240 				scsipkt->pkt_statistics |= STAT_ABORTED;
9241 				/* Should we set key COMMAND_ABPRTED? */
9242 				break;
9243 
9244 			case SATA_PKT_RESET:
9245 				scsipkt->pkt_reason = CMD_RESET;
9246 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
9247 				/*
9248 				 * May be we should set Unit Attention /
9249 				 * Reset. Perhaps the same should be
9250 				 * returned for disks....
9251 				 */
9252 				sense->es_key = KEY_UNIT_ATTENTION;
9253 				sense->es_add_code = SD_SCSI_ASC_RESET;
9254 				break;
9255 
9256 			default:
9257 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9258 				    "sata_txlt_atapi_completion: "
9259 				    "invalid packet completion reason"));
9260 				scsipkt->pkt_reason = CMD_TRAN_ERR;
9261 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
9262 				    STATE_GOT_TARGET | STATE_SENT_CMD |
9263 				    STATE_GOT_STATUS);
9264 				break;
9265 			}
9266 		}
9267 	}
9268 
9269 	SATAATAPITRACE(spx, 0);
9270 
9271 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
9272 	    scsipkt->pkt_comp != NULL) {
9273 		/* scsi callback required */
9274 		(*scsipkt->pkt_comp)(scsipkt);
9275 	}
9276 }
9277 
9278 /*
9279  * Set up error retrieval sata command for ATAPI Packet Command error data
9280  * recovery.
9281  *
9282  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
9283  * returns SATA_FAILURE otherwise.
9284  */
9285 
9286 static int
9287 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
9288 {
9289 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
9290 	sata_cmd_t *scmd;
9291 	struct buf *bp;
9292 
9293 	/*
9294 	 * Allocate dma-able buffer error data.
9295 	 * Buffer allocation will take care of buffer alignment and other DMA
9296 	 * attributes.
9297 	 */
9298 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
9299 	if (bp == NULL) {
9300 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
9301 		    "sata_get_err_retrieval_pkt: "
9302 		    "cannot allocate buffer for error data", NULL);
9303 		return (SATA_FAILURE);
9304 	}
9305 	bp_mapin(bp); /* make data buffer accessible */
9306 
9307 	/* Operation modes are up to the caller */
9308 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9309 
9310 	/* Synchronous mode, no callback - may be changed by the caller */
9311 	spkt->satapkt_comp = NULL;
9312 	spkt->satapkt_time = sata_default_pkt_time;
9313 
9314 	scmd = &spkt->satapkt_cmd;
9315 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9316 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9317 
9318 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9319 
9320 	/*
9321 	 * Set-up acdb. Request Sense CDB (packet command content) is
9322 	 * not in DMA-able buffer. Its handling is HBA-specific (how
9323 	 * it is transfered into packet FIS).
9324 	 */
9325 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9326 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
9327 	/* Following zeroing of pad bytes may not be necessary */
9328 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
9329 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
9330 
9331 	/*
9332 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
9333 	 * before accessing it. Handle is in usual place in translate struct.
9334 	 */
9335 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
9336 
9337 	/*
9338 	 * Preset request sense data to NO SENSE.
9339 	 * Here it is redundant, only for a symetry with scsi-originated
9340 	 * packets. It should not be used for anything but debugging.
9341 	 */
9342 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
9343 	sata_fixed_sense_data_preset(
9344 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9345 
9346 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9347 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9348 
9349 	return (SATA_SUCCESS);
9350 }
9351 
9352 /*
9353  * Set-up ATAPI packet command.
9354  * Data transfer direction has to be set-up in sata_cmd structure prior to
9355  * calling this function.
9356  *
9357  * Returns void
9358  */
9359 
9360 static void
9361 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
9362 {
9363 	scmd->satacmd_addr_type = 0;		/* N/A */
9364 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
9365 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
9366 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
9367 	scmd->satacmd_lba_high_lsb =
9368 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
9369 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
9370 
9371 	/*
9372 	 * We want all data to be transfered via DMA.
9373 	 * But specify it only if drive supports DMA and DMA mode is
9374 	 * selected - some drives are sensitive about it.
9375 	 * Hopefully it wil work for all drives....
9376 	 */
9377 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
9378 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
9379 
9380 	/*
9381 	 * Features register requires special care for devices that use
9382 	 * Serial ATA bridge - they need an explicit specification of
9383 	 * the data transfer direction for Packet DMA commands.
9384 	 * Setting this bit is harmless if DMA is not used.
9385 	 *
9386 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
9387 	 * spec they follow.
9388 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
9389 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
9390 	 * ATA/ATAPI-7 support is explicitly indicated.
9391 	 */
9392 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
9393 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
9394 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
9395 		/*
9396 		 * Specification of major version is valid and version 7
9397 		 * is supported. It does automatically imply that all
9398 		 * spec features are supported. For now, we assume that
9399 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
9400 		 */
9401 		if ((sdinfo->satadrv_id.ai_dirdma &
9402 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
9403 			if (scmd->satacmd_flags.sata_data_direction ==
9404 			    SATA_DIR_READ)
9405 			scmd->satacmd_features_reg |=
9406 			    SATA_ATAPI_F_DATA_DIR_READ;
9407 		}
9408 	}
9409 }
9410 
9411 
9412 #ifdef SATA_DEBUG
9413 
9414 /* Display 18 bytes of Inquiry data */
9415 static void
9416 sata_show_inqry_data(uint8_t *buf)
9417 {
9418 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
9419 	uint8_t *p;
9420 
9421 	cmn_err(CE_NOTE, "Inquiry data:");
9422 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
9423 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
9424 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
9425 	cmn_err(CE_NOTE, "ATAPI transport version %d",
9426 	    SATA_ATAPI_TRANS_VERSION(inq));
9427 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
9428 	    inq->inq_rdf, inq->inq_aenc);
9429 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
9430 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
9431 	p = (uint8_t *)inq->inq_vid;
9432 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
9433 	    "%02x %02x %02x %02x",
9434 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9435 	p = (uint8_t *)inq->inq_vid;
9436 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
9437 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9438 
9439 	p = (uint8_t *)inq->inq_pid;
9440 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
9441 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
9442 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9443 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9444 	p = (uint8_t *)inq->inq_pid;
9445 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
9446 	    "%c %c %c %c %c %c %c %c",
9447 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9448 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9449 
9450 	p = (uint8_t *)inq->inq_revision;
9451 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
9452 	    p[0], p[1], p[2], p[3]);
9453 	p = (uint8_t *)inq->inq_revision;
9454 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
9455 	    p[0], p[1], p[2], p[3]);
9456 
9457 }
9458 
9459 
9460 static void
9461 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
9462 {
9463 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
9464 
9465 	if (scsi_pkt == NULL)
9466 		return;
9467 	if (count != 0) {
9468 		/* saving cdb */
9469 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
9470 		    SATA_ATAPI_MAX_CDB_LEN);
9471 		bcopy(scsi_pkt->pkt_cdbp,
9472 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
9473 	} else {
9474 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
9475 		    sts_sensedata,
9476 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
9477 		    SATA_ATAPI_MIN_RQSENSE_LEN);
9478 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
9479 		    scsi_pkt->pkt_reason;
9480 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
9481 		    spx->txlt_sata_pkt->satapkt_reason;
9482 
9483 		if (++sata_atapi_trace_index >= 64)
9484 			sata_atapi_trace_index = 0;
9485 	}
9486 }
9487 
9488 #endif
9489 
9490 /*
9491  * Fetch inquiry data from ATAPI device
9492  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
9493  *
9494  * Note:
9495  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
9496  * where the caller expects to see the inquiry data.
9497  *
9498  */
9499 
9500 static int
9501 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
9502     sata_address_t *saddr, struct scsi_inquiry *inq)
9503 {
9504 	sata_pkt_txlate_t *spx;
9505 	sata_pkt_t *spkt;
9506 	struct buf *bp;
9507 	sata_drive_info_t *sdinfo;
9508 	sata_cmd_t *scmd;
9509 	int rval;
9510 	uint8_t *rqsp;
9511 	dev_info_t *dip = SATA_DIP(sata_hba);
9512 #ifdef SATA_DEBUG
9513 	char msg_buf[MAXPATHLEN];
9514 #endif
9515 
9516 	ASSERT(sata_hba != NULL);
9517 
9518 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9519 	spx->txlt_sata_hba_inst = sata_hba;
9520 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9521 	spkt = sata_pkt_alloc(spx, NULL);
9522 	if (spkt == NULL) {
9523 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9524 		return (SATA_FAILURE);
9525 	}
9526 	/* address is needed now */
9527 	spkt->satapkt_device.satadev_addr = *saddr;
9528 
9529 	/* scsi_inquiry size buffer */
9530 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
9531 	if (bp == NULL) {
9532 		sata_pkt_free(spx);
9533 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9534 		SATA_LOG_D((sata_hba, CE_WARN,
9535 		    "sata_get_atapi_inquiry_data: "
9536 		    "cannot allocate data buffer"));
9537 		return (SATA_FAILURE);
9538 	}
9539 	bp_mapin(bp); /* make data buffer accessible */
9540 
9541 	scmd = &spkt->satapkt_cmd;
9542 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9543 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9544 
9545 	/* Use synchronous mode */
9546 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9547 	spkt->satapkt_comp = NULL;
9548 	spkt->satapkt_time = sata_default_pkt_time;
9549 
9550 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9551 
9552 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9553 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9554 
9555 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
9556 	sdinfo = sata_get_device_info(sata_hba,
9557 	    &spx->txlt_sata_pkt->satapkt_device);
9558 	if (sdinfo == NULL) {
9559 		/* we have to be carefull about the disapearing device */
9560 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9561 		rval = SATA_FAILURE;
9562 		goto cleanup;
9563 	}
9564 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9565 
9566 	/*
9567 	 * Set-up acdb. This works for atapi transport version 2 and later.
9568 	 */
9569 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9570 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9571 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9572 	scmd->satacmd_acdb[1] = 0x00;
9573 	scmd->satacmd_acdb[2] = 0x00;
9574 	scmd->satacmd_acdb[3] = 0x00;
9575 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9576 	scmd->satacmd_acdb[5] = 0x00;
9577 
9578 	sata_fixed_sense_data_preset(
9579 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9580 
9581 	/* Transfer command to HBA */
9582 	if (sata_hba_start(spx, &rval) != 0) {
9583 		/* Pkt not accepted for execution */
9584 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9585 		    "sata_get_atapi_inquiry_data: "
9586 		    "Packet not accepted for execution - ret: %02x", rval);
9587 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9588 		rval = SATA_FAILURE;
9589 		goto cleanup;
9590 	}
9591 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9592 
9593 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9594 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9595 		    "sata_get_atapi_inquiry_data: "
9596 		    "Packet completed successfully - ret: %02x", rval);
9597 		if (spx->txlt_buf_dma_handle != NULL) {
9598 			/*
9599 			 * Sync buffer. Handle is in usual place in translate
9600 			 * struct.
9601 			 */
9602 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9603 			    DDI_DMA_SYNC_FORCPU);
9604 			ASSERT(rval == DDI_SUCCESS);
9605 		}
9606 
9607 		if (sata_check_for_dma_error(dip, spx)) {
9608 			ddi_fm_service_impact(dip, DDI_SERVICE_UNAFFECTED);
9609 			rval = SATA_FAILURE;
9610 		} else {
9611 			/*
9612 			 * Normal completion - copy data into caller's buffer
9613 			 */
9614 			bcopy(bp->b_un.b_addr, (uint8_t *)inq,
9615 			    sizeof (struct scsi_inquiry));
9616 #ifdef SATA_DEBUG
9617 			if (sata_debug_flags & SATA_DBG_ATAPI) {
9618 				sata_show_inqry_data((uint8_t *)inq);
9619 			}
9620 #endif
9621 			rval = SATA_SUCCESS;
9622 		}
9623 	} else {
9624 		/*
9625 		 * Something went wrong - analyze return - check rqsense data
9626 		 */
9627 		rval = SATA_FAILURE;
9628 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9629 			/*
9630 			 * ARQ data hopefull show something other than NO SENSE
9631 			 */
9632 			rqsp = scmd->satacmd_rqsense;
9633 #ifdef SATA_DEBUG
9634 			if (sata_debug_flags & SATA_DBG_ATAPI) {
9635 				msg_buf[0] = '\0';
9636 				(void) snprintf(msg_buf, MAXPATHLEN,
9637 				    "ATAPI packet completion reason: %02x\n"
9638 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
9639 				    "          %02x %02x %02x %02x %02x %02x\n"
9640 				    "          %02x %02x %02x %02x %02x %02x",
9641 				    spkt->satapkt_reason,
9642 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9643 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9644 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9645 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9646 				    rqsp[16], rqsp[17]);
9647 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9648 				    "%s", msg_buf);
9649 			}
9650 #endif
9651 		} else {
9652 			switch (spkt->satapkt_reason) {
9653 			case SATA_PKT_PORT_ERROR:
9654 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9655 				    "sata_get_atapi_inquiry_data: "
9656 				    "packet reason: port error", NULL);
9657 				break;
9658 
9659 			case SATA_PKT_TIMEOUT:
9660 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9661 				    "sata_get_atapi_inquiry_data: "
9662 				    "packet reason: timeout", NULL);
9663 				break;
9664 
9665 			case SATA_PKT_ABORTED:
9666 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9667 				    "sata_get_atapi_inquiry_data: "
9668 				    "packet reason: aborted", NULL);
9669 				break;
9670 
9671 			case SATA_PKT_RESET:
9672 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9673 				    "sata_get_atapi_inquiry_data: "
9674 				    "packet reason: reset\n", NULL);
9675 				break;
9676 			default:
9677 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9678 				    "sata_get_atapi_inquiry_data: "
9679 				    "invalid packet reason: %02x\n",
9680 				    spkt->satapkt_reason);
9681 				break;
9682 			}
9683 		}
9684 	}
9685 cleanup:
9686 	sata_free_local_buffer(spx);
9687 	sata_pkt_free(spx);
9688 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9689 	return (rval);
9690 }
9691 
9692 
9693 
9694 
9695 
9696 #if 0
9697 #ifdef SATA_DEBUG
9698 
9699 /*
9700  * Test ATAPI packet command.
9701  * Single threaded test: send packet command in synch mode, process completion
9702  *
9703  */
9704 static void
9705 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
9706 {
9707 	sata_pkt_txlate_t *spx;
9708 	sata_pkt_t *spkt;
9709 	struct buf *bp;
9710 	sata_device_t sata_device;
9711 	sata_drive_info_t *sdinfo;
9712 	sata_cmd_t *scmd;
9713 	int rval;
9714 	uint8_t *rqsp;
9715 
9716 	ASSERT(sata_hba_inst != NULL);
9717 	sata_device.satadev_addr.cport = cport;
9718 	sata_device.satadev_addr.pmport = 0;
9719 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
9720 	sata_device.satadev_rev = SATA_DEVICE_REV;
9721 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9722 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
9723 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9724 	if (sdinfo == NULL) {
9725 		sata_log(sata_hba_inst, CE_WARN,
9726 		    "sata_test_atapi_packet_command: "
9727 		    "no device info for cport %d",
9728 		    sata_device.satadev_addr.cport);
9729 		return;
9730 	}
9731 
9732 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9733 	spx->txlt_sata_hba_inst = sata_hba_inst;
9734 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9735 	spkt = sata_pkt_alloc(spx, NULL);
9736 	if (spkt == NULL) {
9737 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9738 		return;
9739 	}
9740 	/* address is needed now */
9741 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
9742 
9743 	/* 1024k buffer */
9744 	bp = sata_alloc_local_buffer(spx, 1024);
9745 	if (bp == NULL) {
9746 		sata_pkt_free(spx);
9747 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9748 		sata_log(sata_hba_inst, CE_WARN,
9749 		    "sata_test_atapi_packet_command: "
9750 		    "cannot allocate data buffer");
9751 		return;
9752 	}
9753 	bp_mapin(bp); /* make data buffer accessible */
9754 
9755 	scmd = &spkt->satapkt_cmd;
9756 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9757 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9758 
9759 	/* Use synchronous mode */
9760 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9761 
9762 	/* Synchronous mode, no callback - may be changed by the caller */
9763 	spkt->satapkt_comp = NULL;
9764 	spkt->satapkt_time = sata_default_pkt_time;
9765 
9766 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9767 
9768 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9769 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9770 
9771 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9772 
9773 	/* Set-up acdb. */
9774 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9775 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9776 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9777 	scmd->satacmd_acdb[1] = 0x00;
9778 	scmd->satacmd_acdb[2] = 0x00;
9779 	scmd->satacmd_acdb[3] = 0x00;
9780 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9781 	scmd->satacmd_acdb[5] = 0x00;
9782 
9783 	sata_fixed_sense_data_preset(
9784 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9785 
9786 	/* Transfer command to HBA */
9787 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9788 	if (sata_hba_start(spx, &rval) != 0) {
9789 		/* Pkt not accepted for execution */
9790 		sata_log(sata_hba_inst, CE_WARN,
9791 		    "sata_test_atapi_packet_command: "
9792 		    "Packet not accepted for execution - ret: %02x", rval);
9793 		mutex_exit(
9794 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9795 		goto cleanup;
9796 	}
9797 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9798 
9799 	if (spx->txlt_buf_dma_handle != NULL) {
9800 		/*
9801 		 * Sync buffer. Handle is in usual place in translate struct.
9802 		 */
9803 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9804 		    DDI_DMA_SYNC_FORCPU);
9805 		ASSERT(rval == DDI_SUCCESS);
9806 	}
9807 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9808 		sata_log(sata_hba_inst, CE_WARN,
9809 		    "sata_test_atapi_packet_command: "
9810 		    "Packet completed successfully");
9811 		/*
9812 		 * Normal completion - show inquiry data
9813 		 */
9814 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
9815 	} else {
9816 		/*
9817 		 * Something went wrong - analyze return - check rqsense data
9818 		 */
9819 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9820 			/*
9821 			 * ARQ data hopefull show something other than NO SENSE
9822 			 */
9823 			rqsp = scmd->satacmd_rqsense;
9824 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9825 			    "ATAPI packet completion reason: %02x\n"
9826 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
9827 			    "          %02x %02x %02x %02x %02x %02x "
9828 			    "          %02x %02x %02x %02x %02x %02x\n",
9829 			    spkt->satapkt_reason,
9830 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9831 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9832 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9833 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9834 			    rqsp[16], rqsp[17]);
9835 		} else {
9836 			switch (spkt->satapkt_reason) {
9837 			case SATA_PKT_PORT_ERROR:
9838 				sata_log(sata_hba_inst, CE_WARN,
9839 				    "sata_test_atapi_packet_command: "
9840 				    "packet reason: port error\n");
9841 				break;
9842 
9843 			case SATA_PKT_TIMEOUT:
9844 				sata_log(sata_hba_inst, CE_WARN,
9845 				    "sata_test_atapi_packet_command: "
9846 				    "packet reason: timeout\n");
9847 				break;
9848 
9849 			case SATA_PKT_ABORTED:
9850 				sata_log(sata_hba_inst, CE_WARN,
9851 				    "sata_test_atapi_packet_command: "
9852 				    "packet reason: aborted\n");
9853 				break;
9854 
9855 			case SATA_PKT_RESET:
9856 				sata_log(sata_hba_inst, CE_WARN,
9857 				    "sata_test_atapi_packet_command: "
9858 				    "packet reason: reset\n");
9859 				break;
9860 			default:
9861 				sata_log(sata_hba_inst, CE_WARN,
9862 				    "sata_test_atapi_packet_command: "
9863 				    "invalid packet reason: %02x\n",
9864 				    spkt->satapkt_reason);
9865 				break;
9866 			}
9867 		}
9868 	}
9869 cleanup:
9870 	sata_free_local_buffer(spx);
9871 	sata_pkt_free(spx);
9872 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9873 }
9874 
9875 #endif /* SATA_DEBUG */
9876 #endif /* 1 */
9877 
9878 
9879 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
9880 
9881 /*
9882  * Validate sata_tran info
9883  * SATA_FAILURE returns if structure is inconsistent or structure revision
9884  * does not match one used by the framework.
9885  *
9886  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
9887  * required function pointers.
9888  * Returns SATA_FAILURE otherwise.
9889  */
9890 static int
9891 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
9892 {
9893 	/*
9894 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
9895 	 * of the SATA interface.
9896 	 */
9897 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
9898 		sata_log(NULL, CE_WARN,
9899 		    "sata: invalid sata_hba_tran version %d for driver %s",
9900 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
9901 		return (SATA_FAILURE);
9902 	}
9903 
9904 	if (dip != sata_tran->sata_tran_hba_dip) {
9905 		SATA_LOG_D((NULL, CE_WARN,
9906 		    "sata: inconsistent sata_tran_hba_dip "
9907 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
9908 		return (SATA_FAILURE);
9909 	}
9910 
9911 	if (sata_tran->sata_tran_probe_port == NULL ||
9912 	    sata_tran->sata_tran_start == NULL ||
9913 	    sata_tran->sata_tran_abort == NULL ||
9914 	    sata_tran->sata_tran_reset_dport == NULL ||
9915 	    sata_tran->sata_tran_hotplug_ops == NULL ||
9916 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
9917 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
9918 	    NULL) {
9919 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
9920 		    "required functions"));
9921 	}
9922 	return (SATA_SUCCESS);
9923 }
9924 
9925 /*
9926  * Remove HBA instance from sata_hba_list.
9927  */
9928 static void
9929 sata_remove_hba_instance(dev_info_t *dip)
9930 {
9931 	sata_hba_inst_t	*sata_hba_inst;
9932 
9933 	mutex_enter(&sata_mutex);
9934 	for (sata_hba_inst = sata_hba_list;
9935 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
9936 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9937 		if (sata_hba_inst->satahba_dip == dip)
9938 			break;
9939 	}
9940 
9941 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
9942 #ifdef SATA_DEBUG
9943 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
9944 		    "unknown HBA instance\n");
9945 #endif
9946 		ASSERT(FALSE);
9947 	}
9948 	if (sata_hba_inst == sata_hba_list) {
9949 		sata_hba_list = sata_hba_inst->satahba_next;
9950 		if (sata_hba_list) {
9951 			sata_hba_list->satahba_prev =
9952 			    (struct sata_hba_inst *)NULL;
9953 		}
9954 		if (sata_hba_inst == sata_hba_list_tail) {
9955 			sata_hba_list_tail = NULL;
9956 		}
9957 	} else if (sata_hba_inst == sata_hba_list_tail) {
9958 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
9959 		if (sata_hba_list_tail) {
9960 			sata_hba_list_tail->satahba_next =
9961 			    (struct sata_hba_inst *)NULL;
9962 		}
9963 	} else {
9964 		sata_hba_inst->satahba_prev->satahba_next =
9965 		    sata_hba_inst->satahba_next;
9966 		sata_hba_inst->satahba_next->satahba_prev =
9967 		    sata_hba_inst->satahba_prev;
9968 	}
9969 	mutex_exit(&sata_mutex);
9970 }
9971 
9972 /*
9973  * Probe all SATA ports of the specified HBA instance.
9974  * The assumption is that there are no target and attachment point minor nodes
9975  * created by the boot subsystems, so we do not need to prune device tree.
9976  *
9977  * This function is called only from sata_hba_attach(). It does not have to
9978  * be protected by controller mutex, because the hba_attached flag is not set
9979  * yet and no one would be touching this HBA instance other than this thread.
9980  * Determines if port is active and what type of the device is attached
9981  * (if any). Allocates necessary structures for each port.
9982  *
9983  * An AP (Attachement Point) node is created for each SATA device port even
9984  * when there is no device attached.
9985  */
9986 
9987 static 	void
9988 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
9989 {
9990 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9991 	int			ncport;
9992 	sata_cport_info_t 	*cportinfo;
9993 	sata_drive_info_t	*drive;
9994 	sata_device_t		sata_device;
9995 	int			rval;
9996 	dev_t			minor_number;
9997 	char			name[16];
9998 	clock_t			start_time, cur_time;
9999 
10000 	/*
10001 	 * Probe controller ports first, to find port status and
10002 	 * any port multiplier attached.
10003 	 */
10004 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
10005 		/* allocate cport structure */
10006 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
10007 		ASSERT(cportinfo != NULL);
10008 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
10009 
10010 		mutex_enter(&cportinfo->cport_mutex);
10011 
10012 		cportinfo->cport_addr.cport = ncport;
10013 		cportinfo->cport_addr.pmport = 0;
10014 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
10015 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10016 		cportinfo->cport_state |= SATA_STATE_PROBING;
10017 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
10018 
10019 		/*
10020 		 * Regardless if a port is usable or not, create
10021 		 * an attachment point
10022 		 */
10023 		mutex_exit(&cportinfo->cport_mutex);
10024 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
10025 		    ncport, 0, SATA_ADDR_CPORT);
10026 		(void) sprintf(name, "%d", ncport);
10027 		if (ddi_create_minor_node(dip, name, S_IFCHR,
10028 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
10029 		    DDI_SUCCESS) {
10030 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
10031 			    "cannot create SATA attachment point for port %d",
10032 			    ncport);
10033 		}
10034 
10035 		/* Probe port */
10036 		start_time = ddi_get_lbolt();
10037 	reprobe_cport:
10038 		sata_device.satadev_addr.cport = ncport;
10039 		sata_device.satadev_addr.pmport = 0;
10040 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
10041 		sata_device.satadev_rev = SATA_DEVICE_REV;
10042 
10043 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10044 		    (dip, &sata_device);
10045 
10046 		mutex_enter(&cportinfo->cport_mutex);
10047 		cportinfo->cport_scr = sata_device.satadev_scr;
10048 		if (rval != SATA_SUCCESS) {
10049 			/* Something went wrong? Fail the port */
10050 			cportinfo->cport_state = SATA_PSTATE_FAILED;
10051 			mutex_exit(&cportinfo->cport_mutex);
10052 			continue;
10053 		}
10054 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
10055 		cportinfo->cport_state |= SATA_STATE_PROBED;
10056 		cportinfo->cport_dev_type = sata_device.satadev_type;
10057 
10058 		cportinfo->cport_state |= SATA_STATE_READY;
10059 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
10060 			mutex_exit(&cportinfo->cport_mutex);
10061 			continue;
10062 		}
10063 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
10064 			/*
10065 			 * There is some device attached.
10066 			 * Allocate device info structure
10067 			 */
10068 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
10069 				mutex_exit(&cportinfo->cport_mutex);
10070 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
10071 				    kmem_zalloc(sizeof (sata_drive_info_t),
10072 				    KM_SLEEP);
10073 				mutex_enter(&cportinfo->cport_mutex);
10074 			}
10075 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
10076 			drive->satadrv_addr = cportinfo->cport_addr;
10077 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
10078 			drive->satadrv_type = cportinfo->cport_dev_type;
10079 			drive->satadrv_state = SATA_STATE_UNKNOWN;
10080 
10081 			mutex_exit(&cportinfo->cport_mutex);
10082 			if (sata_add_device(dip, sata_hba_inst, &sata_device) !=
10083 			    SATA_SUCCESS) {
10084 				/*
10085 				 * Plugged device was not correctly identified.
10086 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
10087 				 */
10088 				cur_time = ddi_get_lbolt();
10089 				if ((cur_time - start_time) <
10090 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
10091 					/* sleep for a while */
10092 					delay(drv_usectohz(
10093 					    SATA_DEV_RETRY_DLY));
10094 					goto reprobe_cport;
10095 				}
10096 			}
10097 		} else { /* SATA_DTYPE_PMULT */
10098 			mutex_exit(&cportinfo->cport_mutex);
10099 
10100 			/* Allocate sata_pmult_info and sata_pmport_info */
10101 			if (sata_alloc_pmult(sata_hba_inst, &sata_device) !=
10102 			    SATA_SUCCESS)
10103 				continue;
10104 
10105 			/* Log the information of the port multiplier */
10106 			sata_show_pmult_info(sata_hba_inst, &sata_device);
10107 
10108 			/* Probe its pmports */
10109 			sata_probe_pmports(sata_hba_inst, ncport);
10110 		}
10111 	}
10112 }
10113 
10114 /*
10115  * Probe all device ports behind a port multiplier.
10116  *
10117  * PMult-related structure should be allocated before by sata_alloc_pmult().
10118  *
10119  * NOTE1: Only called from sata_probe_ports()
10120  * NOTE2: No mutex should be hold.
10121  */
10122 static void
10123 sata_probe_pmports(sata_hba_inst_t *sata_hba_inst, uint8_t ncport)
10124 {
10125 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
10126 	sata_pmult_info_t	*pmultinfo = NULL;
10127 	sata_pmport_info_t 	*pmportinfo = NULL;
10128 	sata_drive_info_t	*drive = NULL;
10129 	sata_device_t		sata_device;
10130 
10131 	clock_t			start_time, cur_time;
10132 	int			npmport;
10133 	int			rval;
10134 
10135 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, ncport);
10136 
10137 	/* Probe Port Multiplier ports */
10138 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports; npmport++) {
10139 		pmportinfo = pmultinfo->pmult_dev_port[npmport];
10140 		start_time = ddi_get_lbolt();
10141 reprobe_pmport:
10142 		sata_device.satadev_addr.cport = ncport;
10143 		sata_device.satadev_addr.pmport = npmport;
10144 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
10145 		sata_device.satadev_rev = SATA_DEVICE_REV;
10146 
10147 		/* Let HBA driver probe it. */
10148 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10149 		    (dip, &sata_device);
10150 		mutex_enter(&pmportinfo->pmport_mutex);
10151 
10152 		pmportinfo->pmport_scr = sata_device.satadev_scr;
10153 
10154 		if (rval != SATA_SUCCESS) {
10155 			pmportinfo->pmport_state =
10156 			    SATA_PSTATE_FAILED;
10157 			mutex_exit(&pmportinfo->pmport_mutex);
10158 			continue;
10159 		}
10160 		pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
10161 		pmportinfo->pmport_state |= SATA_STATE_PROBED;
10162 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
10163 
10164 		pmportinfo->pmport_state |= SATA_STATE_READY;
10165 		if (pmportinfo->pmport_dev_type ==
10166 		    SATA_DTYPE_NONE) {
10167 			SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
10168 			    "no device found at port %d:%d", ncport, npmport);
10169 			mutex_exit(&pmportinfo->pmport_mutex);
10170 			continue;
10171 		}
10172 		/* Port multipliers cannot be chained */
10173 		ASSERT(pmportinfo->pmport_dev_type != SATA_DTYPE_PMULT);
10174 		/*
10175 		 * There is something attached to Port
10176 		 * Multiplier device port
10177 		 * Allocate device info structure
10178 		 */
10179 		if (pmportinfo->pmport_sata_drive == NULL) {
10180 			mutex_exit(&pmportinfo->pmport_mutex);
10181 			pmportinfo->pmport_sata_drive =
10182 			    kmem_zalloc(sizeof (sata_drive_info_t), KM_SLEEP);
10183 			mutex_enter(&pmportinfo->pmport_mutex);
10184 		}
10185 		drive = pmportinfo->pmport_sata_drive;
10186 		drive->satadrv_addr.cport = pmportinfo->pmport_addr.cport;
10187 		drive->satadrv_addr.pmport = npmport;
10188 		drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
10189 		drive->satadrv_type = pmportinfo-> pmport_dev_type;
10190 		drive->satadrv_state = SATA_STATE_UNKNOWN;
10191 
10192 		mutex_exit(&pmportinfo->pmport_mutex);
10193 		rval = sata_add_device(dip, sata_hba_inst, &sata_device);
10194 
10195 		if (rval != SATA_SUCCESS) {
10196 			/*
10197 			 * Plugged device was not correctly identified.
10198 			 * Retry, within the SATA_DEV_IDENTIFY_TIMEOUT
10199 			 */
10200 			cur_time = ddi_get_lbolt();
10201 			if ((cur_time - start_time) < drv_usectohz(
10202 			    SATA_DEV_IDENTIFY_TIMEOUT)) {
10203 				/* sleep for a while */
10204 				delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10205 				goto reprobe_pmport;
10206 			}
10207 		}
10208 	}
10209 }
10210 
10211 /*
10212  * Add SATA device for specified HBA instance & port (SCSI target
10213  * device nodes).
10214  * This function is called (indirectly) only from sata_hba_attach().
10215  * A target node is created when there is a supported type device attached,
10216  * but may be removed if it cannot be put online.
10217  *
10218  * This function cannot be called from an interrupt context.
10219  *
10220  * Create target nodes for disk, CD/DVD, Tape and ATAPI disk devices
10221  *
10222  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
10223  * device identification failed - adding a device could be retried.
10224  *
10225  */
10226 static 	int
10227 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst,
10228     sata_device_t *sata_device)
10229 {
10230 	sata_cport_info_t 	*cportinfo;
10231 	sata_pmult_info_t	*pminfo;
10232 	sata_pmport_info_t	*pmportinfo;
10233 	dev_info_t		*cdip;		/* child dip */
10234 	sata_address_t		*saddr = &sata_device->satadev_addr;
10235 	uint8_t			cport, pmport;
10236 	int			rval;
10237 
10238 	cport = saddr->cport;
10239 	pmport = saddr->pmport;
10240 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10241 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
10242 
10243 	/*
10244 	 * Some device is attached to a controller port.
10245 	 * We rely on controllers distinquishing between no-device,
10246 	 * attached port multiplier and other kind of attached device.
10247 	 * We need to get Identify Device data and determine
10248 	 * positively the dev type before trying to attach
10249 	 * the target driver.
10250 	 */
10251 	sata_device->satadev_rev = SATA_DEVICE_REV;
10252 	switch (saddr->qual) {
10253 	case SATA_ADDR_CPORT:
10254 		/*
10255 		 * Add a non-port-multiplier device at controller port.
10256 		 */
10257 		saddr->qual = SATA_ADDR_DCPORT;
10258 
10259 		rval = sata_probe_device(sata_hba_inst, sata_device);
10260 		if (rval != SATA_SUCCESS ||
10261 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN)
10262 			return (SATA_FAILURE);
10263 
10264 		mutex_enter(&cportinfo->cport_mutex);
10265 		sata_show_drive_info(sata_hba_inst,
10266 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
10267 
10268 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10269 			/*
10270 			 * Could not determine device type or
10271 			 * a device is not supported.
10272 			 * Degrade this device to unknown.
10273 			 */
10274 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10275 			mutex_exit(&cportinfo->cport_mutex);
10276 			return (SATA_SUCCESS);
10277 		}
10278 		cportinfo->cport_dev_type = sata_device->satadev_type;
10279 		cportinfo->cport_tgtnode_clean = B_TRUE;
10280 		mutex_exit(&cportinfo->cport_mutex);
10281 
10282 		/*
10283 		 * Initialize device to the desired state. Even if it
10284 		 * fails, the device will still attach but syslog
10285 		 * will show the warning.
10286 		 */
10287 		if (sata_initialize_device(sata_hba_inst,
10288 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
10289 			/* Retry */
10290 			rval = sata_initialize_device(sata_hba_inst,
10291 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
10292 
10293 			if (rval == SATA_RETRY)
10294 				sata_log(sata_hba_inst, CE_WARN,
10295 				    "SATA device at port %d - "
10296 				    "default device features could not be set."
10297 				    " Device may not operate as expected.",
10298 				    cport);
10299 		}
10300 
10301 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10302 		if (cdip == NULL) {
10303 			/*
10304 			 * Attaching target node failed.
10305 			 * We retain sata_drive_info structure...
10306 			 */
10307 			return (SATA_SUCCESS);
10308 		}
10309 
10310 		mutex_enter(&cportinfo->cport_mutex);
10311 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
10312 		    satadrv_state = SATA_STATE_READY;
10313 		mutex_exit(&cportinfo->cport_mutex);
10314 
10315 		break;
10316 
10317 	case SATA_ADDR_PMPORT:
10318 		saddr->qual = SATA_ADDR_DPMPORT;
10319 
10320 		mutex_enter(&cportinfo->cport_mutex);
10321 		/* It must be a Port Multiplier at the controller port */
10322 		ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
10323 
10324 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
10325 		pmportinfo = pminfo->pmult_dev_port[saddr->pmport];
10326 		mutex_exit(&cportinfo->cport_mutex);
10327 
10328 		rval = sata_probe_device(sata_hba_inst, sata_device);
10329 		if (rval != SATA_SUCCESS ||
10330 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
10331 			return (SATA_FAILURE);
10332 		}
10333 
10334 		mutex_enter(&pmportinfo->pmport_mutex);
10335 		sata_show_drive_info(sata_hba_inst,
10336 		    SATA_PMPORTINFO_DRV_INFO(pmportinfo));
10337 
10338 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10339 			/*
10340 			 * Could not determine device type.
10341 			 * Degrade this device to unknown.
10342 			 */
10343 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
10344 			mutex_exit(&pmportinfo->pmport_mutex);
10345 			return (SATA_SUCCESS);
10346 		}
10347 		pmportinfo->pmport_dev_type = sata_device->satadev_type;
10348 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
10349 		mutex_exit(&pmportinfo->pmport_mutex);
10350 
10351 		/*
10352 		 * Initialize device to the desired state.
10353 		 * Even if it fails, the device will still
10354 		 * attach but syslog will show the warning.
10355 		 */
10356 		if (sata_initialize_device(sata_hba_inst,
10357 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
10358 			/* Retry */
10359 			rval = sata_initialize_device(sata_hba_inst,
10360 			    pmportinfo->pmport_sata_drive);
10361 
10362 			if (rval == SATA_RETRY)
10363 				sata_log(sata_hba_inst, CE_WARN,
10364 				    "SATA device at port %d:%d - "
10365 				    "default device features could not be set."
10366 				    " Device may not operate as expected.",
10367 				    cport, pmport);
10368 		}
10369 
10370 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10371 		if (cdip == NULL) {
10372 			/*
10373 			 * Attaching target node failed.
10374 			 * We retain sata_drive_info structure...
10375 			 */
10376 			return (SATA_SUCCESS);
10377 		}
10378 		mutex_enter(&pmportinfo->pmport_mutex);
10379 		pmportinfo->pmport_sata_drive->satadrv_state |=
10380 		    SATA_STATE_READY;
10381 		mutex_exit(&pmportinfo->pmport_mutex);
10382 
10383 		break;
10384 
10385 	default:
10386 		return (SATA_FAILURE);
10387 	}
10388 
10389 	return (SATA_SUCCESS);
10390 }
10391 
10392 /*
10393  * Clean up target node at specific address.
10394  *
10395  * NOTE: No Mutex should be hold.
10396  */
10397 static int
10398 sata_offline_device(sata_hba_inst_t *sata_hba_inst,
10399     sata_device_t *sata_device, sata_drive_info_t *sdinfo)
10400 {
10401 	uint8_t cport, pmport, qual;
10402 	dev_info_t *tdip;
10403 
10404 	cport = sata_device->satadev_addr.cport;
10405 	pmport = sata_device->satadev_addr.pmport;
10406 	qual = sata_device->satadev_addr.qual;
10407 
10408 	if (qual == SATA_ADDR_DCPORT) {
10409 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10410 		    "sata_hba_ioctl: disconnect device at port %d", cport));
10411 	} else {
10412 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10413 		    "sata_hba_ioctl: disconnect device at port %d:%d",
10414 		    cport, pmport));
10415 	}
10416 
10417 	/* We are addressing attached device, not a port */
10418 	sata_device->satadev_addr.qual =
10419 	    sdinfo->satadrv_addr.qual;
10420 	tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
10421 	    &sata_device->satadev_addr);
10422 	if (tdip != NULL && ndi_devi_offline(tdip,
10423 	    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10424 		/*
10425 		 * Problem :
10426 		 * The target node remained attached.
10427 		 * This happens when the device file was open
10428 		 * or a node was waiting for resources.
10429 		 * Cannot do anything about it.
10430 		 */
10431 		if (qual == SATA_ADDR_DCPORT) {
10432 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10433 			    "sata_hba_ioctl: disconnect: could "
10434 			    "not unconfigure device before "
10435 			    "disconnecting the SATA port %d",
10436 			    cport));
10437 		} else {
10438 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10439 			    "sata_hba_ioctl: disconnect: could "
10440 			    "not unconfigure device before "
10441 			    "disconnecting the SATA port %d:%d",
10442 			    cport, pmport));
10443 		}
10444 		/*
10445 		 * Set DEVICE REMOVED state in the target
10446 		 * node. It will prevent access to the device
10447 		 * even when a new device is attached, until
10448 		 * the old target node is released, removed and
10449 		 * recreated for a new  device.
10450 		 */
10451 		sata_set_device_removed(tdip);
10452 
10453 		/*
10454 		 * Instruct event daemon to try the target
10455 		 * node cleanup later.
10456 		 */
10457 		sata_set_target_node_cleanup(
10458 		    sata_hba_inst, &sata_device->satadev_addr);
10459 	}
10460 
10461 
10462 	return (SATA_SUCCESS);
10463 }
10464 
10465 
10466 /*
10467  * Create scsi target node for attached device, create node properties and
10468  * attach the node.
10469  * The node could be removed if the device onlining fails.
10470  *
10471  * A dev_info_t pointer is returned if operation is successful, NULL is
10472  * returned otherwise.
10473  */
10474 
10475 static dev_info_t *
10476 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
10477 			sata_address_t *sata_addr)
10478 {
10479 	dev_info_t *cdip = NULL;
10480 	int rval;
10481 	char *nname = NULL;
10482 	char **compatible = NULL;
10483 	int ncompatible;
10484 	struct scsi_inquiry inq;
10485 	sata_device_t sata_device;
10486 	sata_drive_info_t *sdinfo;
10487 	int target;
10488 	int i;
10489 
10490 	sata_device.satadev_rev = SATA_DEVICE_REV;
10491 	sata_device.satadev_addr = *sata_addr;
10492 
10493 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
10494 
10495 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
10496 
10497 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
10498 	    sata_addr->pmport, sata_addr->qual);
10499 
10500 	if (sdinfo == NULL) {
10501 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10502 		    sata_addr->cport)));
10503 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10504 		    "sata_create_target_node: no sdinfo for target %x",
10505 		    target));
10506 		return (NULL);
10507 	}
10508 
10509 	/*
10510 	 * create or get scsi inquiry data, expected by
10511 	 * scsi_hba_nodename_compatible_get()
10512 	 * SATA hard disks get Identify Data translated into Inguiry Data.
10513 	 * ATAPI devices respond directly to Inquiry request.
10514 	 */
10515 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10516 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
10517 		    (uint8_t *)&inq);
10518 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10519 		    sata_addr->cport)));
10520 	} else { /* Assume supported ATAPI device */
10521 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10522 		    sata_addr->cport)));
10523 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
10524 		    &inq) == SATA_FAILURE)
10525 			return (NULL);
10526 		/*
10527 		 * Save supported ATAPI transport version
10528 		 */
10529 		sdinfo->satadrv_atapi_trans_ver =
10530 		    SATA_ATAPI_TRANS_VERSION(&inq);
10531 	}
10532 
10533 	/* determine the node name and compatible */
10534 	scsi_hba_nodename_compatible_get(&inq, NULL,
10535 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
10536 
10537 #ifdef SATA_DEBUG
10538 	if (sata_debug_flags & SATA_DBG_NODES) {
10539 		if (nname == NULL) {
10540 			cmn_err(CE_NOTE, "sata_create_target_node: "
10541 			    "cannot determine nodename for target %d\n",
10542 			    target);
10543 		} else {
10544 			cmn_err(CE_WARN, "sata_create_target_node: "
10545 			    "target %d nodename: %s\n", target, nname);
10546 		}
10547 		if (compatible == NULL) {
10548 			cmn_err(CE_WARN,
10549 			    "sata_create_target_node: no compatible name\n");
10550 		} else {
10551 			for (i = 0; i < ncompatible; i++) {
10552 				cmn_err(CE_WARN, "sata_create_target_node: "
10553 				    "compatible name: %s\n", compatible[i]);
10554 			}
10555 		}
10556 	}
10557 #endif
10558 
10559 	/* if nodename can't be determined, log error and exit */
10560 	if (nname == NULL) {
10561 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10562 		    "sata_create_target_node: cannot determine nodename "
10563 		    "for target %d\n", target));
10564 		scsi_hba_nodename_compatible_free(nname, compatible);
10565 		return (NULL);
10566 	}
10567 	/*
10568 	 * Create scsi target node
10569 	 */
10570 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
10571 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10572 	    "device-type", "scsi");
10573 
10574 	if (rval != DDI_PROP_SUCCESS) {
10575 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10576 		    "updating device_type prop failed %d", rval));
10577 		goto fail;
10578 	}
10579 
10580 	/*
10581 	 * Create target node properties: target & lun
10582 	 */
10583 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
10584 	if (rval != DDI_PROP_SUCCESS) {
10585 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10586 		    "updating target prop failed %d", rval));
10587 		goto fail;
10588 	}
10589 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
10590 	if (rval != DDI_PROP_SUCCESS) {
10591 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10592 		    "updating target prop failed %d", rval));
10593 		goto fail;
10594 	}
10595 
10596 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
10597 		/*
10598 		 * Add "variant" property
10599 		 */
10600 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10601 		    "variant", "atapi");
10602 		if (rval != DDI_PROP_SUCCESS) {
10603 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10604 			    "sata_create_target_node: variant atapi "
10605 			    "property could not be created: %d", rval));
10606 			goto fail;
10607 		}
10608 	}
10609 	/* decorate the node with compatible */
10610 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
10611 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
10612 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10613 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
10614 		    (void *)cdip));
10615 		goto fail;
10616 	}
10617 
10618 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10619 		/*
10620 		 * Add "sata-phy" property
10621 		 */
10622 		if (ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "sata-phy",
10623 		    (int)sata_addr->cport) != DDI_PROP_SUCCESS) {
10624 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10625 			    "sata_create_target_node: failed to create "
10626 			    "\"sata-phy\" property: port %d",
10627 			    sata_addr->cport));
10628 		}
10629 	}
10630 
10631 
10632 	/*
10633 	 * Now, try to attach the driver. If probing of the device fails,
10634 	 * the target node may be removed
10635 	 */
10636 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
10637 
10638 	scsi_hba_nodename_compatible_free(nname, compatible);
10639 
10640 	if (rval == NDI_SUCCESS)
10641 		return (cdip);
10642 
10643 	/* target node was removed - are we sure? */
10644 	return (NULL);
10645 
10646 fail:
10647 	scsi_hba_nodename_compatible_free(nname, compatible);
10648 	ddi_prop_remove_all(cdip);
10649 	rval = ndi_devi_free(cdip);
10650 	if (rval != NDI_SUCCESS) {
10651 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10652 		    "node removal failed %d", rval));
10653 	}
10654 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
10655 	    "cannot create target node for SATA device at port %d",
10656 	    sata_addr->cport);
10657 	return (NULL);
10658 }
10659 
10660 /*
10661  * Remove a target node.
10662  */
10663 static void
10664 sata_remove_target_node(sata_hba_inst_t *sata_hba_inst,
10665 			sata_address_t *sata_addr)
10666 {
10667 	dev_info_t *tdip;
10668 	uint8_t cport = sata_addr->cport;
10669 	uint8_t pmport = sata_addr->pmport;
10670 	uint8_t qual = sata_addr->qual;
10671 
10672 	/* Note the sata daemon uses the address of the port/pmport */
10673 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
10674 
10675 	/* Remove target node */
10676 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), cport, pmport);
10677 	if (tdip != NULL) {
10678 		/*
10679 		 * Target node exists.  Unconfigure device
10680 		 * then remove the target node (one ndi
10681 		 * operation).
10682 		 */
10683 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10684 			/*
10685 			 * PROBLEM - no device, but target node remained. This
10686 			 * happens when the file was open or node was waiting
10687 			 * for resources.
10688 			 */
10689 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10690 			    "sata_remove_target_node: "
10691 			    "Failed to remove target node for "
10692 			    "detached SATA device."));
10693 			/*
10694 			 * Set target node state to DEVI_DEVICE_REMOVED. But
10695 			 * re-check first that the node still exists.
10696 			 */
10697 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
10698 			    cport, pmport);
10699 			if (tdip != NULL) {
10700 				sata_set_device_removed(tdip);
10701 				/*
10702 				 * Instruct event daemon to retry the cleanup
10703 				 * later.
10704 				 */
10705 				sata_set_target_node_cleanup(sata_hba_inst,
10706 				    sata_addr);
10707 			}
10708 		}
10709 
10710 		if (qual == SATA_ADDR_CPORT)
10711 			sata_log(sata_hba_inst, CE_WARN,
10712 			    "SATA device detached at port %d", cport);
10713 		else
10714 			sata_log(sata_hba_inst, CE_WARN,
10715 			    "SATA device detached at port %d:%d",
10716 			    cport, pmport);
10717 	}
10718 #ifdef SATA_DEBUG
10719 	else {
10720 		if (qual == SATA_ADDR_CPORT)
10721 			sata_log(sata_hba_inst, CE_WARN,
10722 			    "target node not found at port %d", cport);
10723 		else
10724 			sata_log(sata_hba_inst, CE_WARN,
10725 			    "target node not found at port %d:%d",
10726 			    cport, pmport);
10727 	}
10728 #endif
10729 }
10730 
10731 
10732 /*
10733  * Re-probe sata port, check for a device and attach info
10734  * structures when necessary. Identify Device data is fetched, if possible.
10735  * Assumption: sata address is already validated.
10736  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10737  * the presence of a device and its type.
10738  *
10739  * flag arg specifies that the function should try multiple times to identify
10740  * device type and to initialize it, or it should return immediately on failure.
10741  * SATA_DEV_IDENTIFY_RETRY - retry
10742  * SATA_DEV_IDENTIFY_NORETRY - no retry
10743  *
10744  * SATA_FAILURE is returned if one of the operations failed.
10745  *
10746  * This function cannot be called in interrupt context - it may sleep.
10747  *
10748  * Note: Port multiplier is supported.
10749  */
10750 static int
10751 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10752     int flag)
10753 {
10754 	sata_cport_info_t *cportinfo;
10755 	sata_pmult_info_t *pmultinfo;
10756 	sata_drive_info_t *sdinfo, *osdinfo;
10757 	boolean_t init_device = B_FALSE;
10758 	int prev_device_type = SATA_DTYPE_NONE;
10759 	int prev_device_settings = 0;
10760 	int prev_device_state = 0;
10761 	clock_t start_time;
10762 	int retry = B_FALSE;
10763 	uint8_t cport = sata_device->satadev_addr.cport;
10764 	int rval_probe, rval_init;
10765 
10766 	/*
10767 	 * If target is pmport, sata_reprobe_pmport() will handle it.
10768 	 */
10769 	if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT ||
10770 	    sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT)
10771 		return (sata_reprobe_pmport(sata_hba_inst, sata_device, flag));
10772 
10773 	/* We only care about host sata cport for now */
10774 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
10775 	    sata_device->satadev_addr.cport);
10776 
10777 	/*
10778 	 * If a port multiplier was previously attached (we have no idea it
10779 	 * still there or not), sata_reprobe_pmult() will handle it.
10780 	 */
10781 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT)
10782 		return (sata_reprobe_pmult(sata_hba_inst, sata_device, flag));
10783 
10784 	/* Store sata_drive_info when a non-pmult device was attached. */
10785 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10786 	if (osdinfo != NULL) {
10787 		/*
10788 		 * We are re-probing port with a previously attached device.
10789 		 * Save previous device type and settings.
10790 		 */
10791 		prev_device_type = cportinfo->cport_dev_type;
10792 		prev_device_settings = osdinfo->satadrv_settings;
10793 		prev_device_state = osdinfo->satadrv_state;
10794 	}
10795 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
10796 		start_time = ddi_get_lbolt();
10797 		retry = B_TRUE;
10798 	}
10799 retry_probe:
10800 
10801 	/* probe port */
10802 	mutex_enter(&cportinfo->cport_mutex);
10803 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10804 	cportinfo->cport_state |= SATA_STATE_PROBING;
10805 	mutex_exit(&cportinfo->cport_mutex);
10806 
10807 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10808 	    (SATA_DIP(sata_hba_inst), sata_device);
10809 
10810 	mutex_enter(&cportinfo->cport_mutex);
10811 	if (rval_probe != SATA_SUCCESS) {
10812 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10813 		mutex_exit(&cportinfo->cport_mutex);
10814 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
10815 		    "SATA port %d probing failed",
10816 		    cportinfo->cport_addr.cport));
10817 		return (SATA_FAILURE);
10818 	}
10819 
10820 	/*
10821 	 * update sata port state and set device type
10822 	 */
10823 	sata_update_port_info(sata_hba_inst, sata_device);
10824 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10825 
10826 	/*
10827 	 * Sanity check - Port is active? Is the link active?
10828 	 * Is there any device attached?
10829 	 */
10830 	if ((cportinfo->cport_state &
10831 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10832 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10833 	    SATA_PORT_DEVLINK_UP) {
10834 		/*
10835 		 * Port in non-usable state or no link active/no device.
10836 		 * Free info structure if necessary (direct attached drive
10837 		 * only, for now!
10838 		 */
10839 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10840 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10841 		/* Add here differentiation for device attached or not */
10842 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10843 		mutex_exit(&cportinfo->cport_mutex);
10844 		if (sdinfo != NULL)
10845 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10846 		return (SATA_SUCCESS);
10847 	}
10848 
10849 	cportinfo->cport_state |= SATA_STATE_READY;
10850 	cportinfo->cport_state |= SATA_STATE_PROBED;
10851 
10852 	cportinfo->cport_dev_type = sata_device->satadev_type;
10853 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10854 
10855 	/*
10856 	 * If we are re-probing the port, there may be
10857 	 * sata_drive_info structure attached
10858 	 */
10859 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10860 
10861 		/*
10862 		 * There is no device, so remove device info structure,
10863 		 * if necessary.
10864 		 */
10865 		/* Device change: Drive -> None */
10866 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10867 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10868 		if (sdinfo != NULL) {
10869 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10870 			sata_log(sata_hba_inst, CE_WARN,
10871 			    "SATA device detached "
10872 			    "from port %d", cportinfo->cport_addr.cport);
10873 		}
10874 		mutex_exit(&cportinfo->cport_mutex);
10875 		return (SATA_SUCCESS);
10876 
10877 	}
10878 
10879 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10880 
10881 		/* Device (may) change: Drive -> Drive */
10882 		if (sdinfo == NULL) {
10883 			/*
10884 			 * There is some device attached, but there is
10885 			 * no sata_drive_info structure - allocate one
10886 			 */
10887 			mutex_exit(&cportinfo->cport_mutex);
10888 			sdinfo = kmem_zalloc(
10889 			    sizeof (sata_drive_info_t), KM_SLEEP);
10890 			mutex_enter(&cportinfo->cport_mutex);
10891 			/*
10892 			 * Recheck, that the port state did not change when we
10893 			 * released mutex.
10894 			 */
10895 			if (cportinfo->cport_state & SATA_STATE_READY) {
10896 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
10897 				sdinfo->satadrv_addr = cportinfo->cport_addr;
10898 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
10899 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10900 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10901 			} else {
10902 				/*
10903 				 * Port is not in ready state, we
10904 				 * cannot attach a device.
10905 				 */
10906 				mutex_exit(&cportinfo->cport_mutex);
10907 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
10908 				return (SATA_SUCCESS);
10909 			}
10910 			/*
10911 			 * Since we are adding device, presumably new one,
10912 			 * indicate that it  should be initalized,
10913 			 * as well as some internal framework states).
10914 			 */
10915 			init_device = B_TRUE;
10916 		}
10917 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10918 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10919 	} else {
10920 		/* Device change: Drive -> PMult */
10921 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10922 		if (sdinfo != NULL) {
10923 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10924 			sata_log(sata_hba_inst, CE_WARN,
10925 			    "SATA device detached "
10926 			    "from port %d", cportinfo->cport_addr.cport);
10927 		}
10928 
10929 		sata_log(sata_hba_inst, CE_WARN,
10930 		    "SATA port multiplier detected at port %d",
10931 		    cportinfo->cport_addr.cport);
10932 
10933 		mutex_exit(&cportinfo->cport_mutex);
10934 		if (sata_alloc_pmult(sata_hba_inst, sata_device) !=
10935 		    SATA_SUCCESS)
10936 			return (SATA_FAILURE);
10937 		sata_show_pmult_info(sata_hba_inst, sata_device);
10938 		mutex_enter(&cportinfo->cport_mutex);
10939 
10940 		/*
10941 		 * Mark all the port multiplier port behind the port
10942 		 * multiplier behind with link events, so that the sata daemon
10943 		 * will update their status.
10944 		 */
10945 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10946 		pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10947 		mutex_exit(&cportinfo->cport_mutex);
10948 		return (SATA_SUCCESS);
10949 	}
10950 	mutex_exit(&cportinfo->cport_mutex);
10951 
10952 	/*
10953 	 * Figure out what kind of device we are really
10954 	 * dealing with. Failure of identifying device does not fail this
10955 	 * function.
10956 	 */
10957 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
10958 	rval_init = SATA_FAILURE;
10959 	mutex_enter(&cportinfo->cport_mutex);
10960 	if (rval_probe == SATA_SUCCESS) {
10961 		/*
10962 		 * If we are dealing with the same type of a device as before,
10963 		 * restore its settings flags.
10964 		 */
10965 		if (osdinfo != NULL &&
10966 		    sata_device->satadev_type == prev_device_type)
10967 			sdinfo->satadrv_settings = prev_device_settings;
10968 
10969 		mutex_exit(&cportinfo->cport_mutex);
10970 		rval_init = SATA_SUCCESS;
10971 		/* Set initial device features, if necessary */
10972 		if (init_device == B_TRUE) {
10973 			rval_init = sata_initialize_device(sata_hba_inst,
10974 			    sdinfo);
10975 		}
10976 		if (rval_init == SATA_SUCCESS)
10977 			return (rval_init);
10978 		/* else we will retry if retry was asked for */
10979 
10980 	} else {
10981 		/*
10982 		 * If there was some device info before we probe the device,
10983 		 * restore previous device setting, so we can retry from scratch
10984 		 * later. Providing, of course, that device has not disapear
10985 		 * during probing process.
10986 		 */
10987 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
10988 			if (osdinfo != NULL) {
10989 				cportinfo->cport_dev_type = prev_device_type;
10990 				sdinfo->satadrv_type = prev_device_type;
10991 				sdinfo->satadrv_state = prev_device_state;
10992 			}
10993 		} else {
10994 			/* device is gone */
10995 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10996 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10997 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10998 			mutex_exit(&cportinfo->cport_mutex);
10999 			return (SATA_SUCCESS);
11000 		}
11001 		mutex_exit(&cportinfo->cport_mutex);
11002 	}
11003 
11004 	if (retry) {
11005 		clock_t cur_time = ddi_get_lbolt();
11006 		/*
11007 		 * A device was not successfully identified or initialized.
11008 		 * Track retry time for device identification.
11009 		 */
11010 		if ((cur_time - start_time) <
11011 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11012 			/* sleep for a while */
11013 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11014 			goto retry_probe;
11015 		}
11016 		/* else no more retries */
11017 		mutex_enter(&cportinfo->cport_mutex);
11018 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
11019 			if (rval_init == SATA_RETRY) {
11020 				/*
11021 				 * Setting drive features have failed, but
11022 				 * because the drive is still accessible,
11023 				 * keep it and emit a warning message.
11024 				 */
11025 				sata_log(sata_hba_inst, CE_WARN,
11026 				    "SATA device at port %d - desired "
11027 				    "drive features could not be set. "
11028 				    "Device may not operate as expected.",
11029 				    cportinfo->cport_addr.cport);
11030 			} else {
11031 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
11032 				    satadrv_state = SATA_DSTATE_FAILED;
11033 			}
11034 		}
11035 		mutex_exit(&cportinfo->cport_mutex);
11036 	}
11037 	return (SATA_SUCCESS);
11038 }
11039 
11040 /*
11041  * Reprobe a controller port that connected to a port multiplier.
11042  *
11043  * NOTE: No Mutex should be hold.
11044  */
11045 static int
11046 sata_reprobe_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
11047     int flag)
11048 {
11049 	_NOTE(ARGUNUSED(flag))
11050 	sata_cport_info_t *cportinfo;
11051 	sata_pmult_info_t *pmultinfo;
11052 	uint8_t cport = sata_device->satadev_addr.cport;
11053 	int rval_probe;
11054 
11055 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11056 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
11057 
11058 	/* probe port */
11059 	mutex_enter(&cportinfo->cport_mutex);
11060 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11061 	cportinfo->cport_state |= SATA_STATE_PROBING;
11062 	mutex_exit(&cportinfo->cport_mutex);
11063 
11064 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11065 	    (SATA_DIP(sata_hba_inst), sata_device);
11066 
11067 	mutex_enter(&cportinfo->cport_mutex);
11068 	if (rval_probe != SATA_SUCCESS) {
11069 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11070 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmult: "
11071 		    "SATA port %d probing failed", cport));
11072 		sata_log(sata_hba_inst, CE_WARN,
11073 		    "SATA port multiplier detached at port %d", cport);
11074 		mutex_exit(&cportinfo->cport_mutex);
11075 		sata_free_pmult(sata_hba_inst, sata_device);
11076 		return (SATA_FAILURE);
11077 	}
11078 
11079 	/*
11080 	 * update sata port state and set device type
11081 	 */
11082 	sata_update_port_info(sata_hba_inst, sata_device);
11083 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
11084 	cportinfo->cport_state |= SATA_STATE_PROBED;
11085 
11086 	/*
11087 	 * Sanity check - Port is active? Is the link active?
11088 	 * Is there any device attached?
11089 	 */
11090 	if ((cportinfo->cport_state &
11091 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11092 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11093 	    SATA_PORT_DEVLINK_UP ||
11094 	    (sata_device->satadev_type == SATA_DTYPE_NONE)) {
11095 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11096 		mutex_exit(&cportinfo->cport_mutex);
11097 		sata_free_pmult(sata_hba_inst, sata_device);
11098 		sata_log(sata_hba_inst, CE_WARN,
11099 		    "SATA port multiplier detached at port %d", cport);
11100 		return (SATA_SUCCESS);
11101 	}
11102 
11103 	/*
11104 	 * Device changed: PMult -> Non-PMult
11105 	 *
11106 	 * This situation is uncommon, most possibly being caused by errors
11107 	 * after which the port multiplier is not correct initialized and
11108 	 * recognized. In that case the new device will be marked as unknown
11109 	 * and will not be automatically probed in this routine. Instead
11110 	 * system administrator could manually restart it via cfgadm(1M).
11111 	 */
11112 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
11113 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11114 		mutex_exit(&cportinfo->cport_mutex);
11115 		sata_free_pmult(sata_hba_inst, sata_device);
11116 		sata_log(sata_hba_inst, CE_WARN,
11117 		    "SATA port multiplier detached at port %d", cport);
11118 		return (SATA_FAILURE);
11119 	}
11120 
11121 	/*
11122 	 * Now we know it is a port multiplier. However, if this is not the
11123 	 * previously attached port multiplier - they may have different
11124 	 * pmport numbers - we need to re-allocate data structures for every
11125 	 * pmport and drive.
11126 	 *
11127 	 * Port multipliers of the same model have identical values in these
11128 	 * registers, so it is still necessary to update the information of
11129 	 * all drives attached to the previous port multiplier afterwards.
11130 	 */
11131 	/* Device changed: PMult -> another PMult */
11132 	mutex_exit(&cportinfo->cport_mutex);
11133 	sata_free_pmult(sata_hba_inst, sata_device);
11134 	if (sata_alloc_pmult(sata_hba_inst, sata_device) != SATA_SUCCESS)
11135 		return (SATA_FAILURE);
11136 	mutex_enter(&cportinfo->cport_mutex);
11137 
11138 	SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11139 	    "SATA port multiplier [changed] at port %d", cport);
11140 	sata_log(sata_hba_inst, CE_WARN,
11141 	    "SATA port multiplier detected at port %d", cport);
11142 
11143 	/*
11144 	 * Mark all the port multiplier port behind the port
11145 	 * multiplier behind with link events, so that the sata daemon
11146 	 * will update their status.
11147 	 */
11148 	pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
11149 	mutex_exit(&cportinfo->cport_mutex);
11150 
11151 	return (SATA_SUCCESS);
11152 }
11153 
11154 /*
11155  * Re-probe a port multiplier port, check for a device and attach info
11156  * structures when necessary. Identify Device data is fetched, if possible.
11157  * Assumption: sata address is already validated as port multiplier port.
11158  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
11159  * the presence of a device and its type.
11160  *
11161  * flag arg specifies that the function should try multiple times to identify
11162  * device type and to initialize it, or it should return immediately on failure.
11163  * SATA_DEV_IDENTIFY_RETRY - retry
11164  * SATA_DEV_IDENTIFY_NORETRY - no retry
11165  *
11166  * SATA_FAILURE is returned if one of the operations failed.
11167  *
11168  * This function cannot be called in interrupt context - it may sleep.
11169  *
11170  * NOTE: Should be only called by sata_probe_port() in case target port is a
11171  *       port multiplier port.
11172  * NOTE: No Mutex should be hold.
11173  */
11174 static int
11175 sata_reprobe_pmport(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
11176     int flag)
11177 {
11178 	sata_cport_info_t *cportinfo = NULL;
11179 	sata_pmport_info_t *pmportinfo = NULL;
11180 	sata_drive_info_t *sdinfo, *osdinfo;
11181 	sata_device_t sdevice;
11182 	boolean_t init_device = B_FALSE;
11183 	int prev_device_type = SATA_DTYPE_NONE;
11184 	int prev_device_settings = 0;
11185 	int prev_device_state = 0;
11186 	clock_t start_time;
11187 	uint8_t cport = sata_device->satadev_addr.cport;
11188 	uint8_t pmport = sata_device->satadev_addr.pmport;
11189 	int rval;
11190 
11191 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11192 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11193 	osdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11194 
11195 	if (osdinfo != NULL) {
11196 		/*
11197 		 * We are re-probing port with a previously attached device.
11198 		 * Save previous device type and settings.
11199 		 */
11200 		prev_device_type = pmportinfo->pmport_dev_type;
11201 		prev_device_settings = osdinfo->satadrv_settings;
11202 		prev_device_state = osdinfo->satadrv_state;
11203 	}
11204 
11205 	start_time = ddi_get_lbolt();
11206 
11207 	/* check parent status */
11208 	mutex_enter(&cportinfo->cport_mutex);
11209 	if ((cportinfo->cport_state &
11210 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11211 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11212 	    SATA_PORT_DEVLINK_UP) {
11213 		mutex_exit(&cportinfo->cport_mutex);
11214 		return (SATA_FAILURE);
11215 	}
11216 	mutex_exit(&cportinfo->cport_mutex);
11217 
11218 retry_probe_pmport:
11219 
11220 	/* probe port */
11221 	mutex_enter(&pmportinfo->pmport_mutex);
11222 	pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11223 	pmportinfo->pmport_state |= SATA_STATE_PROBING;
11224 	mutex_exit(&pmportinfo->pmport_mutex);
11225 
11226 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11227 	    (SATA_DIP(sata_hba_inst), sata_device);
11228 
11229 	/* might need retry because we cannot touch registers. */
11230 	if (rval == SATA_FAILURE) {
11231 		mutex_enter(&pmportinfo->pmport_mutex);
11232 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
11233 		mutex_exit(&pmportinfo->pmport_mutex);
11234 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
11235 		    "SATA port %d:%d probing failed",
11236 		    cport, pmport));
11237 		return (SATA_FAILURE);
11238 	} else if (rval == SATA_RETRY) {
11239 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
11240 		    "SATA port %d:%d probing failed, retrying...",
11241 		    cport, pmport));
11242 		clock_t cur_time = ddi_get_lbolt();
11243 		/*
11244 		 * A device was not successfully identified or initialized.
11245 		 * Track retry time for device identification.
11246 		 */
11247 		if ((cur_time - start_time) <
11248 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11249 			/* sleep for a while */
11250 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11251 			goto retry_probe_pmport;
11252 		} else {
11253 			mutex_enter(&pmportinfo->pmport_mutex);
11254 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11255 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11256 				    satadrv_state = SATA_DSTATE_FAILED;
11257 			mutex_exit(&pmportinfo->pmport_mutex);
11258 			return (SATA_SUCCESS);
11259 		}
11260 	}
11261 
11262 	/*
11263 	 * Sanity check - Controller port is active? Is the link active?
11264 	 * Is it still a port multiplier?
11265 	 */
11266 	if ((cportinfo->cport_state &
11267 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11268 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11269 	    SATA_PORT_DEVLINK_UP ||
11270 	    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
11271 		/*
11272 		 * Port in non-usable state or no link active/no
11273 		 * device. Free info structure.
11274 		 */
11275 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11276 
11277 		sdevice.satadev_addr.cport = cport;
11278 		sdevice.satadev_addr.pmport = pmport;
11279 		sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
11280 		mutex_exit(&cportinfo->cport_mutex);
11281 
11282 		sata_free_pmult(sata_hba_inst, &sdevice);
11283 		return (SATA_FAILURE);
11284 	}
11285 
11286 	/* SATA_SUCCESS NOW */
11287 	/*
11288 	 * update sata port state and set device type
11289 	 */
11290 	mutex_enter(&pmportinfo->pmport_mutex);
11291 	sata_update_pmport_info(sata_hba_inst, sata_device);
11292 	pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
11293 
11294 	/*
11295 	 * Sanity check - Port is active? Is the link active?
11296 	 * Is there any device attached?
11297 	 */
11298 	if ((pmportinfo->pmport_state &
11299 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11300 	    (pmportinfo->pmport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11301 	    SATA_PORT_DEVLINK_UP) {
11302 		/*
11303 		 * Port in non-usable state or no link active/no device.
11304 		 * Free info structure if necessary (direct attached drive
11305 		 * only, for now!
11306 		 */
11307 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11308 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11309 		/* Add here differentiation for device attached or not */
11310 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11311 		mutex_exit(&pmportinfo->pmport_mutex);
11312 		if (sdinfo != NULL)
11313 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11314 		return (SATA_SUCCESS);
11315 	}
11316 
11317 	pmportinfo->pmport_state |= SATA_STATE_READY;
11318 	pmportinfo->pmport_dev_type = sata_device->satadev_type;
11319 	sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11320 
11321 	/*
11322 	 * If we are re-probing the port, there may be
11323 	 * sata_drive_info structure attached
11324 	 * (or sata_pm_info, if PMult is supported).
11325 	 */
11326 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
11327 		/*
11328 		 * There is no device, so remove device info structure,
11329 		 * if necessary.
11330 		 */
11331 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11332 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11333 		if (sdinfo != NULL) {
11334 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11335 			sata_log(sata_hba_inst, CE_WARN,
11336 			    "SATA device detached from port %d:%d",
11337 			    cport, pmport);
11338 		}
11339 		mutex_exit(&pmportinfo->pmport_mutex);
11340 		return (SATA_SUCCESS);
11341 	}
11342 
11343 	/* this should not be a pmult */
11344 	ASSERT(sata_device->satadev_type != SATA_DTYPE_PMULT);
11345 	if (sdinfo == NULL) {
11346 		/*
11347 		 * There is some device attached, but there is
11348 		 * no sata_drive_info structure - allocate one
11349 		 */
11350 		mutex_exit(&pmportinfo->pmport_mutex);
11351 		sdinfo = kmem_zalloc(sizeof (sata_drive_info_t),
11352 		    KM_SLEEP);
11353 		mutex_enter(&pmportinfo->pmport_mutex);
11354 		/*
11355 		 * Recheck, that the port state did not change when we
11356 		 * released mutex.
11357 		 */
11358 		if (pmportinfo->pmport_state & SATA_STATE_READY) {
11359 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = sdinfo;
11360 			sdinfo->satadrv_addr = pmportinfo->pmport_addr;
11361 			sdinfo->satadrv_addr.qual = SATA_ADDR_DPMPORT;
11362 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11363 			sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11364 		} else {
11365 			/*
11366 			 * Port is not in ready state, we
11367 			 * cannot attach a device.
11368 			 */
11369 			mutex_exit(&pmportinfo->pmport_mutex);
11370 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11371 			return (SATA_SUCCESS);
11372 		}
11373 		/*
11374 		 * Since we are adding device, presumably new one,
11375 		 * indicate that it  should be initalized,
11376 		 * as well as some internal framework states).
11377 		 */
11378 		init_device = B_TRUE;
11379 	}
11380 
11381 	pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
11382 	sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
11383 
11384 	mutex_exit(&pmportinfo->pmport_mutex);
11385 	/*
11386 	 * Figure out what kind of device we are really
11387 	 * dealing with.
11388 	 */
11389 	rval = sata_probe_device(sata_hba_inst, sata_device);
11390 
11391 	mutex_enter(&pmportinfo->pmport_mutex);
11392 	if (rval == SATA_SUCCESS) {
11393 		/*
11394 		 * If we are dealing with the same type of a device as before,
11395 		 * restore its settings flags.
11396 		 */
11397 		if (osdinfo != NULL &&
11398 		    sata_device->satadev_type == prev_device_type)
11399 			sdinfo->satadrv_settings = prev_device_settings;
11400 
11401 		mutex_exit(&pmportinfo->pmport_mutex);
11402 		/* Set initial device features, if necessary */
11403 		if (init_device == B_TRUE) {
11404 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
11405 		}
11406 		if (rval == SATA_SUCCESS)
11407 			return (rval);
11408 	} else {
11409 		/*
11410 		 * If there was some device info before we probe the device,
11411 		 * restore previous device setting, so we can retry from scratch
11412 		 * later. Providing, of course, that device has not disappeared
11413 		 * during probing process.
11414 		 */
11415 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
11416 			if (osdinfo != NULL) {
11417 				pmportinfo->pmport_dev_type = prev_device_type;
11418 				sdinfo->satadrv_type = prev_device_type;
11419 				sdinfo->satadrv_state = prev_device_state;
11420 			}
11421 		} else {
11422 			/* device is gone */
11423 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11424 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11425 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11426 			mutex_exit(&pmportinfo->pmport_mutex);
11427 			return (SATA_SUCCESS);
11428 		}
11429 		mutex_exit(&pmportinfo->pmport_mutex);
11430 	}
11431 
11432 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
11433 		clock_t cur_time = ddi_get_lbolt();
11434 		/*
11435 		 * A device was not successfully identified or initialized.
11436 		 * Track retry time for device identification.
11437 		 */
11438 		if ((cur_time - start_time) <
11439 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11440 			/* sleep for a while */
11441 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11442 			goto retry_probe_pmport;
11443 		} else {
11444 			mutex_enter(&pmportinfo->pmport_mutex);
11445 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11446 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11447 				    satadrv_state = SATA_DSTATE_FAILED;
11448 			mutex_exit(&pmportinfo->pmport_mutex);
11449 		}
11450 	}
11451 	return (SATA_SUCCESS);
11452 }
11453 
11454 /*
11455  * Allocated related structure for a port multiplier and its device ports
11456  *
11457  * Port multiplier should be ready and probed, and related information like
11458  * the number of the device ports should be store in sata_device_t.
11459  *
11460  * NOTE: No Mutex should be hold.
11461  */
11462 static int
11463 sata_alloc_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11464 {
11465 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
11466 	sata_cport_info_t *cportinfo = NULL;
11467 	sata_pmult_info_t *pmultinfo = NULL;
11468 	sata_pmport_info_t *pmportinfo = NULL;
11469 	sata_device_t sd;
11470 	dev_t minor_number;
11471 	char name[16];
11472 	uint8_t cport = sata_device->satadev_addr.cport;
11473 	int rval;
11474 	int npmport;
11475 
11476 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11477 
11478 	/* This function might be called while a port-mult is hot-plugged. */
11479 	mutex_enter(&cportinfo->cport_mutex);
11480 
11481 	/* dev_type's not updated when get called from sata_reprobe_port() */
11482 	if (SATA_CPORTINFO_PMULT_INFO(cportinfo) == NULL) {
11483 		/* Create a pmult_info structure */
11484 		SATA_CPORTINFO_PMULT_INFO(cportinfo) =
11485 		    kmem_zalloc(sizeof (sata_pmult_info_t), KM_SLEEP);
11486 	}
11487 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11488 
11489 	pmultinfo->pmult_addr = sata_device->satadev_addr;
11490 	pmultinfo->pmult_addr.qual = SATA_ADDR_PMULT;
11491 	pmultinfo->pmult_state = SATA_STATE_PROBING;
11492 
11493 	/*
11494 	 * Probe the port multiplier with qualifier SATA_ADDR_PMULT_SPEC,
11495 	 * The HBA driver should initialize and register the port multiplier,
11496 	 * sata_register_pmult() will fill following fields,
11497 	 *   + sata_pmult_info.pmult_gscr
11498 	 *   + sata_pmult_info.pmult_num_dev_ports
11499 	 */
11500 	sd.satadev_addr = sata_device->satadev_addr;
11501 	sd.satadev_addr.qual = SATA_ADDR_PMULT_SPEC;
11502 	mutex_exit(&cportinfo->cport_mutex);
11503 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11504 	    (SATA_DIP(sata_hba_inst), &sd);
11505 	mutex_enter(&cportinfo->cport_mutex);
11506 
11507 	if (rval != SATA_SUCCESS ||
11508 	    (sd.satadev_type != SATA_DTYPE_PMULT) ||
11509 	    !(sd.satadev_state & SATA_DSTATE_PMULT_INIT)) {
11510 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
11511 		kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11512 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11513 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11514 		mutex_exit(&cportinfo->cport_mutex);
11515 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11516 		    "sata_alloc_pmult: failed to initialize pmult "
11517 		    "at port %d.", cport)
11518 		return (SATA_FAILURE);
11519 	}
11520 
11521 	/* Initialize pmport_info structure */
11522 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11523 	    npmport++) {
11524 
11525 		/* if everything is allocated, skip */
11526 		if (SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) != NULL)
11527 			continue;
11528 
11529 		pmportinfo = kmem_zalloc(sizeof (sata_pmport_info_t), KM_SLEEP);
11530 		mutex_init(&pmportinfo->pmport_mutex, NULL, MUTEX_DRIVER, NULL);
11531 		mutex_exit(&cportinfo->cport_mutex);
11532 
11533 		mutex_enter(&pmportinfo->pmport_mutex);
11534 		pmportinfo->pmport_addr.cport = cport;
11535 		pmportinfo->pmport_addr.pmport = (uint8_t)npmport;
11536 		pmportinfo->pmport_addr.qual = SATA_ADDR_PMPORT;
11537 		pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11538 		mutex_exit(&pmportinfo->pmport_mutex);
11539 
11540 		mutex_enter(&cportinfo->cport_mutex);
11541 		SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) = pmportinfo;
11542 
11543 		/* Create an attachment point */
11544 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
11545 		    cport, (uint8_t)npmport, SATA_ADDR_PMPORT);
11546 		(void) sprintf(name, "%d.%d", cport, npmport);
11547 
11548 		if (ddi_create_minor_node(dip, name, S_IFCHR, minor_number,
11549 		    DDI_NT_SATA_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
11550 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
11551 			    "cannot create SATA attachment point for "
11552 			    "port %d:%d", cport, npmport);
11553 		}
11554 	}
11555 
11556 	pmultinfo->pmult_state &= ~SATA_STATE_PROBING;
11557 	pmultinfo->pmult_state |= (SATA_STATE_PROBED|SATA_STATE_READY);
11558 	cportinfo->cport_dev_type = SATA_DTYPE_PMULT;
11559 
11560 	mutex_exit(&cportinfo->cport_mutex);
11561 	return (SATA_SUCCESS);
11562 }
11563 
11564 /*
11565  * Free data structures when a port multiplier is removed.
11566  *
11567  * NOTE: No Mutex should be hold.
11568  */
11569 static void
11570 sata_free_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11571 {
11572 	sata_cport_info_t *cportinfo;
11573 	sata_pmult_info_t *pmultinfo;
11574 	sata_pmport_info_t *pmportinfo;
11575 	sata_device_t pmport_device;
11576 	sata_drive_info_t *sdinfo;
11577 	dev_info_t *tdip;
11578 	char name[16];
11579 	uint8_t cport = sata_device->satadev_addr.cport;
11580 	int npmport;
11581 
11582 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11583 
11584 	/* This function might be called while port-mult is hot plugged. */
11585 	mutex_enter(&cportinfo->cport_mutex);
11586 
11587 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11588 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11589 	ASSERT(pmultinfo != NULL);
11590 
11591 	/* Free pmport_info structure */
11592 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11593 	    npmport++) {
11594 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
11595 		if (pmportinfo == NULL)
11596 			continue;
11597 		mutex_exit(&cportinfo->cport_mutex);
11598 
11599 		mutex_enter(&pmportinfo->pmport_mutex);
11600 		sdinfo = pmportinfo->pmport_sata_drive;
11601 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11602 		mutex_exit(&pmportinfo->pmport_mutex);
11603 
11604 		/* Remove attachment point. */
11605 		name[0] = '\0';
11606 		(void) sprintf(name, "%d.%d", cport, npmport);
11607 		ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
11608 		sata_log(sata_hba_inst, CE_NOTE,
11609 		    "Remove attachment point of port %d:%d",
11610 		    cport, npmport);
11611 
11612 		/*
11613 		 * Rumove target node
11614 		 */
11615 		bzero(&pmport_device, sizeof (sata_device_t));
11616 		pmport_device.satadev_rev = SATA_DEVICE_REV;
11617 		pmport_device.satadev_addr.cport = cport;
11618 		pmport_device.satadev_addr.pmport = (uint8_t)npmport;
11619 		pmport_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
11620 
11621 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11622 		    &(pmport_device.satadev_addr));
11623 		if (tdip != NULL && ndi_devi_offline(tdip,
11624 		    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11625 			/*
11626 			 * Problem :
11627 			 * The target node remained attached.
11628 			 * This happens when the device file was open
11629 			 * or a node was waiting for resources.
11630 			 * Cannot do anything about it.
11631 			 */
11632 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11633 			    "sata_free_pmult: could not unconfigure device "
11634 			    "before disconnecting the SATA port %d:%d",
11635 			    cport, npmport));
11636 
11637 			/*
11638 			 * Set DEVICE REMOVED state in the target
11639 			 * node. It will prevent access to the device
11640 			 * even when a new device is attached, until
11641 			 * the old target node is released, removed and
11642 			 * recreated for a new  device.
11643 			 */
11644 			sata_set_device_removed(tdip);
11645 
11646 			/*
11647 			 * Instruct event daemon to try the target
11648 			 * node cleanup later.
11649 			 */
11650 			sata_set_target_node_cleanup(
11651 			    sata_hba_inst, &(pmport_device.satadev_addr));
11652 
11653 		}
11654 		mutex_enter(&cportinfo->cport_mutex);
11655 
11656 		/*
11657 		 * Add here differentiation for device attached or not
11658 		 */
11659 		if (sdinfo != NULL)  {
11660 			sata_log(sata_hba_inst, CE_WARN,
11661 			    "SATA device detached from port %d:%d",
11662 			    cport, npmport);
11663 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11664 		}
11665 
11666 		mutex_destroy(&pmportinfo->pmport_mutex);
11667 		kmem_free(pmportinfo, sizeof (sata_pmport_info_t));
11668 	}
11669 
11670 	kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11671 
11672 	cportinfo->cport_devp.cport_sata_pmult = NULL;
11673 
11674 	sata_log(sata_hba_inst, CE_WARN,
11675 	    "SATA port multiplier detached at port %d", cport);
11676 
11677 	mutex_exit(&cportinfo->cport_mutex);
11678 }
11679 
11680 /*
11681  * Initialize device
11682  * Specified device is initialized to a default state.
11683  *
11684  * Returns SATA_SUCCESS if all device features are set successfully,
11685  * SATA_RETRY if device is accessible but device features were not set
11686  * successfully, and SATA_FAILURE otherwise.
11687  */
11688 static int
11689 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
11690     sata_drive_info_t *sdinfo)
11691 {
11692 	int rval;
11693 
11694 	sata_save_drive_settings(sdinfo);
11695 
11696 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
11697 
11698 	sata_init_write_cache_mode(sdinfo);
11699 
11700 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
11701 
11702 	/* Determine current data transfer mode */
11703 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
11704 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11705 	} else if ((sdinfo->satadrv_id.ai_validinfo &
11706 	    SATA_VALIDINFO_88) != 0 &&
11707 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
11708 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11709 	} else if ((sdinfo->satadrv_id.ai_dworddma &
11710 	    SATA_MDMA_SEL_MASK) != 0) {
11711 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11712 	} else
11713 		/* DMA supported, not no DMA transfer mode is selected !? */
11714 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11715 
11716 	if ((sdinfo->satadrv_id.ai_cmdset83 & 0x20) &&
11717 	    (sdinfo->satadrv_id.ai_features86 & 0x20))
11718 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
11719 	else
11720 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
11721 
11722 	return (rval);
11723 }
11724 
11725 
11726 /*
11727  * Initialize write cache mode.
11728  *
11729  * The default write cache setting for SATA HDD is provided by sata_write_cache
11730  * static variable. ATAPI CD/DVDs devices have write cache default is
11731  * determined by sata_atapicdvd_write_cache static variable.
11732  * ATAPI tape devices have write cache default is determined by
11733  * sata_atapitape_write_cache static variable.
11734  * ATAPI disk devices have write cache default is determined by
11735  * sata_atapidisk_write_cache static variable.
11736  * 1 - enable
11737  * 0 - disable
11738  * any other value - current drive setting
11739  *
11740  * Although there is not reason to disable write cache on CD/DVD devices,
11741  * tape devices and ATAPI disk devices, the default setting control is provided
11742  * for the maximun flexibility.
11743  *
11744  * In the future, it may be overridden by the
11745  * disk-write-cache-enable property setting, if it is defined.
11746  * Returns SATA_SUCCESS if all device features are set successfully,
11747  * SATA_FAILURE otherwise.
11748  */
11749 static void
11750 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
11751 {
11752 	switch (sdinfo->satadrv_type) {
11753 	case SATA_DTYPE_ATADISK:
11754 		if (sata_write_cache == 1)
11755 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11756 		else if (sata_write_cache == 0)
11757 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11758 		/*
11759 		 * When sata_write_cache value is not 0 or 1,
11760 		 * a current setting of the drive's write cache is used.
11761 		 */
11762 		break;
11763 	case SATA_DTYPE_ATAPICD:
11764 		if (sata_atapicdvd_write_cache == 1)
11765 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11766 		else if (sata_atapicdvd_write_cache == 0)
11767 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11768 		/*
11769 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
11770 		 * a current setting of the drive's write cache is used.
11771 		 */
11772 		break;
11773 	case SATA_DTYPE_ATAPITAPE:
11774 		if (sata_atapitape_write_cache == 1)
11775 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11776 		else if (sata_atapitape_write_cache == 0)
11777 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11778 		/*
11779 		 * When sata_atapitape_write_cache value is not 0 or 1,
11780 		 * a current setting of the drive's write cache is used.
11781 		 */
11782 		break;
11783 	case SATA_DTYPE_ATAPIDISK:
11784 		if (sata_atapidisk_write_cache == 1)
11785 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11786 		else if (sata_atapidisk_write_cache == 0)
11787 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11788 		/*
11789 		 * When sata_atapidisk_write_cache value is not 0 or 1,
11790 		 * a current setting of the drive's write cache is used.
11791 		 */
11792 		break;
11793 	}
11794 }
11795 
11796 
11797 /*
11798  * Validate sata address.
11799  * Specified cport, pmport and qualifier has to match
11800  * passed sata_scsi configuration info.
11801  * The presence of an attached device is not verified.
11802  *
11803  * Returns 0 when address is valid, -1 otherwise.
11804  */
11805 static int
11806 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
11807 	int pmport, int qual)
11808 {
11809 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
11810 		goto invalid_address;
11811 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11812 		goto invalid_address;
11813 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
11814 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
11815 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
11816 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
11817 		goto invalid_address;
11818 
11819 	return (0);
11820 
11821 invalid_address:
11822 	return (-1);
11823 
11824 }
11825 
11826 /*
11827  * Validate scsi address
11828  * SCSI target address is translated into SATA cport/pmport and compared
11829  * with a controller port/device configuration. LUN has to be 0.
11830  * Returns 0 if a scsi target refers to an attached device,
11831  * returns 1 if address is valid but no valid device is attached,
11832  * returns 2 if address is valid but device type is unknown (not valid device),
11833  * returns -1 if bad address or device is of an unsupported type.
11834  * Upon return sata_device argument is set.
11835  *
11836  * Port multiplier is supported now.
11837  */
11838 static int
11839 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
11840 	struct scsi_address *ap, sata_device_t *sata_device)
11841 {
11842 	int cport, pmport, qual, rval;
11843 
11844 	rval = -1;	/* Invalid address */
11845 	if (ap->a_lun != 0)
11846 		goto out;
11847 
11848 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
11849 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
11850 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
11851 
11852 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
11853 		goto out;
11854 
11855 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
11856 	    0) {
11857 
11858 		sata_cport_info_t *cportinfo;
11859 		sata_pmult_info_t *pmultinfo;
11860 		sata_drive_info_t *sdinfo = NULL;
11861 
11862 		sata_device->satadev_addr.qual = qual;
11863 		sata_device->satadev_addr.cport = cport;
11864 		sata_device->satadev_addr.pmport = pmport;
11865 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
11866 
11867 		rval = 1;	/* Valid sata address */
11868 
11869 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11870 		if (qual == SATA_ADDR_DCPORT) {
11871 			if (cportinfo == NULL ||
11872 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
11873 				goto out;
11874 
11875 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11876 			if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN &&
11877 			    sdinfo != NULL) {
11878 				rval = 2;
11879 				goto out;
11880 			}
11881 
11882 			if ((cportinfo->cport_dev_type &
11883 			    SATA_VALID_DEV_TYPE) == 0) {
11884 				rval = -1;
11885 				goto out;
11886 			}
11887 
11888 		} else if (qual == SATA_ADDR_DPMPORT) {
11889 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11890 			if (pmultinfo == NULL) {
11891 				rval = -1;
11892 				goto out;
11893 			}
11894 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
11895 			    NULL ||
11896 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11897 			    pmport) == SATA_DTYPE_NONE)
11898 				goto out;
11899 
11900 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
11901 			    pmport);
11902 			if (SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11903 			    pmport) == SATA_DTYPE_UNKNOWN && sdinfo != NULL) {
11904 				rval = 2;
11905 				goto out;
11906 			}
11907 
11908 			if ((SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11909 			    pmport) && SATA_VALID_DEV_TYPE) == 0) {
11910 				rval = -1;
11911 				goto out;
11912 			}
11913 
11914 		} else {
11915 			rval = -1;
11916 			goto out;
11917 		}
11918 		if ((sdinfo == NULL) ||
11919 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
11920 			goto out;
11921 
11922 		sata_device->satadev_type = sdinfo->satadrv_type;
11923 
11924 		return (0);
11925 	}
11926 out:
11927 	if (rval > 0) {
11928 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
11929 		    "sata_validate_scsi_address: no valid target %x lun %x",
11930 		    ap->a_target, ap->a_lun);
11931 	}
11932 	return (rval);
11933 }
11934 
11935 /*
11936  * Find dip corresponding to passed device number
11937  *
11938  * Returns NULL if invalid device number is passed or device cannot be found,
11939  * Returns dip is device is found.
11940  */
11941 static dev_info_t *
11942 sata_devt_to_devinfo(dev_t dev)
11943 {
11944 	dev_info_t *dip;
11945 #ifndef __lock_lint
11946 	struct devnames *dnp;
11947 	major_t major = getmajor(dev);
11948 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
11949 
11950 	if (major >= devcnt)
11951 		return (NULL);
11952 
11953 	dnp = &devnamesp[major];
11954 	LOCK_DEV_OPS(&(dnp->dn_lock));
11955 	dip = dnp->dn_head;
11956 	while (dip && (ddi_get_instance(dip) != instance)) {
11957 		dip = ddi_get_next(dip);
11958 	}
11959 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
11960 #endif
11961 
11962 	return (dip);
11963 }
11964 
11965 
11966 /*
11967  * Probe device.
11968  * This function issues Identify Device command and initializes local
11969  * sata_drive_info structure if the device can be identified.
11970  * The device type is determined by examining Identify Device
11971  * command response.
11972  * If the sata_hba_inst has linked drive info structure for this
11973  * device address, the Identify Device data is stored into sata_drive_info
11974  * structure linked to the port info structure.
11975  *
11976  * sata_device has to refer to the valid sata port(s) for HBA described
11977  * by sata_hba_inst structure.
11978  *
11979  * Returns:
11980  *	SATA_SUCCESS if device type was successfully probed and port-linked
11981  *		drive info structure was updated;
11982  * 	SATA_FAILURE if there is no device, or device was not probed
11983  *		successully;
11984  *	SATA_RETRY if device probe can be retried later.
11985  * If a device cannot be identified, sata_device's dev_state and dev_type
11986  * fields are set to unknown.
11987  * There are no retries in this function. Any retries should be managed by
11988  * the caller.
11989  */
11990 
11991 
11992 static int
11993 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11994 {
11995 	sata_pmport_info_t *pmportinfo;
11996 	sata_drive_info_t *sdinfo;
11997 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
11998 	int rval;
11999 
12000 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
12001 	    sata_device->satadev_addr.cport) &
12002 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
12003 
12004 	sata_device->satadev_type = SATA_DTYPE_NONE;
12005 
12006 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12007 	    sata_device->satadev_addr.cport)));
12008 
12009 	if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT) {
12010 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
12011 		    sata_device->satadev_addr.cport,
12012 		    sata_device->satadev_addr.pmport);
12013 		ASSERT(pmportinfo != NULL);
12014 	}
12015 
12016 	/* Get pointer to port-linked sata device info structure */
12017 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12018 	if (sdinfo != NULL) {
12019 		sdinfo->satadrv_state &=
12020 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
12021 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
12022 	} else {
12023 		/* No device to probe */
12024 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12025 		    sata_device->satadev_addr.cport)));
12026 		sata_device->satadev_type = SATA_DTYPE_NONE;
12027 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
12028 		return (SATA_FAILURE);
12029 	}
12030 	/*
12031 	 * Need to issue both types of identify device command and
12032 	 * determine device type by examining retreived data/status.
12033 	 * First, ATA Identify Device.
12034 	 */
12035 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
12036 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
12037 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12038 	    sata_device->satadev_addr.cport)));
12039 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
12040 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
12041 	if (rval == SATA_RETRY) {
12042 		/* We may try to check for ATAPI device */
12043 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
12044 			/*
12045 			 * HBA supports ATAPI - try to issue Identify Packet
12046 			 * Device command.
12047 			 */
12048 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
12049 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
12050 		}
12051 	}
12052 	if (rval == SATA_SUCCESS) {
12053 		/*
12054 		 * Got something responding positively to ATA Identify Device
12055 		 * or to Identify Packet Device cmd.
12056 		 * Save last used device type.
12057 		 */
12058 		sata_device->satadev_type = new_sdinfo.satadrv_type;
12059 
12060 		/* save device info, if possible */
12061 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12062 		    sata_device->satadev_addr.cport)));
12063 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12064 		if (sdinfo == NULL) {
12065 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12066 			    sata_device->satadev_addr.cport)));
12067 			return (SATA_FAILURE);
12068 		}
12069 		/*
12070 		 * Copy drive info into the port-linked drive info structure.
12071 		 */
12072 		*sdinfo = new_sdinfo;
12073 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
12074 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
12075 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
12076 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
12077 			    sata_device->satadev_addr.cport) =
12078 			    sdinfo->satadrv_type;
12079 		else { /* SATA_ADDR_DPMPORT */
12080 			mutex_enter(&pmportinfo->pmport_mutex);
12081 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
12082 			    sata_device->satadev_addr.cport,
12083 			    sata_device->satadev_addr.pmport) =
12084 			    sdinfo->satadrv_type;
12085 			mutex_exit(&pmportinfo->pmport_mutex);
12086 		}
12087 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12088 		    sata_device->satadev_addr.cport)));
12089 		return (SATA_SUCCESS);
12090 	}
12091 
12092 	/*
12093 	 * It may be SATA_RETRY or SATA_FAILURE return.
12094 	 * Looks like we cannot determine the device type at this time.
12095 	 */
12096 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12097 	    sata_device->satadev_addr.cport)));
12098 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12099 	if (sdinfo != NULL) {
12100 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
12101 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12102 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
12103 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
12104 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
12105 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
12106 			    sata_device->satadev_addr.cport) =
12107 			    SATA_DTYPE_UNKNOWN;
12108 		else {
12109 			/* SATA_ADDR_DPMPORT */
12110 			mutex_enter(&pmportinfo->pmport_mutex);
12111 			if ((SATA_PMULT_INFO(sata_hba_inst,
12112 			    sata_device->satadev_addr.cport) != NULL) &&
12113 			    (SATA_PMPORT_INFO(sata_hba_inst,
12114 			    sata_device->satadev_addr.cport,
12115 			    sata_device->satadev_addr.pmport) != NULL))
12116 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
12117 				    sata_device->satadev_addr.cport,
12118 				    sata_device->satadev_addr.pmport) =
12119 				    SATA_DTYPE_UNKNOWN;
12120 			mutex_exit(&pmportinfo->pmport_mutex);
12121 		}
12122 	}
12123 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12124 	    sata_device->satadev_addr.cport)));
12125 	return (rval);
12126 }
12127 
12128 
12129 /*
12130  * Get pointer to sata_drive_info structure.
12131  *
12132  * The sata_device has to contain address (cport, pmport and qualifier) for
12133  * specified sata_scsi structure.
12134  *
12135  * Returns NULL if device address is not valid for this HBA configuration.
12136  * Otherwise, returns a pointer to sata_drive_info structure.
12137  *
12138  * This function should be called with a port mutex held.
12139  */
12140 static sata_drive_info_t *
12141 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
12142     sata_device_t *sata_device)
12143 {
12144 	uint8_t cport = sata_device->satadev_addr.cport;
12145 	uint8_t pmport = sata_device->satadev_addr.pmport;
12146 	uint8_t qual = sata_device->satadev_addr.qual;
12147 
12148 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
12149 		return (NULL);
12150 
12151 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
12152 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
12153 		/* Port not probed yet */
12154 		return (NULL);
12155 
12156 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
12157 		return (NULL);
12158 
12159 	if (qual == SATA_ADDR_DCPORT) {
12160 		/* Request for a device on a controller port */
12161 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
12162 		    SATA_DTYPE_PMULT)
12163 			/* Port multiplier attached */
12164 			return (NULL);
12165 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
12166 	}
12167 	if (qual == SATA_ADDR_DPMPORT) {
12168 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
12169 		    SATA_DTYPE_PMULT)
12170 			return (NULL);
12171 
12172 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
12173 			return (NULL);
12174 
12175 		if (!(SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) &
12176 		    (SATA_STATE_PROBED | SATA_STATE_READY)))
12177 			/* Port multiplier port not probed yet */
12178 			return (NULL);
12179 
12180 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
12181 	}
12182 
12183 	/* we should not get here */
12184 	return (NULL);
12185 }
12186 
12187 
12188 /*
12189  * sata_identify_device.
12190  * Send Identify Device command to SATA HBA driver.
12191  * If command executes successfully, update sata_drive_info structure pointed
12192  * to by sdinfo argument, including Identify Device data.
12193  * If command fails, invalidate data in sata_drive_info.
12194  *
12195  * Cannot be called from interrupt level.
12196  *
12197  * Returns:
12198  * SATA_SUCCESS if the device was identified as a supported device,
12199  * SATA_RETRY if the device was not identified but could be retried,
12200  * SATA_FAILURE if the device was not identified and identify attempt
12201  *	should not be retried.
12202  */
12203 static int
12204 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
12205     sata_drive_info_t *sdinfo)
12206 {
12207 	uint16_t cfg_word;
12208 	int rval;
12209 
12210 	/* fetch device identify data */
12211 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
12212 	    sdinfo)) != SATA_SUCCESS)
12213 		goto fail_unknown;
12214 
12215 	cfg_word = sdinfo->satadrv_id.ai_config;
12216 
12217 	/* Set the correct device type */
12218 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
12219 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
12220 	} else if (cfg_word == SATA_CFA_TYPE) {
12221 		/* It's a Compact Flash media via CF-to-SATA HDD adapter */
12222 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
12223 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
12224 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
12225 		case SATA_ATAPI_CDROM_DEV:
12226 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
12227 			break;
12228 		case SATA_ATAPI_SQACC_DEV:
12229 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
12230 			break;
12231 		case SATA_ATAPI_DIRACC_DEV:
12232 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
12233 			break;
12234 		default:
12235 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12236 		}
12237 	} else {
12238 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12239 	}
12240 
12241 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12242 		if (sdinfo->satadrv_capacity == 0) {
12243 			/* Non-LBA disk. Too bad... */
12244 			sata_log(sata_hba_inst, CE_WARN,
12245 			    "SATA disk device at port %d does not support LBA",
12246 			    sdinfo->satadrv_addr.cport);
12247 			rval = SATA_FAILURE;
12248 			goto fail_unknown;
12249 		}
12250 	}
12251 #if 0
12252 	/* Left for historical reason */
12253 	/*
12254 	 * Some initial version of SATA spec indicated that at least
12255 	 * UDMA mode 4 has to be supported. It is not metioned in
12256 	 * SerialATA 2.6, so this restriction is removed.
12257 	 */
12258 	/* Check for Ultra DMA modes 6 through 0 being supported */
12259 	for (i = 6; i >= 0; --i) {
12260 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
12261 			break;
12262 	}
12263 
12264 	/*
12265 	 * At least UDMA 4 mode has to be supported. If mode 4 or
12266 	 * higher are not supported by the device, fail this
12267 	 * device.
12268 	 */
12269 	if (i < 4) {
12270 		/* No required Ultra DMA mode supported */
12271 		sata_log(sata_hba_inst, CE_WARN,
12272 		    "SATA disk device at port %d does not support UDMA "
12273 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
12274 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12275 		    "mode 4 or higher required, %d supported", i));
12276 		rval = SATA_FAILURE;
12277 		goto fail_unknown;
12278 	}
12279 #endif
12280 
12281 	/*
12282 	 * For Disk devices, if it doesn't support UDMA mode, we would
12283 	 * like to return failure directly.
12284 	 */
12285 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
12286 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
12287 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
12288 		sata_log(sata_hba_inst, CE_WARN,
12289 		    "SATA disk device at port %d does not support UDMA",
12290 		    sdinfo->satadrv_addr.cport);
12291 		rval = SATA_FAILURE;
12292 		goto fail_unknown;
12293 	}
12294 
12295 	return (SATA_SUCCESS);
12296 
12297 fail_unknown:
12298 	/* Invalidate sata_drive_info ? */
12299 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12300 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
12301 	return (rval);
12302 }
12303 
12304 /*
12305  * Log/display device information
12306  */
12307 static void
12308 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
12309     sata_drive_info_t *sdinfo)
12310 {
12311 	int valid_version;
12312 	char msg_buf[MAXPATHLEN];
12313 	int i;
12314 
12315 	/* Show HBA path */
12316 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
12317 
12318 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
12319 
12320 	switch (sdinfo->satadrv_type) {
12321 	case SATA_DTYPE_ATADISK:
12322 		(void) sprintf(msg_buf, "SATA disk device at");
12323 		break;
12324 
12325 	case SATA_DTYPE_ATAPICD:
12326 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
12327 		break;
12328 
12329 	case SATA_DTYPE_ATAPITAPE:
12330 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
12331 		break;
12332 
12333 	case SATA_DTYPE_ATAPIDISK:
12334 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
12335 		break;
12336 
12337 	case SATA_DTYPE_UNKNOWN:
12338 		(void) sprintf(msg_buf,
12339 		    "Unsupported SATA device type (cfg 0x%x) at ",
12340 		    sdinfo->satadrv_id.ai_config);
12341 		break;
12342 	}
12343 
12344 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
12345 		cmn_err(CE_CONT, "?\t%s port %d\n",
12346 		    msg_buf, sdinfo->satadrv_addr.cport);
12347 	else
12348 		cmn_err(CE_CONT, "?\t%s port %d:%d\n",
12349 		    msg_buf, sdinfo->satadrv_addr.cport,
12350 		    sdinfo->satadrv_addr.pmport);
12351 
12352 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
12353 	    sizeof (sdinfo->satadrv_id.ai_model));
12354 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
12355 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
12356 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
12357 
12358 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
12359 	    sizeof (sdinfo->satadrv_id.ai_fw));
12360 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
12361 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
12362 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
12363 
12364 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
12365 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12366 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
12367 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
12368 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12369 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12370 	} else {
12371 		/*
12372 		 * Some drives do not implement serial number and may
12373 		 * violate the spec by providing spaces rather than zeros
12374 		 * in serial number field. Scan the buffer to detect it.
12375 		 */
12376 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
12377 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
12378 				break;
12379 		}
12380 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
12381 			cmn_err(CE_CONT, "?\tserial number - none\n");
12382 		} else {
12383 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12384 		}
12385 	}
12386 
12387 #ifdef SATA_DEBUG
12388 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
12389 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
12390 		int i;
12391 		for (i = 14; i >= 2; i--) {
12392 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
12393 				valid_version = i;
12394 				break;
12395 			}
12396 		}
12397 		cmn_err(CE_CONT,
12398 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
12399 		    valid_version,
12400 		    sdinfo->satadrv_id.ai_majorversion,
12401 		    sdinfo->satadrv_id.ai_minorversion);
12402 	}
12403 #endif
12404 	/* Log some info */
12405 	cmn_err(CE_CONT, "?\tsupported features:\n");
12406 	msg_buf[0] = '\0';
12407 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12408 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
12409 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
12410 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
12411 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
12412 	}
12413 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
12414 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
12415 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
12416 		(void) strlcat(msg_buf, ", Native Command Queueing",
12417 		    MAXPATHLEN);
12418 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
12419 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
12420 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
12421 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
12422 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
12423 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
12424 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
12425 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
12426 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
12427 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
12428 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
12429 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
12430 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
12431 	if (sdinfo->satadrv_features_support &
12432 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
12433 		msg_buf[0] = '\0';
12434 		(void) snprintf(msg_buf, MAXPATHLEN,
12435 		    "Supported queue depth %d",
12436 		    sdinfo->satadrv_queue_depth);
12437 		if (!(sata_func_enable &
12438 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
12439 			(void) strlcat(msg_buf,
12440 			    " - queueing disabled globally", MAXPATHLEN);
12441 		else if (sdinfo->satadrv_queue_depth >
12442 		    sdinfo->satadrv_max_queue_depth) {
12443 			(void) snprintf(&msg_buf[strlen(msg_buf)],
12444 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
12445 			    (int)sdinfo->satadrv_max_queue_depth);
12446 		}
12447 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
12448 	}
12449 
12450 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12451 #ifdef __i386
12452 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
12453 		    sdinfo->satadrv_capacity);
12454 #else
12455 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
12456 		    sdinfo->satadrv_capacity);
12457 #endif
12458 		cmn_err(CE_CONT, "?%s", msg_buf);
12459 	}
12460 }
12461 
12462 /*
12463  * Log/display port multiplier information
12464  * No Mutex should be hold.
12465  */
12466 static void
12467 sata_show_pmult_info(sata_hba_inst_t *sata_hba_inst,
12468     sata_device_t *sata_device)
12469 {
12470 	_NOTE(ARGUNUSED(sata_hba_inst))
12471 
12472 	int cport = sata_device->satadev_addr.cport;
12473 	sata_pmult_info_t *pmultinfo;
12474 	char msg_buf[MAXPATHLEN];
12475 	uint32_t gscr0, gscr1, gscr2, gscr64;
12476 
12477 	mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12478 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
12479 	if (pmultinfo == NULL) {
12480 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12481 		return;
12482 	}
12483 
12484 	gscr0 = pmultinfo->pmult_gscr.gscr0;
12485 	gscr1 = pmultinfo->pmult_gscr.gscr1;
12486 	gscr2 = pmultinfo->pmult_gscr.gscr2;
12487 	gscr64 = pmultinfo->pmult_gscr.gscr64;
12488 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12489 
12490 	cmn_err(CE_CONT, "?Port Multiplier %d device-ports found at port %d",
12491 	    sata_device->satadev_add_info, sata_device->satadev_addr.cport);
12492 
12493 	(void) sprintf(msg_buf, "\tVendor_ID 0x%04x, Module_ID 0x%04x",
12494 	    gscr0 & 0xffff, (gscr0 >> 16) & 0xffff);
12495 	cmn_err(CE_CONT, "?%s", msg_buf);
12496 
12497 	(void) strcpy(msg_buf, "\tSupport SATA PMP Spec ");
12498 	if (gscr1 & (1 << 3))
12499 		(void) strlcat(msg_buf, "1.2", MAXPATHLEN);
12500 	else if (gscr1 & (1 << 2))
12501 		(void) strlcat(msg_buf, "1.1", MAXPATHLEN);
12502 	else if (gscr1 & (1 << 1))
12503 		(void) strlcat(msg_buf, "1.0", MAXPATHLEN);
12504 	else
12505 		(void) strlcat(msg_buf, "unknown", MAXPATHLEN);
12506 	cmn_err(CE_CONT, "?%s", msg_buf);
12507 
12508 	(void) strcpy(msg_buf, "\tSupport ");
12509 	if (gscr64 & (1 << 3))
12510 		(void) strlcat(msg_buf, "Asy-Notif, ",
12511 		    MAXPATHLEN);
12512 	if (gscr64 & (1 << 2))
12513 		(void) strlcat(msg_buf, "Dyn-SSC, ", MAXPATHLEN);
12514 	if (gscr64 & (1 << 1))
12515 		(void) strlcat(msg_buf, "Iss-PMREQ, ", MAXPATHLEN);
12516 	if (gscr64 & (1 << 0))
12517 		(void) strlcat(msg_buf, "BIST", MAXPATHLEN);
12518 	if ((gscr64 & 0xf) == 0)
12519 		(void) strlcat(msg_buf, "nothing", MAXPATHLEN);
12520 	cmn_err(CE_CONT, "?%s", msg_buf);
12521 
12522 	(void) sprintf(msg_buf, "\tNumber of exposed device fan-out ports: %d",
12523 	    gscr2 & SATA_PMULT_PORTNUM_MASK);
12524 	cmn_err(CE_CONT, "?%s", msg_buf);
12525 }
12526 
12527 /*
12528  * sata_save_drive_settings extracts current setting of the device and stores
12529  * it for future reference, in case the device setup would need to be restored
12530  * after the device reset.
12531  *
12532  * For all devices read ahead and write cache settings are saved, if the
12533  * device supports these features at all.
12534  * For ATAPI devices the Removable Media Status Notification setting is saved.
12535  */
12536 static void
12537 sata_save_drive_settings(sata_drive_info_t *sdinfo)
12538 {
12539 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
12540 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
12541 
12542 		/* Current setting of Read Ahead (and Read Cache) */
12543 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
12544 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
12545 		else
12546 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
12547 
12548 		/* Current setting of Write Cache */
12549 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
12550 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12551 		else
12552 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12553 	}
12554 
12555 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
12556 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
12557 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
12558 		else
12559 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
12560 	}
12561 }
12562 
12563 
12564 /*
12565  * sata_check_capacity function determines a disk capacity
12566  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
12567  *
12568  * NOTE: CHS mode is not supported! If a device does not support LBA,
12569  * this function is not called.
12570  *
12571  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
12572  */
12573 static uint64_t
12574 sata_check_capacity(sata_drive_info_t *sdinfo)
12575 {
12576 	uint64_t capacity = 0;
12577 	int i;
12578 
12579 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
12580 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
12581 		/* Capacity valid only for LBA-addressable disk devices */
12582 		return (0);
12583 
12584 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
12585 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
12586 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
12587 		/* LBA48 mode supported and enabled */
12588 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
12589 		    SATA_DEV_F_LBA28;
12590 		for (i = 3;  i >= 0;  --i) {
12591 			capacity <<= 16;
12592 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
12593 		}
12594 	} else {
12595 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
12596 		capacity <<= 16;
12597 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
12598 		if (capacity >= 0x1000000)
12599 			/* LBA28 mode */
12600 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
12601 	}
12602 	return (capacity);
12603 }
12604 
12605 
12606 /*
12607  * Allocate consistent buffer for DMA transfer
12608  *
12609  * Cannot be called from interrupt level or with mutex held - it may sleep.
12610  *
12611  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
12612  */
12613 static struct buf *
12614 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
12615 {
12616 	struct scsi_address ap;
12617 	struct buf *bp;
12618 	ddi_dma_attr_t	cur_dma_attr;
12619 
12620 	ASSERT(spx->txlt_sata_pkt != NULL);
12621 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
12622 	ap.a_target = SATA_TO_SCSI_TARGET(
12623 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
12624 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
12625 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
12626 	ap.a_lun = 0;
12627 
12628 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
12629 	    B_READ, SLEEP_FUNC, NULL);
12630 
12631 	if (bp != NULL) {
12632 		/* Allocate DMA resources for this buffer */
12633 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
12634 		/*
12635 		 * We use a local version of the dma_attr, to account
12636 		 * for a device addressing limitations.
12637 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
12638 		 * will cause dma attributes to be adjusted to a lowest
12639 		 * acceptable level.
12640 		 */
12641 		sata_adjust_dma_attr(NULL,
12642 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
12643 
12644 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
12645 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
12646 			scsi_free_consistent_buf(bp);
12647 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12648 			bp = NULL;
12649 		}
12650 	}
12651 	return (bp);
12652 }
12653 
12654 /*
12655  * Release local buffer (consistent buffer for DMA transfer) allocated
12656  * via sata_alloc_local_buffer().
12657  */
12658 static void
12659 sata_free_local_buffer(sata_pkt_txlate_t *spx)
12660 {
12661 	ASSERT(spx->txlt_sata_pkt != NULL);
12662 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
12663 
12664 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
12665 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
12666 
12667 	sata_common_free_dma_rsrcs(spx);
12668 
12669 	/* Free buffer */
12670 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
12671 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12672 }
12673 
12674 /*
12675  * Allocate sata_pkt
12676  * Pkt structure version and embedded strcutures version are initialized.
12677  * sata_pkt and sata_pkt_txlate structures are cross-linked.
12678  *
12679  * Since this may be called in interrupt context by sata_scsi_init_pkt,
12680  * callback argument determines if it can sleep or not.
12681  * Hence, it should not be called from interrupt context.
12682  *
12683  * If successful, non-NULL pointer to a sata pkt is returned.
12684  * Upon failure, NULL pointer is returned.
12685  */
12686 static sata_pkt_t *
12687 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
12688 {
12689 	sata_pkt_t *spkt;
12690 	int kmsflag;
12691 
12692 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
12693 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
12694 	if (spkt == NULL) {
12695 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12696 		    "sata_pkt_alloc: failed"));
12697 		return (NULL);
12698 	}
12699 	spkt->satapkt_rev = SATA_PKT_REV;
12700 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
12701 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
12702 	spkt->satapkt_framework_private = spx;
12703 	spx->txlt_sata_pkt = spkt;
12704 	return (spkt);
12705 }
12706 
12707 /*
12708  * Free sata pkt allocated via sata_pkt_alloc()
12709  */
12710 static void
12711 sata_pkt_free(sata_pkt_txlate_t *spx)
12712 {
12713 	ASSERT(spx->txlt_sata_pkt != NULL);
12714 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
12715 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
12716 	spx->txlt_sata_pkt = NULL;
12717 }
12718 
12719 
12720 /*
12721  * Adjust DMA attributes.
12722  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
12723  * from 8 bits to 16 bits, depending on a command being used.
12724  * Limiting max block count arbitrarily to 256 for all read/write
12725  * commands may affects performance, so check both the device and
12726  * controller capability before adjusting dma attributes.
12727  */
12728 void
12729 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
12730     ddi_dma_attr_t *adj_dma_attr)
12731 {
12732 	uint32_t count_max;
12733 
12734 	/* Copy original attributes */
12735 	*adj_dma_attr = *dma_attr;
12736 	/*
12737 	 * Things to consider: device addressing capability,
12738 	 * "excessive" controller DMA capabilities.
12739 	 * If a device is being probed/initialized, there are
12740 	 * no device info - use default limits then.
12741 	 */
12742 	if (sdinfo == NULL) {
12743 		count_max = dma_attr->dma_attr_granular * 0x100;
12744 		if (dma_attr->dma_attr_count_max > count_max)
12745 			adj_dma_attr->dma_attr_count_max = count_max;
12746 		if (dma_attr->dma_attr_maxxfer > count_max)
12747 			adj_dma_attr->dma_attr_maxxfer = count_max;
12748 		return;
12749 	}
12750 
12751 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12752 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
12753 			/*
12754 			 * 16-bit sector count may be used - we rely on
12755 			 * the assumption that only read and write cmds
12756 			 * will request more than 256 sectors worth of data
12757 			 */
12758 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
12759 		} else {
12760 			/*
12761 			 * 8-bit sector count will be used - default limits
12762 			 * for dma attributes
12763 			 */
12764 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
12765 		}
12766 		/*
12767 		 * Adjust controler dma attributes, if necessary
12768 		 */
12769 		if (dma_attr->dma_attr_count_max > count_max)
12770 			adj_dma_attr->dma_attr_count_max = count_max;
12771 		if (dma_attr->dma_attr_maxxfer > count_max)
12772 			adj_dma_attr->dma_attr_maxxfer = count_max;
12773 	}
12774 }
12775 
12776 
12777 /*
12778  * Allocate DMA resources for the buffer
12779  * This function handles initial DMA resource allocation as well as
12780  * DMA window shift and may be called repeatedly for the same DMA window
12781  * until all DMA cookies in the DMA window are processed.
12782  * To guarantee that there is always a coherent set of cookies to process
12783  * by SATA HBA driver (observing alignment, device granularity, etc.),
12784  * the number of slots for DMA cookies is equal to lesser of  a number of
12785  * cookies in a DMA window and a max number of scatter/gather entries.
12786  *
12787  * Returns DDI_SUCCESS upon successful operation.
12788  * Return failure code of a failing command or DDI_FAILURE when
12789  * internal cleanup failed.
12790  */
12791 static int
12792 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
12793     int (*callback)(caddr_t), caddr_t arg,
12794     ddi_dma_attr_t *cur_dma_attr)
12795 {
12796 	int	rval;
12797 	off_t	offset;
12798 	size_t	size;
12799 	int	max_sg_len, req_len, i;
12800 	uint_t	dma_flags;
12801 	struct buf	*bp;
12802 	uint64_t	cur_txfer_len;
12803 
12804 
12805 	ASSERT(spx->txlt_sata_pkt != NULL);
12806 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
12807 	ASSERT(bp != NULL);
12808 
12809 
12810 	if (spx->txlt_buf_dma_handle == NULL) {
12811 		/*
12812 		 * No DMA resources allocated so far - this is a first call
12813 		 * for this sata pkt.
12814 		 */
12815 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
12816 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
12817 
12818 		if (rval != DDI_SUCCESS) {
12819 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12820 			    "sata_dma_buf_setup: no buf DMA resources %x",
12821 			    rval));
12822 			return (rval);
12823 		}
12824 
12825 		if (bp->b_flags & B_READ)
12826 			dma_flags = DDI_DMA_READ;
12827 		else
12828 			dma_flags = DDI_DMA_WRITE;
12829 
12830 		if (flags & PKT_CONSISTENT)
12831 			dma_flags |= DDI_DMA_CONSISTENT;
12832 
12833 		if (flags & PKT_DMA_PARTIAL)
12834 			dma_flags |= DDI_DMA_PARTIAL;
12835 
12836 		/*
12837 		 * Check buffer alignment and size against dma attributes
12838 		 * Consider dma_attr_align only. There may be requests
12839 		 * with the size lower than device granularity, but they
12840 		 * will not read/write from/to the device, so no adjustment
12841 		 * is necessary. The dma_attr_minxfer theoretically should
12842 		 * be considered, but no HBA driver is checking it.
12843 		 */
12844 		if (IS_P2ALIGNED(bp->b_un.b_addr,
12845 		    cur_dma_attr->dma_attr_align)) {
12846 			rval = ddi_dma_buf_bind_handle(
12847 			    spx->txlt_buf_dma_handle,
12848 			    bp, dma_flags, callback, arg,
12849 			    &spx->txlt_dma_cookie,
12850 			    &spx->txlt_curwin_num_dma_cookies);
12851 		} else { /* Buffer is not aligned */
12852 
12853 			int	(*ddicallback)(caddr_t);
12854 			size_t	bufsz;
12855 
12856 			/* Check id sleeping is allowed */
12857 			ddicallback = (callback == NULL_FUNC) ?
12858 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
12859 
12860 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12861 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
12862 			    (void *)bp->b_un.b_addr, bp->b_bcount);
12863 
12864 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
12865 				/*
12866 				 * CPU will need to access data in the buffer
12867 				 * (for copying) so map it.
12868 				 */
12869 				bp_mapin(bp);
12870 
12871 			ASSERT(spx->txlt_tmp_buf == NULL);
12872 
12873 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
12874 			rval = ddi_dma_mem_alloc(
12875 			    spx->txlt_buf_dma_handle,
12876 			    bp->b_bcount,
12877 			    &sata_acc_attr,
12878 			    DDI_DMA_STREAMING,
12879 			    ddicallback, NULL,
12880 			    &spx->txlt_tmp_buf,
12881 			    &bufsz,
12882 			    &spx->txlt_tmp_buf_handle);
12883 
12884 			if (rval != DDI_SUCCESS) {
12885 				/* DMA mapping failed */
12886 				(void) ddi_dma_free_handle(
12887 				    &spx->txlt_buf_dma_handle);
12888 				spx->txlt_buf_dma_handle = NULL;
12889 #ifdef SATA_DEBUG
12890 				mbuffail_count++;
12891 #endif
12892 				SATADBG1(SATA_DBG_DMA_SETUP,
12893 				    spx->txlt_sata_hba_inst,
12894 				    "sata_dma_buf_setup: "
12895 				    "buf dma mem alloc failed %x\n", rval);
12896 				return (rval);
12897 			}
12898 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
12899 			    cur_dma_attr->dma_attr_align));
12900 
12901 #ifdef SATA_DEBUG
12902 			mbuf_count++;
12903 
12904 			if (bp->b_bcount != bufsz)
12905 				/*
12906 				 * This will require special handling, because
12907 				 * DMA cookies will be based on the temporary
12908 				 * buffer size, not the original buffer
12909 				 * b_bcount, so the residue may have to
12910 				 * be counted differently.
12911 				 */
12912 				SATADBG2(SATA_DBG_DMA_SETUP,
12913 				    spx->txlt_sata_hba_inst,
12914 				    "sata_dma_buf_setup: bp size %x != "
12915 				    "bufsz %x\n", bp->b_bcount, bufsz);
12916 #endif
12917 			if (dma_flags & DDI_DMA_WRITE) {
12918 				/*
12919 				 * Write operation - copy data into
12920 				 * an aligned temporary buffer. Buffer will be
12921 				 * synced for device by ddi_dma_addr_bind_handle
12922 				 */
12923 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
12924 				    bp->b_bcount);
12925 			}
12926 
12927 			rval = ddi_dma_addr_bind_handle(
12928 			    spx->txlt_buf_dma_handle,
12929 			    NULL,
12930 			    spx->txlt_tmp_buf,
12931 			    bufsz, dma_flags, ddicallback, 0,
12932 			    &spx->txlt_dma_cookie,
12933 			    &spx->txlt_curwin_num_dma_cookies);
12934 		}
12935 
12936 		switch (rval) {
12937 		case DDI_DMA_PARTIAL_MAP:
12938 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12939 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
12940 			/*
12941 			 * Partial DMA mapping.
12942 			 * Retrieve number of DMA windows for this request.
12943 			 */
12944 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
12945 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
12946 				if (spx->txlt_tmp_buf != NULL) {
12947 					ddi_dma_mem_free(
12948 					    &spx->txlt_tmp_buf_handle);
12949 					spx->txlt_tmp_buf = NULL;
12950 				}
12951 				(void) ddi_dma_unbind_handle(
12952 				    spx->txlt_buf_dma_handle);
12953 				(void) ddi_dma_free_handle(
12954 				    &spx->txlt_buf_dma_handle);
12955 				spx->txlt_buf_dma_handle = NULL;
12956 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12957 				    "sata_dma_buf_setup: numwin failed\n"));
12958 				return (DDI_FAILURE);
12959 			}
12960 			SATADBG2(SATA_DBG_DMA_SETUP,
12961 			    spx->txlt_sata_hba_inst,
12962 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
12963 			    spx->txlt_num_dma_win,
12964 			    spx->txlt_curwin_num_dma_cookies);
12965 			spx->txlt_cur_dma_win = 0;
12966 			break;
12967 
12968 		case DDI_DMA_MAPPED:
12969 			/* DMA fully mapped */
12970 			spx->txlt_num_dma_win = 1;
12971 			spx->txlt_cur_dma_win = 0;
12972 			SATADBG1(SATA_DBG_DMA_SETUP,
12973 			    spx->txlt_sata_hba_inst,
12974 			    "sata_dma_buf_setup: windows: 1 "
12975 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
12976 			break;
12977 
12978 		default:
12979 			/* DMA mapping failed */
12980 			if (spx->txlt_tmp_buf != NULL) {
12981 				ddi_dma_mem_free(
12982 				    &spx->txlt_tmp_buf_handle);
12983 				spx->txlt_tmp_buf = NULL;
12984 			}
12985 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12986 			spx->txlt_buf_dma_handle = NULL;
12987 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12988 			    "sata_dma_buf_setup: buf dma handle binding "
12989 			    "failed %x\n", rval));
12990 			return (rval);
12991 		}
12992 		spx->txlt_curwin_processed_dma_cookies = 0;
12993 		spx->txlt_dma_cookie_list = NULL;
12994 	} else {
12995 		/*
12996 		 * DMA setup is reused. Check if we need to process more
12997 		 * cookies in current window, or to get next window, if any.
12998 		 */
12999 
13000 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
13001 		    spx->txlt_curwin_num_dma_cookies);
13002 
13003 		if (spx->txlt_curwin_processed_dma_cookies ==
13004 		    spx->txlt_curwin_num_dma_cookies) {
13005 			/*
13006 			 * All cookies from current DMA window were processed.
13007 			 * Get next DMA window.
13008 			 */
13009 			spx->txlt_cur_dma_win++;
13010 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
13011 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
13012 				    spx->txlt_cur_dma_win, &offset, &size,
13013 				    &spx->txlt_dma_cookie,
13014 				    &spx->txlt_curwin_num_dma_cookies);
13015 				spx->txlt_curwin_processed_dma_cookies = 0;
13016 			} else {
13017 				/* No more windows! End of request! */
13018 				/* What to do? - panic for now */
13019 				ASSERT(spx->txlt_cur_dma_win >=
13020 				    spx->txlt_num_dma_win);
13021 
13022 				spx->txlt_curwin_num_dma_cookies = 0;
13023 				spx->txlt_curwin_processed_dma_cookies = 0;
13024 				spx->txlt_sata_pkt->
13025 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
13026 				return (DDI_SUCCESS);
13027 			}
13028 		}
13029 	}
13030 	/* There better be at least one DMA cookie outstanding */
13031 	ASSERT((spx->txlt_curwin_num_dma_cookies -
13032 	    spx->txlt_curwin_processed_dma_cookies) > 0);
13033 
13034 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
13035 		/* The default cookie slot was used in previous run */
13036 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
13037 		spx->txlt_dma_cookie_list = NULL;
13038 		spx->txlt_dma_cookie_list_len = 0;
13039 	}
13040 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
13041 		/*
13042 		 * Processing a new DMA window - set-up dma cookies list.
13043 		 * We may reuse previously allocated cookie array if it is
13044 		 * possible.
13045 		 */
13046 		if (spx->txlt_dma_cookie_list != NULL &&
13047 		    spx->txlt_dma_cookie_list_len <
13048 		    spx->txlt_curwin_num_dma_cookies) {
13049 			/*
13050 			 * New DMA window contains more cookies than
13051 			 * the previous one. We need larger cookie list - free
13052 			 * the old one.
13053 			 */
13054 			(void) kmem_free(spx->txlt_dma_cookie_list,
13055 			    spx->txlt_dma_cookie_list_len *
13056 			    sizeof (ddi_dma_cookie_t));
13057 			spx->txlt_dma_cookie_list = NULL;
13058 			spx->txlt_dma_cookie_list_len = 0;
13059 		}
13060 		if (spx->txlt_dma_cookie_list == NULL) {
13061 			/*
13062 			 * Calculate lesser of number of cookies in this
13063 			 * DMA window and number of s/g entries.
13064 			 */
13065 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
13066 			req_len = MIN(max_sg_len,
13067 			    spx->txlt_curwin_num_dma_cookies);
13068 
13069 			/* Allocate new dma cookie array if necessary */
13070 			if (req_len == 1) {
13071 				/* Only one cookie - no need for a list */
13072 				spx->txlt_dma_cookie_list =
13073 				    &spx->txlt_dma_cookie;
13074 				spx->txlt_dma_cookie_list_len = 1;
13075 			} else {
13076 				/*
13077 				 * More than one cookie - try to allocate space.
13078 				 */
13079 				spx->txlt_dma_cookie_list = kmem_zalloc(
13080 				    sizeof (ddi_dma_cookie_t) * req_len,
13081 				    callback == NULL_FUNC ? KM_NOSLEEP :
13082 				    KM_SLEEP);
13083 				if (spx->txlt_dma_cookie_list == NULL) {
13084 					SATADBG1(SATA_DBG_DMA_SETUP,
13085 					    spx->txlt_sata_hba_inst,
13086 					    "sata_dma_buf_setup: cookie list "
13087 					    "allocation failed\n", NULL);
13088 					/*
13089 					 * We could not allocate space for
13090 					 * neccessary number of dma cookies in
13091 					 * this window, so we fail this request.
13092 					 * Next invocation would try again to
13093 					 * allocate space for cookie list.
13094 					 * Note:Packet residue was not modified.
13095 					 */
13096 					return (DDI_DMA_NORESOURCES);
13097 				} else {
13098 					spx->txlt_dma_cookie_list_len = req_len;
13099 				}
13100 			}
13101 		}
13102 		/*
13103 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
13104 		 * First cookie was already fetched.
13105 		 */
13106 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
13107 		cur_txfer_len =
13108 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
13109 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
13110 		spx->txlt_curwin_processed_dma_cookies++;
13111 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
13112 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
13113 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
13114 			    &spx->txlt_dma_cookie_list[i]);
13115 			cur_txfer_len +=
13116 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
13117 			spx->txlt_curwin_processed_dma_cookies++;
13118 			spx->txlt_sata_pkt->
13119 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
13120 		}
13121 	} else {
13122 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
13123 		    "sata_dma_buf_setup: sliding within DMA window, "
13124 		    "cur cookie %d, total cookies %d\n",
13125 		    spx->txlt_curwin_processed_dma_cookies,
13126 		    spx->txlt_curwin_num_dma_cookies);
13127 
13128 		/*
13129 		 * Not all cookies from the current dma window were used because
13130 		 * of s/g limitation.
13131 		 * There is no need to re-size the list - it was set at
13132 		 * optimal size, or only default entry is used (s/g = 1).
13133 		 */
13134 		if (spx->txlt_dma_cookie_list == NULL) {
13135 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
13136 			spx->txlt_dma_cookie_list_len = 1;
13137 		}
13138 		/*
13139 		 * Since we are processing remaining cookies in a DMA window,
13140 		 * there may be less of them than the number of entries in the
13141 		 * current dma cookie list.
13142 		 */
13143 		req_len = MIN(spx->txlt_dma_cookie_list_len,
13144 		    (spx->txlt_curwin_num_dma_cookies -
13145 		    spx->txlt_curwin_processed_dma_cookies));
13146 
13147 		/* Fetch the next batch of cookies */
13148 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
13149 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
13150 			    &spx->txlt_dma_cookie_list[i]);
13151 			cur_txfer_len +=
13152 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
13153 			spx->txlt_sata_pkt->
13154 			    satapkt_cmd.satacmd_num_dma_cookies++;
13155 			spx->txlt_curwin_processed_dma_cookies++;
13156 		}
13157 	}
13158 
13159 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
13160 
13161 	/* Point sata_cmd to the cookie list */
13162 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
13163 	    &spx->txlt_dma_cookie_list[0];
13164 
13165 	/* Remember number of DMA cookies passed in sata packet */
13166 	spx->txlt_num_dma_cookies =
13167 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
13168 
13169 	ASSERT(cur_txfer_len != 0);
13170 	if (cur_txfer_len <= bp->b_bcount)
13171 		spx->txlt_total_residue -= cur_txfer_len;
13172 	else {
13173 		/*
13174 		 * Temporary DMA buffer has been padded by
13175 		 * ddi_dma_mem_alloc()!
13176 		 * This requires special handling, because DMA cookies are
13177 		 * based on the temporary buffer size, not the b_bcount,
13178 		 * and we have extra bytes to transfer - but the packet
13179 		 * residue has to stay correct because we will copy only
13180 		 * the requested number of bytes.
13181 		 */
13182 		spx->txlt_total_residue -= bp->b_bcount;
13183 	}
13184 
13185 	return (DDI_SUCCESS);
13186 }
13187 
13188 /*
13189  * Common routine for releasing DMA resources
13190  */
13191 static void
13192 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
13193 {
13194 	if (spx->txlt_buf_dma_handle != NULL) {
13195 		if (spx->txlt_tmp_buf != NULL)  {
13196 			/*
13197 			 * Intermediate DMA buffer was allocated.
13198 			 * Free allocated buffer and associated access handle.
13199 			 */
13200 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
13201 			spx->txlt_tmp_buf = NULL;
13202 		}
13203 		/*
13204 		 * Free DMA resources - cookies and handles
13205 		 */
13206 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
13207 		if (spx->txlt_dma_cookie_list != NULL) {
13208 			if (spx->txlt_dma_cookie_list !=
13209 			    &spx->txlt_dma_cookie) {
13210 				(void) kmem_free(spx->txlt_dma_cookie_list,
13211 				    spx->txlt_dma_cookie_list_len *
13212 				    sizeof (ddi_dma_cookie_t));
13213 				spx->txlt_dma_cookie_list = NULL;
13214 			}
13215 		}
13216 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
13217 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
13218 		spx->txlt_buf_dma_handle = NULL;
13219 	}
13220 }
13221 
13222 /*
13223  * Free DMA resources
13224  * Used by the HBA driver to release DMA resources that it does not use.
13225  *
13226  * Returns Void
13227  */
13228 void
13229 sata_free_dma_resources(sata_pkt_t *sata_pkt)
13230 {
13231 	sata_pkt_txlate_t *spx;
13232 
13233 	if (sata_pkt == NULL)
13234 		return;
13235 
13236 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
13237 
13238 	sata_common_free_dma_rsrcs(spx);
13239 }
13240 
13241 /*
13242  * Fetch Device Identify data.
13243  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
13244  * command to a device and get the device identify data.
13245  * The device_info structure has to be set to device type (for selecting proper
13246  * device identify command).
13247  *
13248  * Returns:
13249  * SATA_SUCCESS if cmd succeeded
13250  * SATA_RETRY if cmd was rejected and could be retried,
13251  * SATA_FAILURE if cmd failed and should not be retried (port error)
13252  *
13253  * Cannot be called in an interrupt context.
13254  */
13255 
13256 static int
13257 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
13258     sata_drive_info_t *sdinfo)
13259 {
13260 	struct buf *bp;
13261 	sata_pkt_t *spkt;
13262 	sata_cmd_t *scmd;
13263 	sata_pkt_txlate_t *spx;
13264 	int rval;
13265 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
13266 
13267 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13268 	spx->txlt_sata_hba_inst = sata_hba_inst;
13269 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13270 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13271 	if (spkt == NULL) {
13272 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13273 		return (SATA_RETRY); /* may retry later */
13274 	}
13275 	/* address is needed now */
13276 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13277 
13278 	/*
13279 	 * Allocate buffer for Identify Data return data
13280 	 */
13281 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
13282 	if (bp == NULL) {
13283 		sata_pkt_free(spx);
13284 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13285 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13286 		    "sata_fetch_device_identify_data: "
13287 		    "cannot allocate buffer for ID"));
13288 		return (SATA_RETRY); /* may retry later */
13289 	}
13290 
13291 	/* Fill sata_pkt */
13292 	sdinfo->satadrv_state = SATA_STATE_PROBING;
13293 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13294 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13295 	/* Synchronous mode, no callback */
13296 	spkt->satapkt_comp = NULL;
13297 	/* Timeout 30s */
13298 	spkt->satapkt_time = sata_default_pkt_time;
13299 
13300 	scmd = &spkt->satapkt_cmd;
13301 	scmd->satacmd_bp = bp;
13302 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13303 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13304 
13305 	/* Build Identify Device cmd in the sata_pkt */
13306 	scmd->satacmd_addr_type = 0;		/* N/A */
13307 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
13308 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
13309 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
13310 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
13311 	scmd->satacmd_features_reg = 0;		/* N/A */
13312 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13313 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
13314 		/* Identify Packet Device cmd */
13315 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
13316 	} else {
13317 		/* Identify Device cmd - mandatory for all other devices */
13318 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
13319 	}
13320 
13321 	/* Send pkt to SATA HBA driver */
13322 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
13323 
13324 #ifdef SATA_INJECT_FAULTS
13325 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13326 #endif
13327 
13328 	if (rval == SATA_TRAN_ACCEPTED &&
13329 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
13330 		if (spx->txlt_buf_dma_handle != NULL) {
13331 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13332 			    DDI_DMA_SYNC_FORKERNEL);
13333 			ASSERT(rval == DDI_SUCCESS);
13334 			if (sata_check_for_dma_error(dip, spx)) {
13335 				ddi_fm_service_impact(dip,
13336 				    DDI_SERVICE_UNAFFECTED);
13337 				rval = SATA_RETRY;
13338 				goto fail;
13339 			}
13340 
13341 		}
13342 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
13343 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
13344 			SATA_LOG_D((sata_hba_inst, CE_WARN,
13345 			    "SATA disk device at port %d - "
13346 			    "partial Identify Data",
13347 			    sdinfo->satadrv_addr.cport));
13348 			rval = SATA_RETRY; /* may retry later */
13349 			goto fail;
13350 		}
13351 		/* Update sata_drive_info */
13352 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
13353 		    sizeof (sata_id_t));
13354 
13355 		sdinfo->satadrv_features_support = 0;
13356 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
13357 			/*
13358 			 * Retrieve capacity (disks only) and addressing mode
13359 			 */
13360 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
13361 		} else {
13362 			/*
13363 			 * For ATAPI devices one would have to issue
13364 			 * Get Capacity cmd for media capacity. Not here.
13365 			 */
13366 			sdinfo->satadrv_capacity = 0;
13367 			/*
13368 			 * Check what cdb length is supported
13369 			 */
13370 			if ((sdinfo->satadrv_id.ai_config &
13371 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
13372 				sdinfo->satadrv_atapi_cdb_len = 16;
13373 			else
13374 				sdinfo->satadrv_atapi_cdb_len = 12;
13375 		}
13376 		/* Setup supported features flags */
13377 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
13378 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
13379 
13380 		/* Check for SATA GEN and NCQ support */
13381 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
13382 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
13383 			/* SATA compliance */
13384 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
13385 				sdinfo->satadrv_features_support |=
13386 				    SATA_DEV_F_NCQ;
13387 			if (sdinfo->satadrv_id.ai_satacap &
13388 			    (SATA_1_SPEED | SATA_2_SPEED)) {
13389 				if (sdinfo->satadrv_id.ai_satacap &
13390 				    SATA_2_SPEED)
13391 					sdinfo->satadrv_features_support |=
13392 					    SATA_DEV_F_SATA2;
13393 				if (sdinfo->satadrv_id.ai_satacap &
13394 				    SATA_1_SPEED)
13395 					sdinfo->satadrv_features_support |=
13396 					    SATA_DEV_F_SATA1;
13397 			} else {
13398 				sdinfo->satadrv_features_support |=
13399 				    SATA_DEV_F_SATA1;
13400 			}
13401 		}
13402 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
13403 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
13404 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
13405 
13406 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
13407 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
13408 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
13409 			++sdinfo->satadrv_queue_depth;
13410 			/* Adjust according to controller capabilities */
13411 			sdinfo->satadrv_max_queue_depth = MIN(
13412 			    sdinfo->satadrv_queue_depth,
13413 			    SATA_QDEPTH(sata_hba_inst));
13414 			/* Adjust according to global queue depth limit */
13415 			sdinfo->satadrv_max_queue_depth = MIN(
13416 			    sdinfo->satadrv_max_queue_depth,
13417 			    sata_current_max_qdepth);
13418 			if (sdinfo->satadrv_max_queue_depth == 0)
13419 				sdinfo->satadrv_max_queue_depth = 1;
13420 		} else
13421 			sdinfo->satadrv_max_queue_depth = 1;
13422 
13423 		rval = SATA_SUCCESS;
13424 	} else {
13425 		/*
13426 		 * Woops, no Identify Data.
13427 		 */
13428 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
13429 			rval = SATA_RETRY; /* may retry later */
13430 		} else if (rval == SATA_TRAN_ACCEPTED) {
13431 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
13432 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
13433 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
13434 			    spkt->satapkt_reason == SATA_PKT_RESET)
13435 				rval = SATA_RETRY; /* may retry later */
13436 			else
13437 				rval = SATA_FAILURE;
13438 		} else {
13439 			rval = SATA_FAILURE;
13440 		}
13441 	}
13442 fail:
13443 	/* Free allocated resources */
13444 	sata_free_local_buffer(spx);
13445 	sata_pkt_free(spx);
13446 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13447 
13448 	return (rval);
13449 }
13450 
13451 
13452 /*
13453  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
13454  * UDMA mode is checked first, followed by MWDMA mode.
13455  * set correctly, so this function is setting it to the highest supported level.
13456  * Older SATA spec required that the device supports at least DMA 4 mode and
13457  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
13458  * restriction has been removed.
13459  *
13460  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
13461  * Returns SATA_FAILURE if proper DMA mode could not be selected.
13462  *
13463  * NOTE: This function should be called only if DMA mode is supported.
13464  */
13465 static int
13466 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
13467 {
13468 	sata_pkt_t *spkt;
13469 	sata_cmd_t *scmd;
13470 	sata_pkt_txlate_t *spx;
13471 	int i, mode;
13472 	uint8_t subcmd;
13473 	int rval = SATA_SUCCESS;
13474 
13475 	ASSERT(sdinfo != NULL);
13476 	ASSERT(sata_hba_inst != NULL);
13477 
13478 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
13479 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
13480 		/* Find highest Ultra DMA mode supported */
13481 		for (mode = 6; mode >= 0; --mode) {
13482 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
13483 				break;
13484 		}
13485 #if 0
13486 		/* Left for historical reasons */
13487 		/*
13488 		 * Some initial version of SATA spec indicated that at least
13489 		 * UDMA mode 4 has to be supported. It is not mentioned in
13490 		 * SerialATA 2.6, so this restriction is removed.
13491 		 */
13492 		if (mode < 4)
13493 			return (SATA_FAILURE);
13494 #endif
13495 
13496 		/*
13497 		 * For disk, we're still going to set DMA mode whatever is
13498 		 * selected by default
13499 		 *
13500 		 * We saw an old maxtor sata drive will select Ultra DMA and
13501 		 * Multi-Word DMA simultaneouly by default, which is going
13502 		 * to cause DMA command timed out, so we need to select DMA
13503 		 * mode even when it's already done by default
13504 		 */
13505 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13506 
13507 			/* Find UDMA mode currently selected */
13508 			for (i = 6; i >= 0; --i) {
13509 				if (sdinfo->satadrv_id.ai_ultradma &
13510 				    (1 << (i + 8)))
13511 					break;
13512 			}
13513 			if (i >= mode)
13514 				/* Nothing to do */
13515 				return (SATA_SUCCESS);
13516 		}
13517 
13518 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
13519 
13520 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
13521 		/* Find highest MultiWord DMA mode supported */
13522 		for (mode = 2; mode >= 0; --mode) {
13523 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
13524 				break;
13525 		}
13526 
13527 		/*
13528 		 * For disk, We're still going to set DMA mode whatever is
13529 		 * selected by default
13530 		 *
13531 		 * We saw an old maxtor sata drive will select Ultra DMA and
13532 		 * Multi-Word DMA simultaneouly by default, which is going
13533 		 * to cause DMA command timed out, so we need to select DMA
13534 		 * mode even when it's already done by default
13535 		 */
13536 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13537 
13538 			/* Find highest MultiWord DMA mode selected */
13539 			for (i = 2; i >= 0; --i) {
13540 				if (sdinfo->satadrv_id.ai_dworddma &
13541 				    (1 << (i + 8)))
13542 					break;
13543 			}
13544 			if (i >= mode)
13545 				/* Nothing to do */
13546 				return (SATA_SUCCESS);
13547 		}
13548 
13549 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
13550 	} else
13551 		return (SATA_SUCCESS);
13552 
13553 	/*
13554 	 * Set DMA mode via SET FEATURES COMMAND.
13555 	 * Prepare packet for SET FEATURES COMMAND.
13556 	 */
13557 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13558 	spx->txlt_sata_hba_inst = sata_hba_inst;
13559 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13560 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13561 	if (spkt == NULL) {
13562 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13563 		    "sata_set_dma_mode: could not set DMA mode %d", mode));
13564 		rval = SATA_FAILURE;
13565 		goto done;
13566 	}
13567 	/* Fill sata_pkt */
13568 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13569 	/* Timeout 30s */
13570 	spkt->satapkt_time = sata_default_pkt_time;
13571 	/* Synchronous mode, no callback, interrupts */
13572 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13573 	spkt->satapkt_comp = NULL;
13574 	scmd = &spkt->satapkt_cmd;
13575 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13576 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13577 	scmd->satacmd_addr_type = 0;
13578 	scmd->satacmd_device_reg = 0;
13579 	scmd->satacmd_status_reg = 0;
13580 	scmd->satacmd_error_reg = 0;
13581 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13582 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
13583 	scmd->satacmd_sec_count_lsb = subcmd | mode;
13584 
13585 	/* Transfer command to HBA */
13586 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
13587 	    spkt) != SATA_TRAN_ACCEPTED ||
13588 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13589 		/* Pkt execution failed */
13590 		rval = SATA_FAILURE;
13591 	}
13592 done:
13593 
13594 	/* Free allocated resources */
13595 	if (spkt != NULL)
13596 		sata_pkt_free(spx);
13597 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13598 
13599 	return (rval);
13600 }
13601 
13602 
13603 /*
13604  * Set device caching mode.
13605  * One of the following operations should be specified:
13606  * SATAC_SF_ENABLE_READ_AHEAD
13607  * SATAC_SF_DISABLE_READ_AHEAD
13608  * SATAC_SF_ENABLE_WRITE_CACHE
13609  * SATAC_SF_DISABLE_WRITE_CACHE
13610  *
13611  * If operation fails, system log messgage is emitted.
13612  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
13613  * command was sent but did not succeed, and SATA_FAILURE otherwise.
13614  */
13615 
13616 static int
13617 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13618     int cache_op)
13619 {
13620 	sata_pkt_t *spkt;
13621 	sata_cmd_t *scmd;
13622 	sata_pkt_txlate_t *spx;
13623 	int rval = SATA_SUCCESS;
13624 	int hba_rval;
13625 	char *infop;
13626 
13627 	ASSERT(sdinfo != NULL);
13628 	ASSERT(sata_hba_inst != NULL);
13629 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
13630 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
13631 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
13632 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
13633 
13634 
13635 	/* Prepare packet for SET FEATURES COMMAND */
13636 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13637 	spx->txlt_sata_hba_inst = sata_hba_inst;
13638 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13639 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13640 	if (spkt == NULL) {
13641 		rval = SATA_FAILURE;
13642 		goto failure;
13643 	}
13644 	/* Fill sata_pkt */
13645 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13646 	/* Timeout 30s */
13647 	spkt->satapkt_time = sata_default_pkt_time;
13648 	/* Synchronous mode, no callback, interrupts */
13649 	spkt->satapkt_op_mode =
13650 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13651 	spkt->satapkt_comp = NULL;
13652 	scmd = &spkt->satapkt_cmd;
13653 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13654 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13655 	scmd->satacmd_addr_type = 0;
13656 	scmd->satacmd_device_reg = 0;
13657 	scmd->satacmd_status_reg = 0;
13658 	scmd->satacmd_error_reg = 0;
13659 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13660 	scmd->satacmd_features_reg = cache_op;
13661 
13662 	/* Transfer command to HBA */
13663 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
13664 	    SATA_DIP(sata_hba_inst), spkt);
13665 
13666 #ifdef SATA_INJECT_FAULTS
13667 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13668 #endif
13669 
13670 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
13671 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13672 		/* Pkt execution failed */
13673 		switch (cache_op) {
13674 		case SATAC_SF_ENABLE_READ_AHEAD:
13675 			infop = "enabling read ahead failed";
13676 			break;
13677 		case SATAC_SF_DISABLE_READ_AHEAD:
13678 			infop = "disabling read ahead failed";
13679 			break;
13680 		case SATAC_SF_ENABLE_WRITE_CACHE:
13681 			infop = "enabling write cache failed";
13682 			break;
13683 		case SATAC_SF_DISABLE_WRITE_CACHE:
13684 			infop = "disabling write cache failed";
13685 			break;
13686 		}
13687 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13688 		rval = SATA_RETRY;
13689 	}
13690 failure:
13691 	/* Free allocated resources */
13692 	if (spkt != NULL)
13693 		sata_pkt_free(spx);
13694 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13695 	return (rval);
13696 }
13697 
13698 /*
13699  * Set Removable Media Status Notification (enable/disable)
13700  * state == 0 , disable
13701  * state != 0 , enable
13702  *
13703  * If operation fails, system log messgage is emitted.
13704  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
13705  */
13706 
13707 static int
13708 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13709     int state)
13710 {
13711 	sata_pkt_t *spkt;
13712 	sata_cmd_t *scmd;
13713 	sata_pkt_txlate_t *spx;
13714 	int rval = SATA_SUCCESS;
13715 	char *infop;
13716 
13717 	ASSERT(sdinfo != NULL);
13718 	ASSERT(sata_hba_inst != NULL);
13719 
13720 	/* Prepare packet for SET FEATURES COMMAND */
13721 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13722 	spx->txlt_sata_hba_inst = sata_hba_inst;
13723 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13724 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13725 	if (spkt == NULL) {
13726 		rval = SATA_FAILURE;
13727 		goto failure;
13728 	}
13729 	/* Fill sata_pkt */
13730 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13731 	/* Timeout 30s */
13732 	spkt->satapkt_time = sata_default_pkt_time;
13733 	/* Synchronous mode, no callback, interrupts */
13734 	spkt->satapkt_op_mode =
13735 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13736 	spkt->satapkt_comp = NULL;
13737 	scmd = &spkt->satapkt_cmd;
13738 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13739 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13740 	scmd->satacmd_addr_type = 0;
13741 	scmd->satacmd_device_reg = 0;
13742 	scmd->satacmd_status_reg = 0;
13743 	scmd->satacmd_error_reg = 0;
13744 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13745 	if (state == 0)
13746 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
13747 	else
13748 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
13749 
13750 	/* Transfer command to HBA */
13751 	if (((*SATA_START_FUNC(sata_hba_inst))(
13752 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
13753 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13754 		/* Pkt execution failed */
13755 		if (state == 0)
13756 			infop = "disabling Removable Media Status "
13757 			    "Notification failed";
13758 		else
13759 			infop = "enabling Removable Media Status "
13760 			    "Notification failed";
13761 
13762 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13763 		rval = SATA_FAILURE;
13764 	}
13765 failure:
13766 	/* Free allocated resources */
13767 	if (spkt != NULL)
13768 		sata_pkt_free(spx);
13769 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13770 	return (rval);
13771 }
13772 
13773 
13774 /*
13775  * Update state and copy port ss* values from passed sata_device structure.
13776  * sata_address is validated - if not valid, nothing is changed in sata_scsi
13777  * configuration struct.
13778  *
13779  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
13780  * regardless of the state in device argument.
13781  *
13782  * Port mutex should be held while calling this function.
13783  */
13784 static void
13785 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
13786     sata_device_t *sata_device)
13787 {
13788 	sata_cport_info_t *cportinfo;
13789 
13790 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
13791 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
13792 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
13793 		    sata_device->satadev_addr.cport)
13794 			return;
13795 
13796 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
13797 		    sata_device->satadev_addr.cport);
13798 
13799 		ASSERT(mutex_owned(&cportinfo->cport_mutex));
13800 		cportinfo->cport_scr = sata_device->satadev_scr;
13801 
13802 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
13803 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
13804 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13805 		cportinfo->cport_state |=
13806 		    sata_device->satadev_state & SATA_PSTATE_VALID;
13807 	}
13808 }
13809 
13810 void
13811 sata_update_pmport_info(sata_hba_inst_t *sata_hba_inst,
13812     sata_device_t *sata_device)
13813 {
13814 	sata_pmport_info_t *pmportinfo;
13815 
13816 	if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT &&
13817 	    sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
13818 	    SATA_NUM_PMPORTS(sata_hba_inst,
13819 	    sata_device->satadev_addr.cport) <
13820 	    sata_device->satadev_addr.pmport) {
13821 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
13822 		    "sata_update_port_info: error address %p.",
13823 		    &sata_device->satadev_addr);
13824 		return;
13825 	}
13826 
13827 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
13828 	    sata_device->satadev_addr.cport,
13829 	    sata_device->satadev_addr.pmport);
13830 
13831 	ASSERT(mutex_owned(&pmportinfo->pmport_mutex));
13832 	pmportinfo->pmport_scr = sata_device->satadev_scr;
13833 
13834 	/* Preserve SATA_PSTATE_SHUTDOWN flag */
13835 	pmportinfo->pmport_state &=
13836 	    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13837 	pmportinfo->pmport_state |=
13838 	    sata_device->satadev_state & SATA_PSTATE_VALID;
13839 }
13840 
13841 /*
13842  * Extract SATA port specification from an IOCTL argument.
13843  *
13844  * This function return the port the user land send us as is, unless it
13845  * cannot retrieve port spec, then -1 is returned.
13846  *
13847  * Support port multiplier.
13848  */
13849 static int32_t
13850 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
13851 {
13852 	int32_t port;
13853 
13854 	/* Extract port number from nvpair in dca structure  */
13855 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
13856 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
13857 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
13858 		    port));
13859 		port = -1;
13860 	}
13861 
13862 	return (port);
13863 }
13864 
13865 /*
13866  * Get dev_info_t pointer to the device node pointed to by port argument.
13867  * NOTE: target argument is a value used in ioctls to identify
13868  * the AP - it is not a sata_address.
13869  * It is a combination of cport, pmport and address qualifier, encodded same
13870  * way as a scsi target number.
13871  * At this moment it carries only cport number.
13872  *
13873  * PMult hotplug is supported now.
13874  *
13875  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13876  */
13877 
13878 static dev_info_t *
13879 sata_get_target_dip(dev_info_t *dip, uint8_t cport, uint8_t pmport)
13880 {
13881 	dev_info_t	*cdip = NULL;
13882 	int		target, tgt;
13883 	int 		circ;
13884 	uint8_t		qual;
13885 
13886 	sata_hba_inst_t	*sata_hba_inst;
13887 	scsi_hba_tran_t *scsi_hba_tran;
13888 
13889 	/* Get target id */
13890 	scsi_hba_tran = ddi_get_driver_private(dip);
13891 	if (scsi_hba_tran == NULL)
13892 		return (NULL);
13893 
13894 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
13895 
13896 	if (sata_hba_inst == NULL)
13897 		return (NULL);
13898 
13899 	/* Identify a port-mult by cport_info.cport_dev_type */
13900 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT)
13901 		qual = SATA_ADDR_DPMPORT;
13902 	else
13903 		qual = SATA_ADDR_DCPORT;
13904 
13905 	target = SATA_TO_SCSI_TARGET(cport, pmport, qual);
13906 
13907 	/* Retrieve target dip */
13908 	ndi_devi_enter(dip, &circ);
13909 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13910 		dev_info_t *next = ddi_get_next_sibling(cdip);
13911 
13912 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13913 		    DDI_PROP_DONTPASS, "target", -1);
13914 		if (tgt == -1) {
13915 			/*
13916 			 * This is actually an error condition, but not
13917 			 * a fatal one. Just continue the search.
13918 			 */
13919 			cdip = next;
13920 			continue;
13921 		}
13922 
13923 		if (tgt == target)
13924 			break;
13925 
13926 		cdip = next;
13927 	}
13928 	ndi_devi_exit(dip, circ);
13929 
13930 	return (cdip);
13931 }
13932 
13933 /*
13934  * Get dev_info_t pointer to the device node pointed to by port argument.
13935  * NOTE: target argument is a value used in ioctls to identify
13936  * the AP - it is not a sata_address.
13937  * It is a combination of cport, pmport and address qualifier, encoded same
13938  * way as a scsi target number.
13939  *
13940  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13941  */
13942 
13943 static dev_info_t *
13944 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
13945 {
13946 	dev_info_t	*cdip = NULL;
13947 	int		target, tgt;
13948 	int 		circ;
13949 
13950 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
13951 
13952 	ndi_devi_enter(dip, &circ);
13953 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13954 		dev_info_t *next = ddi_get_next_sibling(cdip);
13955 
13956 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13957 		    DDI_PROP_DONTPASS, "target", -1);
13958 		if (tgt == -1) {
13959 			/*
13960 			 * This is actually an error condition, but not
13961 			 * a fatal one. Just continue the search.
13962 			 */
13963 			cdip = next;
13964 			continue;
13965 		}
13966 
13967 		if (tgt == target)
13968 			break;
13969 
13970 		cdip = next;
13971 	}
13972 	ndi_devi_exit(dip, circ);
13973 
13974 	return (cdip);
13975 }
13976 
13977 /*
13978  * Process sata port disconnect request.
13979  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
13980  * before this request. Nevertheless, if a device is still configured,
13981  * we need to attempt to offline and unconfigure device.
13982  * Regardless of the unconfigure operation results the port is marked as
13983  * deactivated and no access to the attached device is possible.
13984  * If the target node remains because unconfigure operation failed, its state
13985  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
13986  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
13987  * the device and remove old target node.
13988  *
13989  * This function invokes sata_hba_inst->satahba_tran->
13990  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13991  * If successful, the device structure (if any) attached to the specified port
13992  * is removed and state of the port marked appropriately.
13993  * Failure of the port_deactivate may keep port in the physically active state,
13994  * or may fail the port.
13995  *
13996  * NOTE: Port multiplier is supported.
13997  */
13998 
13999 static int
14000 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
14001     sata_device_t *sata_device)
14002 {
14003 	sata_drive_info_t *sdinfo = NULL, *subsdinfo = NULL;
14004 	sata_cport_info_t *cportinfo = NULL;
14005 	sata_pmport_info_t *pmportinfo = NULL;
14006 	sata_pmult_info_t *pmultinfo = NULL;
14007 	sata_device_t subsdevice;
14008 	int cport, pmport, qual;
14009 	int rval = SATA_SUCCESS;
14010 	int npmport = 0;
14011 	int rv = 0;
14012 
14013 	cport = sata_device->satadev_addr.cport;
14014 	pmport = sata_device->satadev_addr.pmport;
14015 	qual = sata_device->satadev_addr.qual;
14016 
14017 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14018 	if (qual == SATA_ADDR_DCPORT)
14019 		qual = SATA_ADDR_CPORT;
14020 	else
14021 		qual = SATA_ADDR_PMPORT;
14022 
14023 	/*
14024 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
14025 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
14026 	 * Do the sanity check.
14027 	 */
14028 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
14029 		/* No physical port deactivation supported. */
14030 		return (EINVAL);
14031 	}
14032 
14033 	/* Check the current state of the port */
14034 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14035 	    (SATA_DIP(sata_hba_inst), sata_device);
14036 
14037 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14038 
14039 	/*
14040 	 * Processing port mulitiplier
14041 	 */
14042 	if (qual == SATA_ADDR_CPORT &&
14043 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
14044 		mutex_enter(&cportinfo->cport_mutex);
14045 
14046 		/* Check controller port status */
14047 		sata_update_port_info(sata_hba_inst, sata_device);
14048 		if (rval != SATA_SUCCESS ||
14049 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14050 			/*
14051 			 * Device port status is unknown or it is in failed
14052 			 * state
14053 			 */
14054 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14055 			    SATA_PSTATE_FAILED;
14056 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14057 			    "sata_hba_ioctl: connect: failed to deactivate "
14058 			    "SATA port %d", cport);
14059 			mutex_exit(&cportinfo->cport_mutex);
14060 			return (EIO);
14061 		}
14062 
14063 		/* Disconnect all sub-devices. */
14064 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14065 		if (pmultinfo != NULL) {
14066 
14067 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
14068 			    sata_hba_inst, cport); npmport ++) {
14069 				subsdinfo = SATA_PMPORT_DRV_INFO(
14070 				    sata_hba_inst, cport, npmport);
14071 				if (subsdinfo == NULL)
14072 					continue;
14073 
14074 				subsdevice.satadev_addr = subsdinfo->
14075 				    satadrv_addr;
14076 
14077 				mutex_exit(&cportinfo->cport_mutex);
14078 				if (sata_ioctl_disconnect(sata_hba_inst,
14079 				    &subsdevice) == SATA_SUCCESS) {
14080 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14081 					"[Remove] device at port %d:%d "
14082 					"successfully.", cport, npmport);
14083 				}
14084 				mutex_enter(&cportinfo->cport_mutex);
14085 			}
14086 		}
14087 
14088 		/* Disconnect the port multiplier */
14089 		cportinfo->cport_state &= ~SATA_STATE_READY;
14090 		mutex_exit(&cportinfo->cport_mutex);
14091 
14092 		sata_device->satadev_addr.qual = qual;
14093 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14094 		    (SATA_DIP(sata_hba_inst), sata_device);
14095 
14096 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14097 		    SE_NO_HINT);
14098 
14099 		mutex_enter(&cportinfo->cport_mutex);
14100 		sata_update_port_info(sata_hba_inst, sata_device);
14101 		if (rval != SATA_SUCCESS &&
14102 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14103 			cportinfo->cport_state = SATA_PSTATE_FAILED;
14104 			rv = EIO;
14105 		} else {
14106 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14107 		}
14108 		mutex_exit(&cportinfo->cport_mutex);
14109 
14110 		return (rv);
14111 	}
14112 
14113 	/*
14114 	 * Process non-port-multiplier device - it could be a drive connected
14115 	 * to a port multiplier port or a controller port.
14116 	 */
14117 	if (qual == SATA_ADDR_PMPORT) {
14118 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14119 		mutex_enter(&pmportinfo->pmport_mutex);
14120 		sata_update_pmport_info(sata_hba_inst, sata_device);
14121 		if (rval != SATA_SUCCESS ||
14122 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14123 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
14124 			    SATA_PSTATE_FAILED;
14125 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
14126 			    "sata_hba_ioctl: connect: failed to deactivate "
14127 			    "SATA port %d:%d", cport, pmport);
14128 			mutex_exit(&pmportinfo->pmport_mutex);
14129 			return (EIO);
14130 		}
14131 
14132 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
14133 			sdinfo = pmportinfo->pmport_sata_drive;
14134 			ASSERT(sdinfo != NULL);
14135 		}
14136 
14137 		/*
14138 		 * Set port's dev_state to not ready - this will disable
14139 		 * an access to a potentially attached device.
14140 		 */
14141 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
14142 
14143 		/* Remove and release sata_drive info structure. */
14144 		if (sdinfo != NULL) {
14145 			if ((sdinfo->satadrv_type &
14146 			    SATA_VALID_DEV_TYPE) != 0) {
14147 				/*
14148 				 * If a target node exists, try to offline
14149 				 * a device and remove target node.
14150 				 */
14151 				mutex_exit(&pmportinfo->pmport_mutex);
14152 				(void) sata_offline_device(sata_hba_inst,
14153 				    sata_device, sdinfo);
14154 				mutex_enter(&pmportinfo->pmport_mutex);
14155 			}
14156 
14157 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
14158 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
14159 			(void) kmem_free((void *)sdinfo,
14160 			    sizeof (sata_drive_info_t));
14161 		}
14162 		mutex_exit(&pmportinfo->pmport_mutex);
14163 
14164 	} else if (qual == SATA_ADDR_CPORT) {
14165 		mutex_enter(&cportinfo->cport_mutex);
14166 		sata_update_port_info(sata_hba_inst, sata_device);
14167 		if (rval != SATA_SUCCESS ||
14168 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14169 			/*
14170 			 * Device port status is unknown or it is in failed
14171 			 * state
14172 			 */
14173 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14174 			    SATA_PSTATE_FAILED;
14175 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14176 			    "sata_hba_ioctl: connect: failed to deactivate "
14177 			    "SATA port %d", cport);
14178 			mutex_exit(&cportinfo->cport_mutex);
14179 			return (EIO);
14180 		}
14181 
14182 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
14183 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14184 			ASSERT(pmultinfo != NULL);
14185 		} else if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14186 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14187 			ASSERT(sdinfo != NULL);
14188 		}
14189 		cportinfo->cport_state &= ~SATA_STATE_READY;
14190 
14191 		if (sdinfo != NULL) {
14192 			if ((sdinfo->satadrv_type &
14193 			    SATA_VALID_DEV_TYPE) != 0) {
14194 				/*
14195 				 * If a target node exists, try to offline
14196 				 * a device and remove target node.
14197 				 */
14198 				mutex_exit(&cportinfo->cport_mutex);
14199 				(void) sata_offline_device(sata_hba_inst,
14200 				    sata_device, sdinfo);
14201 				mutex_enter(&cportinfo->cport_mutex);
14202 			}
14203 
14204 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14205 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14206 			(void) kmem_free((void *)sdinfo,
14207 			    sizeof (sata_drive_info_t));
14208 		}
14209 		mutex_exit(&cportinfo->cport_mutex);
14210 	}
14211 
14212 	/* Just ask HBA driver to deactivate port */
14213 	sata_device->satadev_addr.qual = qual;
14214 
14215 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14216 	    (SATA_DIP(sata_hba_inst), sata_device);
14217 
14218 	/*
14219 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14220 	 * without the hint (to force listener to investivate the state).
14221 	 */
14222 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14223 	    SE_NO_HINT);
14224 
14225 	if (qual == SATA_ADDR_PMPORT) {
14226 		mutex_enter(&pmportinfo->pmport_mutex);
14227 		sata_update_pmport_info(sata_hba_inst, sata_device);
14228 
14229 		if (rval != SATA_SUCCESS &&
14230 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14231 			/*
14232 			 * Port deactivation failure - do not change port
14233 			 * state unless the state returned by HBA indicates a
14234 			 * port failure.
14235 			 *
14236 			 * NOTE: device structures were released, so devices
14237 			 * now are invisible! Port reset is needed to
14238 			 * re-enumerate devices.
14239 			 */
14240 			pmportinfo->pmport_state = SATA_PSTATE_FAILED;
14241 			rv = EIO;
14242 		} else {
14243 			/*
14244 			 * Deactivation succeded. From now on the sata framework
14245 			 * will not care what is happening to the device, until
14246 			 * the port is activated again.
14247 			 */
14248 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14249 		}
14250 		mutex_exit(&pmportinfo->pmport_mutex);
14251 	} else if (qual == SATA_ADDR_CPORT) {
14252 		mutex_enter(&cportinfo->cport_mutex);
14253 		sata_update_port_info(sata_hba_inst, sata_device);
14254 
14255 		if (rval != SATA_SUCCESS &&
14256 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14257 			cportinfo->cport_state = SATA_PSTATE_FAILED;
14258 			rv = EIO;
14259 		} else {
14260 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14261 		}
14262 		mutex_exit(&cportinfo->cport_mutex);
14263 	}
14264 
14265 	return (rv);
14266 }
14267 
14268 
14269 
14270 /*
14271  * Process sata port connect request
14272  * The sata cfgadm pluging will invoke this operation only if port was found
14273  * in the disconnect state (failed state is also treated as the disconnected
14274  * state).
14275  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
14276  * sata_tran_hotplug_ops->sata_tran_port_activate().
14277  * If successful and a device is found attached to the port,
14278  * the initialization sequence is executed to attach a device structure to
14279  * a port structure. The state of the port and a device would be set
14280  * appropriately.
14281  * The device is not set in configured state (system-wise) by this operation.
14282  *
14283  * Note, that activating the port may generate link events,
14284  * so it is important that following processing and the
14285  * event processing does not interfere with each other!
14286  *
14287  * This operation may remove port failed state and will
14288  * try to make port active and in good standing.
14289  *
14290  * NOTE: Port multiplier is supported.
14291  */
14292 
14293 static int
14294 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
14295     sata_device_t *sata_device)
14296 {
14297 	sata_pmport_info_t	*pmportinfo = NULL;
14298 	uint8_t cport, pmport, qual;
14299 	int rv = 0;
14300 
14301 	cport = sata_device->satadev_addr.cport;
14302 	pmport = sata_device->satadev_addr.pmport;
14303 	qual = sata_device->satadev_addr.qual;
14304 
14305 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14306 	if (qual == SATA_ADDR_DCPORT)
14307 		qual = SATA_ADDR_CPORT;
14308 	else
14309 		qual = SATA_ADDR_PMPORT;
14310 
14311 	if (qual == SATA_ADDR_PMPORT)
14312 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14313 
14314 	/*
14315 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
14316 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
14317 	 * Perform sanity check now.
14318 	 */
14319 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
14320 		/* No physical port activation supported. */
14321 		return (EINVAL);
14322 	}
14323 
14324 	/* Just ask HBA driver to activate port */
14325 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14326 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14327 		/*
14328 		 * Port activation failure.
14329 		 */
14330 		if (qual == SATA_ADDR_CPORT) {
14331 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14332 			    cport)->cport_mutex);
14333 			sata_update_port_info(sata_hba_inst, sata_device);
14334 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14335 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14336 				    SATA_PSTATE_FAILED;
14337 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14338 				    "sata_hba_ioctl: connect: failed to "
14339 				    "activate SATA port %d", cport);
14340 			}
14341 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14342 			    cport)->cport_mutex);
14343 		} else { /* port multiplier device port */
14344 			mutex_enter(&pmportinfo->pmport_mutex);
14345 			sata_update_pmport_info(sata_hba_inst, sata_device);
14346 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14347 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14348 				    pmport) = SATA_PSTATE_FAILED;
14349 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
14350 				    "sata_hba_ioctl: connect: failed to "
14351 				    "activate SATA port %d:%d", cport, pmport);
14352 			}
14353 			mutex_exit(&pmportinfo->pmport_mutex);
14354 		}
14355 		return (EIO);
14356 	}
14357 
14358 	/* Virgin port state - will be updated by the port re-probe. */
14359 	if (qual == SATA_ADDR_CPORT) {
14360 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14361 		    cport)->cport_mutex);
14362 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
14363 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14364 		    cport)->cport_mutex);
14365 	} else { /* port multiplier device port */
14366 		mutex_enter(&pmportinfo->pmport_mutex);
14367 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
14368 		mutex_exit(&pmportinfo->pmport_mutex);
14369 	}
14370 
14371 	/*
14372 	 * Probe the port to find its state and attached device.
14373 	 */
14374 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14375 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
14376 		rv = EIO;
14377 
14378 	/*
14379 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14380 	 * without the hint
14381 	 */
14382 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14383 	    SE_NO_HINT);
14384 
14385 	/*
14386 	 * If there is a device attached to the port, emit
14387 	 * a message.
14388 	 */
14389 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
14390 
14391 		if (qual == SATA_ADDR_CPORT) {
14392 			if (sata_device->satadev_type == SATA_DTYPE_PMULT) {
14393 				sata_log(sata_hba_inst, CE_WARN,
14394 				    "SATA port multiplier detected "
14395 				    "at port %d", cport);
14396 			} else {
14397 				sata_log(sata_hba_inst, CE_WARN,
14398 				    "SATA device detected at port %d", cport);
14399 				if (sata_device->satadev_type ==
14400 				    SATA_DTYPE_UNKNOWN) {
14401 				/*
14402 				 * A device was not successfully identified
14403 				 */
14404 				sata_log(sata_hba_inst, CE_WARN,
14405 				    "Could not identify SATA "
14406 				    "device at port %d", cport);
14407 				}
14408 			}
14409 		} else { /* port multiplier device port */
14410 			sata_log(sata_hba_inst, CE_WARN,
14411 			    "SATA device detected at port %d:%d",
14412 			    cport, pmport);
14413 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14414 				/*
14415 				 * A device was not successfully identified
14416 				 */
14417 				sata_log(sata_hba_inst, CE_WARN,
14418 				    "Could not identify SATA "
14419 				    "device at port %d:%d", cport, pmport);
14420 			}
14421 		}
14422 	}
14423 
14424 	return (rv);
14425 }
14426 
14427 
14428 /*
14429  * Process sata device unconfigure request.
14430  * The unconfigure operation uses generic nexus operation to
14431  * offline a device. It leaves a target device node attached.
14432  * and obviously sata_drive_info attached as well, because
14433  * from the hardware point of view nothing has changed.
14434  */
14435 static int
14436 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
14437     sata_device_t *sata_device)
14438 {
14439 	int rv = 0;
14440 	dev_info_t *tdip;
14441 
14442 	/* We are addressing attached device, not a port */
14443 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
14444 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14445 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
14446 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14447 
14448 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14449 	    &sata_device->satadev_addr)) != NULL) {
14450 
14451 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
14452 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14453 			    "sata_hba_ioctl: unconfigure: "
14454 			    "failed to unconfigure device at SATA port %d:%d",
14455 			    sata_device->satadev_addr.cport,
14456 			    sata_device->satadev_addr.pmport));
14457 			rv = EIO;
14458 		}
14459 		/*
14460 		 * The target node devi_state should be marked with
14461 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
14462 		 * This would be the indication for cfgadm that
14463 		 * the AP node occupant state is 'unconfigured'.
14464 		 */
14465 
14466 	} else {
14467 		/*
14468 		 * This would indicate a failure on the part of cfgadm
14469 		 * to detect correct state of the node prior to this
14470 		 * call - one cannot unconfigure non-existing device.
14471 		 */
14472 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14473 		    "sata_hba_ioctl: unconfigure: "
14474 		    "attempt to unconfigure non-existing device "
14475 		    "at SATA port %d:%d",
14476 		    sata_device->satadev_addr.cport,
14477 		    sata_device->satadev_addr.pmport));
14478 		rv = ENXIO;
14479 	}
14480 	return (rv);
14481 }
14482 
14483 /*
14484  * Process sata device configure request
14485  * If port is in a failed state, operation is aborted - one has to use
14486  * an explicit connect or port activate request to try to get a port into
14487  * non-failed mode. Port reset wil also work in such situation.
14488  * If the port is in disconnected (shutdown) state, the connect operation is
14489  * attempted prior to any other action.
14490  * When port is in the active state, there is a device attached and the target
14491  * node exists, a device was most likely offlined.
14492  * If target node does not exist, a new target node is created. In both cases
14493  * an attempt is made to online (configure) the device.
14494  *
14495  * NOTE: Port multiplier is supported.
14496  */
14497 static int
14498 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
14499     sata_device_t *sata_device)
14500 {
14501 	int cport, pmport, qual;
14502 	int rval;
14503 	boolean_t target = B_TRUE;
14504 	sata_cport_info_t *cportinfo;
14505 	sata_pmport_info_t *pmportinfo = NULL;
14506 	dev_info_t *tdip;
14507 	sata_drive_info_t *sdinfo;
14508 
14509 	cport = sata_device->satadev_addr.cport;
14510 	pmport = sata_device->satadev_addr.pmport;
14511 	qual = sata_device->satadev_addr.qual;
14512 
14513 	/* Get current port state */
14514 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14515 	    (SATA_DIP(sata_hba_inst), sata_device);
14516 
14517 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14518 	if (qual == SATA_ADDR_DPMPORT) {
14519 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14520 		mutex_enter(&pmportinfo->pmport_mutex);
14521 		sata_update_pmport_info(sata_hba_inst, sata_device);
14522 		if (rval != SATA_SUCCESS ||
14523 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14524 			/*
14525 			 * Obviously, device on a failed port is not visible
14526 			 */
14527 			mutex_exit(&pmportinfo->pmport_mutex);
14528 			return (ENXIO);
14529 		}
14530 		mutex_exit(&pmportinfo->pmport_mutex);
14531 	} else {
14532 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14533 		    cport)->cport_mutex);
14534 		sata_update_port_info(sata_hba_inst, sata_device);
14535 		if (rval != SATA_SUCCESS ||
14536 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14537 			/*
14538 			 * Obviously, device on a failed port is not visible
14539 			 */
14540 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14541 			    cport)->cport_mutex);
14542 			return (ENXIO);
14543 		}
14544 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14545 		    cport)->cport_mutex);
14546 	}
14547 
14548 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
14549 		/* need to activate port */
14550 		target = B_FALSE;
14551 
14552 		/* Sanity check */
14553 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14554 			return (ENXIO);
14555 
14556 		/* Just let HBA driver to activate port */
14557 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14558 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14559 			/*
14560 			 * Port activation failure - do not change port state
14561 			 * unless the state returned by HBA indicates a port
14562 			 * failure.
14563 			 */
14564 			if (qual == SATA_ADDR_DPMPORT) {
14565 				mutex_enter(&pmportinfo->pmport_mutex);
14566 				sata_update_pmport_info(sata_hba_inst,
14567 				    sata_device);
14568 				if (sata_device->satadev_state &
14569 				    SATA_PSTATE_FAILED)
14570 					pmportinfo->pmport_state =
14571 					    SATA_PSTATE_FAILED;
14572 				mutex_exit(&pmportinfo->pmport_mutex);
14573 			} else {
14574 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14575 				    cport)->cport_mutex);
14576 				sata_update_port_info(sata_hba_inst,
14577 				    sata_device);
14578 				if (sata_device->satadev_state &
14579 				    SATA_PSTATE_FAILED)
14580 					cportinfo->cport_state =
14581 					    SATA_PSTATE_FAILED;
14582 				mutex_exit(&SATA_CPORT_INFO(
14583 				    sata_hba_inst, cport)->cport_mutex);
14584 			}
14585 		}
14586 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14587 		    "sata_hba_ioctl: configure: "
14588 		    "failed to activate SATA port %d:%d",
14589 		    cport, pmport));
14590 		return (EIO);
14591 	}
14592 	/*
14593 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14594 	 * without the hint.
14595 	 */
14596 	sata_gen_sysevent(sata_hba_inst,
14597 	    &sata_device->satadev_addr, SE_NO_HINT);
14598 
14599 	/* Virgin port state */
14600 	if (qual == SATA_ADDR_DPMPORT) {
14601 		mutex_enter(&pmportinfo->pmport_mutex);
14602 		pmportinfo->pmport_state = 0;
14603 		mutex_exit(&pmportinfo->pmport_mutex);
14604 	} else {
14605 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14606 		    cport)-> cport_mutex);
14607 		cportinfo->cport_state = 0;
14608 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14609 		    cport)->cport_mutex);
14610 	}
14611 	/*
14612 	 * Always reprobe port, to get current device info.
14613 	 */
14614 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14615 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14616 		return (EIO);
14617 
14618 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == B_FALSE) {
14619 		if (qual == SATA_ADDR_DPMPORT) {
14620 			/*
14621 			 * That's the transition from "inactive" port
14622 			 * to active one with device attached.
14623 			 */
14624 			sata_log(sata_hba_inst, CE_WARN,
14625 			    "SATA device detected at port %d:%d",
14626 			    cport, pmport);
14627 		} else {
14628 			/*
14629 			 * When PM is attached to the cport and cport is
14630 			 * activated, every PM device port needs to be reprobed.
14631 			 * We need to emit message for all devices detected
14632 			 * at port multiplier's device ports.
14633 			 * Add such code here.
14634 			 * For now, just inform about device attached to
14635 			 * cport.
14636 			 */
14637 			sata_log(sata_hba_inst, CE_WARN,
14638 			    "SATA device detected at port %d", cport);
14639 		}
14640 	}
14641 
14642 	/*
14643 	 * This is where real configuration operation starts.
14644 	 *
14645 	 * When PM is attached to the cport and cport is activated,
14646 	 * devices attached PM device ports may have to be configured
14647 	 * explicitly. This may change when port multiplier is supported.
14648 	 * For now, configure only disks and other valid target devices.
14649 	 */
14650 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
14651 		if (qual == SATA_ADDR_DCPORT) {
14652 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14653 				/*
14654 				 * A device was not successfully identified
14655 				 */
14656 				sata_log(sata_hba_inst, CE_WARN,
14657 				    "Could not identify SATA "
14658 				    "device at port %d", cport);
14659 			}
14660 		} else { /* port multiplier device port */
14661 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14662 				/*
14663 				 * A device was not successfully identified
14664 				 */
14665 				sata_log(sata_hba_inst, CE_WARN,
14666 				    "Could not identify SATA "
14667 				    "device at port %d:%d", cport, pmport);
14668 			}
14669 		}
14670 		return (ENXIO);		/* No device to configure */
14671 	}
14672 
14673 	/*
14674 	 * Here we may have a device in reset condition,
14675 	 * but because we are just configuring it, there is
14676 	 * no need to process the reset other than just
14677 	 * to clear device reset condition in the HBA driver.
14678 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
14679 	 * cause a first command sent the HBA driver with the request
14680 	 * to clear device reset condition.
14681 	 */
14682 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14683 	if (qual == SATA_ADDR_DPMPORT)
14684 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14685 	else
14686 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14687 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
14688 	if (sdinfo == NULL) {
14689 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14690 		return (ENXIO);
14691 	}
14692 	if (sdinfo->satadrv_event_flags &
14693 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
14694 		sdinfo->satadrv_event_flags = 0;
14695 	}
14696 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
14697 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14698 
14699 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14700 	    &sata_device->satadev_addr)) != NULL) {
14701 		/*
14702 		 * Target node exists. Verify, that it belongs
14703 		 * to existing, attached device and not to
14704 		 * a removed device.
14705 		 */
14706 		if (sata_check_device_removed(tdip) == B_TRUE) {
14707 			if (qual == SATA_ADDR_DPMPORT)
14708 				sata_log(sata_hba_inst, CE_WARN,
14709 				    "SATA device at port %d cannot be "
14710 				    "configured. "
14711 				    "Application(s) accessing "
14712 				    "previously attached device "
14713 				    "have to release it before newly "
14714 				    "inserted device can be made accessible.",
14715 				    cport);
14716 			else
14717 				sata_log(sata_hba_inst, CE_WARN,
14718 				    "SATA device at port %d:%d cannot be"
14719 				    "configured. "
14720 				    "Application(s) accessing "
14721 				    "previously attached device "
14722 				    "have to release it before newly "
14723 				    "inserted device can be made accessible.",
14724 				    cport, pmport);
14725 			return (EIO);
14726 		}
14727 		/*
14728 		 * Device was not removed and re-inserted.
14729 		 * Try to online it.
14730 		 */
14731 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
14732 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14733 			    "sata_hba_ioctl: configure: "
14734 			    "onlining device at SATA port "
14735 			    "%d:%d failed", cport, pmport));
14736 			return (EIO);
14737 		}
14738 
14739 		if (qual == SATA_ADDR_DPMPORT) {
14740 			mutex_enter(&pmportinfo->pmport_mutex);
14741 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14742 			mutex_exit(&pmportinfo->pmport_mutex);
14743 		} else {
14744 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14745 			    cport)->cport_mutex);
14746 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14747 			mutex_exit(&SATA_CPORT_INFO(
14748 			    sata_hba_inst, cport)->cport_mutex);
14749 		}
14750 	} else {
14751 		/*
14752 		 * No target node - need to create a new target node.
14753 		 */
14754 		if (qual == SATA_ADDR_DPMPORT) {
14755 			mutex_enter(&pmportinfo->pmport_mutex);
14756 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14757 			mutex_exit(&pmportinfo->pmport_mutex);
14758 		} else {
14759 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14760 			    cport_mutex);
14761 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14762 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14763 			    cport_mutex);
14764 		}
14765 
14766 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
14767 		    sata_hba_inst, &sata_device->satadev_addr);
14768 		if (tdip == NULL) {
14769 			/* Configure operation failed */
14770 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14771 			    "sata_hba_ioctl: configure: "
14772 			    "configuring SATA device at port %d:%d "
14773 			    "failed", cport, pmport));
14774 			return (EIO);
14775 		}
14776 	}
14777 	return (0);
14778 }
14779 
14780 
14781 /*
14782  * Process ioctl deactivate port request.
14783  * Arbitrarily unconfigure attached device, if any.
14784  * Even if the unconfigure fails, proceed with the
14785  * port deactivation.
14786  *
14787  * NOTE: Port Multiplier is supported now.
14788  */
14789 
14790 static int
14791 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
14792     sata_device_t *sata_device)
14793 {
14794 	int cport, pmport, qual;
14795 	int rval, rv = 0;
14796 	int npmport;
14797 	sata_cport_info_t *cportinfo;
14798 	sata_pmport_info_t *pmportinfo;
14799 	sata_pmult_info_t *pmultinfo;
14800 	dev_info_t *tdip;
14801 	sata_drive_info_t *sdinfo = NULL;
14802 	sata_device_t subsdevice;
14803 
14804 	/* Sanity check */
14805 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
14806 		return (ENOTSUP);
14807 
14808 	cport = sata_device->satadev_addr.cport;
14809 	pmport = sata_device->satadev_addr.pmport;
14810 	qual = sata_device->satadev_addr.qual;
14811 
14812 	/* SCSI_TO_SATA_ADDR_QUAL() translate ap_id into a device qualifier */
14813 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14814 	if (qual == SATA_ADDR_DCPORT)
14815 		qual = SATA_ADDR_CPORT;
14816 	else
14817 		qual = SATA_ADDR_PMPORT;
14818 
14819 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14820 	if (qual == SATA_ADDR_PMPORT)
14821 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14822 
14823 	/*
14824 	 * Processing port multiplier
14825 	 */
14826 	if (qual == SATA_ADDR_CPORT &&
14827 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
14828 		mutex_enter(&cportinfo->cport_mutex);
14829 
14830 		/* Deactivate all sub-deices */
14831 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14832 		if (pmultinfo != NULL) {
14833 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
14834 			    sata_hba_inst, cport); npmport++) {
14835 
14836 				subsdevice.satadev_addr.cport = cport;
14837 				subsdevice.satadev_addr.pmport =
14838 				    (uint8_t)npmport;
14839 				subsdevice.satadev_addr.qual =
14840 				    SATA_ADDR_DPMPORT;
14841 
14842 				SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14843 				    "sata_hba_ioctl: deactivate: trying to "
14844 				    "deactivate SATA port %d:%d",
14845 				    cport, npmport);
14846 
14847 				mutex_exit(&cportinfo->cport_mutex);
14848 				if (sata_ioctl_deactivate(sata_hba_inst,
14849 				    &subsdevice) == SATA_SUCCESS) {
14850 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14851 					    "[Deactivate] device at port %d:%d "
14852 					    "successfully.", cport, npmport);
14853 				}
14854 				mutex_enter(&cportinfo->cport_mutex);
14855 			}
14856 		}
14857 
14858 		/* Deactivate the port multiplier now. */
14859 		cportinfo->cport_state &= ~SATA_STATE_READY;
14860 		mutex_exit(&cportinfo->cport_mutex);
14861 
14862 		sata_device->satadev_addr.qual = qual;
14863 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14864 		    (SATA_DIP(sata_hba_inst), sata_device);
14865 
14866 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14867 		    SE_NO_HINT);
14868 
14869 		mutex_enter(&cportinfo->cport_mutex);
14870 		sata_update_port_info(sata_hba_inst, sata_device);
14871 		if (rval != SATA_SUCCESS) {
14872 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14873 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14874 			}
14875 			rv = EIO;
14876 		} else {
14877 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14878 		}
14879 		mutex_exit(&cportinfo->cport_mutex);
14880 
14881 		return (rv);
14882 	}
14883 
14884 	/*
14885 	 * Process non-port-multiplier device - it could be a drive connected
14886 	 * to a port multiplier port or a controller port.
14887 	 */
14888 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14889 	if (qual == SATA_ADDR_CPORT) {
14890 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14891 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14892 			/* deal only with valid devices */
14893 			if ((cportinfo->cport_dev_type &
14894 			    SATA_VALID_DEV_TYPE) != 0)
14895 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14896 		}
14897 		cportinfo->cport_state &= ~SATA_STATE_READY;
14898 	} else {
14899 		/* Port multiplier device port */
14900 		mutex_enter(&pmportinfo->pmport_mutex);
14901 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14902 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
14903 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
14904 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
14905 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
14906 		mutex_exit(&pmportinfo->pmport_mutex);
14907 	}
14908 
14909 	if (sdinfo != NULL) {
14910 		/*
14911 		 * If a target node exists, try to offline a device and
14912 		 * to remove a target node.
14913 		 */
14914 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14915 		    cport_mutex);
14916 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14917 		    &sata_device->satadev_addr);
14918 		if (tdip != NULL) {
14919 			/* target node exist */
14920 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14921 			    "sata_hba_ioctl: port deactivate: "
14922 			    "target node exists.", NULL);
14923 
14924 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
14925 			    NDI_SUCCESS) {
14926 				SATA_LOG_D((sata_hba_inst, CE_WARN,
14927 				    "sata_hba_ioctl: port deactivate: "
14928 				    "failed to unconfigure device at port "
14929 				    "%d:%d before deactivating the port",
14930 				    cport, pmport));
14931 				/*
14932 				 * Set DEVICE REMOVED state in the target
14933 				 * node. It will prevent an access to
14934 				 * the device even when a new device is
14935 				 * attached, until the old target node is
14936 				 * released, removed and recreated for a new
14937 				 * device.
14938 				 */
14939 				sata_set_device_removed(tdip);
14940 
14941 				/*
14942 				 * Instruct the event daemon to try the
14943 				 * target node cleanup later.
14944 				 */
14945 				sata_set_target_node_cleanup(sata_hba_inst,
14946 				    &sata_device->satadev_addr);
14947 			}
14948 		}
14949 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14950 		    cport_mutex);
14951 		/*
14952 		 * In any case, remove and release sata_drive_info
14953 		 * structure.
14954 		 */
14955 		if (qual == SATA_ADDR_CPORT) {
14956 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14957 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14958 		} else { /* port multiplier device port */
14959 			mutex_enter(&pmportinfo->pmport_mutex);
14960 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
14961 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
14962 			mutex_exit(&pmportinfo->pmport_mutex);
14963 		}
14964 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
14965 	}
14966 
14967 	if (qual == SATA_ADDR_CPORT) {
14968 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
14969 		    SATA_STATE_PROBING);
14970 	} else if (qual == SATA_ADDR_PMPORT) {
14971 		mutex_enter(&pmportinfo->pmport_mutex);
14972 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
14973 		    SATA_STATE_PROBING);
14974 		mutex_exit(&pmportinfo->pmport_mutex);
14975 	}
14976 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14977 
14978 	/* Just let HBA driver to deactivate port */
14979 	sata_device->satadev_addr.qual = qual;
14980 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14981 	    (SATA_DIP(sata_hba_inst), sata_device);
14982 
14983 	/*
14984 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14985 	 * without the hint
14986 	 */
14987 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14988 	    SE_NO_HINT);
14989 
14990 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14991 	sata_update_port_info(sata_hba_inst, sata_device);
14992 	if (qual == SATA_ADDR_CPORT) {
14993 		if (rval != SATA_SUCCESS) {
14994 			/*
14995 			 * Port deactivation failure - do not change port state
14996 			 * unless the state returned by HBA indicates a port
14997 			 * failure.
14998 			 */
14999 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
15000 				SATA_CPORT_STATE(sata_hba_inst, cport) =
15001 				    SATA_PSTATE_FAILED;
15002 			}
15003 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15004 			    "sata_hba_ioctl: port deactivate: "
15005 			    "cannot deactivate SATA port %d", cport));
15006 			rv = EIO;
15007 		} else {
15008 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
15009 		}
15010 	} else {
15011 		mutex_enter(&pmportinfo->pmport_mutex);
15012 		if (rval != SATA_SUCCESS) {
15013 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
15014 				SATA_PMPORT_STATE(sata_hba_inst, cport,
15015 				    pmport) = SATA_PSTATE_FAILED;
15016 			}
15017 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15018 			    "sata_hba_ioctl: port deactivate: "
15019 			    "cannot deactivate SATA port %d:%d",
15020 			    cport, pmport));
15021 			rv = EIO;
15022 		} else {
15023 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
15024 		}
15025 		mutex_exit(&pmportinfo->pmport_mutex);
15026 	}
15027 
15028 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15029 
15030 	return (rv);
15031 }
15032 
15033 /*
15034  * Process ioctl port activate request.
15035  *
15036  * NOTE: Port multiplier is supported now.
15037  */
15038 static int
15039 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
15040     sata_device_t *sata_device)
15041 {
15042 	int cport, pmport, qual;
15043 	sata_cport_info_t *cportinfo;
15044 	sata_pmport_info_t *pmportinfo = NULL;
15045 	boolean_t dev_existed = B_TRUE;
15046 
15047 	/* Sanity check */
15048 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
15049 		return (ENOTSUP);
15050 
15051 	cport = sata_device->satadev_addr.cport;
15052 	pmport = sata_device->satadev_addr.pmport;
15053 	qual = sata_device->satadev_addr.qual;
15054 
15055 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
15056 
15057 	/*
15058 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
15059 	 * is a device. But what we are dealing with is port/pmport.
15060 	 */
15061 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
15062 	if (qual == SATA_ADDR_DCPORT)
15063 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
15064 	else
15065 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
15066 
15067 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15068 	if (qual == SATA_ADDR_PMPORT) {
15069 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
15070 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
15071 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
15072 			dev_existed = B_FALSE;
15073 	} else { /* cport */
15074 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
15075 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
15076 			dev_existed = B_FALSE;
15077 	}
15078 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15079 
15080 	/* Just let HBA driver to activate port, if necessary */
15081 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
15082 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15083 		/*
15084 		 * Port activation failure - do not change port state unless
15085 		 * the state returned by HBA indicates a port failure.
15086 		 */
15087 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15088 		    cport)->cport_mutex);
15089 		sata_update_port_info(sata_hba_inst, sata_device);
15090 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
15091 			if (qual == SATA_ADDR_PMPORT) {
15092 				mutex_enter(&pmportinfo->pmport_mutex);
15093 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
15094 				mutex_exit(&pmportinfo->pmport_mutex);
15095 			} else
15096 				cportinfo->cport_state = SATA_PSTATE_FAILED;
15097 
15098 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15099 			    cport)->cport_mutex);
15100 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15101 			    "sata_hba_ioctl: port activate: cannot activate "
15102 			    "SATA port %d:%d", cport, pmport));
15103 			return (EIO);
15104 		}
15105 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15106 	}
15107 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15108 	if (qual == SATA_ADDR_PMPORT) {
15109 		mutex_enter(&pmportinfo->pmport_mutex);
15110 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
15111 		mutex_exit(&pmportinfo->pmport_mutex);
15112 	} else
15113 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
15114 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15115 
15116 	/*
15117 	 * Re-probe port to find its current state and possibly attached device.
15118 	 * Port re-probing may change the cportinfo device type if device is
15119 	 * found attached.
15120 	 * If port probing failed, the device type would be set to
15121 	 * SATA_DTYPE_NONE.
15122 	 */
15123 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
15124 	    SATA_DEV_IDENTIFY_RETRY);
15125 
15126 	/*
15127 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
15128 	 * without the hint.
15129 	 */
15130 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
15131 	    SE_NO_HINT);
15132 
15133 	if (dev_existed == B_FALSE) {
15134 		if (qual == SATA_ADDR_PMPORT &&
15135 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
15136 			/*
15137 			 * That's the transition from the "inactive" port state
15138 			 * or the active port without a device attached to the
15139 			 * active port state with a device attached.
15140 			 */
15141 			sata_log(sata_hba_inst, CE_WARN,
15142 			    "SATA device detected at port %d:%d",
15143 			    cport, pmport);
15144 		} else if (qual == SATA_ADDR_CPORT &&
15145 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
15146 			/*
15147 			 * That's the transition from the "inactive" port state
15148 			 * or the active port without a device attached to the
15149 			 * active port state with a device attached.
15150 			 */
15151 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
15152 				sata_log(sata_hba_inst, CE_WARN,
15153 				    "SATA device detected at port %d", cport);
15154 			} else {
15155 				sata_log(sata_hba_inst, CE_WARN,
15156 				    "SATA port multiplier detected at port %d",
15157 				    cport);
15158 			}
15159 		}
15160 	}
15161 	return (0);
15162 }
15163 
15164 
15165 
15166 /*
15167  * Process ioctl reset port request.
15168  *
15169  * NOTE: Port-Multiplier is supported.
15170  */
15171 static int
15172 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
15173     sata_device_t *sata_device)
15174 {
15175 	int cport, pmport, qual;
15176 	int rv = 0;
15177 
15178 	cport = sata_device->satadev_addr.cport;
15179 	pmport = sata_device->satadev_addr.pmport;
15180 	qual = sata_device->satadev_addr.qual;
15181 
15182 	/*
15183 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
15184 	 * is a device. But what we are dealing with is port/pmport.
15185 	 */
15186 	if (qual == SATA_ADDR_DCPORT)
15187 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
15188 	else
15189 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
15190 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
15191 
15192 	/* Sanity check */
15193 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15194 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15195 		    "sata_hba_ioctl: sata_hba_tran missing required "
15196 		    "function sata_tran_reset_dport"));
15197 		return (ENOTSUP);
15198 	}
15199 
15200 	/* Ask HBA to reset port */
15201 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
15202 	    sata_device) != SATA_SUCCESS) {
15203 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15204 		    "sata_hba_ioctl: reset port: failed %d:%d",
15205 		    cport, pmport));
15206 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15207 		    cport_mutex);
15208 		sata_update_port_info(sata_hba_inst, sata_device);
15209 		if (qual == SATA_ADDR_CPORT)
15210 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15211 			    SATA_PSTATE_FAILED;
15212 		else {
15213 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
15214 			    pmport));
15215 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15216 			    SATA_PSTATE_FAILED;
15217 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
15218 			    pmport));
15219 		}
15220 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15221 		    cport_mutex);
15222 		rv = EIO;
15223 	}
15224 	/*
15225 	 * Beacuse the port was reset, it should be probed and
15226 	 * attached device reinitialized. At this point the
15227 	 * port state is unknown - it's state is HBA-specific.
15228 	 * Re-probe port to get its state.
15229 	 */
15230 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15231 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
15232 		rv = EIO;
15233 	}
15234 	return (rv);
15235 }
15236 
15237 /*
15238  * Process ioctl reset device request.
15239  *
15240  * NOTE: Port multiplier is supported.
15241  */
15242 static int
15243 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
15244     sata_device_t *sata_device)
15245 {
15246 	sata_drive_info_t *sdinfo = NULL;
15247 	sata_pmult_info_t *pmultinfo = NULL;
15248 	int cport, pmport;
15249 	int rv = 0;
15250 
15251 	/* Sanity check */
15252 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15253 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15254 		    "sata_hba_ioctl: sata_hba_tran missing required "
15255 		    "function sata_tran_reset_dport"));
15256 		return (ENOTSUP);
15257 	}
15258 
15259 	cport = sata_device->satadev_addr.cport;
15260 	pmport = sata_device->satadev_addr.pmport;
15261 
15262 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15263 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
15264 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
15265 		    SATA_DTYPE_PMULT)
15266 			pmultinfo = SATA_CPORT_INFO(sata_hba_inst, cport)->
15267 			    cport_devp.cport_sata_pmult;
15268 		else
15269 			sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15270 			    sata_device->satadev_addr.cport);
15271 	} else { /* port multiplier */
15272 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
15273 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15274 		    sata_device->satadev_addr.cport,
15275 		    sata_device->satadev_addr.pmport);
15276 	}
15277 	if (sdinfo == NULL && pmultinfo == NULL) {
15278 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15279 		return (EINVAL);
15280 	}
15281 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15282 
15283 	/* Ask HBA to reset device */
15284 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15285 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15286 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15287 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
15288 		    cport, pmport));
15289 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15290 		    cport_mutex);
15291 		sata_update_port_info(sata_hba_inst, sata_device);
15292 		/*
15293 		 * Device info structure remains attached. Another device reset
15294 		 * or port disconnect/connect and re-probing is
15295 		 * needed to change it's state
15296 		 */
15297 		if (sdinfo != NULL) {
15298 			sdinfo->satadrv_state &= ~SATA_STATE_READY;
15299 			sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
15300 		} else if (pmultinfo != NULL) {
15301 			pmultinfo->pmult_state &= ~SATA_STATE_READY;
15302 			pmultinfo->pmult_state |= SATA_DSTATE_FAILED;
15303 		}
15304 
15305 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15306 		rv = EIO;
15307 	}
15308 	/*
15309 	 * If attached device was a port multiplier, some extra processing
15310 	 * may be needed to bring it back. SATA specification requies a
15311 	 * mandatory software reset on host port to reliably enumerate a port
15312 	 * multiplier, the HBA driver should handle that after reset
15313 	 * operation.
15314 	 */
15315 	return (rv);
15316 }
15317 
15318 
15319 /*
15320  * Process ioctl reset all request.
15321  */
15322 static int
15323 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
15324 {
15325 	sata_device_t sata_device;
15326 	int rv = 0;
15327 	int tcport;
15328 	int tpmport = 0;
15329 
15330 	sata_device.satadev_rev = SATA_DEVICE_REV;
15331 
15332 	/*
15333 	 * There is no protection here for configured devices.
15334 	 */
15335 	/* Sanity check */
15336 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15337 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15338 		    "sata_hba_ioctl: sata_hba_tran missing required "
15339 		    "function sata_tran_reset_dport"));
15340 		return (ENOTSUP);
15341 	}
15342 
15343 	/*
15344 	 * Need to lock all ports, not just one.
15345 	 * If any port is locked by event processing, fail the whole operation.
15346 	 * One port is already locked, but for simplicity lock it again.
15347 	 */
15348 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15349 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15350 		    cport_mutex);
15351 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
15352 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
15353 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15354 			    cport_mutex);
15355 			rv = EBUSY;
15356 			break;
15357 		} else {
15358 			/*
15359 			 * It is enough to lock cport in command-based
15360 			 * switching mode.
15361 			 */
15362 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
15363 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
15364 		}
15365 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15366 		    cport_mutex);
15367 	}
15368 
15369 	if (rv == 0) {
15370 		/*
15371 		 * All cports were successfully locked.
15372 		 * Reset main SATA controller.
15373 		 * Set the device address to port 0, to have a valid device
15374 		 * address.
15375 		 */
15376 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
15377 		sata_device.satadev_addr.cport = 0;
15378 		sata_device.satadev_addr.pmport = 0;
15379 
15380 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15381 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
15382 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15383 			    "sata_hba_ioctl: reset controller failed"));
15384 			return (EIO);
15385 		}
15386 		/*
15387 		 * Because ports were reset, port states are unknown.
15388 		 * They should be re-probed to get their state and
15389 		 * attached devices should be reinitialized.
15390 		 */
15391 		for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst);
15392 		    tcport++) {
15393 			sata_device.satadev_addr.cport = tcport;
15394 			sata_device.satadev_addr.pmport = tpmport;
15395 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
15396 
15397 			/*
15398 			 * The sata_reprobe_port() will mark a
15399 			 * SATA_EVNT_DEVICE_RESET event on the port
15400 			 * multiplier, all its sub-ports will be probed by
15401 			 * sata daemon afterwards.
15402 			 */
15403 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
15404 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15405 				rv = EIO;
15406 		}
15407 	}
15408 	/*
15409 	 * Unlock all ports
15410 	 */
15411 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15412 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15413 		    cport_mutex);
15414 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
15415 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
15416 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15417 		    cport_mutex);
15418 	}
15419 
15420 	/*
15421 	 * This operation returns EFAULT if either reset
15422 	 * controller failed or a re-probing of any port failed.
15423 	 */
15424 	return (rv);
15425 }
15426 
15427 
15428 /*
15429  * Process ioctl port self test request.
15430  *
15431  * NOTE: Port multiplier code is not completed nor tested.
15432  */
15433 static int
15434 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
15435     sata_device_t *sata_device)
15436 {
15437 	int cport, pmport, qual;
15438 	int rv = 0;
15439 
15440 	/* Sanity check */
15441 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
15442 		return (ENOTSUP);
15443 
15444 	cport = sata_device->satadev_addr.cport;
15445 	pmport = sata_device->satadev_addr.pmport;
15446 	qual = sata_device->satadev_addr.qual;
15447 
15448 	/*
15449 	 * There is no protection here for a configured
15450 	 * device attached to this port.
15451 	 */
15452 
15453 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
15454 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15455 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15456 		    "sata_hba_ioctl: port selftest: "
15457 		    "failed port %d:%d", cport, pmport));
15458 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15459 		    cport_mutex);
15460 		sata_update_port_info(sata_hba_inst, sata_device);
15461 		if (qual == SATA_ADDR_CPORT)
15462 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15463 			    SATA_PSTATE_FAILED;
15464 		else { /* port multiplier device port */
15465 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
15466 			    cport, pmport));
15467 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15468 			    SATA_PSTATE_FAILED;
15469 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
15470 			    cport, pmport));
15471 		}
15472 
15473 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15474 		    cport_mutex);
15475 		return (EIO);
15476 	}
15477 	/*
15478 	 * Beacuse the port was reset in the course of testing, it should be
15479 	 * re-probed and attached device state should be restored. At this
15480 	 * point the port state is unknown - it's state is HBA-specific.
15481 	 * Force port re-probing to get it into a known state.
15482 	 */
15483 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15484 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15485 		rv = EIO;
15486 	return (rv);
15487 }
15488 
15489 
15490 /*
15491  * sata_cfgadm_state:
15492  * Use the sata port state and state of the target node to figure out
15493  * the cfgadm_state.
15494  *
15495  * The port argument is a value with encoded cport,
15496  * pmport and address qualifier, in the same manner as a scsi target number.
15497  * SCSI_TO_SATA_CPORT macro extracts cport number,
15498  * SCSI_TO_SATA_PMPORT extracts pmport number and
15499  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
15500  *
15501  * Port multiplier is supported.
15502  */
15503 
15504 static void
15505 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
15506     devctl_ap_state_t *ap_state)
15507 {
15508 	uint8_t		cport, pmport, qual;
15509 	uint32_t	port_state, pmult_state;
15510 	uint32_t	dev_type;
15511 	sata_drive_info_t *sdinfo;
15512 
15513 	cport = SCSI_TO_SATA_CPORT(port);
15514 	pmport = SCSI_TO_SATA_PMPORT(port);
15515 	qual = SCSI_TO_SATA_ADDR_QUAL(port);
15516 
15517 	/* Check cport state */
15518 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
15519 	if (port_state & SATA_PSTATE_SHUTDOWN ||
15520 	    port_state & SATA_PSTATE_FAILED) {
15521 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15522 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15523 		if (port_state & SATA_PSTATE_FAILED)
15524 			ap_state->ap_condition = AP_COND_FAILED;
15525 		else
15526 			ap_state->ap_condition = AP_COND_UNKNOWN;
15527 
15528 		return;
15529 	}
15530 
15531 	/* cport state is okay. Now check pmport state */
15532 	if (qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) {
15533 		/* Sanity check */
15534 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
15535 		    SATA_DTYPE_PMULT || SATA_PMPORT_INFO(sata_hba_inst,
15536 		    cport, pmport) == NULL)
15537 			return;
15538 		port_state = SATA_PMPORT_STATE(sata_hba_inst, cport, pmport);
15539 		if (port_state & SATA_PSTATE_SHUTDOWN ||
15540 		    port_state & SATA_PSTATE_FAILED) {
15541 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15542 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15543 			if (port_state & SATA_PSTATE_FAILED)
15544 				ap_state->ap_condition = AP_COND_FAILED;
15545 			else
15546 				ap_state->ap_condition = AP_COND_UNKNOWN;
15547 
15548 			return;
15549 		}
15550 	}
15551 
15552 	/* Port is enabled and ready */
15553 	if (qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_CPORT)
15554 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst, cport);
15555 	else
15556 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport, pmport);
15557 
15558 	switch (dev_type) {
15559 	case SATA_DTYPE_NONE:
15560 	{
15561 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15562 		ap_state->ap_condition = AP_COND_OK;
15563 		/* No device attached */
15564 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
15565 		break;
15566 	}
15567 	case SATA_DTYPE_PMULT:
15568 	{
15569 		/* Need to check port multiplier state */
15570 		ASSERT(qual == SATA_ADDR_DCPORT);
15571 		pmult_state = SATA_PMULT_INFO(sata_hba_inst, cport)->
15572 		    pmult_state;
15573 		if (pmult_state & (SATA_PSTATE_SHUTDOWN|SATA_PSTATE_FAILED)) {
15574 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15575 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15576 			if (pmult_state & SATA_PSTATE_FAILED)
15577 				ap_state->ap_condition = AP_COND_FAILED;
15578 			else
15579 				ap_state->ap_condition = AP_COND_UNKNOWN;
15580 
15581 			return;
15582 		}
15583 
15584 		/* Port multiplier is not configurable */
15585 		ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
15586 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15587 		ap_state->ap_condition = AP_COND_OK;
15588 		break;
15589 	}
15590 
15591 	case SATA_DTYPE_ATADISK:
15592 	case SATA_DTYPE_ATAPICD:
15593 	case SATA_DTYPE_ATAPITAPE:
15594 	case SATA_DTYPE_ATAPIDISK:
15595 	{
15596 		dev_info_t *tdip = NULL;
15597 		dev_info_t *dip = NULL;
15598 		int circ;
15599 
15600 		dip = SATA_DIP(sata_hba_inst);
15601 		tdip = sata_get_target_dip(dip, cport, pmport);
15602 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15603 		if (tdip != NULL) {
15604 			ndi_devi_enter(dip, &circ);
15605 			mutex_enter(&(DEVI(tdip)->devi_lock));
15606 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
15607 				/*
15608 				 * There could be the case where previously
15609 				 * configured and opened device was removed
15610 				 * and unknown device was plugged.
15611 				 * In such case we want to show a device, and
15612 				 * its configured or unconfigured state but
15613 				 * indicate unusable condition untill the
15614 				 * old target node is released and removed.
15615 				 */
15616 				ap_state->ap_condition = AP_COND_UNUSABLE;
15617 			} else {
15618 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
15619 				    cport));
15620 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15621 				    cport);
15622 				if (sdinfo != NULL) {
15623 					if ((sdinfo->satadrv_state &
15624 					    SATA_DSTATE_FAILED) != 0)
15625 						ap_state->ap_condition =
15626 						    AP_COND_FAILED;
15627 					else
15628 						ap_state->ap_condition =
15629 						    AP_COND_OK;
15630 				} else {
15631 					ap_state->ap_condition =
15632 					    AP_COND_UNKNOWN;
15633 				}
15634 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
15635 				    cport));
15636 			}
15637 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
15638 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
15639 				ap_state->ap_ostate =
15640 				    AP_OSTATE_UNCONFIGURED;
15641 			} else {
15642 				ap_state->ap_ostate =
15643 				    AP_OSTATE_CONFIGURED;
15644 			}
15645 			mutex_exit(&(DEVI(tdip)->devi_lock));
15646 			ndi_devi_exit(dip, circ);
15647 		} else {
15648 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15649 			ap_state->ap_condition = AP_COND_UNKNOWN;
15650 		}
15651 		break;
15652 	}
15653 	default:
15654 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15655 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15656 		ap_state->ap_condition = AP_COND_UNKNOWN;
15657 		/*
15658 		 * This is actually internal error condition (non fatal),
15659 		 * because we have already checked all defined device types.
15660 		 */
15661 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15662 		    "sata_cfgadm_state: Internal error: "
15663 		    "unknown device type"));
15664 		break;
15665 	}
15666 }
15667 
15668 
15669 /*
15670  * Process ioctl get device path request.
15671  *
15672  * NOTE: Port multiplier has no target dip. Devices connected to port
15673  * multiplier have target node attached to the HBA node. The only difference
15674  * between them and the directly-attached device node is a target address.
15675  */
15676 static int
15677 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
15678     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15679 {
15680 	char path[MAXPATHLEN];
15681 	uint32_t size;
15682 	dev_info_t *tdip;
15683 
15684 	(void) strcpy(path, "/devices");
15685 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
15686 	    &sata_device->satadev_addr)) == NULL) {
15687 		/*
15688 		 * No such device. If this is a request for a size, do not
15689 		 * return EINVAL for non-existing target, because cfgadm
15690 		 * will then indicate a meaningless ioctl failure.
15691 		 * If this is a request for a path, indicate invalid
15692 		 * argument.
15693 		 */
15694 		if (ioc->get_size == 0)
15695 			return (EINVAL);
15696 	} else {
15697 		(void) ddi_pathname(tdip, path + strlen(path));
15698 	}
15699 	size = strlen(path) + 1;
15700 
15701 	if (ioc->get_size != 0) {
15702 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
15703 		    mode) != 0)
15704 			return (EFAULT);
15705 	} else {
15706 		if (ioc->bufsiz != size)
15707 			return (EINVAL);
15708 
15709 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
15710 		    mode) != 0)
15711 			return (EFAULT);
15712 	}
15713 	return (0);
15714 }
15715 
15716 /*
15717  * Process ioctl get attachment point type request.
15718  *
15719  * NOTE: Port multiplier is supported.
15720  */
15721 static	int
15722 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
15723     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15724 {
15725 	uint32_t	type_len;
15726 	const char	*ap_type;
15727 	int		dev_type;
15728 
15729 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15730 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
15731 		    sata_device->satadev_addr.cport);
15732 	else /* pmport */
15733 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
15734 		    sata_device->satadev_addr.cport,
15735 		    sata_device->satadev_addr.pmport);
15736 
15737 	switch (dev_type) {
15738 	case SATA_DTYPE_NONE:
15739 		ap_type = "port";
15740 		break;
15741 
15742 	case SATA_DTYPE_ATADISK:
15743 	case SATA_DTYPE_ATAPIDISK:
15744 		ap_type = "disk";
15745 		break;
15746 
15747 	case SATA_DTYPE_ATAPICD:
15748 		ap_type = "cd/dvd";
15749 		break;
15750 
15751 	case SATA_DTYPE_ATAPITAPE:
15752 		ap_type = "tape";
15753 		break;
15754 
15755 	case SATA_DTYPE_PMULT:
15756 		ap_type = "sata-pmult";
15757 		break;
15758 
15759 	case SATA_DTYPE_UNKNOWN:
15760 		ap_type = "unknown";
15761 		break;
15762 
15763 	default:
15764 		ap_type = "unsupported";
15765 		break;
15766 
15767 	} /* end of dev_type switch */
15768 
15769 	type_len = strlen(ap_type) + 1;
15770 
15771 	if (ioc->get_size) {
15772 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
15773 		    mode) != 0)
15774 			return (EFAULT);
15775 	} else {
15776 		if (ioc->bufsiz != type_len)
15777 			return (EINVAL);
15778 
15779 		if (ddi_copyout((void *)ap_type, ioc->buf,
15780 		    ioc->bufsiz, mode) != 0)
15781 			return (EFAULT);
15782 	}
15783 	return (0);
15784 
15785 }
15786 
15787 /*
15788  * Process ioctl get device model info request.
15789  * This operation should return to cfgadm the device model
15790  * information string
15791  *
15792  * NOTE: Port multiplier is supported.
15793  */
15794 static	int
15795 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
15796     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15797 {
15798 	sata_drive_info_t *sdinfo;
15799 	uint32_t info_len;
15800 	char ap_info[SATA_ID_MODEL_LEN + 1];
15801 
15802 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15803 	    sata_device->satadev_addr.cport)->cport_mutex);
15804 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15805 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15806 		    sata_device->satadev_addr.cport);
15807 	else /* port multiplier */
15808 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15809 		    sata_device->satadev_addr.cport,
15810 		    sata_device->satadev_addr.pmport);
15811 	if (sdinfo == NULL) {
15812 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15813 		    sata_device->satadev_addr.cport)->cport_mutex);
15814 		return (EINVAL);
15815 	}
15816 
15817 #ifdef	_LITTLE_ENDIAN
15818 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15819 #else	/* _LITTLE_ENDIAN */
15820 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15821 #endif	/* _LITTLE_ENDIAN */
15822 
15823 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15824 	    sata_device->satadev_addr.cport)->cport_mutex);
15825 
15826 	ap_info[SATA_ID_MODEL_LEN] = '\0';
15827 
15828 	info_len = strlen(ap_info) + 1;
15829 
15830 	if (ioc->get_size) {
15831 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15832 		    mode) != 0)
15833 			return (EFAULT);
15834 	} else {
15835 		if (ioc->bufsiz < info_len)
15836 			return (EINVAL);
15837 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15838 		    mode) != 0)
15839 			return (EFAULT);
15840 	}
15841 	return (0);
15842 }
15843 
15844 
15845 /*
15846  * Process ioctl get device firmware revision info request.
15847  * This operation should return to cfgadm the device firmware revision
15848  * information string
15849  *
15850  * Port multiplier is supported.
15851  */
15852 static	int
15853 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
15854     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15855 {
15856 	sata_drive_info_t *sdinfo;
15857 	uint32_t info_len;
15858 	char ap_info[SATA_ID_FW_LEN + 1];
15859 
15860 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15861 	    sata_device->satadev_addr.cport)->cport_mutex);
15862 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15863 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15864 		    sata_device->satadev_addr.cport);
15865 	else /* port multiplier */
15866 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15867 		    sata_device->satadev_addr.cport,
15868 		    sata_device->satadev_addr.pmport);
15869 	if (sdinfo == NULL) {
15870 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15871 		    sata_device->satadev_addr.cport)->cport_mutex);
15872 		return (EINVAL);
15873 	}
15874 
15875 #ifdef	_LITTLE_ENDIAN
15876 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15877 #else	/* _LITTLE_ENDIAN */
15878 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15879 #endif	/* _LITTLE_ENDIAN */
15880 
15881 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15882 	    sata_device->satadev_addr.cport)->cport_mutex);
15883 
15884 	ap_info[SATA_ID_FW_LEN] = '\0';
15885 
15886 	info_len = strlen(ap_info) + 1;
15887 
15888 	if (ioc->get_size) {
15889 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15890 		    mode) != 0)
15891 			return (EFAULT);
15892 	} else {
15893 		if (ioc->bufsiz < info_len)
15894 			return (EINVAL);
15895 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15896 		    mode) != 0)
15897 			return (EFAULT);
15898 	}
15899 	return (0);
15900 }
15901 
15902 
15903 /*
15904  * Process ioctl get device serial number info request.
15905  * This operation should return to cfgadm the device serial number string.
15906  *
15907  * NOTE: Port multiplier is supported.
15908  */
15909 static	int
15910 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
15911     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15912 {
15913 	sata_drive_info_t *sdinfo;
15914 	uint32_t info_len;
15915 	char ap_info[SATA_ID_SERIAL_LEN + 1];
15916 
15917 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15918 	    sata_device->satadev_addr.cport)->cport_mutex);
15919 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15920 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15921 		    sata_device->satadev_addr.cport);
15922 	else /* port multiplier */
15923 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15924 		    sata_device->satadev_addr.cport,
15925 		    sata_device->satadev_addr.pmport);
15926 	if (sdinfo == NULL) {
15927 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15928 		    sata_device->satadev_addr.cport)->cport_mutex);
15929 		return (EINVAL);
15930 	}
15931 
15932 #ifdef	_LITTLE_ENDIAN
15933 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15934 #else	/* _LITTLE_ENDIAN */
15935 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15936 #endif	/* _LITTLE_ENDIAN */
15937 
15938 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15939 	    sata_device->satadev_addr.cport)->cport_mutex);
15940 
15941 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
15942 
15943 	info_len = strlen(ap_info) + 1;
15944 
15945 	if (ioc->get_size) {
15946 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15947 		    mode) != 0)
15948 			return (EFAULT);
15949 	} else {
15950 		if (ioc->bufsiz < info_len)
15951 			return (EINVAL);
15952 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15953 		    mode) != 0)
15954 			return (EFAULT);
15955 	}
15956 	return (0);
15957 }
15958 
15959 
15960 /*
15961  * Preset scsi extended sense data (to NO SENSE)
15962  * First 18 bytes of the sense data are preset to current valid sense
15963  * with a key NO SENSE data.
15964  *
15965  * Returns void
15966  */
15967 static void
15968 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
15969 {
15970 	sense->es_valid = 1;		/* Valid sense */
15971 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
15972 	sense->es_key = KEY_NO_SENSE;
15973 	sense->es_info_1 = 0;
15974 	sense->es_info_2 = 0;
15975 	sense->es_info_3 = 0;
15976 	sense->es_info_4 = 0;
15977 	sense->es_add_len = 10;	/* Additional length - replace with a def */
15978 	sense->es_cmd_info[0] = 0;
15979 	sense->es_cmd_info[1] = 0;
15980 	sense->es_cmd_info[2] = 0;
15981 	sense->es_cmd_info[3] = 0;
15982 	sense->es_add_code = 0;
15983 	sense->es_qual_code = 0;
15984 }
15985 
15986 /*
15987  * Register a legacy cmdk-style devid for the target (disk) device.
15988  *
15989  * Note: This function is called only when the HBA devinfo node has the
15990  * property "use-cmdk-devid-format" set. This property indicates that
15991  * devid compatible with old cmdk (target) driver is to be generated
15992  * for any target device attached to this controller. This will take
15993  * precedence over the devid generated by sd (target) driver.
15994  * This function is derived from cmdk_devid_setup() function in cmdk.c.
15995  */
15996 static void
15997 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
15998 {
15999 	char	*hwid;
16000 	int	modlen;
16001 	int	serlen;
16002 	int	rval;
16003 	ddi_devid_t	devid;
16004 
16005 	/*
16006 	 * device ID is a concatanation of model number, "=", serial number.
16007 	 */
16008 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
16009 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
16010 	    sizeof (sdinfo->satadrv_id.ai_model));
16011 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
16012 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
16013 	if (modlen == 0)
16014 		goto err;
16015 	hwid[modlen++] = '=';
16016 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
16017 	    sizeof (sdinfo->satadrv_id.ai_drvser));
16018 	swab(&hwid[modlen], &hwid[modlen],
16019 	    sizeof (sdinfo->satadrv_id.ai_drvser));
16020 	serlen = sata_check_modser(&hwid[modlen],
16021 	    sizeof (sdinfo->satadrv_id.ai_drvser));
16022 	if (serlen == 0)
16023 		goto err;
16024 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
16025 
16026 	/* initialize/register devid */
16027 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
16028 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
16029 		rval = ddi_devid_register(dip, devid);
16030 		/*
16031 		 * Free up the allocated devid buffer.
16032 		 * NOTE: This doesn't mean unregistering devid.
16033 		 */
16034 		ddi_devid_free(devid);
16035 	}
16036 
16037 	if (rval != DDI_SUCCESS)
16038 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
16039 		    " on port %d", sdinfo->satadrv_addr.cport);
16040 err:
16041 	kmem_free(hwid, LEGACY_HWID_LEN);
16042 }
16043 
16044 /*
16045  * valid model/serial string must contain a non-zero non-space characters.
16046  * trim trailing spaces/NULLs.
16047  */
16048 static int
16049 sata_check_modser(char *buf, int buf_len)
16050 {
16051 	boolean_t ret;
16052 	char *s;
16053 	int i;
16054 	int tb;
16055 	char ch;
16056 
16057 	ret = B_FALSE;
16058 	s = buf;
16059 	for (i = 0; i < buf_len; i++) {
16060 		ch = *s++;
16061 		if (ch != ' ' && ch != '\0')
16062 			tb = i + 1;
16063 		if (ch != ' ' && ch != '\0' && ch != '0')
16064 			ret = B_TRUE;
16065 	}
16066 
16067 	if (ret == B_FALSE)
16068 		return (0); /* invalid string */
16069 
16070 	return (tb); /* return length */
16071 }
16072 
16073 /*
16074  * sata_set_drive_features function compares current device features setting
16075  * with the saved device features settings and, if there is a difference,
16076  * it restores device features setting to the previously saved state.
16077  * It also arbitrarily tries to select the highest supported DMA mode.
16078  * Device Identify or Identify Packet Device data has to be current.
16079  * At the moment read ahead and write cache are considered for all devices.
16080  * For atapi devices, Removable Media Status Notification is set in addition
16081  * to common features.
16082  *
16083  * This function cannot be called in the interrupt context (it may sleep).
16084  *
16085  * The input argument sdinfo should point to the drive info structure
16086  * to be updated after features are set. Note, that only
16087  * device (packet) identify data is updated, not the flags indicating the
16088  * supported features.
16089  *
16090  * Returns SATA_SUCCESS if successful or there was nothing to do.
16091  * Device Identify data in the drive info structure pointed to by the sdinfo
16092  * arguments is updated even when no features were set or changed.
16093  *
16094  * Returns SATA_FAILURE if device features could not be set or DMA mode
16095  * for a disk cannot be set and device identify data cannot be fetched.
16096  *
16097  * Returns SATA_RETRY if device features could not be set (other than disk
16098  * DMA mode) but the device identify data was fetched successfully.
16099  *
16100  * Note: This function may fail the port, making it inaccessible.
16101  * In such case the explicit port disconnect/connect or physical device
16102  * detach/attach is required to re-evaluate port state again.
16103  */
16104 
16105 static int
16106 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
16107     sata_drive_info_t *sdinfo, int restore)
16108 {
16109 	int rval = SATA_SUCCESS;
16110 	int rval_set;
16111 	sata_drive_info_t new_sdinfo;
16112 	char *finfo = "sata_set_drive_features: cannot";
16113 	char *finfox;
16114 	int cache_op;
16115 
16116 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
16117 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
16118 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
16119 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
16120 		/*
16121 		 * Cannot get device identification - caller may retry later
16122 		 */
16123 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16124 		    "%s fetch device identify data\n", finfo);
16125 		return (SATA_FAILURE);
16126 	}
16127 	finfox = (restore != 0) ? " restore device features" :
16128 	    " initialize device features\n";
16129 
16130 	switch (sdinfo->satadrv_type) {
16131 	case SATA_DTYPE_ATADISK:
16132 		/* Arbitrarily set UDMA mode */
16133 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
16134 		    SATA_SUCCESS) {
16135 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16136 			    "%s set UDMA mode\n", finfo));
16137 			return (SATA_FAILURE);
16138 		}
16139 		break;
16140 	case SATA_DTYPE_ATAPICD:
16141 	case SATA_DTYPE_ATAPITAPE:
16142 	case SATA_DTYPE_ATAPIDISK:
16143 		/*  Set Removable Media Status Notification, if necessary */
16144 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
16145 		    restore != 0) {
16146 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
16147 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
16148 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
16149 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
16150 				/* Current setting does not match saved one */
16151 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
16152 				    sdinfo->satadrv_settings &
16153 				    SATA_DEV_RMSN) != SATA_SUCCESS)
16154 					rval = SATA_FAILURE;
16155 			}
16156 		}
16157 		/*
16158 		 * We have to set Multiword DMA or UDMA, if it is supported, as
16159 		 * we want to use DMA transfer mode whenever possible.
16160 		 * Some devices require explicit setting of the DMA mode.
16161 		 */
16162 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
16163 			/* Set highest supported DMA mode */
16164 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
16165 			    SATA_SUCCESS) {
16166 				SATA_LOG_D((sata_hba_inst, CE_WARN,
16167 				    "%s set UDMA mode\n", finfo));
16168 				rval = SATA_FAILURE;
16169 			}
16170 		}
16171 		break;
16172 	}
16173 
16174 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
16175 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
16176 		/*
16177 		 * neither READ AHEAD nor WRITE CACHE is supported
16178 		 * - do nothing
16179 		 */
16180 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16181 		    "settable features not supported\n", NULL);
16182 		goto update_sdinfo;
16183 	}
16184 
16185 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
16186 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
16187 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
16188 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
16189 		/*
16190 		 * both READ AHEAD and WRITE CACHE are enabled
16191 		 * - Nothing to do
16192 		 */
16193 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16194 		    "no device features to set\n", NULL);
16195 		goto update_sdinfo;
16196 	}
16197 
16198 	cache_op = 0;
16199 
16200 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
16201 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
16202 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
16203 			/* Enable read ahead / read cache */
16204 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
16205 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16206 			    "enabling read cache\n", NULL);
16207 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
16208 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
16209 			/* Disable read ahead  / read cache */
16210 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
16211 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16212 			    "disabling read cache\n", NULL);
16213 		}
16214 
16215 		if (cache_op != 0) {
16216 			/* Try to set read cache mode */
16217 			rval_set = sata_set_cache_mode(sata_hba_inst,
16218 			    &new_sdinfo, cache_op);
16219 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
16220 				rval = rval_set;
16221 		}
16222 	}
16223 
16224 	cache_op = 0;
16225 
16226 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
16227 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
16228 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
16229 			/* Enable write cache */
16230 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
16231 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16232 			    "enabling write cache\n", NULL);
16233 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
16234 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
16235 			/* Disable write cache */
16236 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
16237 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16238 			    "disabling write cache\n", NULL);
16239 		}
16240 
16241 		if (cache_op != 0) {
16242 			/* Try to set write cache mode */
16243 			rval_set = sata_set_cache_mode(sata_hba_inst,
16244 			    &new_sdinfo, cache_op);
16245 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
16246 				rval = rval_set;
16247 		}
16248 	}
16249 	if (rval != SATA_SUCCESS)
16250 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16251 		    "%s %s", finfo, finfox));
16252 
16253 update_sdinfo:
16254 	/*
16255 	 * We need to fetch Device Identify data again
16256 	 */
16257 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
16258 		/*
16259 		 * Cannot get device identification - retry later
16260 		 */
16261 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16262 		    "%s re-fetch device identify data\n", finfo));
16263 		rval = SATA_FAILURE;
16264 	}
16265 	/* Copy device sata info. */
16266 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
16267 
16268 	return (rval);
16269 }
16270 
16271 
16272 /*
16273  *
16274  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
16275  * unable to determine.
16276  *
16277  * Cannot be called in an interrupt context.
16278  *
16279  * Called by sata_build_lsense_page_2f()
16280  */
16281 
16282 static int
16283 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
16284     sata_drive_info_t *sdinfo)
16285 {
16286 	sata_pkt_t *spkt;
16287 	sata_cmd_t *scmd;
16288 	sata_pkt_txlate_t *spx;
16289 	int rval;
16290 
16291 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16292 	spx->txlt_sata_hba_inst = sata_hba_inst;
16293 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16294 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16295 	if (spkt == NULL) {
16296 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16297 		return (-1);
16298 	}
16299 	/* address is needed now */
16300 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16301 
16302 
16303 	/* Fill sata_pkt */
16304 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16305 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16306 	/* Synchronous mode, no callback */
16307 	spkt->satapkt_comp = NULL;
16308 	/* Timeout 30s */
16309 	spkt->satapkt_time = sata_default_pkt_time;
16310 
16311 	scmd = &spkt->satapkt_cmd;
16312 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
16313 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
16314 
16315 	/* Set up which registers need to be returned */
16316 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
16317 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
16318 
16319 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
16320 	scmd->satacmd_addr_type = 0;		/* N/A */
16321 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16322 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16323 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16324 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16325 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
16326 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16327 	scmd->satacmd_cmd_reg = SATAC_SMART;
16328 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16329 	    sdinfo->satadrv_addr.cport)));
16330 
16331 
16332 	/* Send pkt to SATA HBA driver */
16333 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16334 	    SATA_TRAN_ACCEPTED ||
16335 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16336 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16337 		    sdinfo->satadrv_addr.cport)));
16338 		/*
16339 		 * Whoops, no SMART RETURN STATUS
16340 		 */
16341 		rval = -1;
16342 	} else {
16343 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16344 		    sdinfo->satadrv_addr.cport)));
16345 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
16346 			rval = -1;
16347 			goto fail;
16348 		}
16349 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
16350 			rval = -1;
16351 			goto fail;
16352 		}
16353 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
16354 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
16355 			rval = 0;
16356 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
16357 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
16358 			rval = 1;
16359 		else {
16360 			rval = -1;
16361 			goto fail;
16362 		}
16363 	}
16364 fail:
16365 	/* Free allocated resources */
16366 	sata_pkt_free(spx);
16367 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16368 
16369 	return (rval);
16370 }
16371 
16372 /*
16373  *
16374  * Returns 0 if succeeded, -1 otherwise
16375  *
16376  * Cannot be called in an interrupt context.
16377  *
16378  */
16379 static int
16380 sata_fetch_smart_data(
16381 	sata_hba_inst_t *sata_hba_inst,
16382 	sata_drive_info_t *sdinfo,
16383 	struct smart_data *smart_data)
16384 {
16385 	sata_pkt_t *spkt;
16386 	sata_cmd_t *scmd;
16387 	sata_pkt_txlate_t *spx;
16388 	int rval;
16389 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
16390 
16391 #if ! defined(lint)
16392 	ASSERT(sizeof (struct smart_data) == 512);
16393 #endif
16394 
16395 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16396 	spx->txlt_sata_hba_inst = sata_hba_inst;
16397 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16398 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16399 	if (spkt == NULL) {
16400 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16401 		return (-1);
16402 	}
16403 	/* address is needed now */
16404 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16405 
16406 
16407 	/* Fill sata_pkt */
16408 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16409 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16410 	/* Synchronous mode, no callback */
16411 	spkt->satapkt_comp = NULL;
16412 	/* Timeout 30s */
16413 	spkt->satapkt_time = sata_default_pkt_time;
16414 
16415 	scmd = &spkt->satapkt_cmd;
16416 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16417 
16418 	/*
16419 	 * Allocate buffer for SMART data
16420 	 */
16421 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16422 	    sizeof (struct smart_data));
16423 	if (scmd->satacmd_bp == NULL) {
16424 		sata_pkt_free(spx);
16425 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16426 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16427 		    "sata_fetch_smart_data: "
16428 		    "cannot allocate buffer"));
16429 		return (-1);
16430 	}
16431 
16432 
16433 	/* Build SMART_READ_DATA cmd in the sata_pkt */
16434 	scmd->satacmd_addr_type = 0;		/* N/A */
16435 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16436 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16437 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16438 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16439 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
16440 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16441 	scmd->satacmd_cmd_reg = SATAC_SMART;
16442 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16443 	    sdinfo->satadrv_addr.cport)));
16444 
16445 	/* Send pkt to SATA HBA driver */
16446 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16447 	    SATA_TRAN_ACCEPTED ||
16448 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16449 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16450 		    sdinfo->satadrv_addr.cport)));
16451 		/*
16452 		 * Whoops, no SMART DATA available
16453 		 */
16454 		rval = -1;
16455 		goto fail;
16456 	} else {
16457 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16458 		    sdinfo->satadrv_addr.cport)));
16459 		if (spx->txlt_buf_dma_handle != NULL) {
16460 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16461 			    DDI_DMA_SYNC_FORKERNEL);
16462 			ASSERT(rval == DDI_SUCCESS);
16463 			if (sata_check_for_dma_error(dip, spx)) {
16464 				ddi_fm_service_impact(dip,
16465 				    DDI_SERVICE_UNAFFECTED);
16466 				rval = -1;
16467 				goto fail;
16468 			}
16469 		}
16470 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
16471 		    sizeof (struct smart_data));
16472 	}
16473 
16474 fail:
16475 	/* Free allocated resources */
16476 	sata_free_local_buffer(spx);
16477 	sata_pkt_free(spx);
16478 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16479 
16480 	return (rval);
16481 }
16482 
16483 /*
16484  * Used by LOG SENSE page 0x10
16485  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
16486  * Note: cannot be called in the interrupt context.
16487  *
16488  * return 0 for success, -1 otherwise
16489  *
16490  */
16491 static int
16492 sata_ext_smart_selftest_read_log(
16493 	sata_hba_inst_t *sata_hba_inst,
16494 	sata_drive_info_t *sdinfo,
16495 	struct smart_ext_selftest_log *ext_selftest_log,
16496 	uint16_t block_num)
16497 {
16498 	sata_pkt_txlate_t *spx;
16499 	sata_pkt_t *spkt;
16500 	sata_cmd_t *scmd;
16501 	int rval;
16502 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
16503 
16504 #if ! defined(lint)
16505 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
16506 #endif
16507 
16508 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16509 	spx->txlt_sata_hba_inst = sata_hba_inst;
16510 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16511 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16512 	if (spkt == NULL) {
16513 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16514 		return (-1);
16515 	}
16516 	/* address is needed now */
16517 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16518 
16519 
16520 	/* Fill sata_pkt */
16521 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16522 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16523 	/* Synchronous mode, no callback */
16524 	spkt->satapkt_comp = NULL;
16525 	/* Timeout 30s */
16526 	spkt->satapkt_time = sata_default_pkt_time;
16527 
16528 	scmd = &spkt->satapkt_cmd;
16529 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16530 
16531 	/*
16532 	 * Allocate buffer for SMART extended self-test log
16533 	 */
16534 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16535 	    sizeof (struct smart_ext_selftest_log));
16536 	if (scmd->satacmd_bp == NULL) {
16537 		sata_pkt_free(spx);
16538 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16539 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16540 		    "sata_ext_smart_selftest_log: "
16541 		    "cannot allocate buffer"));
16542 		return (-1);
16543 	}
16544 
16545 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
16546 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16547 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
16548 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
16549 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
16550 	scmd->satacmd_lba_low_msb = 0;
16551 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
16552 	scmd->satacmd_lba_mid_msb = block_num >> 8;
16553 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16554 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16555 
16556 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16557 	    sdinfo->satadrv_addr.cport)));
16558 
16559 	/* Send pkt to SATA HBA driver */
16560 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16561 	    SATA_TRAN_ACCEPTED ||
16562 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16563 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16564 		    sdinfo->satadrv_addr.cport)));
16565 
16566 		/*
16567 		 * Whoops, no SMART selftest log info available
16568 		 */
16569 		rval = -1;
16570 		goto fail;
16571 	} else {
16572 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16573 		    sdinfo->satadrv_addr.cport)));
16574 
16575 		if (spx->txlt_buf_dma_handle != NULL) {
16576 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16577 			    DDI_DMA_SYNC_FORKERNEL);
16578 			ASSERT(rval == DDI_SUCCESS);
16579 			if (sata_check_for_dma_error(dip, spx)) {
16580 				ddi_fm_service_impact(dip,
16581 				    DDI_SERVICE_UNAFFECTED);
16582 				rval = -1;
16583 				goto fail;
16584 			}
16585 		}
16586 		bcopy(scmd->satacmd_bp->b_un.b_addr,
16587 		    (uint8_t *)ext_selftest_log,
16588 		    sizeof (struct smart_ext_selftest_log));
16589 		rval = 0;
16590 	}
16591 
16592 fail:
16593 	/* Free allocated resources */
16594 	sata_free_local_buffer(spx);
16595 	sata_pkt_free(spx);
16596 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16597 
16598 	return (rval);
16599 }
16600 
16601 /*
16602  * Returns 0 for success, -1 otherwise
16603  *
16604  * SMART self-test log data is returned in buffer pointed to by selftest_log
16605  */
16606 static int
16607 sata_smart_selftest_log(
16608 	sata_hba_inst_t *sata_hba_inst,
16609 	sata_drive_info_t *sdinfo,
16610 	struct smart_selftest_log *selftest_log)
16611 {
16612 	sata_pkt_t *spkt;
16613 	sata_cmd_t *scmd;
16614 	sata_pkt_txlate_t *spx;
16615 	int rval;
16616 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
16617 
16618 #if ! defined(lint)
16619 	ASSERT(sizeof (struct smart_selftest_log) == 512);
16620 #endif
16621 
16622 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16623 	spx->txlt_sata_hba_inst = sata_hba_inst;
16624 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16625 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16626 	if (spkt == NULL) {
16627 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16628 		return (-1);
16629 	}
16630 	/* address is needed now */
16631 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16632 
16633 
16634 	/* Fill sata_pkt */
16635 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16636 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16637 	/* Synchronous mode, no callback */
16638 	spkt->satapkt_comp = NULL;
16639 	/* Timeout 30s */
16640 	spkt->satapkt_time = sata_default_pkt_time;
16641 
16642 	scmd = &spkt->satapkt_cmd;
16643 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16644 
16645 	/*
16646 	 * Allocate buffer for SMART SELFTEST LOG
16647 	 */
16648 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16649 	    sizeof (struct smart_selftest_log));
16650 	if (scmd->satacmd_bp == NULL) {
16651 		sata_pkt_free(spx);
16652 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16653 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16654 		    "sata_smart_selftest_log: "
16655 		    "cannot allocate buffer"));
16656 		return (-1);
16657 	}
16658 
16659 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16660 	scmd->satacmd_addr_type = 0;		/* N/A */
16661 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
16662 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
16663 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16664 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16665 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16666 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16667 	scmd->satacmd_cmd_reg = SATAC_SMART;
16668 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16669 	    sdinfo->satadrv_addr.cport)));
16670 
16671 	/* Send pkt to SATA HBA driver */
16672 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16673 	    SATA_TRAN_ACCEPTED ||
16674 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16675 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16676 		    sdinfo->satadrv_addr.cport)));
16677 		/*
16678 		 * Whoops, no SMART DATA available
16679 		 */
16680 		rval = -1;
16681 		goto fail;
16682 	} else {
16683 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16684 		    sdinfo->satadrv_addr.cport)));
16685 		if (spx->txlt_buf_dma_handle != NULL) {
16686 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16687 			    DDI_DMA_SYNC_FORKERNEL);
16688 			ASSERT(rval == DDI_SUCCESS);
16689 			if (sata_check_for_dma_error(dip, spx)) {
16690 				ddi_fm_service_impact(dip,
16691 				    DDI_SERVICE_UNAFFECTED);
16692 				rval = -1;
16693 				goto fail;
16694 			}
16695 		}
16696 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
16697 		    sizeof (struct smart_selftest_log));
16698 		rval = 0;
16699 	}
16700 
16701 fail:
16702 	/* Free allocated resources */
16703 	sata_free_local_buffer(spx);
16704 	sata_pkt_free(spx);
16705 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16706 
16707 	return (rval);
16708 }
16709 
16710 
16711 /*
16712  * Returns 0 for success, -1 otherwise
16713  *
16714  * SMART READ LOG data is returned in buffer pointed to by smart_log
16715  */
16716 static int
16717 sata_smart_read_log(
16718 	sata_hba_inst_t *sata_hba_inst,
16719 	sata_drive_info_t *sdinfo,
16720 	uint8_t *smart_log,		/* where the data should be returned */
16721 	uint8_t which_log,		/* which log should be returned */
16722 	uint8_t log_size)		/* # of 512 bytes in log */
16723 {
16724 	sata_pkt_t *spkt;
16725 	sata_cmd_t *scmd;
16726 	sata_pkt_txlate_t *spx;
16727 	int rval;
16728 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
16729 
16730 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16731 	spx->txlt_sata_hba_inst = sata_hba_inst;
16732 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16733 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16734 	if (spkt == NULL) {
16735 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16736 		return (-1);
16737 	}
16738 	/* address is needed now */
16739 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16740 
16741 
16742 	/* Fill sata_pkt */
16743 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16744 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16745 	/* Synchronous mode, no callback */
16746 	spkt->satapkt_comp = NULL;
16747 	/* Timeout 30s */
16748 	spkt->satapkt_time = sata_default_pkt_time;
16749 
16750 	scmd = &spkt->satapkt_cmd;
16751 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16752 
16753 	/*
16754 	 * Allocate buffer for SMART READ LOG
16755 	 */
16756 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
16757 	if (scmd->satacmd_bp == NULL) {
16758 		sata_pkt_free(spx);
16759 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16760 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16761 		    "sata_smart_read_log: " "cannot allocate buffer"));
16762 		return (-1);
16763 	}
16764 
16765 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16766 	scmd->satacmd_addr_type = 0;		/* N/A */
16767 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
16768 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
16769 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16770 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16771 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16772 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16773 	scmd->satacmd_cmd_reg = SATAC_SMART;
16774 
16775 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16776 	    sdinfo->satadrv_addr.cport)));
16777 
16778 	/* Send pkt to SATA HBA driver */
16779 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16780 	    SATA_TRAN_ACCEPTED ||
16781 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16782 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16783 		    sdinfo->satadrv_addr.cport)));
16784 
16785 		/*
16786 		 * Whoops, no SMART DATA available
16787 		 */
16788 		rval = -1;
16789 		goto fail;
16790 	} else {
16791 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16792 		    sdinfo->satadrv_addr.cport)));
16793 
16794 		if (spx->txlt_buf_dma_handle != NULL) {
16795 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16796 			    DDI_DMA_SYNC_FORKERNEL);
16797 			ASSERT(rval == DDI_SUCCESS);
16798 			if (sata_check_for_dma_error(dip, spx)) {
16799 				ddi_fm_service_impact(dip,
16800 				    DDI_SERVICE_UNAFFECTED);
16801 				rval = -1;
16802 				goto fail;
16803 			}
16804 		}
16805 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
16806 		rval = 0;
16807 	}
16808 
16809 fail:
16810 	/* Free allocated resources */
16811 	sata_free_local_buffer(spx);
16812 	sata_pkt_free(spx);
16813 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16814 
16815 	return (rval);
16816 }
16817 
16818 /*
16819  * Used by LOG SENSE page 0x10
16820  *
16821  * return 0 for success, -1 otherwise
16822  *
16823  */
16824 static int
16825 sata_read_log_ext_directory(
16826 	sata_hba_inst_t *sata_hba_inst,
16827 	sata_drive_info_t *sdinfo,
16828 	struct read_log_ext_directory *logdir)
16829 {
16830 	sata_pkt_txlate_t *spx;
16831 	sata_pkt_t *spkt;
16832 	sata_cmd_t *scmd;
16833 	int rval;
16834 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
16835 
16836 #if ! defined(lint)
16837 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
16838 #endif
16839 
16840 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16841 	spx->txlt_sata_hba_inst = sata_hba_inst;
16842 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16843 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16844 	if (spkt == NULL) {
16845 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16846 		return (-1);
16847 	}
16848 
16849 	/* Fill sata_pkt */
16850 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16851 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16852 	/* Synchronous mode, no callback */
16853 	spkt->satapkt_comp = NULL;
16854 	/* Timeout 30s */
16855 	spkt->satapkt_time = sata_default_pkt_time;
16856 
16857 	scmd = &spkt->satapkt_cmd;
16858 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16859 
16860 	/*
16861 	 * Allocate buffer for SMART READ LOG EXTENDED command
16862 	 */
16863 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16864 	    sizeof (struct read_log_ext_directory));
16865 	if (scmd->satacmd_bp == NULL) {
16866 		sata_pkt_free(spx);
16867 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16868 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16869 		    "sata_read_log_ext_directory: "
16870 		    "cannot allocate buffer"));
16871 		return (-1);
16872 	}
16873 
16874 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
16875 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16876 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
16877 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
16878 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
16879 	scmd->satacmd_lba_low_msb = 0;
16880 	scmd->satacmd_lba_mid_lsb = 0;
16881 	scmd->satacmd_lba_mid_msb = 0;
16882 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16883 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16884 
16885 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16886 	    sdinfo->satadrv_addr.cport)));
16887 
16888 	/* Send pkt to SATA HBA driver */
16889 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16890 	    SATA_TRAN_ACCEPTED ||
16891 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16892 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16893 		    sdinfo->satadrv_addr.cport)));
16894 		/*
16895 		 * Whoops, no SMART selftest log info available
16896 		 */
16897 		rval = -1;
16898 		goto fail;
16899 	} else {
16900 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16901 		    sdinfo->satadrv_addr.cport)));
16902 		if (spx->txlt_buf_dma_handle != NULL) {
16903 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16904 			    DDI_DMA_SYNC_FORKERNEL);
16905 			ASSERT(rval == DDI_SUCCESS);
16906 			if (sata_check_for_dma_error(dip, spx)) {
16907 				ddi_fm_service_impact(dip,
16908 				    DDI_SERVICE_UNAFFECTED);
16909 				rval = -1;
16910 				goto fail;
16911 			}
16912 		}
16913 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
16914 		    sizeof (struct read_log_ext_directory));
16915 		rval = 0;
16916 	}
16917 
16918 fail:
16919 	/* Free allocated resources */
16920 	sata_free_local_buffer(spx);
16921 	sata_pkt_free(spx);
16922 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16923 
16924 	return (rval);
16925 }
16926 
16927 /*
16928  * Set up error retrieval sata command for NCQ command error data
16929  * recovery.
16930  *
16931  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
16932  * returns SATA_FAILURE otherwise.
16933  */
16934 static int
16935 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
16936 {
16937 #ifndef __lock_lint
16938 	_NOTE(ARGUNUSED(sdinfo))
16939 #endif
16940 
16941 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
16942 	sata_cmd_t *scmd;
16943 	struct buf *bp;
16944 
16945 	/* Operation modes are up to the caller */
16946 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16947 
16948 	/* Synchronous mode, no callback - may be changed by the caller */
16949 	spkt->satapkt_comp = NULL;
16950 	spkt->satapkt_time = sata_default_pkt_time;
16951 
16952 	scmd = &spkt->satapkt_cmd;
16953 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
16954 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
16955 
16956 	/*
16957 	 * Allocate dma_able buffer error data.
16958 	 * Buffer allocation will take care of buffer alignment and other DMA
16959 	 * attributes.
16960 	 */
16961 	bp = sata_alloc_local_buffer(spx,
16962 	    sizeof (struct sata_ncq_error_recovery_page));
16963 	if (bp == NULL)
16964 		return (SATA_FAILURE);
16965 
16966 	bp_mapin(bp); /* make data buffer accessible */
16967 	scmd->satacmd_bp = bp;
16968 
16969 	/*
16970 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
16971 	 * before accessing it. Handle is in usual place in translate struct.
16972 	 */
16973 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
16974 
16975 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
16976 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
16977 
16978 	return (SATA_SUCCESS);
16979 }
16980 
16981 /*
16982  * sata_xlate_errors() is used to translate (S)ATA error
16983  * information to SCSI information returned in the SCSI
16984  * packet.
16985  */
16986 static void
16987 sata_xlate_errors(sata_pkt_txlate_t *spx)
16988 {
16989 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
16990 	struct scsi_extended_sense *sense;
16991 
16992 	scsipkt->pkt_reason = CMD_INCOMPLETE;
16993 	*scsipkt->pkt_scbp = STATUS_CHECK;
16994 	sense = sata_arq_sense(spx);
16995 
16996 	switch (spx->txlt_sata_pkt->satapkt_reason) {
16997 	case SATA_PKT_PORT_ERROR:
16998 		/*
16999 		 * We have no device data. Assume no data transfered.
17000 		 */
17001 		sense->es_key = KEY_HARDWARE_ERROR;
17002 		break;
17003 
17004 	case SATA_PKT_DEV_ERROR:
17005 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
17006 		    SATA_STATUS_ERR) {
17007 			/*
17008 			 * determine dev error reason from error
17009 			 * reg content
17010 			 */
17011 			sata_decode_device_error(spx, sense);
17012 			break;
17013 		}
17014 		/* No extended sense key - no info available */
17015 		break;
17016 
17017 	case SATA_PKT_TIMEOUT:
17018 		scsipkt->pkt_reason = CMD_TIMEOUT;
17019 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
17020 		/* No extended sense key */
17021 		break;
17022 
17023 	case SATA_PKT_ABORTED:
17024 		scsipkt->pkt_reason = CMD_ABORTED;
17025 		scsipkt->pkt_statistics |= STAT_ABORTED;
17026 		/* No extended sense key */
17027 		break;
17028 
17029 	case SATA_PKT_RESET:
17030 		/*
17031 		 * pkt aborted either by an explicit reset request from
17032 		 * a host, or due to error recovery
17033 		 */
17034 		scsipkt->pkt_reason = CMD_RESET;
17035 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
17036 		break;
17037 
17038 	default:
17039 		scsipkt->pkt_reason = CMD_TRAN_ERR;
17040 		break;
17041 	}
17042 }
17043 
17044 
17045 
17046 
17047 /*
17048  * Log sata message
17049  * dev pathname msg line preceeds the logged message.
17050  */
17051 
17052 static	void
17053 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
17054 {
17055 	char pathname[128];
17056 	dev_info_t *dip = NULL;
17057 	va_list ap;
17058 
17059 	mutex_enter(&sata_log_mutex);
17060 
17061 	va_start(ap, fmt);
17062 	(void) vsprintf(sata_log_buf, fmt, ap);
17063 	va_end(ap);
17064 
17065 	if (sata_hba_inst != NULL) {
17066 		dip = SATA_DIP(sata_hba_inst);
17067 		(void) ddi_pathname(dip, pathname);
17068 	} else {
17069 		pathname[0] = 0;
17070 	}
17071 	if (level == CE_CONT) {
17072 		if (sata_debug_flags == 0)
17073 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
17074 		else
17075 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
17076 	} else {
17077 		if (level != CE_NOTE) {
17078 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
17079 		} else if (sata_msg) {
17080 			cmn_err(level, "%s:\n %s", pathname,
17081 			    sata_log_buf);
17082 		}
17083 	}
17084 
17085 	/* sata trace debug */
17086 	sata_trace_debug(dip, sata_log_buf);
17087 
17088 	mutex_exit(&sata_log_mutex);
17089 }
17090 
17091 
17092 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
17093 
17094 /*
17095  * Start or terminate the thread, depending on flag arg and current state
17096  */
17097 static void
17098 sata_event_thread_control(int startstop)
17099 {
17100 	static 	int sata_event_thread_terminating = 0;
17101 	static 	int sata_event_thread_starting = 0;
17102 	int i;
17103 
17104 	mutex_enter(&sata_event_mutex);
17105 
17106 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
17107 	    sata_event_thread_terminating == 1)) {
17108 		mutex_exit(&sata_event_mutex);
17109 		return;
17110 	}
17111 	if (startstop == 1 && sata_event_thread_starting == 1) {
17112 		mutex_exit(&sata_event_mutex);
17113 		return;
17114 	}
17115 	if (startstop == 1 && sata_event_thread_terminating == 1) {
17116 		sata_event_thread_starting = 1;
17117 		/* wait til terminate operation completes */
17118 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
17119 		while (sata_event_thread_terminating == 1) {
17120 			if (i-- <= 0) {
17121 				sata_event_thread_starting = 0;
17122 				mutex_exit(&sata_event_mutex);
17123 #ifdef SATA_DEBUG
17124 				cmn_err(CE_WARN, "sata_event_thread_control: "
17125 				    "timeout waiting for thread to terminate");
17126 #endif
17127 				return;
17128 			}
17129 			mutex_exit(&sata_event_mutex);
17130 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
17131 			mutex_enter(&sata_event_mutex);
17132 		}
17133 	}
17134 	if (startstop == 1) {
17135 		if (sata_event_thread == NULL) {
17136 			sata_event_thread = thread_create(NULL, 0,
17137 			    (void (*)())sata_event_daemon,
17138 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
17139 		}
17140 		sata_event_thread_starting = 0;
17141 		mutex_exit(&sata_event_mutex);
17142 		return;
17143 	}
17144 
17145 	/*
17146 	 * If we got here, thread may need to be terminated
17147 	 */
17148 	if (sata_event_thread != NULL) {
17149 		int i;
17150 		/* Signal event thread to go away */
17151 		sata_event_thread_terminating = 1;
17152 		sata_event_thread_terminate = 1;
17153 		cv_signal(&sata_event_cv);
17154 		/*
17155 		 * Wait til daemon terminates.
17156 		 */
17157 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
17158 		while (sata_event_thread_terminate == 1) {
17159 			mutex_exit(&sata_event_mutex);
17160 			if (i-- <= 0) {
17161 				/* Daemon did not go away !!! */
17162 #ifdef SATA_DEBUG
17163 				cmn_err(CE_WARN, "sata_event_thread_control: "
17164 				    "cannot terminate event daemon thread");
17165 #endif
17166 				mutex_enter(&sata_event_mutex);
17167 				break;
17168 			}
17169 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
17170 			mutex_enter(&sata_event_mutex);
17171 		}
17172 		sata_event_thread_terminating = 0;
17173 	}
17174 	ASSERT(sata_event_thread_terminating == 0);
17175 	ASSERT(sata_event_thread_starting == 0);
17176 	mutex_exit(&sata_event_mutex);
17177 }
17178 
17179 
17180 /*
17181  * SATA HBA event notification function.
17182  * Events reported by SATA HBA drivers per HBA instance relate to a change in
17183  * a port and/or device state or a controller itself.
17184  * Events for different addresses/addr types cannot be combined.
17185  * A warning message is generated for each event type.
17186  * Events are not processed by this function, so only the
17187  * event flag(s)is set for an affected entity and the event thread is
17188  * waken up. Event daemon thread processes all events.
17189  *
17190  * NOTE: Since more than one event may be reported at the same time, one
17191  * cannot determine a sequence of events when opposite event are reported, eg.
17192  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
17193  * is taking precedence over reported events, i.e. may cause ignoring some
17194  * events.
17195  */
17196 #define	SATA_EVENT_MAX_MSG_LENGTH	79
17197 
17198 void
17199 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
17200 {
17201 	sata_hba_inst_t *sata_hba_inst = NULL;
17202 	sata_address_t *saddr;
17203 	sata_pmult_info_t *pmultinfo;
17204 	sata_drive_info_t *sdinfo;
17205 	sata_port_stats_t *pstats;
17206 	sata_cport_info_t *cportinfo;
17207 	sata_pmport_info_t *pmportinfo;
17208 	int cport, pmport;
17209 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
17210 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
17211 	char *lcp;
17212 	static char *err_msg_evnt_1 =
17213 	    "sata_hba_event_notify: invalid port event 0x%x ";
17214 	static char *err_msg_evnt_2 =
17215 	    "sata_hba_event_notify: invalid device event 0x%x ";
17216 	int linkevent;
17217 
17218 	/*
17219 	 * There is a possibility that an event will be generated on HBA
17220 	 * that has not completed attachment or is detaching. We still want
17221 	 * to process events until HBA is detached.
17222 	 */
17223 	mutex_enter(&sata_mutex);
17224 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17225 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17226 		if (SATA_DIP(sata_hba_inst) == dip)
17227 			if (sata_hba_inst->satahba_attached == 1)
17228 				break;
17229 	}
17230 	mutex_exit(&sata_mutex);
17231 	if (sata_hba_inst == NULL)
17232 		/* HBA not attached */
17233 		return;
17234 
17235 	ASSERT(sata_device != NULL);
17236 
17237 	/*
17238 	 * Validate address before - do not proceed with invalid address.
17239 	 */
17240 	saddr = &sata_device->satadev_addr;
17241 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
17242 		return;
17243 
17244 	cport = saddr->cport;
17245 	pmport = saddr->pmport;
17246 
17247 	buf1[0] = buf2[0] = '\0';
17248 
17249 	/*
17250 	 * If event relates to port or device, check port state.
17251 	 * Port has to be initialized, or we cannot accept an event.
17252 	 */
17253 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
17254 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT | SATA_ADDR_PMULT)) != 0) {
17255 		mutex_enter(&sata_hba_inst->satahba_mutex);
17256 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17257 		mutex_exit(&sata_hba_inst->satahba_mutex);
17258 		if (cportinfo == NULL || cportinfo->cport_state == 0)
17259 			return;
17260 	}
17261 
17262 	if ((saddr->qual & (SATA_ADDR_PMULT | SATA_ADDR_PMPORT |
17263 	    SATA_ADDR_DPMPORT)) != 0) {
17264 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
17265 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17266 			    "sata_hba_event_notify: Non-pmult device (0x%x)"
17267 			    "is attached to port %d, ignore pmult/pmport "
17268 			    "event 0x%x", cportinfo->cport_dev_type,
17269 			    cport, event));
17270 			return;
17271 		}
17272 
17273 		mutex_enter(&cportinfo->cport_mutex);
17274 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17275 		mutex_exit(&cportinfo->cport_mutex);
17276 
17277 		/*
17278 		 * The daemon might be processing attachment of port
17279 		 * multiplier, in that case we should ignore events on its
17280 		 * sub-devices.
17281 		 *
17282 		 * NOTE: Only pmult_state is checked in sata_hba_event_notify.
17283 		 * The pmport_state is checked by sata daemon.
17284 		 */
17285 		if (pmultinfo == NULL ||
17286 		    pmultinfo->pmult_state == SATA_STATE_UNKNOWN) {
17287 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17288 			    "sata_hba_event_notify: pmult is not"
17289 			    "available at port %d:%d, ignore event 0x%x",
17290 			    cport, pmport, event));
17291 			return;
17292 		}
17293 	}
17294 
17295 	if ((saddr->qual &
17296 	    (SATA_ADDR_PMPORT | SATA_ADDR_DPMPORT)) != 0) {
17297 
17298 		mutex_enter(&cportinfo->cport_mutex);
17299 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport)) {
17300 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17301 			    "sata_hba_event_notify: invalid/"
17302 			    "un-implemented port %d:%d (%d ports), "
17303 			    "ignore event 0x%x", cport, pmport,
17304 			    SATA_NUM_PMPORTS(sata_hba_inst, cport), event));
17305 			mutex_exit(&cportinfo->cport_mutex);
17306 			return;
17307 		}
17308 		mutex_exit(&cportinfo->cport_mutex);
17309 
17310 		mutex_enter(&sata_hba_inst->satahba_mutex);
17311 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17312 		    cport, pmport);
17313 		mutex_exit(&sata_hba_inst->satahba_mutex);
17314 
17315 		/* pmport is implemented/valid? */
17316 		if (pmportinfo == NULL) {
17317 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17318 			    "sata_hba_event_notify: invalid/"
17319 			    "un-implemented port %d:%d, ignore "
17320 			    "event 0x%x", cport, pmport, event));
17321 			return;
17322 		}
17323 	}
17324 
17325 	/*
17326 	 * Events refer to devices, ports and controllers - each has
17327 	 * unique address. Events for different addresses cannot be combined.
17328 	 */
17329 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
17330 
17331 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17332 
17333 		/* qualify this event(s) */
17334 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
17335 			/* Invalid event for the device port */
17336 			(void) sprintf(buf2, err_msg_evnt_1,
17337 			    event & SATA_EVNT_PORT_EVENTS);
17338 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17339 			goto event_info;
17340 		}
17341 		if (saddr->qual == SATA_ADDR_CPORT) {
17342 			/* Controller's device port event */
17343 
17344 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
17345 			    cport_event_flags |=
17346 			    event & SATA_EVNT_PORT_EVENTS;
17347 			pstats =
17348 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
17349 			    cport_stats;
17350 		} else {
17351 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17352 			mutex_enter(&pmportinfo->pmport_mutex);
17353 			/* Port multiplier's device port event */
17354 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17355 			    pmport_event_flags |=
17356 			    event & SATA_EVNT_PORT_EVENTS;
17357 			pstats =
17358 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17359 			    pmport_stats;
17360 			mutex_exit(&pmportinfo->pmport_mutex);
17361 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17362 		}
17363 
17364 		/*
17365 		 * Add to statistics and log the message. We have to do it
17366 		 * here rather than in the event daemon, because there may be
17367 		 * multiple events occuring before they are processed.
17368 		 */
17369 		linkevent = event &
17370 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
17371 		if (linkevent) {
17372 			if (linkevent == (SATA_EVNT_LINK_LOST |
17373 			    SATA_EVNT_LINK_ESTABLISHED)) {
17374 				/* This is likely event combination */
17375 				(void) strlcat(buf1, "link lost/established, ",
17376 				    SATA_EVENT_MAX_MSG_LENGTH);
17377 
17378 				if (pstats->link_lost < 0xffffffffffffffffULL)
17379 					pstats->link_lost++;
17380 				if (pstats->link_established <
17381 				    0xffffffffffffffffULL)
17382 					pstats->link_established++;
17383 				linkevent = 0;
17384 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
17385 				(void) strlcat(buf1, "link lost, ",
17386 				    SATA_EVENT_MAX_MSG_LENGTH);
17387 
17388 				if (pstats->link_lost < 0xffffffffffffffffULL)
17389 					pstats->link_lost++;
17390 			} else {
17391 				(void) strlcat(buf1, "link established, ",
17392 				    SATA_EVENT_MAX_MSG_LENGTH);
17393 				if (pstats->link_established <
17394 				    0xffffffffffffffffULL)
17395 					pstats->link_established++;
17396 			}
17397 		}
17398 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
17399 			(void) strlcat(buf1, "device attached, ",
17400 			    SATA_EVENT_MAX_MSG_LENGTH);
17401 			if (pstats->device_attached < 0xffffffffffffffffULL)
17402 				pstats->device_attached++;
17403 		}
17404 		if (event & SATA_EVNT_DEVICE_DETACHED) {
17405 			(void) strlcat(buf1, "device detached, ",
17406 			    SATA_EVENT_MAX_MSG_LENGTH);
17407 			if (pstats->device_detached < 0xffffffffffffffffULL)
17408 				pstats->device_detached++;
17409 		}
17410 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
17411 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17412 			    "port %d power level changed", cport);
17413 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
17414 				pstats->port_pwr_changed++;
17415 		}
17416 
17417 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
17418 			/* There should be no other events for this address */
17419 			(void) sprintf(buf2, err_msg_evnt_1,
17420 			    event & ~SATA_EVNT_PORT_EVENTS);
17421 		}
17422 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17423 
17424 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
17425 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17426 
17427 		/* qualify this event */
17428 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
17429 			/* Invalid event for a device */
17430 			(void) sprintf(buf2, err_msg_evnt_2,
17431 			    event & SATA_EVNT_DEVICE_RESET);
17432 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17433 			goto event_info;
17434 		}
17435 		/* drive event */
17436 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
17437 		if (sdinfo != NULL) {
17438 			if (event & SATA_EVNT_DEVICE_RESET) {
17439 				(void) strlcat(buf1, "device reset, ",
17440 				    SATA_EVENT_MAX_MSG_LENGTH);
17441 				if (sdinfo->satadrv_stats.drive_reset <
17442 				    0xffffffffffffffffULL)
17443 					sdinfo->satadrv_stats.drive_reset++;
17444 				sdinfo->satadrv_event_flags |=
17445 				    SATA_EVNT_DEVICE_RESET;
17446 			}
17447 		}
17448 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
17449 			/* Invalid event for a device */
17450 			(void) sprintf(buf2, err_msg_evnt_2,
17451 			    event & ~SATA_EVNT_DRIVE_EVENTS);
17452 		}
17453 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17454 	} else if (saddr->qual == SATA_ADDR_PMULT) {
17455 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17456 
17457 		/* qualify this event */
17458 		if ((event & (SATA_EVNT_DEVICE_RESET |
17459 		    SATA_EVNT_PMULT_LINK_CHANGED)) == 0) {
17460 			/* Invalid event for a port multiplier */
17461 			(void) sprintf(buf2, err_msg_evnt_2,
17462 			    event & SATA_EVNT_DEVICE_RESET);
17463 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17464 			goto event_info;
17465 		}
17466 
17467 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17468 
17469 		if (event & SATA_EVNT_DEVICE_RESET) {
17470 
17471 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17472 			    "[Reset] port-mult on cport %d", cport);
17473 			pmultinfo->pmult_event_flags |=
17474 			    SATA_EVNT_DEVICE_RESET;
17475 			(void) strlcat(buf1, "pmult reset, ",
17476 			    SATA_EVENT_MAX_MSG_LENGTH);
17477 		}
17478 
17479 		if (event & SATA_EVNT_PMULT_LINK_CHANGED) {
17480 
17481 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17482 			    "pmult link changed on cport %d", cport);
17483 			pmultinfo->pmult_event_flags |=
17484 			    SATA_EVNT_PMULT_LINK_CHANGED;
17485 			(void) strlcat(buf1, "pmult link changed, ",
17486 			    SATA_EVENT_MAX_MSG_LENGTH);
17487 		}
17488 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17489 
17490 	} else {
17491 		if (saddr->qual != SATA_ADDR_NULL) {
17492 			/* Wrong address qualifier */
17493 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17494 			    "sata_hba_event_notify: invalid address 0x%x",
17495 			    *(uint32_t *)saddr));
17496 			return;
17497 		}
17498 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
17499 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
17500 			/* Invalid event for the controller */
17501 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17502 			    "sata_hba_event_notify: invalid event 0x%x for "
17503 			    "controller",
17504 			    event & SATA_EVNT_CONTROLLER_EVENTS));
17505 			return;
17506 		}
17507 		buf1[0] = '\0';
17508 		/* This may be a frequent and not interesting event */
17509 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17510 		    "controller power level changed\n", NULL);
17511 
17512 		mutex_enter(&sata_hba_inst->satahba_mutex);
17513 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
17514 		    0xffffffffffffffffULL)
17515 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
17516 
17517 		sata_hba_inst->satahba_event_flags |=
17518 		    SATA_EVNT_PWR_LEVEL_CHANGED;
17519 		mutex_exit(&sata_hba_inst->satahba_mutex);
17520 	}
17521 	/*
17522 	 * If we got here, there is something to do with this HBA
17523 	 * instance.
17524 	 */
17525 	mutex_enter(&sata_hba_inst->satahba_mutex);
17526 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17527 	mutex_exit(&sata_hba_inst->satahba_mutex);
17528 	mutex_enter(&sata_mutex);
17529 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
17530 	mutex_exit(&sata_mutex);
17531 
17532 	/* Tickle event thread */
17533 	mutex_enter(&sata_event_mutex);
17534 	if (sata_event_thread_active == 0)
17535 		cv_signal(&sata_event_cv);
17536 	mutex_exit(&sata_event_mutex);
17537 
17538 event_info:
17539 	if (buf1[0] != '\0') {
17540 		lcp = strrchr(buf1, ',');
17541 		if (lcp != NULL)
17542 			*lcp = '\0';
17543 	}
17544 	if (saddr->qual == SATA_ADDR_CPORT ||
17545 	    saddr->qual == SATA_ADDR_DCPORT) {
17546 		if (buf1[0] != '\0') {
17547 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17548 			    cport, buf1);
17549 		}
17550 		if (buf2[0] != '\0') {
17551 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17552 			    cport, buf2);
17553 		}
17554 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
17555 	    saddr->qual == SATA_ADDR_DPMPORT) {
17556 		if (buf1[0] != '\0') {
17557 			sata_log(sata_hba_inst, CE_NOTE,
17558 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
17559 		}
17560 		if (buf2[0] != '\0') {
17561 			sata_log(sata_hba_inst, CE_NOTE,
17562 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
17563 		}
17564 	}
17565 }
17566 
17567 
17568 /*
17569  * Event processing thread.
17570  * Arg is a pointer to the sata_hba_list pointer.
17571  * It is not really needed, because sata_hba_list is global and static
17572  */
17573 static void
17574 sata_event_daemon(void *arg)
17575 {
17576 #ifndef __lock_lint
17577 	_NOTE(ARGUNUSED(arg))
17578 #endif
17579 	sata_hba_inst_t *sata_hba_inst;
17580 	clock_t delta;
17581 
17582 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17583 	    "SATA event daemon started\n", NULL);
17584 loop:
17585 	/*
17586 	 * Process events here. Walk through all registered HBAs
17587 	 */
17588 	mutex_enter(&sata_mutex);
17589 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17590 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17591 		ASSERT(sata_hba_inst != NULL);
17592 		mutex_enter(&sata_hba_inst->satahba_mutex);
17593 		if (sata_hba_inst->satahba_attached == 0 ||
17594 		    (sata_hba_inst->satahba_event_flags &
17595 		    SATA_EVNT_SKIP) != 0) {
17596 			mutex_exit(&sata_hba_inst->satahba_mutex);
17597 			continue;
17598 		}
17599 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
17600 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
17601 			mutex_exit(&sata_hba_inst->satahba_mutex);
17602 			mutex_exit(&sata_mutex);
17603 			/* Got the controller with pending event */
17604 			sata_process_controller_events(sata_hba_inst);
17605 			/*
17606 			 * Since global mutex was released, there is a
17607 			 * possibility that HBA list has changed, so start
17608 			 * over from the top. Just processed controller
17609 			 * will be passed-over because of the SKIP flag.
17610 			 */
17611 			goto loop;
17612 		}
17613 		mutex_exit(&sata_hba_inst->satahba_mutex);
17614 	}
17615 	/* Clear SKIP flag in all controllers */
17616 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17617 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17618 		mutex_enter(&sata_hba_inst->satahba_mutex);
17619 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
17620 		mutex_exit(&sata_hba_inst->satahba_mutex);
17621 	}
17622 	mutex_exit(&sata_mutex);
17623 
17624 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17625 	    "SATA EVENT DAEMON suspending itself", NULL);
17626 
17627 #ifdef SATA_DEBUG
17628 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
17629 		sata_log(sata_hba_inst, CE_WARN,
17630 		    "SATA EVENTS PROCESSING DISABLED\n");
17631 		thread_exit(); /* Daemon will not run again */
17632 	}
17633 #endif
17634 	mutex_enter(&sata_event_mutex);
17635 	sata_event_thread_active = 0;
17636 	mutex_exit(&sata_event_mutex);
17637 	/*
17638 	 * Go to sleep/suspend itself and wake up either because new event or
17639 	 * wait timeout. Exit if there is a termination request (driver
17640 	 * unload).
17641 	 */
17642 	delta = drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
17643 	do {
17644 		mutex_enter(&sata_event_mutex);
17645 		(void) cv_reltimedwait(&sata_event_cv, &sata_event_mutex,
17646 		    delta, TR_CLOCK_TICK);
17647 
17648 		if (sata_event_thread_active != 0) {
17649 			mutex_exit(&sata_event_mutex);
17650 			continue;
17651 		}
17652 
17653 		/* Check if it is time to go away */
17654 		if (sata_event_thread_terminate == 1) {
17655 			/*
17656 			 * It is up to the thread setting above flag to make
17657 			 * sure that this thread is not killed prematurely.
17658 			 */
17659 			sata_event_thread_terminate = 0;
17660 			sata_event_thread = NULL;
17661 			mutex_exit(&sata_event_mutex);
17662 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17663 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
17664 			thread_exit();  { _NOTE(NOT_REACHED) }
17665 		}
17666 		mutex_exit(&sata_event_mutex);
17667 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
17668 
17669 	mutex_enter(&sata_event_mutex);
17670 	sata_event_thread_active = 1;
17671 	mutex_exit(&sata_event_mutex);
17672 
17673 	mutex_enter(&sata_mutex);
17674 	sata_event_pending &= ~SATA_EVNT_MAIN;
17675 	mutex_exit(&sata_mutex);
17676 
17677 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17678 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
17679 
17680 	goto loop;
17681 }
17682 
17683 /*
17684  * Specific HBA instance event processing.
17685  *
17686  * NOTE: At the moment, device event processing is limited to hard disks
17687  * only.
17688  * Port multiplier is supported now.
17689  */
17690 static void
17691 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
17692 {
17693 	int ncport;
17694 	uint32_t event_flags;
17695 	sata_address_t *saddr;
17696 	sata_cport_info_t *cportinfo;
17697 	sata_pmult_info_t *pmultinfo;
17698 
17699 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
17700 	    "Processing controller %d event(s)",
17701 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
17702 
17703 	mutex_enter(&sata_hba_inst->satahba_mutex);
17704 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
17705 	event_flags = sata_hba_inst->satahba_event_flags;
17706 	mutex_exit(&sata_hba_inst->satahba_mutex);
17707 	/*
17708 	 * Process controller power change first
17709 	 * HERE
17710 	 */
17711 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
17712 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
17713 
17714 	/*
17715 	 * Search through ports/devices to identify affected port/device.
17716 	 * We may have to process events for more than one port/device.
17717 	 */
17718 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
17719 		/*
17720 		 * Not all ports may be processed in attach by the time we
17721 		 * get an event. Check if port info is initialized.
17722 		 */
17723 		mutex_enter(&sata_hba_inst->satahba_mutex);
17724 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
17725 		mutex_exit(&sata_hba_inst->satahba_mutex);
17726 		if (cportinfo == NULL || cportinfo->cport_state == NULL)
17727 			continue;
17728 
17729 		/* We have initialized controller port info */
17730 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17731 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
17732 		    cport_event_flags;
17733 		/* Check if port was locked by IOCTL processing */
17734 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
17735 			/*
17736 			 * We ignore port events because port is busy
17737 			 * with AP control processing. Set again
17738 			 * controller and main event flag, so that
17739 			 * events may be processed by the next daemon
17740 			 * run.
17741 			 */
17742 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17743 			mutex_enter(&sata_hba_inst->satahba_mutex);
17744 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17745 			mutex_exit(&sata_hba_inst->satahba_mutex);
17746 			mutex_enter(&sata_mutex);
17747 			sata_event_pending |= SATA_EVNT_MAIN;
17748 			mutex_exit(&sata_mutex);
17749 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
17750 			    "Event processing postponed until "
17751 			    "AP control processing completes",
17752 			    NULL);
17753 			/* Check other ports */
17754 			continue;
17755 		} else {
17756 			/*
17757 			 * Set BSY flag so that AP control would not
17758 			 * interfere with events processing for
17759 			 * this port.
17760 			 */
17761 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17762 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
17763 		}
17764 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17765 
17766 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
17767 
17768 		if ((event_flags &
17769 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17770 			/*
17771 			 * Got port event.
17772 			 * We need some hierarchy of event processing as they
17773 			 * are affecting each other:
17774 			 * 1. port failed
17775 			 * 2. device detached/attached
17776 			 * 3. link events - link events may trigger device
17777 			 *    detached or device attached events in some
17778 			 *    circumstances.
17779 			 * 4. port power level changed
17780 			 */
17781 			if (event_flags & SATA_EVNT_PORT_FAILED) {
17782 				sata_process_port_failed_event(sata_hba_inst,
17783 				    saddr);
17784 			}
17785 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17786 				sata_process_device_detached(sata_hba_inst,
17787 				    saddr);
17788 			}
17789 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17790 				sata_process_device_attached(sata_hba_inst,
17791 				    saddr);
17792 			}
17793 			if (event_flags &
17794 			    (SATA_EVNT_LINK_ESTABLISHED |
17795 			    SATA_EVNT_LINK_LOST)) {
17796 				sata_process_port_link_events(sata_hba_inst,
17797 				    saddr);
17798 			}
17799 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
17800 				sata_process_port_pwr_change(sata_hba_inst,
17801 				    saddr);
17802 			}
17803 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17804 				sata_process_target_node_cleanup(
17805 				    sata_hba_inst, saddr);
17806 			}
17807 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
17808 				sata_process_device_autoonline(
17809 				    sata_hba_inst, saddr);
17810 			}
17811 		}
17812 
17813 
17814 		/*
17815 		 * Scan port multiplier and all its sub-ports event flags.
17816 		 * The events are marked by
17817 		 * (1) sata_pmult_info.pmult_event_flags
17818 		 * (2) sata_pmport_info.pmport_event_flags
17819 		 */
17820 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17821 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
17822 			/*
17823 			 * There should be another extra check: this
17824 			 * port multiplier still exists?
17825 			 */
17826 			pmultinfo = SATA_PMULT_INFO(sata_hba_inst,
17827 			    ncport);
17828 
17829 			if (pmultinfo != NULL) {
17830 				mutex_exit(&(SATA_CPORT_MUTEX(
17831 				    sata_hba_inst, ncport)));
17832 				sata_process_pmult_events(
17833 				    sata_hba_inst, ncport);
17834 				mutex_enter(&(SATA_CPORT_MUTEX(
17835 				    sata_hba_inst, ncport)));
17836 			} else {
17837 				SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17838 				    "Port-multiplier is gone. "
17839 				    "Ignore all sub-device events "
17840 				    "at port %d.", ncport);
17841 			}
17842 		}
17843 
17844 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
17845 		    SATA_DTYPE_NONE) &&
17846 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
17847 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
17848 			    satadrv_event_flags &
17849 			    (SATA_EVNT_DEVICE_RESET |
17850 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17851 				/* Have device event */
17852 				sata_process_device_reset(sata_hba_inst,
17853 				    saddr);
17854 			}
17855 		}
17856 		/* Release PORT_BUSY flag */
17857 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17858 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17859 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17860 
17861 	} /* End of loop through the controller SATA ports */
17862 }
17863 
17864 /*
17865  * Specific port multiplier instance event processing. At the moment, device
17866  * event processing is limited to link/attach event only.
17867  *
17868  * NOTE: power management event is not supported yet.
17869  */
17870 static void
17871 sata_process_pmult_events(sata_hba_inst_t *sata_hba_inst, uint8_t cport)
17872 {
17873 	sata_cport_info_t *cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17874 	sata_pmult_info_t *pmultinfo;
17875 	sata_pmport_info_t *pmportinfo;
17876 	sata_address_t *saddr;
17877 	sata_device_t sata_device;
17878 	uint32_t event_flags;
17879 	int npmport;
17880 	int rval;
17881 
17882 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17883 	    "Processing pmult event(s) on cport %d of controller %d",
17884 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17885 
17886 	/* First process events on port multiplier */
17887 	mutex_enter(&cportinfo->cport_mutex);
17888 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17889 	event_flags = pmultinfo->pmult_event_flags;
17890 
17891 	/*
17892 	 * Reset event (of port multiplier) has higher priority because the
17893 	 * port multiplier itself might be failed or removed after reset.
17894 	 */
17895 	if (event_flags & SATA_EVNT_DEVICE_RESET) {
17896 		/*
17897 		 * The status of the sub-links are uncertain,
17898 		 * so mark all sub-ports as RESET
17899 		 */
17900 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(
17901 		    sata_hba_inst, cport); npmport ++) {
17902 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17903 			    cport, npmport);
17904 			if (pmportinfo == NULL) {
17905 				/* That's weird. */
17906 				SATA_LOG_D((sata_hba_inst, CE_WARN,
17907 				    "sata_hba_event_notify: "
17908 				    "invalid/un-implemented "
17909 				    "port %d:%d (%d ports), ",
17910 				    cport, npmport, SATA_NUM_PMPORTS(
17911 				    sata_hba_inst, cport)));
17912 				continue;
17913 			}
17914 
17915 			mutex_enter(&pmportinfo->pmport_mutex);
17916 
17917 			/* Mark all pmport to unknow state. */
17918 			pmportinfo->pmport_state = SATA_STATE_UNKNOWN;
17919 			/* Mark all pmports with link events. */
17920 			pmportinfo->pmport_event_flags =
17921 			    (SATA_EVNT_LINK_ESTABLISHED|SATA_EVNT_LINK_LOST);
17922 			mutex_exit(&pmportinfo->pmport_mutex);
17923 		}
17924 
17925 	} else if (event_flags & SATA_EVNT_PMULT_LINK_CHANGED) {
17926 		/*
17927 		 * We need probe the port multiplier to know what has
17928 		 * happened.
17929 		 */
17930 		bzero(&sata_device, sizeof (sata_device_t));
17931 		sata_device.satadev_rev = SATA_DEVICE_REV;
17932 		sata_device.satadev_addr.cport = cport;
17933 		sata_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
17934 		sata_device.satadev_addr.qual = SATA_ADDR_PMULT;
17935 
17936 		mutex_exit(&cportinfo->cport_mutex);
17937 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17938 		    (SATA_DIP(sata_hba_inst), &sata_device);
17939 		mutex_enter(&cportinfo->cport_mutex);
17940 		if (rval != SATA_SUCCESS) {
17941 			/* Something went wrong? Fail the port */
17942 			cportinfo->cport_state = SATA_PSTATE_FAILED;
17943 			mutex_exit(&cportinfo->cport_mutex);
17944 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17945 			    "SATA port %d probing failed", cport));
17946 
17947 			/* PMult structure must be released.  */
17948 			sata_free_pmult(sata_hba_inst, &sata_device);
17949 			return;
17950 		}
17951 
17952 		sata_update_port_info(sata_hba_inst, &sata_device);
17953 
17954 		/*
17955 		 * Sanity check - Port is active? Is the link active?
17956 		 * The device is still a port multiplier?
17957 		 */
17958 		if ((cportinfo->cport_state &
17959 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
17960 		    ((cportinfo->cport_scr.sstatus &
17961 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) ||
17962 		    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
17963 			mutex_exit(&cportinfo->cport_mutex);
17964 
17965 			/* PMult structure must be released.  */
17966 			sata_free_pmult(sata_hba_inst, &sata_device);
17967 			return;
17968 		}
17969 
17970 		/* Probed succeed, set port ready. */
17971 		cportinfo->cport_state |=
17972 		    SATA_STATE_PROBED | SATA_STATE_READY;
17973 	}
17974 
17975 	/* Release port multiplier event flags. */
17976 	pmultinfo->pmult_event_flags &=
17977 	    ~(SATA_EVNT_DEVICE_RESET|SATA_EVNT_PMULT_LINK_CHANGED);
17978 	mutex_exit(&cportinfo->cport_mutex);
17979 
17980 	/*
17981 	 * Check all sub-links.
17982 	 */
17983 	for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst, cport);
17984 	    npmport ++) {
17985 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
17986 		mutex_enter(&pmportinfo->pmport_mutex);
17987 		event_flags = pmportinfo->pmport_event_flags;
17988 		mutex_exit(&pmportinfo->pmport_mutex);
17989 		saddr = &pmportinfo->pmport_addr;
17990 
17991 		if ((event_flags &
17992 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17993 			/*
17994 			 * Got port multiplier port event.
17995 			 * We need some hierarchy of event processing as they
17996 			 * are affecting each other:
17997 			 * 1. device detached/attached
17998 			 * 2. link events - link events may trigger device
17999 			 *    detached or device attached events in some
18000 			 *    circumstances.
18001 			 */
18002 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
18003 				sata_process_pmdevice_detached(sata_hba_inst,
18004 				    saddr);
18005 			}
18006 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
18007 				sata_process_pmdevice_attached(sata_hba_inst,
18008 				    saddr);
18009 			}
18010 			if (event_flags & SATA_EVNT_LINK_ESTABLISHED ||
18011 			    event_flags & SATA_EVNT_LINK_LOST) {
18012 				sata_process_pmport_link_events(sata_hba_inst,
18013 				    saddr);
18014 			}
18015 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
18016 				sata_process_target_node_cleanup(
18017 				    sata_hba_inst, saddr);
18018 			}
18019 		}
18020 
18021 		/* Checking drive event(s). */
18022 		mutex_enter(&pmportinfo->pmport_mutex);
18023 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
18024 		    pmportinfo->pmport_sata_drive != NULL) {
18025 			event_flags = pmportinfo->pmport_sata_drive->
18026 			    satadrv_event_flags;
18027 			if (event_flags & (SATA_EVNT_DEVICE_RESET |
18028 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
18029 
18030 				/* Have device event */
18031 				sata_process_pmdevice_reset(sata_hba_inst,
18032 				    saddr);
18033 			}
18034 		}
18035 		mutex_exit(&pmportinfo->pmport_mutex);
18036 
18037 		/* Release PORT_BUSY flag */
18038 		mutex_enter(&cportinfo->cport_mutex);
18039 		cportinfo->cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
18040 		mutex_exit(&cportinfo->cport_mutex);
18041 	}
18042 
18043 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
18044 	    "[DONE] pmult event(s) on cport %d of controller %d",
18045 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
18046 }
18047 
18048 /*
18049  * Process HBA power level change reported by HBA driver.
18050  * Not implemented at this time - event is ignored.
18051  */
18052 static void
18053 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
18054 {
18055 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18056 	    "Processing controller power level change", NULL);
18057 
18058 	/* Ignoring it for now */
18059 	mutex_enter(&sata_hba_inst->satahba_mutex);
18060 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
18061 	mutex_exit(&sata_hba_inst->satahba_mutex);
18062 }
18063 
18064 /*
18065  * Process port power level change reported by HBA driver.
18066  * Not implemented at this time - event is ignored.
18067  */
18068 static void
18069 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
18070     sata_address_t *saddr)
18071 {
18072 	sata_cport_info_t *cportinfo;
18073 
18074 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18075 	    "Processing port power level change", NULL);
18076 
18077 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18078 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18079 	/* Reset event flag */
18080 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
18081 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18082 }
18083 
18084 /*
18085  * Process port failure reported by HBA driver.
18086  * cports support only - no pmports.
18087  */
18088 static void
18089 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
18090     sata_address_t *saddr)
18091 {
18092 	sata_cport_info_t *cportinfo;
18093 
18094 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18095 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18096 	/* Reset event flag first */
18097 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
18098 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
18099 	if ((cportinfo->cport_state &
18100 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
18101 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18102 		    cport_mutex);
18103 		return;
18104 	}
18105 	/* Fail the port */
18106 	cportinfo->cport_state = SATA_PSTATE_FAILED;
18107 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18108 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
18109 }
18110 
18111 /*
18112  * Device Reset Event processing.
18113  * The seqeunce is managed by 3 stage flags:
18114  * - reset event reported,
18115  * - reset event being processed,
18116  * - request to clear device reset state.
18117  *
18118  * NOTE: This function has to be entered with cport mutex held. It exits with
18119  * mutex held as well, but can release mutex during the processing.
18120  */
18121 static void
18122 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
18123     sata_address_t *saddr)
18124 {
18125 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
18126 	sata_drive_info_t *sdinfo;
18127 	sata_cport_info_t *cportinfo;
18128 	sata_device_t sata_device;
18129 	int rval_probe, rval_set;
18130 
18131 	/* We only care about host sata cport for now */
18132 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18133 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18134 	/*
18135 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
18136 	 * state, ignore reset event.
18137 	 */
18138 	if (((cportinfo->cport_state &
18139 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
18140 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
18141 		sdinfo->satadrv_event_flags &=
18142 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
18143 		return;
18144 	}
18145 
18146 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) ==
18147 	    SATA_DTYPE_PMULT)) {
18148 		/*
18149 		 * Should not happened: this is already handled in
18150 		 * sata_hba_event_notify()
18151 		 */
18152 		mutex_exit(&cportinfo->cport_mutex);
18153 		goto done;
18154 	}
18155 
18156 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
18157 	    SATA_VALID_DEV_TYPE) == 0) {
18158 		/*
18159 		 * This should not happen - coding error.
18160 		 * But we can recover, so do not panic, just clean up
18161 		 * and if in debug mode, log the message.
18162 		 */
18163 #ifdef SATA_DEBUG
18164 		sata_log(sata_hba_inst, CE_WARN,
18165 		    "sata_process_device_reset: "
18166 		    "Invalid device type with sdinfo!", NULL);
18167 #endif
18168 		sdinfo->satadrv_event_flags = 0;
18169 		return;
18170 	}
18171 
18172 #ifdef SATA_DEBUG
18173 	if ((sdinfo->satadrv_event_flags &
18174 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
18175 		/* Nothing to do */
18176 		/* Something is weird - why we are processing dev reset? */
18177 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18178 		    "No device reset event!!!!", NULL);
18179 
18180 		return;
18181 	}
18182 	if ((sdinfo->satadrv_event_flags &
18183 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
18184 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
18185 		/* Something is weird - new device reset event */
18186 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18187 		    "Overlapping device reset events!", NULL);
18188 	}
18189 #endif
18190 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18191 	    "Processing port %d device reset", saddr->cport);
18192 
18193 	/* Clear event flag */
18194 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
18195 
18196 	/* It seems that we always need to check the port state first */
18197 	sata_device.satadev_rev = SATA_DEVICE_REV;
18198 	sata_device.satadev_addr = *saddr;
18199 	/*
18200 	 * We have to exit mutex, because the HBA probe port function may
18201 	 * block on its own mutex.
18202 	 */
18203 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18204 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18205 	    (SATA_DIP(sata_hba_inst), &sata_device);
18206 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18207 	sata_update_port_info(sata_hba_inst, &sata_device);
18208 	if (rval_probe != SATA_SUCCESS) {
18209 		/* Something went wrong? Fail the port */
18210 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18211 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18212 		if (sdinfo != NULL)
18213 			sdinfo->satadrv_event_flags = 0;
18214 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18215 		    cport_mutex);
18216 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18217 		    "SATA port %d probing failed",
18218 		    saddr->cport));
18219 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
18220 		    saddr->cport)->cport_mutex);
18221 		return;
18222 	}
18223 	if ((sata_device.satadev_scr.sstatus  &
18224 	    SATA_PORT_DEVLINK_UP_MASK) !=
18225 	    SATA_PORT_DEVLINK_UP ||
18226 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18227 		/*
18228 		 * No device to process, anymore. Some other event processing
18229 		 * would or have already performed port info cleanup.
18230 		 * To be safe (HBA may need it), request clearing device
18231 		 * reset condition.
18232 		 */
18233 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18234 		if (sdinfo != NULL) {
18235 			sdinfo->satadrv_event_flags &=
18236 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18237 			sdinfo->satadrv_event_flags |=
18238 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18239 		}
18240 		return;
18241 	}
18242 
18243 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18244 	if (sdinfo == NULL) {
18245 		return;
18246 	}
18247 	if ((sdinfo->satadrv_event_flags &
18248 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18249 		/*
18250 		 * Start tracking time for device feature restoration and
18251 		 * identification. Save current time (lbolt value).
18252 		 */
18253 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18254 	}
18255 	/* Mark device reset processing as active */
18256 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18257 
18258 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18259 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18260 
18261 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
18262 
18263 	if (rval_set  != SATA_SUCCESS) {
18264 		/*
18265 		 * Restoring drive setting failed.
18266 		 * Probe the port first, to check if the port state has changed
18267 		 */
18268 		sata_device.satadev_rev = SATA_DEVICE_REV;
18269 		sata_device.satadev_addr = *saddr;
18270 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
18271 		/* probe port */
18272 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18273 		    (SATA_DIP(sata_hba_inst), &sata_device);
18274 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18275 		    cport_mutex);
18276 		if (rval_probe == SATA_SUCCESS &&
18277 		    (sata_device.satadev_state &
18278 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18279 		    (sata_device.satadev_scr.sstatus  &
18280 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18281 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18282 			/*
18283 			 * We may retry this a bit later - in-process reset
18284 			 * condition should be already set.
18285 			 * Track retry time for device identification.
18286 			 */
18287 			if ((cportinfo->cport_dev_type &
18288 			    SATA_VALID_DEV_TYPE) != 0 &&
18289 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
18290 			    sdinfo->satadrv_reset_time != 0) {
18291 				clock_t cur_time = ddi_get_lbolt();
18292 				/*
18293 				 * If the retry time limit was not
18294 				 * exceeded, retry.
18295 				 */
18296 				if ((cur_time - sdinfo->satadrv_reset_time) <
18297 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18298 					mutex_enter(
18299 					    &sata_hba_inst->satahba_mutex);
18300 					sata_hba_inst->satahba_event_flags |=
18301 					    SATA_EVNT_MAIN;
18302 					mutex_exit(
18303 					    &sata_hba_inst->satahba_mutex);
18304 					mutex_enter(&sata_mutex);
18305 					sata_event_pending |= SATA_EVNT_MAIN;
18306 					mutex_exit(&sata_mutex);
18307 					return;
18308 				}
18309 				if (rval_set == SATA_RETRY) {
18310 					/*
18311 					 * Setting drive features failed, but
18312 					 * the drive is still accessible,
18313 					 * so emit a warning message before
18314 					 * return.
18315 					 */
18316 					mutex_exit(&SATA_CPORT_INFO(
18317 					    sata_hba_inst,
18318 					    saddr->cport)->cport_mutex);
18319 					goto done;
18320 				}
18321 			}
18322 			/* Fail the drive */
18323 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18324 
18325 			sata_log(sata_hba_inst, CE_WARN,
18326 			    "SATA device at port %d - device failed",
18327 			    saddr->cport);
18328 		}
18329 		/*
18330 		 * No point of retrying - device failed or some other event
18331 		 * processing or already did or will do port info cleanup.
18332 		 * To be safe (HBA may need it),
18333 		 * request clearing device reset condition.
18334 		 */
18335 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
18336 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18337 		sdinfo->satadrv_reset_time = 0;
18338 		return;
18339 	}
18340 done:
18341 	/*
18342 	 * If setting of drive features failed, but the drive is still
18343 	 * accessible, emit a warning message.
18344 	 */
18345 	if (rval_set == SATA_RETRY) {
18346 		sata_log(sata_hba_inst, CE_WARN,
18347 		    "SATA device at port %d - desired setting could not be "
18348 		    "restored after reset. Device may not operate as expected.",
18349 		    saddr->cport);
18350 	}
18351 	/*
18352 	 * Raise the flag indicating that the next sata command could
18353 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18354 	 * reset is reported.
18355 	 */
18356 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18357 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18358 		sdinfo->satadrv_reset_time = 0;
18359 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
18360 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18361 			sdinfo->satadrv_event_flags &=
18362 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18363 			sdinfo->satadrv_event_flags |=
18364 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18365 		}
18366 	}
18367 }
18368 
18369 
18370 /*
18371  * Port Multiplier Port Device Reset Event processing.
18372  *
18373  * NOTE: This function has to be entered with pmport mutex held. It exits with
18374  * mutex held as well, but can release mutex during the processing.
18375  */
18376 static void
18377 sata_process_pmdevice_reset(sata_hba_inst_t *sata_hba_inst,
18378     sata_address_t *saddr)
18379 {
18380 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
18381 	sata_drive_info_t *sdinfo = NULL;
18382 	sata_cport_info_t *cportinfo = NULL;
18383 	sata_pmport_info_t *pmportinfo = NULL;
18384 	sata_pmult_info_t *pminfo = NULL;
18385 	sata_device_t sata_device;
18386 	uint8_t cport = saddr->cport;
18387 	uint8_t pmport = saddr->pmport;
18388 	int rval;
18389 
18390 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18391 	    "Processing drive reset at port %d:%d", cport, pmport);
18392 
18393 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
18394 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18395 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport);
18396 
18397 	/*
18398 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
18399 	 * state, ignore reset event.
18400 	 */
18401 	if (((cportinfo->cport_state &
18402 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
18403 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
18404 		sdinfo->satadrv_event_flags &=
18405 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
18406 		return;
18407 	}
18408 
18409 	if ((pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
18410 		/*
18411 		 * This should not happen - coding error.
18412 		 * But we can recover, so do not panic, just clean up
18413 		 * and if in debug mode, log the message.
18414 		 */
18415 #ifdef SATA_DEBUG
18416 		sata_log(sata_hba_inst, CE_WARN,
18417 		    "sata_process_pmdevice_reset: "
18418 		    "Invalid device type with sdinfo!", NULL);
18419 #endif
18420 		sdinfo->satadrv_event_flags = 0;
18421 		return;
18422 	}
18423 
18424 #ifdef SATA_DEBUG
18425 	if ((sdinfo->satadrv_event_flags &
18426 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
18427 		/* Nothing to do */
18428 		/* Something is weird - why we are processing dev reset? */
18429 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18430 		    "No device reset event!!!!", NULL);
18431 
18432 		return;
18433 	}
18434 	if ((sdinfo->satadrv_event_flags &
18435 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
18436 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
18437 		/* Something is weird - new device reset event */
18438 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18439 		    "Overlapping device reset events!", NULL);
18440 	}
18441 #endif
18442 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18443 	    "Processing port %d:%d device reset", cport, pmport);
18444 
18445 	/* Clear event flag */
18446 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
18447 
18448 	/* It seems that we always need to check the port state first */
18449 	sata_device.satadev_rev = SATA_DEVICE_REV;
18450 	sata_device.satadev_addr = *saddr;
18451 	/*
18452 	 * We have to exit mutex, because the HBA probe port function may
18453 	 * block on its own mutex.
18454 	 */
18455 	mutex_exit(&pmportinfo->pmport_mutex);
18456 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18457 	    (SATA_DIP(sata_hba_inst), &sata_device);
18458 	mutex_enter(&pmportinfo->pmport_mutex);
18459 
18460 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18461 	if (rval != SATA_SUCCESS) {
18462 		/* Something went wrong? Fail the port */
18463 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18464 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18465 		    saddr->pmport);
18466 		if (sdinfo != NULL)
18467 			sdinfo->satadrv_event_flags = 0;
18468 		mutex_exit(&pmportinfo->pmport_mutex);
18469 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18470 		    "SATA port %d:%d probing failed",
18471 		    saddr->cport, saddr->pmport));
18472 		mutex_enter(&pmportinfo->pmport_mutex);
18473 		return;
18474 	}
18475 	if ((sata_device.satadev_scr.sstatus  &
18476 	    SATA_PORT_DEVLINK_UP_MASK) !=
18477 	    SATA_PORT_DEVLINK_UP ||
18478 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18479 		/*
18480 		 * No device to process, anymore. Some other event processing
18481 		 * would or have already performed port info cleanup.
18482 		 * To be safe (HBA may need it), request clearing device
18483 		 * reset condition.
18484 		 */
18485 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18486 		    saddr->pmport);
18487 		if (sdinfo != NULL) {
18488 			sdinfo->satadrv_event_flags &=
18489 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18490 			/* must clear flags on cport */
18491 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18492 			    saddr->cport);
18493 			pminfo->pmult_event_flags |=
18494 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18495 		}
18496 		return;
18497 	}
18498 
18499 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18500 	    saddr->pmport);
18501 	if (sdinfo == NULL) {
18502 		return;
18503 	}
18504 	if ((sdinfo->satadrv_event_flags &
18505 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18506 		/*
18507 		 * Start tracking time for device feature restoration and
18508 		 * identification. Save current time (lbolt value).
18509 		 */
18510 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18511 	}
18512 	/* Mark device reset processing as active */
18513 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18514 
18515 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18516 	mutex_exit(&pmportinfo->pmport_mutex);
18517 
18518 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
18519 	    SATA_FAILURE) {
18520 		/*
18521 		 * Restoring drive setting failed.
18522 		 * Probe the port first, to check if the port state has changed
18523 		 */
18524 		sata_device.satadev_rev = SATA_DEVICE_REV;
18525 		sata_device.satadev_addr = *saddr;
18526 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
18527 
18528 		/* probe port */
18529 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18530 		    (SATA_DIP(sata_hba_inst), &sata_device);
18531 		mutex_enter(&pmportinfo->pmport_mutex);
18532 		if (rval == SATA_SUCCESS &&
18533 		    (sata_device.satadev_state &
18534 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18535 		    (sata_device.satadev_scr.sstatus  &
18536 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18537 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18538 			/*
18539 			 * We may retry this a bit later - in-process reset
18540 			 * condition should be already set.
18541 			 * Track retry time for device identification.
18542 			 */
18543 			if ((pmportinfo->pmport_dev_type &
18544 			    SATA_VALID_DEV_TYPE) != 0 &&
18545 			    SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL &&
18546 			    sdinfo->satadrv_reset_time != 0) {
18547 				clock_t cur_time = ddi_get_lbolt();
18548 				/*
18549 				 * If the retry time limit was not
18550 				 * exceeded, retry.
18551 				 */
18552 				if ((cur_time - sdinfo->satadrv_reset_time) <
18553 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18554 					mutex_enter(
18555 					    &sata_hba_inst->satahba_mutex);
18556 					sata_hba_inst->satahba_event_flags |=
18557 					    SATA_EVNT_MAIN;
18558 					mutex_exit(
18559 					    &sata_hba_inst->satahba_mutex);
18560 					mutex_enter(&sata_mutex);
18561 					sata_event_pending |= SATA_EVNT_MAIN;
18562 					mutex_exit(&sata_mutex);
18563 					return;
18564 				}
18565 			}
18566 			/* Fail the drive */
18567 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18568 
18569 			sata_log(sata_hba_inst, CE_WARN,
18570 			    "SATA device at port %d:%d - device failed",
18571 			    saddr->cport, saddr->pmport);
18572 		} else {
18573 			/*
18574 			 * No point of retrying - some other event processing
18575 			 * would or already did port info cleanup.
18576 			 * To be safe (HBA may need it),
18577 			 * request clearing device reset condition.
18578 			 */
18579 			sdinfo->satadrv_event_flags |=
18580 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18581 		}
18582 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18583 		sdinfo->satadrv_reset_time = 0;
18584 		return;
18585 	}
18586 	/*
18587 	 * Raise the flag indicating that the next sata command could
18588 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18589 	 * reset is reported.
18590 	 */
18591 	mutex_enter(&pmportinfo->pmport_mutex);
18592 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18593 		sdinfo->satadrv_reset_time = 0;
18594 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
18595 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18596 			sdinfo->satadrv_event_flags &=
18597 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18598 			/* must clear flags on cport */
18599 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18600 			    saddr->cport);
18601 			pminfo->pmult_event_flags |=
18602 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18603 		}
18604 	}
18605 }
18606 
18607 /*
18608  * Port Link Events processing.
18609  * Every link established event may involve device reset (due to
18610  * COMRESET signal, equivalent of the hard reset) so arbitrarily
18611  * set device reset event for an attached device (if any).
18612  * If the port is in SHUTDOWN or FAILED state, ignore link events.
18613  *
18614  * The link established event processing varies, depending on the state
18615  * of the target node, HBA hotplugging capabilities, state of the port.
18616  * If the link is not active, the link established event is ignored.
18617  * If HBA cannot detect device attachment and there is no target node,
18618  * the link established event triggers device attach event processing.
18619  * Else, link established event triggers device reset event processing.
18620  *
18621  * The link lost event processing varies, depending on a HBA hotplugging
18622  * capability and the state of the port (link active or not active).
18623  * If the link is active, the lost link event is ignored.
18624  * If HBA cannot detect device removal, the lost link event triggers
18625  * device detached event processing after link lost timeout.
18626  * Else, the event is ignored.
18627  *
18628  * NOTE: Port multiplier ports events are handled by
18629  * sata_process_pmport_link_events();
18630  */
18631 static void
18632 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
18633     sata_address_t *saddr)
18634 {
18635 	sata_device_t sata_device;
18636 	sata_cport_info_t *cportinfo;
18637 	sata_drive_info_t *sdinfo;
18638 	uint32_t event_flags;
18639 	int rval;
18640 
18641 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18642 	    "Processing port %d link event(s)", saddr->cport);
18643 
18644 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18645 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18646 	event_flags = cportinfo->cport_event_flags;
18647 
18648 	/* Reset event flags first */
18649 	cportinfo->cport_event_flags &=
18650 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18651 
18652 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18653 	if ((cportinfo->cport_state &
18654 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18655 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18656 		    cport_mutex);
18657 		return;
18658 	}
18659 
18660 	/*
18661 	 * For the sanity sake get current port state.
18662 	 * Set device address only. Other sata_device fields should be
18663 	 * set by HBA driver.
18664 	 */
18665 	sata_device.satadev_rev = SATA_DEVICE_REV;
18666 	sata_device.satadev_addr = *saddr;
18667 	/*
18668 	 * We have to exit mutex, because the HBA probe port function may
18669 	 * block on its own mutex.
18670 	 */
18671 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18672 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18673 	    (SATA_DIP(sata_hba_inst), &sata_device);
18674 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18675 	sata_update_port_info(sata_hba_inst, &sata_device);
18676 	if (rval != SATA_SUCCESS) {
18677 		/* Something went wrong? Fail the port */
18678 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18679 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18680 		    cport_mutex);
18681 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18682 		    "SATA port %d probing failed",
18683 		    saddr->cport));
18684 		/*
18685 		 * We may want to release device info structure, but
18686 		 * it is not necessary.
18687 		 */
18688 		return;
18689 	} else {
18690 		/* port probed successfully */
18691 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18692 	}
18693 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18694 
18695 		if ((sata_device.satadev_scr.sstatus &
18696 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18697 			/* Ignore event */
18698 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18699 			    "Ignoring port %d link established event - "
18700 			    "link down",
18701 			    saddr->cport);
18702 			goto linklost;
18703 		}
18704 
18705 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18706 		    "Processing port %d link established event",
18707 		    saddr->cport);
18708 
18709 		/*
18710 		 * For the sanity sake check if a device is attached - check
18711 		 * return state of a port probing.
18712 		 */
18713 		if (sata_device.satadev_type != SATA_DTYPE_NONE) {
18714 			/*
18715 			 * HBA port probe indicated that there is a device
18716 			 * attached. Check if the framework had device info
18717 			 * structure attached for this device.
18718 			 */
18719 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
18720 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
18721 				    NULL);
18722 
18723 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18724 				if ((sdinfo->satadrv_type &
18725 				    SATA_VALID_DEV_TYPE) != 0) {
18726 					/*
18727 					 * Dev info structure is present.
18728 					 * If dev_type is set to known type in
18729 					 * the framework's drive info struct
18730 					 * then the device existed before and
18731 					 * the link was probably lost
18732 					 * momentarily - in such case
18733 					 * we may want to check device
18734 					 * identity.
18735 					 * Identity check is not supported now.
18736 					 *
18737 					 * Link established event
18738 					 * triggers device reset event.
18739 					 */
18740 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
18741 					    satadrv_event_flags |=
18742 					    SATA_EVNT_DEVICE_RESET;
18743 				}
18744 			} else if (cportinfo->cport_dev_type ==
18745 			    SATA_DTYPE_NONE) {
18746 				/*
18747 				 * We got new device attached! If HBA does not
18748 				 * generate device attached events, trigger it
18749 				 * here.
18750 				 */
18751 				if (!(SATA_FEATURES(sata_hba_inst) &
18752 				    SATA_CTLF_HOTPLUG)) {
18753 					cportinfo->cport_event_flags |=
18754 					    SATA_EVNT_DEVICE_ATTACHED;
18755 				}
18756 			}
18757 			/* Reset link lost timeout */
18758 			cportinfo->cport_link_lost_time = 0;
18759 		}
18760 	}
18761 linklost:
18762 	if (event_flags & SATA_EVNT_LINK_LOST) {
18763 		if ((sata_device.satadev_scr.sstatus &
18764 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18765 			/* Ignore event */
18766 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18767 			    "Ignoring port %d link lost event - link is up",
18768 			    saddr->cport);
18769 			goto done;
18770 		}
18771 #ifdef SATA_DEBUG
18772 		if (cportinfo->cport_link_lost_time == 0) {
18773 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18774 			    "Processing port %d link lost event",
18775 			    saddr->cport);
18776 		}
18777 #endif
18778 		/*
18779 		 * When HBA cannot generate device attached/detached events,
18780 		 * we need to track link lost time and eventually generate
18781 		 * device detach event.
18782 		 */
18783 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18784 			/* We are tracking link lost time */
18785 			if (cportinfo->cport_link_lost_time == 0) {
18786 				/* save current time (lbolt value) */
18787 				cportinfo->cport_link_lost_time =
18788 				    ddi_get_lbolt();
18789 				/* just keep link lost event */
18790 				cportinfo->cport_event_flags |=
18791 				    SATA_EVNT_LINK_LOST;
18792 			} else {
18793 				clock_t cur_time = ddi_get_lbolt();
18794 				if ((cur_time -
18795 				    cportinfo->cport_link_lost_time) >=
18796 				    drv_usectohz(
18797 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18798 					/* trigger device detach event */
18799 					cportinfo->cport_event_flags |=
18800 					    SATA_EVNT_DEVICE_DETACHED;
18801 					cportinfo->cport_link_lost_time = 0;
18802 					SATADBG1(SATA_DBG_EVENTS,
18803 					    sata_hba_inst,
18804 					    "Triggering port %d "
18805 					    "device detached event",
18806 					    saddr->cport);
18807 				} else {
18808 					/* keep link lost event */
18809 					cportinfo->cport_event_flags |=
18810 					    SATA_EVNT_LINK_LOST;
18811 				}
18812 			}
18813 		}
18814 		/*
18815 		 * We could change port state to disable/delay access to
18816 		 * the attached device until the link is recovered.
18817 		 */
18818 	}
18819 done:
18820 	event_flags = cportinfo->cport_event_flags;
18821 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18822 	if (event_flags != 0) {
18823 		mutex_enter(&sata_hba_inst->satahba_mutex);
18824 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18825 		mutex_exit(&sata_hba_inst->satahba_mutex);
18826 		mutex_enter(&sata_mutex);
18827 		sata_event_pending |= SATA_EVNT_MAIN;
18828 		mutex_exit(&sata_mutex);
18829 	}
18830 }
18831 
18832 /*
18833  * Port Multiplier Port Link Events processing.
18834  */
18835 static void
18836 sata_process_pmport_link_events(sata_hba_inst_t *sata_hba_inst,
18837     sata_address_t *saddr)
18838 {
18839 	sata_device_t sata_device;
18840 	sata_pmport_info_t *pmportinfo = NULL;
18841 	sata_drive_info_t *sdinfo = NULL;
18842 	uint32_t event_flags;
18843 	uint8_t cport = saddr->cport;
18844 	uint8_t pmport = saddr->pmport;
18845 	int rval;
18846 
18847 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18848 	    "Processing port %d:%d link event(s)",
18849 	    cport, pmport);
18850 
18851 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18852 	mutex_enter(&pmportinfo->pmport_mutex);
18853 	event_flags = pmportinfo->pmport_event_flags;
18854 
18855 	/* Reset event flags first */
18856 	pmportinfo->pmport_event_flags &=
18857 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18858 
18859 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18860 	if ((pmportinfo->pmport_state &
18861 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18862 		mutex_exit(&pmportinfo->pmport_mutex);
18863 		return;
18864 	}
18865 
18866 	/*
18867 	 * For the sanity sake get current port state.
18868 	 * Set device address only. Other sata_device fields should be
18869 	 * set by HBA driver.
18870 	 */
18871 	sata_device.satadev_rev = SATA_DEVICE_REV;
18872 	sata_device.satadev_addr = *saddr;
18873 	/*
18874 	 * We have to exit mutex, because the HBA probe port function may
18875 	 * block on its own mutex.
18876 	 */
18877 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18878 	    saddr->pmport));
18879 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18880 	    (SATA_DIP(sata_hba_inst), &sata_device);
18881 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18882 	    saddr->pmport));
18883 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18884 	if (rval != SATA_SUCCESS) {
18885 		/* Something went wrong? Fail the port */
18886 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18887 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18888 		    saddr->pmport));
18889 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18890 		    "SATA port %d:%d probing failed",
18891 		    saddr->cport, saddr->pmport));
18892 		/*
18893 		 * We may want to release device info structure, but
18894 		 * it is not necessary.
18895 		 */
18896 		return;
18897 	} else {
18898 		/* port probed successfully */
18899 		pmportinfo->pmport_state |=
18900 		    SATA_STATE_PROBED | SATA_STATE_READY;
18901 	}
18902 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
18903 	    saddr->cport, saddr->pmport));
18904 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
18905 	    saddr->cport, saddr->pmport));
18906 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18907 
18908 		if ((sata_device.satadev_scr.sstatus &
18909 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18910 			/* Ignore event */
18911 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18912 			    "Ignoring port %d:%d link established event - "
18913 			    "link down",
18914 			    saddr->cport, saddr->pmport);
18915 			goto linklost;
18916 		}
18917 
18918 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18919 		    "Processing port %d:%d link established event",
18920 		    cport, pmport);
18921 
18922 		/*
18923 		 * For the sanity sake check if a device is attached - check
18924 		 * return state of a port probing.
18925 		 */
18926 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
18927 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
18928 			/*
18929 			 * HBA port probe indicated that there is a device
18930 			 * attached. Check if the framework had device info
18931 			 * structure attached for this device.
18932 			 */
18933 			if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
18934 				ASSERT(SATA_PMPORTINFO_DRV_INFO(pmportinfo) !=
18935 				    NULL);
18936 
18937 				sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18938 				if ((sdinfo->satadrv_type &
18939 				    SATA_VALID_DEV_TYPE) != 0) {
18940 					/*
18941 					 * Dev info structure is present.
18942 					 * If dev_type is set to known type in
18943 					 * the framework's drive info struct
18944 					 * then the device existed before and
18945 					 * the link was probably lost
18946 					 * momentarily - in such case
18947 					 * we may want to check device
18948 					 * identity.
18949 					 * Identity check is not supported now.
18950 					 *
18951 					 * Link established event
18952 					 * triggers device reset event.
18953 					 */
18954 					(SATA_PMPORTINFO_DRV_INFO(pmportinfo))->
18955 					    satadrv_event_flags |=
18956 					    SATA_EVNT_DEVICE_RESET;
18957 				}
18958 			} else if (pmportinfo->pmport_dev_type ==
18959 			    SATA_DTYPE_NONE) {
18960 				/*
18961 				 * We got new device attached! If HBA does not
18962 				 * generate device attached events, trigger it
18963 				 * here.
18964 				 */
18965 				if (!(SATA_FEATURES(sata_hba_inst) &
18966 				    SATA_CTLF_HOTPLUG)) {
18967 					pmportinfo->pmport_event_flags |=
18968 					    SATA_EVNT_DEVICE_ATTACHED;
18969 				}
18970 			}
18971 			/* Reset link lost timeout */
18972 			pmportinfo->pmport_link_lost_time = 0;
18973 		}
18974 	}
18975 linklost:
18976 	if (event_flags & SATA_EVNT_LINK_LOST) {
18977 #ifdef SATA_DEBUG
18978 		if (pmportinfo->pmport_link_lost_time == 0) {
18979 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18980 			    "Processing port %d:%d link lost event",
18981 			    saddr->cport, saddr->pmport);
18982 		}
18983 #endif
18984 		if ((sata_device.satadev_scr.sstatus &
18985 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18986 			/* Ignore event */
18987 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18988 			    "Ignoring port %d:%d link lost event - link is up",
18989 			    saddr->cport, saddr->pmport);
18990 			goto done;
18991 		}
18992 		/*
18993 		 * When HBA cannot generate device attached/detached events,
18994 		 * we need to track link lost time and eventually generate
18995 		 * device detach event.
18996 		 */
18997 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18998 			/* We are tracking link lost time */
18999 			if (pmportinfo->pmport_link_lost_time == 0) {
19000 				/* save current time (lbolt value) */
19001 				pmportinfo->pmport_link_lost_time =
19002 				    ddi_get_lbolt();
19003 				/* just keep link lost event */
19004 				pmportinfo->pmport_event_flags |=
19005 				    SATA_EVNT_LINK_LOST;
19006 			} else {
19007 				clock_t cur_time = ddi_get_lbolt();
19008 				if ((cur_time -
19009 				    pmportinfo->pmport_link_lost_time) >=
19010 				    drv_usectohz(
19011 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
19012 					/* trigger device detach event */
19013 					pmportinfo->pmport_event_flags |=
19014 					    SATA_EVNT_DEVICE_DETACHED;
19015 					pmportinfo->pmport_link_lost_time = 0;
19016 					SATADBG2(SATA_DBG_EVENTS,
19017 					    sata_hba_inst,
19018 					    "Triggering port %d:%d "
19019 					    "device detached event",
19020 					    saddr->cport, saddr->pmport);
19021 				} else {
19022 					/* keep link lost event */
19023 					pmportinfo->pmport_event_flags |=
19024 					    SATA_EVNT_LINK_LOST;
19025 				}
19026 			}
19027 		}
19028 		/*
19029 		 * We could change port state to disable/delay access to
19030 		 * the attached device until the link is recovered.
19031 		 */
19032 	}
19033 done:
19034 	event_flags = pmportinfo->pmport_event_flags;
19035 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
19036 	    saddr->pmport));
19037 	if (event_flags != 0) {
19038 		mutex_enter(&sata_hba_inst->satahba_mutex);
19039 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19040 		mutex_exit(&sata_hba_inst->satahba_mutex);
19041 		mutex_enter(&sata_mutex);
19042 		sata_event_pending |= SATA_EVNT_MAIN;
19043 		mutex_exit(&sata_mutex);
19044 	}
19045 }
19046 
19047 /*
19048  * Device Detached Event processing.
19049  * Port is probed to find if a device is really gone. If so,
19050  * the device info structure is detached from the SATA port info structure
19051  * and released.
19052  * Port status is updated.
19053  *
19054  * NOTE: Port multiplier ports events are handled by
19055  * sata_process_pmdevice_detached()
19056  */
19057 static void
19058 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
19059     sata_address_t *saddr)
19060 {
19061 	sata_cport_info_t *cportinfo;
19062 	sata_pmport_info_t *pmportinfo;
19063 	sata_drive_info_t *sdevinfo;
19064 	sata_device_t sata_device;
19065 	sata_address_t pmport_addr;
19066 	char name[16];
19067 	uint8_t cport = saddr->cport;
19068 	int npmport;
19069 	int rval;
19070 
19071 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19072 	    "Processing port %d device detached", saddr->cport);
19073 
19074 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19075 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19076 	/* Clear event flag */
19077 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
19078 
19079 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
19080 	if ((cportinfo->cport_state &
19081 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19082 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19083 		    cport_mutex);
19084 		return;
19085 	}
19086 	/* For sanity, re-probe the port */
19087 	sata_device.satadev_rev = SATA_DEVICE_REV;
19088 	sata_device.satadev_addr = *saddr;
19089 
19090 	/*
19091 	 * We have to exit mutex, because the HBA probe port function may
19092 	 * block on its own mutex.
19093 	 */
19094 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19095 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19096 	    (SATA_DIP(sata_hba_inst), &sata_device);
19097 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19098 	sata_update_port_info(sata_hba_inst, &sata_device);
19099 	if (rval != SATA_SUCCESS) {
19100 		/* Something went wrong? Fail the port */
19101 		cportinfo->cport_state = SATA_PSTATE_FAILED;
19102 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19103 		    cport_mutex);
19104 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19105 		    "SATA port %d probing failed",
19106 		    saddr->cport));
19107 		/*
19108 		 * We may want to release device info structure, but
19109 		 * it is not necessary.
19110 		 */
19111 		return;
19112 	} else {
19113 		/* port probed successfully */
19114 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
19115 	}
19116 	/*
19117 	 * Check if a device is still attached. For sanity, check also
19118 	 * link status - if no link, there is no device.
19119 	 */
19120 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
19121 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
19122 	    SATA_DTYPE_NONE) {
19123 		/*
19124 		 * Device is still attached - ignore detach event.
19125 		 */
19126 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19127 		    cport_mutex);
19128 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19129 		    "Ignoring detach - device still attached to port %d",
19130 		    sata_device.satadev_addr.cport);
19131 		return;
19132 	}
19133 	/*
19134 	 * We need to detach and release device info structure here
19135 	 */
19136 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19137 		/*
19138 		 * A port-multiplier is removed.
19139 		 *
19140 		 * Calling sata_process_pmdevice_detached() does not work
19141 		 * here. The port multiplier is gone, so we cannot probe
19142 		 * sub-port any more and all pmult-related data structure must
19143 		 * be de-allocated immediately. Following structure of every
19144 		 * implemented sub-port behind the pmult are required to
19145 		 * released.
19146 		 *
19147 		 *   - attachment point
19148 		 *   - target node
19149 		 *   - sata_drive_info
19150 		 *   - sata_pmport_info
19151 		 */
19152 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst,
19153 		    cport); npmport ++) {
19154 			SATADBG2(SATA_DBG_PMULT|SATA_DBG_EVENTS_PROC,
19155 			    sata_hba_inst,
19156 			    "Detaching target node at port %d:%d",
19157 			    cport, npmport);
19158 
19159 			mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
19160 
19161 			/* Remove attachment point. */
19162 			name[0] = '\0';
19163 			(void) sprintf(name, "%d.%d", cport, npmport);
19164 			ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
19165 			sata_log(sata_hba_inst, CE_NOTE,
19166 			    "Remove attachment point of port %d:%d",
19167 			    cport, npmport);
19168 
19169 			/* Remove target node */
19170 			pmport_addr.cport = cport;
19171 			pmport_addr.pmport = (uint8_t)npmport;
19172 			pmport_addr.qual = SATA_ADDR_PMPORT;
19173 			sata_remove_target_node(sata_hba_inst, &pmport_addr);
19174 
19175 			mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
19176 
19177 			/* Release sata_pmport_info & sata_drive_info. */
19178 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19179 			    cport, npmport);
19180 			ASSERT(pmportinfo != NULL);
19181 
19182 			sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19183 			if (sdevinfo != NULL) {
19184 				(void) kmem_free((void *) sdevinfo,
19185 				    sizeof (sata_drive_info_t));
19186 			}
19187 
19188 			/* Release sata_pmport_info at last */
19189 			(void) kmem_free((void *) pmportinfo,
19190 			    sizeof (sata_pmport_info_t));
19191 		}
19192 
19193 		/* Finally, release sata_pmult_info */
19194 		(void) kmem_free((void *)
19195 		    SATA_CPORTINFO_PMULT_INFO(cportinfo),
19196 		    sizeof (sata_pmult_info_t));
19197 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
19198 
19199 		sata_log(sata_hba_inst, CE_WARN,
19200 		    "SATA port-multiplier detached at port %d", cport);
19201 
19202 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19203 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19204 		    saddr->cport)->cport_mutex);
19205 	} else {
19206 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19207 			sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
19208 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
19209 			(void) kmem_free((void *)sdevinfo,
19210 			    sizeof (sata_drive_info_t));
19211 		}
19212 		sata_log(sata_hba_inst, CE_WARN,
19213 		    "SATA device detached at port %d", cport);
19214 
19215 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19216 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19217 		    saddr->cport)->cport_mutex);
19218 
19219 		/*
19220 		 * Try to offline a device and remove target node
19221 		 * if it still exists
19222 		 */
19223 		sata_remove_target_node(sata_hba_inst, saddr);
19224 	}
19225 
19226 
19227 	/*
19228 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19229 	 * with the hint: SE_HINT_REMOVE
19230 	 */
19231 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
19232 }
19233 
19234 /*
19235  * Port Multiplier Port Device Deattached Event processing.
19236  *
19237  * NOTE: No Mutex should be hold.
19238  */
19239 static void
19240 sata_process_pmdevice_detached(sata_hba_inst_t *sata_hba_inst,
19241     sata_address_t *saddr)
19242 {
19243 	sata_pmport_info_t *pmportinfo;
19244 	sata_drive_info_t *sdevinfo;
19245 	sata_device_t sata_device;
19246 	int rval;
19247 	uint8_t cport, pmport;
19248 
19249 	cport = saddr->cport;
19250 	pmport = saddr->pmport;
19251 
19252 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19253 	    "Processing port %d:%d device detached",
19254 	    cport, pmport);
19255 
19256 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19257 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19258 
19259 	/* Clear event flag */
19260 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
19261 
19262 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
19263 	if ((pmportinfo->pmport_state &
19264 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19265 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19266 		return;
19267 	}
19268 	/* For sanity, re-probe the port */
19269 	sata_device.satadev_rev = SATA_DEVICE_REV;
19270 	sata_device.satadev_addr = *saddr;
19271 
19272 	/*
19273 	 * We have to exit mutex, because the HBA probe port function may
19274 	 * block on its own mutex.
19275 	 */
19276 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19277 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19278 	    (SATA_DIP(sata_hba_inst), &sata_device);
19279 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19280 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19281 	if (rval != SATA_SUCCESS) {
19282 		/* Something went wrong? Fail the port */
19283 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19284 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19285 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19286 		    "SATA port %d:%d probing failed",
19287 		    saddr->pmport));
19288 		/*
19289 		 * We may want to release device info structure, but
19290 		 * it is not necessary.
19291 		 */
19292 		return;
19293 	} else {
19294 		/* port probed successfully */
19295 		pmportinfo->pmport_state |=
19296 		    SATA_STATE_PROBED | SATA_STATE_READY;
19297 	}
19298 	/*
19299 	 * Check if a device is still attached. For sanity, check also
19300 	 * link status - if no link, there is no device.
19301 	 */
19302 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
19303 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
19304 	    SATA_DTYPE_NONE) {
19305 		/*
19306 		 * Device is still attached - ignore detach event.
19307 		 */
19308 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19309 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19310 		    "Ignoring detach - device still attached to port %d",
19311 		    sata_device.satadev_addr.pmport);
19312 		return;
19313 	}
19314 	/*
19315 	 * We need to detach and release device info structure here
19316 	 */
19317 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19318 		sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19319 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19320 		(void) kmem_free((void *)sdevinfo,
19321 		    sizeof (sata_drive_info_t));
19322 	}
19323 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19324 	/*
19325 	 * Device cannot be reached anymore, even if the target node may be
19326 	 * still present.
19327 	 */
19328 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19329 
19330 	/*
19331 	 * Try to offline a device and remove target node if it still exists
19332 	 */
19333 	sata_remove_target_node(sata_hba_inst, saddr);
19334 
19335 	/*
19336 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19337 	 * with the hint: SE_HINT_REMOVE
19338 	 */
19339 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
19340 }
19341 
19342 
19343 /*
19344  * Device Attached Event processing.
19345  * Port state is checked to verify that a device is really attached. If so,
19346  * the device info structure is created and attached to the SATA port info
19347  * structure.
19348  *
19349  * If attached device cannot be identified or set-up, the retry for the
19350  * attach processing is set-up. Subsequent daemon run would try again to
19351  * identify the device, until the time limit is reached
19352  * (SATA_DEV_IDENTIFY_TIMEOUT).
19353  *
19354  * This function cannot be called in interrupt context (it may sleep).
19355  *
19356  * NOTE: Port multiplier ports events are handled by
19357  * sata_process_pmdevice_attached()
19358  */
19359 static void
19360 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
19361     sata_address_t *saddr)
19362 {
19363 	sata_cport_info_t *cportinfo = NULL;
19364 	sata_drive_info_t *sdevinfo = NULL;
19365 	sata_pmult_info_t *pmultinfo = NULL;
19366 	sata_pmport_info_t *pmportinfo = NULL;
19367 	sata_device_t sata_device;
19368 	dev_info_t *tdip;
19369 	uint32_t event_flags = 0, pmult_event_flags = 0;
19370 	int rval;
19371 	int npmport;
19372 
19373 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19374 	    "Processing port %d device attached", saddr->cport);
19375 
19376 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19377 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19378 
19379 	/* Clear attach event flag first */
19380 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19381 
19382 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19383 	if ((cportinfo->cport_state &
19384 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19385 		cportinfo->cport_dev_attach_time = 0;
19386 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19387 		    cport_mutex);
19388 		return;
19389 	}
19390 
19391 	/*
19392 	 * If the sata_drive_info structure is found attached to the port info,
19393 	 * despite the fact the device was removed and now it is re-attached,
19394 	 * the old drive info structure was not removed.
19395 	 * Arbitrarily release device info structure.
19396 	 */
19397 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19398 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
19399 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
19400 		(void) kmem_free((void *)sdevinfo,
19401 		    sizeof (sata_drive_info_t));
19402 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19403 		    "Arbitrarily detaching old device info.", NULL);
19404 	}
19405 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19406 
19407 	/* For sanity, re-probe the port */
19408 	sata_device.satadev_rev = SATA_DEVICE_REV;
19409 	sata_device.satadev_addr = *saddr;
19410 
19411 	/*
19412 	 * We have to exit mutex, because the HBA probe port function may
19413 	 * block on its own mutex.
19414 	 */
19415 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19416 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19417 	    (SATA_DIP(sata_hba_inst), &sata_device);
19418 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19419 	sata_update_port_info(sata_hba_inst, &sata_device);
19420 	if (rval != SATA_SUCCESS) {
19421 		/* Something went wrong? Fail the port */
19422 		cportinfo->cport_state = SATA_PSTATE_FAILED;
19423 		cportinfo->cport_dev_attach_time = 0;
19424 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19425 		    cport_mutex);
19426 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19427 		    "SATA port %d probing failed",
19428 		    saddr->cport));
19429 		return;
19430 	} else {
19431 		/* port probed successfully */
19432 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
19433 	}
19434 	/*
19435 	 * Check if a device is still attached. For sanity, check also
19436 	 * link status - if no link, there is no device.
19437 	 */
19438 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19439 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19440 	    SATA_DTYPE_NONE) {
19441 		/*
19442 		 * No device - ignore attach event.
19443 		 */
19444 		cportinfo->cport_dev_attach_time = 0;
19445 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19446 		    cport_mutex);
19447 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19448 		    "Ignoring attach - no device connected to port %d",
19449 		    sata_device.satadev_addr.cport);
19450 		return;
19451 	}
19452 
19453 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19454 	/*
19455 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19456 	 * with the hint: SE_HINT_INSERT
19457 	 */
19458 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19459 
19460 	/*
19461 	 * Port reprobing will take care of the creation of the device
19462 	 * info structure and determination of the device type.
19463 	 */
19464 	sata_device.satadev_addr = *saddr;
19465 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19466 	    SATA_DEV_IDENTIFY_NORETRY);
19467 
19468 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19469 	    cport_mutex);
19470 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
19471 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
19472 		/* Some device is attached to the port */
19473 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
19474 			/*
19475 			 * A device was not successfully attached.
19476 			 * Track retry time for device identification.
19477 			 */
19478 			if (cportinfo->cport_dev_attach_time != 0) {
19479 				clock_t cur_time = ddi_get_lbolt();
19480 				/*
19481 				 * If the retry time limit was not exceeded,
19482 				 * reinstate attach event.
19483 				 */
19484 				if ((cur_time -
19485 				    cportinfo->cport_dev_attach_time) <
19486 				    drv_usectohz(
19487 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19488 					/* OK, restore attach event */
19489 					cportinfo->cport_event_flags |=
19490 					    SATA_EVNT_DEVICE_ATTACHED;
19491 				} else {
19492 					/* Timeout - cannot identify device */
19493 					cportinfo->cport_dev_attach_time = 0;
19494 					sata_log(sata_hba_inst,
19495 					    CE_WARN,
19496 					    "Could not identify SATA device "
19497 					    "at port %d",
19498 					    saddr->cport);
19499 				}
19500 			} else {
19501 				/*
19502 				 * Start tracking time for device
19503 				 * identification.
19504 				 * Save current time (lbolt value).
19505 				 */
19506 				cportinfo->cport_dev_attach_time =
19507 				    ddi_get_lbolt();
19508 				/* Restore attach event */
19509 				cportinfo->cport_event_flags |=
19510 				    SATA_EVNT_DEVICE_ATTACHED;
19511 			}
19512 		} else if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19513 			cportinfo->cport_dev_attach_time = 0;
19514 			sata_log(sata_hba_inst, CE_NOTE,
19515 			    "SATA port-multiplier detected at port %d",
19516 			    saddr->cport);
19517 
19518 			if (SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL) {
19519 				/* Log the info of new port multiplier */
19520 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19521 				    saddr->cport)->cport_mutex);
19522 				sata_show_pmult_info(sata_hba_inst,
19523 				    &sata_device);
19524 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19525 				    saddr->cport)->cport_mutex);
19526 			}
19527 
19528 			ASSERT(SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL);
19529 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
19530 			for (npmport = 0; npmport <
19531 			    pmultinfo->pmult_num_dev_ports; npmport++) {
19532 				pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19533 				    saddr->cport, npmport);
19534 				ASSERT(pmportinfo != NULL);
19535 
19536 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19537 				    saddr->cport)->cport_mutex);
19538 				mutex_enter(&pmportinfo->pmport_mutex);
19539 				/* Marked all pmports with link events. */
19540 				pmportinfo->pmport_event_flags =
19541 				    SATA_EVNT_LINK_ESTABLISHED;
19542 				pmult_event_flags |=
19543 				    pmportinfo->pmport_event_flags;
19544 				mutex_exit(&pmportinfo->pmport_mutex);
19545 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19546 				    saddr->cport)->cport_mutex);
19547 			}
19548 			/* Auto-online is not available for PMult now. */
19549 
19550 		} else {
19551 			/*
19552 			 * If device was successfully attached, the subsequent
19553 			 * action depends on a state of the
19554 			 * sata_auto_online variable. If it is set to zero.
19555 			 * an explicit 'configure' command will be needed to
19556 			 * configure it. If its value is non-zero, we will
19557 			 * attempt to online (configure) the device.
19558 			 * First, log the message indicating that a device
19559 			 * was attached.
19560 			 */
19561 			cportinfo->cport_dev_attach_time = 0;
19562 			sata_log(sata_hba_inst, CE_WARN,
19563 			    "SATA device detected at port %d", saddr->cport);
19564 
19565 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19566 				sata_drive_info_t new_sdinfo;
19567 
19568 				/* Log device info data */
19569 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
19570 				    cportinfo));
19571 				sata_show_drive_info(sata_hba_inst,
19572 				    &new_sdinfo);
19573 			}
19574 
19575 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19576 			    saddr->cport)->cport_mutex);
19577 
19578 			/*
19579 			 * Make sure that there is no target node for that
19580 			 * device. If so, release it. It should not happen,
19581 			 * unless we had problem removing the node when
19582 			 * device was detached.
19583 			 */
19584 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19585 			    saddr->cport, saddr->pmport);
19586 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19587 			    saddr->cport)->cport_mutex);
19588 			if (tdip != NULL) {
19589 
19590 #ifdef SATA_DEBUG
19591 				if ((cportinfo->cport_event_flags &
19592 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19593 					sata_log(sata_hba_inst, CE_WARN,
19594 					    "sata_process_device_attached: "
19595 					    "old device target node exists!");
19596 #endif
19597 				/*
19598 				 * target node exists - try to unconfigure
19599 				 * device and remove the node.
19600 				 */
19601 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19602 				    saddr->cport)->cport_mutex);
19603 				rval = ndi_devi_offline(tdip,
19604 				    NDI_DEVI_REMOVE);
19605 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19606 				    saddr->cport)->cport_mutex);
19607 
19608 				if (rval == NDI_SUCCESS) {
19609 					cportinfo->cport_event_flags &=
19610 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19611 					cportinfo->cport_tgtnode_clean = B_TRUE;
19612 				} else {
19613 					/*
19614 					 * PROBLEM - the target node remained
19615 					 * and it belongs to a previously
19616 					 * attached device.
19617 					 * This happens when the file was open
19618 					 * or the node was waiting for
19619 					 * resources at the time the
19620 					 * associated device was removed.
19621 					 * Instruct event daemon to retry the
19622 					 * cleanup later.
19623 					 */
19624 					sata_log(sata_hba_inst,
19625 					    CE_WARN,
19626 					    "Application(s) accessing "
19627 					    "previously attached SATA "
19628 					    "device have to release "
19629 					    "it before newly inserted "
19630 					    "device can be made accessible.",
19631 					    saddr->cport);
19632 					cportinfo->cport_event_flags |=
19633 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19634 					cportinfo->cport_tgtnode_clean =
19635 					    B_FALSE;
19636 				}
19637 			}
19638 			if (sata_auto_online != 0) {
19639 				cportinfo->cport_event_flags |=
19640 				    SATA_EVNT_AUTOONLINE_DEVICE;
19641 			}
19642 
19643 		}
19644 	} else {
19645 		cportinfo->cport_dev_attach_time = 0;
19646 	}
19647 
19648 	event_flags = cportinfo->cport_event_flags;
19649 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19650 	if (event_flags != 0 || pmult_event_flags != 0) {
19651 		mutex_enter(&sata_hba_inst->satahba_mutex);
19652 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19653 		mutex_exit(&sata_hba_inst->satahba_mutex);
19654 		mutex_enter(&sata_mutex);
19655 		sata_event_pending |= SATA_EVNT_MAIN;
19656 		mutex_exit(&sata_mutex);
19657 	}
19658 }
19659 
19660 /*
19661  * Port Multiplier Port Device Attached Event processing.
19662  *
19663  * NOTE: No Mutex should be hold.
19664  */
19665 static void
19666 sata_process_pmdevice_attached(sata_hba_inst_t *sata_hba_inst,
19667     sata_address_t *saddr)
19668 {
19669 	sata_pmport_info_t *pmportinfo;
19670 	sata_drive_info_t *sdinfo;
19671 	sata_device_t sata_device;
19672 	dev_info_t *tdip;
19673 	uint32_t event_flags;
19674 	uint8_t cport = saddr->cport;
19675 	uint8_t pmport = saddr->pmport;
19676 	int rval;
19677 
19678 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19679 	    "Processing port %d:%d device attached", cport, pmport);
19680 
19681 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19682 
19683 	mutex_enter(&pmportinfo->pmport_mutex);
19684 
19685 	/* Clear attach event flag first */
19686 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19687 
19688 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19689 	if ((pmportinfo->pmport_state &
19690 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19691 		pmportinfo->pmport_dev_attach_time = 0;
19692 		mutex_exit(&pmportinfo->pmport_mutex);
19693 		return;
19694 	}
19695 
19696 	/*
19697 	 * If the sata_drive_info structure is found attached to the port info,
19698 	 * despite the fact the device was removed and now it is re-attached,
19699 	 * the old drive info structure was not removed.
19700 	 * Arbitrarily release device info structure.
19701 	 */
19702 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19703 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19704 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19705 		(void) kmem_free((void *)sdinfo,
19706 		    sizeof (sata_drive_info_t));
19707 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19708 		    "Arbitrarily detaching old device info.", NULL);
19709 	}
19710 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19711 
19712 	/* For sanity, re-probe the port */
19713 	sata_device.satadev_rev = SATA_DEVICE_REV;
19714 	sata_device.satadev_addr = *saddr;
19715 
19716 	/*
19717 	 * We have to exit mutex, because the HBA probe port function may
19718 	 * block on its own mutex.
19719 	 */
19720 	mutex_exit(&pmportinfo->pmport_mutex);
19721 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19722 	    (SATA_DIP(sata_hba_inst), &sata_device);
19723 	mutex_enter(&pmportinfo->pmport_mutex);
19724 
19725 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19726 	if (rval != SATA_SUCCESS) {
19727 		/* Something went wrong? Fail the port */
19728 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19729 		pmportinfo->pmport_dev_attach_time = 0;
19730 		mutex_exit(&pmportinfo->pmport_mutex);
19731 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19732 		    "SATA port %d:%d probing failed", cport, pmport));
19733 		return;
19734 	} else {
19735 		/* pmport probed successfully */
19736 		pmportinfo->pmport_state |=
19737 		    SATA_STATE_PROBED | SATA_STATE_READY;
19738 	}
19739 	/*
19740 	 * Check if a device is still attached. For sanity, check also
19741 	 * link status - if no link, there is no device.
19742 	 */
19743 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19744 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19745 	    SATA_DTYPE_NONE) {
19746 		/*
19747 		 * No device - ignore attach event.
19748 		 */
19749 		pmportinfo->pmport_dev_attach_time = 0;
19750 		mutex_exit(&pmportinfo->pmport_mutex);
19751 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19752 		    "Ignoring attach - no device connected to port %d:%d",
19753 		    cport, pmport);
19754 		return;
19755 	}
19756 
19757 	mutex_exit(&pmportinfo->pmport_mutex);
19758 	/*
19759 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19760 	 * with the hint: SE_HINT_INSERT
19761 	 */
19762 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19763 
19764 	/*
19765 	 * Port reprobing will take care of the creation of the device
19766 	 * info structure and determination of the device type.
19767 	 */
19768 	sata_device.satadev_addr = *saddr;
19769 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19770 	    SATA_DEV_IDENTIFY_NORETRY);
19771 
19772 	mutex_enter(&pmportinfo->pmport_mutex);
19773 	if ((pmportinfo->pmport_state & SATA_STATE_READY) &&
19774 	    (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE)) {
19775 		/* Some device is attached to the port */
19776 		if (pmportinfo->pmport_dev_type == SATA_DTYPE_UNKNOWN) {
19777 			/*
19778 			 * A device was not successfully attached.
19779 			 * Track retry time for device identification.
19780 			 */
19781 			if (pmportinfo->pmport_dev_attach_time != 0) {
19782 				clock_t cur_time = ddi_get_lbolt();
19783 				/*
19784 				 * If the retry time limit was not exceeded,
19785 				 * reinstate attach event.
19786 				 */
19787 				if ((cur_time -
19788 				    pmportinfo->pmport_dev_attach_time) <
19789 				    drv_usectohz(
19790 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19791 					/* OK, restore attach event */
19792 					pmportinfo->pmport_event_flags |=
19793 					    SATA_EVNT_DEVICE_ATTACHED;
19794 				} else {
19795 					/* Timeout - cannot identify device */
19796 					pmportinfo->pmport_dev_attach_time = 0;
19797 					sata_log(sata_hba_inst, CE_WARN,
19798 					    "Could not identify SATA device "
19799 					    "at port %d:%d",
19800 					    cport, pmport);
19801 				}
19802 			} else {
19803 				/*
19804 				 * Start tracking time for device
19805 				 * identification.
19806 				 * Save current time (lbolt value).
19807 				 */
19808 				pmportinfo->pmport_dev_attach_time =
19809 				    ddi_get_lbolt();
19810 				/* Restore attach event */
19811 				pmportinfo->pmport_event_flags |=
19812 				    SATA_EVNT_DEVICE_ATTACHED;
19813 			}
19814 		} else {
19815 			/*
19816 			 * If device was successfully attached, the subsequent
19817 			 * action depends on a state of the
19818 			 * sata_auto_online variable. If it is set to zero.
19819 			 * an explicit 'configure' command will be needed to
19820 			 * configure it. If its value is non-zero, we will
19821 			 * attempt to online (configure) the device.
19822 			 * First, log the message indicating that a device
19823 			 * was attached.
19824 			 */
19825 			pmportinfo->pmport_dev_attach_time = 0;
19826 			sata_log(sata_hba_inst, CE_WARN,
19827 			    "SATA device detected at port %d:%d",
19828 			    cport, pmport);
19829 
19830 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19831 				sata_drive_info_t new_sdinfo;
19832 
19833 				/* Log device info data */
19834 				new_sdinfo = *(SATA_PMPORTINFO_DRV_INFO(
19835 				    pmportinfo));
19836 				sata_show_drive_info(sata_hba_inst,
19837 				    &new_sdinfo);
19838 			}
19839 
19840 			mutex_exit(&pmportinfo->pmport_mutex);
19841 
19842 			/*
19843 			 * Make sure that there is no target node for that
19844 			 * device. If so, release it. It should not happen,
19845 			 * unless we had problem removing the node when
19846 			 * device was detached.
19847 			 */
19848 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19849 			    saddr->cport, saddr->pmport);
19850 			mutex_enter(&pmportinfo->pmport_mutex);
19851 			if (tdip != NULL) {
19852 
19853 #ifdef SATA_DEBUG
19854 				if ((pmportinfo->pmport_event_flags &
19855 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19856 					sata_log(sata_hba_inst, CE_WARN,
19857 					    "sata_process_device_attached: "
19858 					    "old device target node exists!");
19859 #endif
19860 				/*
19861 				 * target node exists - try to unconfigure
19862 				 * device and remove the node.
19863 				 */
19864 				mutex_exit(&pmportinfo->pmport_mutex);
19865 				rval = ndi_devi_offline(tdip,
19866 				    NDI_DEVI_REMOVE);
19867 				mutex_enter(&pmportinfo->pmport_mutex);
19868 
19869 				if (rval == NDI_SUCCESS) {
19870 					pmportinfo->pmport_event_flags &=
19871 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19872 					pmportinfo->pmport_tgtnode_clean =
19873 					    B_TRUE;
19874 				} else {
19875 					/*
19876 					 * PROBLEM - the target node remained
19877 					 * and it belongs to a previously
19878 					 * attached device.
19879 					 * This happens when the file was open
19880 					 * or the node was waiting for
19881 					 * resources at the time the
19882 					 * associated device was removed.
19883 					 * Instruct event daemon to retry the
19884 					 * cleanup later.
19885 					 */
19886 					sata_log(sata_hba_inst,
19887 					    CE_WARN,
19888 					    "Application(s) accessing "
19889 					    "previously attached SATA "
19890 					    "device have to release "
19891 					    "it before newly inserted "
19892 					    "device can be made accessible."
19893 					    "at port %d:%d",
19894 					    cport, pmport);
19895 					pmportinfo->pmport_event_flags |=
19896 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19897 					pmportinfo->pmport_tgtnode_clean =
19898 					    B_FALSE;
19899 				}
19900 			}
19901 			if (sata_auto_online != 0) {
19902 				pmportinfo->pmport_event_flags |=
19903 				    SATA_EVNT_AUTOONLINE_DEVICE;
19904 			}
19905 
19906 		}
19907 	} else {
19908 		pmportinfo->pmport_dev_attach_time = 0;
19909 	}
19910 
19911 	event_flags = pmportinfo->pmport_event_flags;
19912 	mutex_exit(&pmportinfo->pmport_mutex);
19913 	if (event_flags != 0) {
19914 		mutex_enter(&sata_hba_inst->satahba_mutex);
19915 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19916 		mutex_exit(&sata_hba_inst->satahba_mutex);
19917 		mutex_enter(&sata_mutex);
19918 		sata_event_pending |= SATA_EVNT_MAIN;
19919 		mutex_exit(&sata_mutex);
19920 	}
19921 
19922 	/* clear the reset_in_progress events */
19923 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19924 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
19925 			/* must clear flags on cport */
19926 			sata_pmult_info_t *pminfo =
19927 			    SATA_PMULT_INFO(sata_hba_inst,
19928 			    saddr->cport);
19929 			pminfo->pmult_event_flags |=
19930 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19931 		}
19932 	}
19933 }
19934 
19935 /*
19936  * Device Target Node Cleanup Event processing.
19937  * If the target node associated with a sata port device is in
19938  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
19939  * If the target node cannot be removed, the event flag is left intact,
19940  * so that event daemon may re-run this function later.
19941  *
19942  * This function cannot be called in interrupt context (it may sleep).
19943  *
19944  * NOTE: Processes cport events only, not port multiplier ports.
19945  */
19946 static void
19947 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19948     sata_address_t *saddr)
19949 {
19950 	sata_cport_info_t *cportinfo;
19951 	dev_info_t *tdip;
19952 
19953 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19954 	    "Processing port %d device target node cleanup", saddr->cport);
19955 
19956 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19957 
19958 	/*
19959 	 * Check if there is target node for that device and it is in the
19960 	 * DEVI_DEVICE_REMOVED state. If so, release it.
19961 	 */
19962 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19963 	    saddr->pmport);
19964 	if (tdip != NULL) {
19965 		/*
19966 		 * target node exists - check if it is target node of
19967 		 * a removed device.
19968 		 */
19969 		if (sata_check_device_removed(tdip) == B_TRUE) {
19970 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19971 			    "sata_process_target_node_cleanup: "
19972 			    "old device target node exists!", NULL);
19973 			/*
19974 			 * Unconfigure and remove the target node
19975 			 */
19976 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
19977 			    NDI_SUCCESS) {
19978 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19979 				    saddr->cport)->cport_mutex);
19980 				cportinfo->cport_event_flags &=
19981 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19982 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19983 				    saddr->cport)->cport_mutex);
19984 				return;
19985 			}
19986 			/*
19987 			 * Event daemon will retry the cleanup later.
19988 			 */
19989 			mutex_enter(&sata_hba_inst->satahba_mutex);
19990 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19991 			mutex_exit(&sata_hba_inst->satahba_mutex);
19992 			mutex_enter(&sata_mutex);
19993 			sata_event_pending |= SATA_EVNT_MAIN;
19994 			mutex_exit(&sata_mutex);
19995 		}
19996 	} else {
19997 		if (saddr->qual == SATA_ADDR_CPORT ||
19998 		    saddr->qual == SATA_ADDR_DCPORT) {
19999 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20000 			    saddr->cport)->cport_mutex);
20001 			cportinfo->cport_event_flags &=
20002 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
20003 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20004 			    saddr->cport)->cport_mutex);
20005 		} else {
20006 			/* sanity check */
20007 			if (SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) !=
20008 			    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
20009 			    saddr->cport) == NULL)
20010 				return;
20011 			if (SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
20012 			    saddr->pmport) == NULL)
20013 				return;
20014 
20015 			mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
20016 			    saddr->cport, saddr->pmport)->pmport_mutex);
20017 			SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
20018 			    saddr->pmport)->pmport_event_flags &=
20019 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
20020 			mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
20021 			    saddr->cport, saddr->pmport)->pmport_mutex);
20022 		}
20023 	}
20024 }
20025 
20026 /*
20027  * Device AutoOnline Event processing.
20028  * If attached device is to be onlined, an attempt is made to online this
20029  * device, but only if there is no lingering (old) target node present.
20030  * If the device cannot be onlined, the event flag is left intact,
20031  * so that event daemon may re-run this function later.
20032  *
20033  * This function cannot be called in interrupt context (it may sleep).
20034  *
20035  * NOTE: Processes cport events only, not port multiplier ports.
20036  */
20037 static void
20038 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
20039     sata_address_t *saddr)
20040 {
20041 	sata_cport_info_t *cportinfo;
20042 	sata_drive_info_t *sdinfo;
20043 	sata_device_t sata_device;
20044 	dev_info_t *tdip;
20045 
20046 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20047 	    "Processing port %d attached device auto-onlining", saddr->cport);
20048 
20049 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
20050 
20051 	/*
20052 	 * Check if device is present and recognized. If not, reset event.
20053 	 */
20054 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
20055 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
20056 		/* Nothing to online */
20057 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
20058 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20059 		    saddr->cport)->cport_mutex);
20060 		return;
20061 	}
20062 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
20063 
20064 	/*
20065 	 * Check if there is target node for this device and if it is in the
20066 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
20067 	 * the event for later processing.
20068 	 */
20069 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
20070 	    saddr->pmport);
20071 	if (tdip != NULL) {
20072 		/*
20073 		 * target node exists - check if it is target node of
20074 		 * a removed device.
20075 		 */
20076 		if (sata_check_device_removed(tdip) == B_TRUE) {
20077 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20078 			    "sata_process_device_autoonline: "
20079 			    "old device target node exists!", NULL);
20080 			/*
20081 			 * Event daemon will retry device onlining later.
20082 			 */
20083 			mutex_enter(&sata_hba_inst->satahba_mutex);
20084 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20085 			mutex_exit(&sata_hba_inst->satahba_mutex);
20086 			mutex_enter(&sata_mutex);
20087 			sata_event_pending |= SATA_EVNT_MAIN;
20088 			mutex_exit(&sata_mutex);
20089 			return;
20090 		}
20091 		/*
20092 		 * If the target node is not in the 'removed" state, assume
20093 		 * that it belongs to this device. There is nothing more to do,
20094 		 * but reset the event.
20095 		 */
20096 	} else {
20097 
20098 		/*
20099 		 * Try to online the device
20100 		 * If there is any reset-related event, remove it. We are
20101 		 * configuring the device and no state restoring is needed.
20102 		 */
20103 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20104 		    saddr->cport)->cport_mutex);
20105 		sata_device.satadev_addr = *saddr;
20106 		if (saddr->qual == SATA_ADDR_CPORT)
20107 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
20108 		else
20109 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
20110 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
20111 		if (sdinfo != NULL) {
20112 			if (sdinfo->satadrv_event_flags &
20113 			    (SATA_EVNT_DEVICE_RESET |
20114 			    SATA_EVNT_INPROC_DEVICE_RESET))
20115 				sdinfo->satadrv_event_flags = 0;
20116 			sdinfo->satadrv_event_flags |=
20117 			    SATA_EVNT_CLEAR_DEVICE_RESET;
20118 
20119 			/* Need to create a new target node. */
20120 			cportinfo->cport_tgtnode_clean = B_TRUE;
20121 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20122 			    saddr->cport)->cport_mutex);
20123 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
20124 			    sata_hba_inst, &sata_device.satadev_addr);
20125 			if (tdip == NULL) {
20126 				/*
20127 				 * Configure (onlining) failed.
20128 				 * We will NOT retry
20129 				 */
20130 				SATA_LOG_D((sata_hba_inst, CE_WARN,
20131 				    "sata_process_device_autoonline: "
20132 				    "configuring SATA device at port %d failed",
20133 				    saddr->cport));
20134 			}
20135 		} else {
20136 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20137 			    saddr->cport)->cport_mutex);
20138 		}
20139 
20140 	}
20141 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
20142 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
20143 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20144 	    saddr->cport)->cport_mutex);
20145 }
20146 
20147 
20148 static void
20149 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
20150     int hint)
20151 {
20152 	char ap[MAXPATHLEN];
20153 	nvlist_t *ev_attr_list = NULL;
20154 	int err;
20155 
20156 	/* Allocate and build sysevent attribute list */
20157 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
20158 	if (err != 0) {
20159 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20160 		    "sata_gen_sysevent: "
20161 		    "cannot allocate memory for sysevent attributes\n"));
20162 		return;
20163 	}
20164 	/* Add hint attribute */
20165 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
20166 	if (err != 0) {
20167 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20168 		    "sata_gen_sysevent: "
20169 		    "failed to add DR_HINT attr for sysevent"));
20170 		nvlist_free(ev_attr_list);
20171 		return;
20172 	}
20173 	/*
20174 	 * Add AP attribute.
20175 	 * Get controller pathname and convert it into AP pathname by adding
20176 	 * a target number.
20177 	 */
20178 	(void) snprintf(ap, MAXPATHLEN, "/devices");
20179 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
20180 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
20181 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
20182 
20183 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
20184 	if (err != 0) {
20185 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20186 		    "sata_gen_sysevent: "
20187 		    "failed to add DR_AP_ID attr for sysevent"));
20188 		nvlist_free(ev_attr_list);
20189 		return;
20190 	}
20191 
20192 	/* Generate/log sysevent */
20193 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
20194 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
20195 	if (err != DDI_SUCCESS) {
20196 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20197 		    "sata_gen_sysevent: "
20198 		    "cannot log sysevent, err code %x\n", err));
20199 	}
20200 
20201 	nvlist_free(ev_attr_list);
20202 }
20203 
20204 
20205 
20206 
20207 /*
20208  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
20209  */
20210 static void
20211 sata_set_device_removed(dev_info_t *tdip)
20212 {
20213 	int circ;
20214 
20215 	ASSERT(tdip != NULL);
20216 
20217 	ndi_devi_enter(tdip, &circ);
20218 	mutex_enter(&DEVI(tdip)->devi_lock);
20219 	DEVI_SET_DEVICE_REMOVED(tdip);
20220 	mutex_exit(&DEVI(tdip)->devi_lock);
20221 	ndi_devi_exit(tdip, circ);
20222 }
20223 
20224 
20225 /*
20226  * Set internal event instructing event daemon to try
20227  * to perform the target node cleanup.
20228  */
20229 static void
20230 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
20231     sata_address_t *saddr)
20232 {
20233 	if (saddr->qual == SATA_ADDR_CPORT ||
20234 	    saddr->qual == SATA_ADDR_DCPORT) {
20235 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20236 		    saddr->cport)->cport_mutex);
20237 		SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
20238 		    SATA_EVNT_TARGET_NODE_CLEANUP;
20239 		SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
20240 		    cport_tgtnode_clean = B_FALSE;
20241 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20242 		    saddr->cport)->cport_mutex);
20243 	} else {
20244 		mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
20245 		    saddr->cport, saddr->pmport)->pmport_mutex);
20246 		SATA_PMPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport,
20247 		    saddr->pmport) |= SATA_EVNT_TARGET_NODE_CLEANUP;
20248 		SATA_PMPORT_INFO(sata_hba_inst, saddr->cport, saddr->pmport)->
20249 		    pmport_tgtnode_clean = B_FALSE;
20250 		mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
20251 		    saddr->cport, saddr->pmport)->pmport_mutex);
20252 	}
20253 	mutex_enter(&sata_hba_inst->satahba_mutex);
20254 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20255 	mutex_exit(&sata_hba_inst->satahba_mutex);
20256 	mutex_enter(&sata_mutex);
20257 	sata_event_pending |= SATA_EVNT_MAIN;
20258 	mutex_exit(&sata_mutex);
20259 }
20260 
20261 
20262 /*
20263  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
20264  * i.e. check if the target node state indicates that it belongs to a removed
20265  * device.
20266  *
20267  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
20268  * B_FALSE otherwise.
20269  */
20270 static boolean_t
20271 sata_check_device_removed(dev_info_t *tdip)
20272 {
20273 	ASSERT(tdip != NULL);
20274 
20275 	if (DEVI_IS_DEVICE_REMOVED(tdip))
20276 		return (B_TRUE);
20277 	else
20278 		return (B_FALSE);
20279 }
20280 
20281 
20282 /*
20283  * Check for DMA error. Return B_TRUE if error, B_FALSE otherwise.
20284  */
20285 static boolean_t
20286 sata_check_for_dma_error(dev_info_t *dip, sata_pkt_txlate_t *spx)
20287 {
20288 	int fm_capability = ddi_fm_capable(dip);
20289 	ddi_fm_error_t de;
20290 
20291 	if (fm_capability & DDI_FM_DMACHK_CAPABLE) {
20292 		if (spx->txlt_buf_dma_handle != NULL) {
20293 			ddi_fm_dma_err_get(spx->txlt_buf_dma_handle, &de,
20294 			    DDI_FME_VERSION);
20295 			if (de.fme_status != DDI_SUCCESS)
20296 				return (B_TRUE);
20297 		}
20298 	}
20299 	return (B_FALSE);
20300 }
20301 
20302 
20303 /* ************************ FAULT INJECTTION **************************** */
20304 
20305 #ifdef SATA_INJECT_FAULTS
20306 
20307 static	uint32_t sata_fault_count = 0;
20308 static	uint32_t sata_fault_suspend_count = 0;
20309 
20310 /*
20311  * Inject sata pkt fault
20312  * It modifies returned values of the sata packet.
20313  * It returns immediately if:
20314  * pkt fault injection is not enabled (via sata_inject_fault,
20315  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
20316  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
20317  * pkt is not directed to specified fault controller/device
20318  * (sata_fault_ctrl_dev and sata_fault_device).
20319  * If fault controller is not specified, fault injection applies to all
20320  * controllers and devices.
20321  *
20322  * First argument is the pointer to the executed sata packet.
20323  * Second argument is a pointer to a value returned by the HBA tran_start
20324  * function.
20325  * Third argument specifies injected error. Injected sata packet faults
20326  * are the satapkt_reason values.
20327  * SATA_PKT_BUSY		-1	Not completed, busy
20328  * SATA_PKT_DEV_ERROR		1	Device reported error
20329  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
20330  * SATA_PKT_PORT_ERROR		3	Not completed, port error
20331  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
20332  * SATA_PKT_ABORTED		5	Aborted by request
20333  * SATA_PKT_TIMEOUT		6	Operation timeut
20334  * SATA_PKT_RESET		7	Aborted by reset request
20335  *
20336  * Additional global variables affecting the execution:
20337  *
20338  * sata_inject_fault_count variable specifies number of times in row the
20339  * error is injected. Value of -1 specifies permanent fault, ie. every time
20340  * the fault injection point is reached, the fault is injected and a pause
20341  * between fault injection specified by sata_inject_fault_pause_count is
20342  * ignored). Fault injection routine decrements sata_inject_fault_count
20343  * (if greater than zero) until it reaches 0. No fault is injected when
20344  * sata_inject_fault_count is 0 (zero).
20345  *
20346  * sata_inject_fault_pause_count variable specifies number of times a fault
20347  * injection is bypassed (pause between fault injections).
20348  * If set to 0, a fault is injected only a number of times specified by
20349  * sata_inject_fault_count.
20350  *
20351  * The fault counts are static, so for periodic errors they have to be manually
20352  * reset to start repetition sequence from scratch.
20353  * If the original value returned by the HBA tran_start function is not
20354  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
20355  * is injected (to avoid masking real problems);
20356  *
20357  * NOTE: In its current incarnation, this function should be invoked only for
20358  * commands executed in SYNCHRONOUS mode.
20359  */
20360 
20361 
20362 static void
20363 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
20364 {
20365 
20366 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
20367 		return;
20368 
20369 	if (sata_inject_fault_count == 0)
20370 		return;
20371 
20372 	if (fault == 0)
20373 		return;
20374 
20375 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
20376 		return;
20377 
20378 	if (sata_fault_ctrl != NULL) {
20379 		sata_pkt_txlate_t *spx =
20380 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
20381 
20382 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
20383 		    spx->txlt_sata_hba_inst->satahba_dip)
20384 			return;
20385 
20386 		if (sata_fault_device.satadev_addr.cport !=
20387 		    spkt->satapkt_device.satadev_addr.cport ||
20388 		    sata_fault_device.satadev_addr.pmport !=
20389 		    spkt->satapkt_device.satadev_addr.pmport ||
20390 		    sata_fault_device.satadev_addr.qual !=
20391 		    spkt->satapkt_device.satadev_addr.qual)
20392 			return;
20393 	}
20394 
20395 	/* Modify pkt return parameters */
20396 	if (*rval != SATA_TRAN_ACCEPTED ||
20397 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
20398 		sata_fault_count = 0;
20399 		sata_fault_suspend_count = 0;
20400 		return;
20401 	}
20402 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
20403 		/* Pause in the injection */
20404 		sata_fault_suspend_count -= 1;
20405 		return;
20406 	}
20407 
20408 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
20409 		/*
20410 		 * Init inject fault cycle. If fault count is set to -1,
20411 		 * it is a permanent fault.
20412 		 */
20413 		if (sata_inject_fault_count != -1) {
20414 			sata_fault_count = sata_inject_fault_count;
20415 			sata_fault_suspend_count =
20416 			    sata_inject_fault_pause_count;
20417 			if (sata_fault_suspend_count == 0)
20418 				sata_inject_fault_count = 0;
20419 		}
20420 	}
20421 
20422 	if (sata_fault_count != 0)
20423 		sata_fault_count -= 1;
20424 
20425 	switch (fault) {
20426 	case SATA_PKT_BUSY:
20427 		*rval = SATA_TRAN_BUSY;
20428 		spkt->satapkt_reason = SATA_PKT_BUSY;
20429 		break;
20430 
20431 	case SATA_PKT_QUEUE_FULL:
20432 		*rval = SATA_TRAN_QUEUE_FULL;
20433 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
20434 		break;
20435 
20436 	case SATA_PKT_CMD_UNSUPPORTED:
20437 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
20438 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
20439 		break;
20440 
20441 	case SATA_PKT_PORT_ERROR:
20442 		/* This is "rejected" command */
20443 		*rval = SATA_TRAN_PORT_ERROR;
20444 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
20445 		/* Additional error setup could be done here - port state */
20446 		break;
20447 
20448 	case SATA_PKT_DEV_ERROR:
20449 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
20450 		/*
20451 		 * Additional error setup could be done here
20452 		 */
20453 		break;
20454 
20455 	case SATA_PKT_ABORTED:
20456 		spkt->satapkt_reason = SATA_PKT_ABORTED;
20457 		break;
20458 
20459 	case SATA_PKT_TIMEOUT:
20460 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
20461 		/* Additional error setup could be done here */
20462 		break;
20463 
20464 	case SATA_PKT_RESET:
20465 		spkt->satapkt_reason = SATA_PKT_RESET;
20466 		/*
20467 		 * Additional error setup could be done here - device reset
20468 		 */
20469 		break;
20470 
20471 	default:
20472 		break;
20473 	}
20474 }
20475 
20476 #endif
20477 
20478 /*
20479  * SATA Trace Ring Buffer
20480  * ----------------------
20481  *
20482  * Overview
20483  *
20484  * The SATA trace ring buffer is a ring buffer created and managed by
20485  * the SATA framework module that can be used by any module or driver
20486  * within the SATA framework to store debug messages.
20487  *
20488  * Ring Buffer Interfaces:
20489  *
20490  *	sata_vtrace_debug()	<-- Adds debug message to ring buffer
20491  *	sata_trace_debug()	<-- Wraps varargs into sata_vtrace_debug()
20492  *
20493  *	Note that the sata_trace_debug() interface was created to give
20494  *	consumers the flexibilty of sending debug messages to ring buffer
20495  *	as variable arguments.  Consumers can send type va_list debug
20496  *	messages directly to sata_vtrace_debug(). The sata_trace_debug()
20497  *	and sata_vtrace_debug() relationship is similar to that of
20498  *	cmn_err(9F) and vcmn_err(9F).
20499  *
20500  * Below is a diagram of the SATA trace ring buffer interfaces and
20501  * sample consumers:
20502  *
20503  * +---------------------------------+
20504  * |    o  o  SATA Framework Module  |
20505  * | o  SATA  o     +------------------+      +------------------+
20506  * |o   Trace  o <--|sata_vtrace_debug/|<-----|SATA HBA Driver #1|
20507  * |o   R-Buf  o    |sata_trace_debug  |<--+  +------------------+
20508  * | o        o     +------------------+   |  +------------------+
20509  * |    o  o                ^        |     +--|SATA HBA Driver #2|
20510  * |                        |        |        +------------------+
20511  * |           +------------------+  |
20512  * |           |SATA Debug Message|  |
20513  * |           +------------------+  |
20514  * +---------------------------------+
20515  *
20516  * Supporting Routines:
20517  *
20518  *	sata_trace_rbuf_alloc()	<-- Initializes ring buffer
20519  *	sata_trace_rbuf_free()	<-- Destroys ring buffer
20520  *	sata_trace_dmsg_alloc() <-- Creates or reuses buffer in ring buffer
20521  *	sata_trace_dmsg_free()	<-- Destroys content of ring buffer
20522  *
20523  * The default SATA trace ring buffer size is defined by DMSG_RING_SIZE.
20524  * The ring buffer size can be adjusted by setting dmsg_ring_size in
20525  * /etc/system to desired size in unit of bytes.
20526  *
20527  * The individual debug message size in the ring buffer is restricted
20528  * to DMSG_BUF_SIZE.
20529  */
20530 void
20531 sata_vtrace_debug(dev_info_t *dip, const char *fmt, va_list ap)
20532 {
20533 	sata_trace_dmsg_t *dmsg;
20534 
20535 	if (sata_debug_rbuf == NULL) {
20536 		return;
20537 	}
20538 
20539 	/*
20540 	 * If max size of ring buffer is smaller than size
20541 	 * required for one debug message then just return
20542 	 * since we have no room for the debug message.
20543 	 */
20544 	if (sata_debug_rbuf->maxsize < (sizeof (sata_trace_dmsg_t))) {
20545 		return;
20546 	}
20547 
20548 	mutex_enter(&sata_debug_rbuf->lock);
20549 
20550 	/* alloc or reuse on ring buffer */
20551 	dmsg = sata_trace_dmsg_alloc();
20552 
20553 	if (dmsg == NULL) {
20554 		/* resource allocation failed */
20555 		mutex_exit(&sata_debug_rbuf->lock);
20556 		return;
20557 	}
20558 
20559 	dmsg->dip = dip;
20560 	gethrestime(&dmsg->timestamp);
20561 
20562 	(void) vsnprintf(dmsg->buf, sizeof (dmsg->buf), fmt, ap);
20563 
20564 	mutex_exit(&sata_debug_rbuf->lock);
20565 }
20566 
20567 void
20568 sata_trace_debug(dev_info_t *dip, const char *fmt, ...)
20569 {
20570 	va_list ap;
20571 
20572 	va_start(ap, fmt);
20573 	sata_vtrace_debug(dip, fmt, ap);
20574 	va_end(ap);
20575 }
20576 
20577 /*
20578  * This routine is used to manage debug messages
20579  * on ring buffer.
20580  */
20581 static sata_trace_dmsg_t *
20582 sata_trace_dmsg_alloc(void)
20583 {
20584 	sata_trace_dmsg_t *dmsg_alloc, *dmsg = sata_debug_rbuf->dmsgp;
20585 
20586 	if (sata_debug_rbuf->looped == TRUE) {
20587 		sata_debug_rbuf->dmsgp = dmsg->next;
20588 		return (sata_debug_rbuf->dmsgp);
20589 	}
20590 
20591 	/*
20592 	 * If we're looping for the first time,
20593 	 * connect the ring.
20594 	 */
20595 	if (((sata_debug_rbuf->size + (sizeof (sata_trace_dmsg_t))) >
20596 	    sata_debug_rbuf->maxsize) && (sata_debug_rbuf->dmsgh != NULL)) {
20597 		dmsg->next = sata_debug_rbuf->dmsgh;
20598 		sata_debug_rbuf->dmsgp = sata_debug_rbuf->dmsgh;
20599 		sata_debug_rbuf->looped = TRUE;
20600 		return (sata_debug_rbuf->dmsgp);
20601 	}
20602 
20603 	/* If we've gotten this far then memory allocation is needed */
20604 	dmsg_alloc = kmem_zalloc(sizeof (sata_trace_dmsg_t), KM_NOSLEEP);
20605 	if (dmsg_alloc == NULL) {
20606 		sata_debug_rbuf->allocfailed++;
20607 		return (dmsg_alloc);
20608 	} else {
20609 		sata_debug_rbuf->size += sizeof (sata_trace_dmsg_t);
20610 	}
20611 
20612 	if (sata_debug_rbuf->dmsgp != NULL) {
20613 		dmsg->next = dmsg_alloc;
20614 		sata_debug_rbuf->dmsgp = dmsg->next;
20615 		return (sata_debug_rbuf->dmsgp);
20616 	} else {
20617 		/*
20618 		 * We should only be here if we're initializing
20619 		 * the ring buffer.
20620 		 */
20621 		if (sata_debug_rbuf->dmsgh == NULL) {
20622 			sata_debug_rbuf->dmsgh = dmsg_alloc;
20623 		} else {
20624 			/* Something is wrong */
20625 			kmem_free(dmsg_alloc, sizeof (sata_trace_dmsg_t));
20626 			return (NULL);
20627 		}
20628 
20629 		sata_debug_rbuf->dmsgp = dmsg_alloc;
20630 		return (sata_debug_rbuf->dmsgp);
20631 	}
20632 }
20633 
20634 
20635 /*
20636  * Free all messages on debug ring buffer.
20637  */
20638 static void
20639 sata_trace_dmsg_free(void)
20640 {
20641 	sata_trace_dmsg_t *dmsg_next, *dmsg = sata_debug_rbuf->dmsgh;
20642 
20643 	while (dmsg != NULL) {
20644 		dmsg_next = dmsg->next;
20645 		kmem_free(dmsg, sizeof (sata_trace_dmsg_t));
20646 
20647 		/*
20648 		 * If we've looped around the ring than we're done.
20649 		 */
20650 		if (dmsg_next == sata_debug_rbuf->dmsgh) {
20651 			break;
20652 		} else {
20653 			dmsg = dmsg_next;
20654 		}
20655 	}
20656 }
20657 
20658 
20659 /*
20660  * This function can block
20661  */
20662 static void
20663 sata_trace_rbuf_alloc(void)
20664 {
20665 	sata_debug_rbuf = kmem_zalloc(sizeof (sata_trace_rbuf_t), KM_SLEEP);
20666 
20667 	mutex_init(&sata_debug_rbuf->lock, NULL, MUTEX_DRIVER, NULL);
20668 
20669 	if (dmsg_ring_size > 0) {
20670 		sata_debug_rbuf->maxsize = (size_t)dmsg_ring_size;
20671 	}
20672 }
20673 
20674 
20675 static void
20676 sata_trace_rbuf_free(void)
20677 {
20678 	sata_trace_dmsg_free();
20679 	mutex_destroy(&sata_debug_rbuf->lock);
20680 	kmem_free(sata_debug_rbuf, sizeof (sata_trace_rbuf_t));
20681 }
20682 
20683 /*
20684  * If SATA_DEBUG is not defined then this routine is called instead
20685  * of sata_log() via the SATA_LOG_D macro.
20686  */
20687 static void
20688 sata_trace_log(sata_hba_inst_t *sata_hba_inst, uint_t level,
20689     const char *fmt, ...)
20690 {
20691 #ifndef __lock_lint
20692 	_NOTE(ARGUNUSED(level))
20693 #endif
20694 
20695 	dev_info_t *dip = NULL;
20696 	va_list ap;
20697 
20698 	if (sata_hba_inst != NULL) {
20699 		dip = SATA_DIP(sata_hba_inst);
20700 	}
20701 
20702 	va_start(ap, fmt);
20703 	sata_vtrace_debug(dip, fmt, ap);
20704 	va_end(ap);
20705 }
20706