xref: /illumos-gate/usr/src/uts/common/io/sata/impl/sata.c (revision b1e2e3fb17324e9ddf43db264a0c64da7756d9e6)
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  * Copyright 2017 Nexenta Systems, Inc.  All rights reserved.
27  * Copyright 2016 Argo Technologies SA
28  * Copyright (c) 2018, Joyent, Inc.
29  */
30 
31 /*
32  * SATA Framework
33  * Generic SATA Host Adapter Implementation
34  */
35 
36 #include <sys/conf.h>
37 #include <sys/file.h>
38 #include <sys/ddi.h>
39 #include <sys/sunddi.h>
40 #include <sys/modctl.h>
41 #include <sys/cmn_err.h>
42 #include <sys/errno.h>
43 #include <sys/thread.h>
44 #include <sys/kstat.h>
45 #include <sys/note.h>
46 #include <sys/sysevent.h>
47 #include <sys/sysevent/eventdefs.h>
48 #include <sys/sysevent/dr.h>
49 #include <sys/taskq.h>
50 #include <sys/disp.h>
51 #include <sys/sdt.h>
52 
53 #include <sys/sata/impl/sata.h>
54 #include <sys/sata/sata_hba.h>
55 #include <sys/sata/sata_defs.h>
56 #include <sys/sata/sata_cfgadm.h>
57 #include <sys/sata/sata_blacklist.h>
58 #include <sys/sata/sata_satl.h>
59 
60 #include <sys/scsi/impl/spc3_types.h>
61 
62 /*
63  * FMA header files
64  */
65 #include <sys/ddifm.h>
66 #include <sys/fm/protocol.h>
67 #include <sys/fm/util.h>
68 #include <sys/fm/io/ddi.h>
69 
70 /* Debug flags - defined in sata.h */
71 int	sata_debug_flags = 0;
72 int	sata_msg = 0;
73 
74 /*
75  * Flags enabling selected SATA HBA framework functionality
76  */
77 #define	SATA_ENABLE_QUEUING		1
78 #define	SATA_ENABLE_NCQ			2
79 #define	SATA_ENABLE_PROCESS_EVENTS	4
80 #define	SATA_ENABLE_PMULT_FBS		8 /* FIS-Based Switching */
81 int sata_func_enable =
82 	SATA_ENABLE_PROCESS_EVENTS | SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ;
83 
84 /*
85  * Global variable setting default maximum queue depth (NCQ or TCQ)
86  * Note:minimum queue depth is 1
87  */
88 int sata_max_queue_depth = SATA_MAX_QUEUE_DEPTH; /* max NCQ/TCQ queue depth */
89 
90 /*
91  * Currently used default NCQ/TCQ queue depth. It is set-up during the driver
92  * initialization, using value from sata_max_queue_depth
93  * It is adjusted to minimum supported by the controller and by the device,
94  * if queueing is enabled.
95  */
96 static	int sata_current_max_qdepth;
97 
98 /*
99  * Global variable determining the default behavior after device hotpluggin.
100  * If non-zero, the hotplugged device is onlined (if possible) without explicit
101  * IOCTL request (AP_CONFIGURE).
102  * If zero, hotplugged device is identified, but not onlined.
103  * Enabling (AP_CONNECT) device port with an attached device does not result
104  * in device onlining regardless of the flag setting
105  */
106 int sata_auto_online = 0;
107 
108 #ifdef SATA_DEBUG
109 
110 #define	SATA_LOG_D(args)	sata_log args
111 uint64_t mbuf_count = 0;
112 uint64_t mbuffail_count = 0;
113 
114 sata_atapi_cmd_t sata_atapi_trace[64];
115 uint32_t sata_atapi_trace_index = 0;
116 int sata_atapi_trace_save = 1;
117 static	void sata_save_atapi_trace(sata_pkt_txlate_t *, int);
118 #define	SATAATAPITRACE(spx, count)	if (sata_atapi_trace_save) \
119     sata_save_atapi_trace(spx, count);
120 
121 #else
122 #define	SATA_LOG_D(args)	sata_trace_log args
123 #define	SATAATAPITRACE(spx, count)
124 #endif
125 
126 #if 0
127 static void
128 sata_test_atapi_packet_command(sata_hba_inst_t *, int);
129 #endif
130 
131 #ifdef SATA_INJECT_FAULTS
132 
133 #define		SATA_INJECT_PKT_FAULT	1
134 uint32_t	sata_inject_fault = 0;
135 
136 uint32_t	sata_inject_fault_count = 0;
137 uint32_t	sata_inject_fault_pause_count = 0;
138 uint32_t	sata_fault_type = 0;
139 uint32_t	sata_fault_cmd = 0;
140 dev_info_t	*sata_fault_ctrl = NULL;
141 sata_device_t	sata_fault_device;
142 
143 static	void sata_inject_pkt_fault(sata_pkt_t *, int *, int);
144 
145 #endif
146 
147 #define	LEGACY_HWID_LEN	64	/* Model (40) + Serial (20) + pad */
148 
149 static char sata_rev_tag[] = {"1.46"};
150 
151 /*
152  * SATA cb_ops functions
153  */
154 static	int sata_hba_open(dev_t *, int, int, cred_t *);
155 static	int sata_hba_close(dev_t, int, int, cred_t *);
156 static	int sata_hba_ioctl(dev_t, int, intptr_t, int, cred_t *,	int *);
157 
158 /*
159  * SCSA required entry points
160  */
161 static	int sata_scsi_tgt_init(dev_info_t *, dev_info_t *,
162     scsi_hba_tran_t *, struct scsi_device *);
163 static	int sata_scsi_tgt_probe(struct scsi_device *,
164     int (*callback)(void));
165 static void sata_scsi_tgt_free(dev_info_t *, dev_info_t *,
166     scsi_hba_tran_t *, struct scsi_device *);
167 static	int sata_scsi_start(struct scsi_address *, struct scsi_pkt *);
168 static	int sata_scsi_abort(struct scsi_address *, struct scsi_pkt *);
169 static	int sata_scsi_reset(struct scsi_address *, int);
170 static	int sata_scsi_getcap(struct scsi_address *, char *, int);
171 static	int sata_scsi_setcap(struct scsi_address *, char *, int, int);
172 static	struct scsi_pkt *sata_scsi_init_pkt(struct scsi_address *,
173     struct scsi_pkt *, struct buf *, int, int, int, int, int (*)(caddr_t),
174     caddr_t);
175 static	void sata_scsi_destroy_pkt(struct scsi_address *, struct scsi_pkt *);
176 static	void sata_scsi_dmafree(struct scsi_address *, struct scsi_pkt *);
177 static	void sata_scsi_sync_pkt(struct scsi_address *, struct scsi_pkt *);
178 
179 /*
180  * SATA HBA interface functions are defined in sata_hba.h header file
181  */
182 
183 /* Event processing functions */
184 static	void sata_event_daemon(void *);
185 static	void sata_event_thread_control(int);
186 static	void sata_process_controller_events(sata_hba_inst_t *sata_hba_inst);
187 static	void sata_process_pmult_events(sata_hba_inst_t *, uint8_t);
188 static	void sata_process_device_reset(sata_hba_inst_t *, sata_address_t *);
189 static	void sata_process_pmdevice_reset(sata_hba_inst_t *, sata_address_t *);
190 static	void sata_process_port_failed_event(sata_hba_inst_t *,
191     sata_address_t *);
192 static	void sata_process_port_link_events(sata_hba_inst_t *,
193     sata_address_t *);
194 static	void sata_process_pmport_link_events(sata_hba_inst_t *,
195     sata_address_t *);
196 static	void sata_process_device_detached(sata_hba_inst_t *, sata_address_t *);
197 static	void sata_process_pmdevice_detached(sata_hba_inst_t *,
198     sata_address_t *);
199 static	void sata_process_device_attached(sata_hba_inst_t *, sata_address_t *);
200 static	void sata_process_pmdevice_attached(sata_hba_inst_t *,
201     sata_address_t *);
202 static	void sata_process_port_pwr_change(sata_hba_inst_t *, sata_address_t *);
203 static	void sata_process_cntrl_pwr_level_change(sata_hba_inst_t *);
204 static	void sata_process_target_node_cleanup(sata_hba_inst_t *,
205     sata_address_t *);
206 static	void sata_process_device_autoonline(sata_hba_inst_t *,
207     sata_address_t *saddr);
208 
209 /*
210  * Local translation functions
211  */
212 static	int sata_txlt_inquiry(sata_pkt_txlate_t *);
213 static	int sata_txlt_test_unit_ready(sata_pkt_txlate_t *);
214 static	int sata_txlt_start_stop_unit(sata_pkt_txlate_t *);
215 static	int sata_txlt_read_capacity(sata_pkt_txlate_t *);
216 static	int sata_txlt_read_capacity16(sata_pkt_txlate_t *);
217 static  int sata_txlt_unmap(sata_pkt_txlate_t *);
218 static	int sata_txlt_request_sense(sata_pkt_txlate_t *);
219 static	int sata_txlt_read(sata_pkt_txlate_t *);
220 static	int sata_txlt_write(sata_pkt_txlate_t *);
221 static	int sata_txlt_log_sense(sata_pkt_txlate_t *);
222 static	int sata_txlt_log_select(sata_pkt_txlate_t *);
223 static	int sata_txlt_mode_sense(sata_pkt_txlate_t *);
224 static	int sata_txlt_mode_select(sata_pkt_txlate_t *);
225 static	int sata_txlt_ata_pass_thru(sata_pkt_txlate_t *);
226 static	int sata_txlt_synchronize_cache(sata_pkt_txlate_t *);
227 static	int sata_txlt_write_buffer(sata_pkt_txlate_t *);
228 static	int sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *);
229 
230 static	int sata_hba_start(sata_pkt_txlate_t *, int *);
231 static	int sata_txlt_invalid_command(sata_pkt_txlate_t *);
232 static	int sata_txlt_check_condition(sata_pkt_txlate_t *, uchar_t, uchar_t);
233 static	int sata_txlt_lba_out_of_range(sata_pkt_txlate_t *);
234 static	int sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *);
235 static  int sata_txlt_unmap_nodata_cmd(sata_pkt_txlate_t *);
236 static	void sata_txlt_rw_completion(sata_pkt_t *);
237 static	void sata_txlt_nodata_cmd_completion(sata_pkt_t *);
238 static	void sata_txlt_apt_completion(sata_pkt_t *sata_pkt);
239 static	void sata_txlt_unmap_completion(sata_pkt_t *sata_pkt);
240 static	void sata_txlt_download_mcode_cmd_completion(sata_pkt_t *);
241 static	int sata_emul_rw_completion(sata_pkt_txlate_t *);
242 static	void sata_fill_ata_return_desc(sata_pkt_t *, uint8_t, uint8_t,
243     uint8_t);
244 static	struct scsi_extended_sense *sata_immediate_error_response(
245     sata_pkt_txlate_t *, int);
246 static	struct scsi_extended_sense *sata_arq_sense(sata_pkt_txlate_t *);
247 
248 static	int sata_txlt_atapi(sata_pkt_txlate_t *);
249 static	void sata_txlt_atapi_completion(sata_pkt_t *);
250 
251 /*
252  * Local functions for ioctl
253  */
254 static	int32_t sata_get_port_num(sata_hba_inst_t *,  struct devctl_iocdata *);
255 static	void sata_cfgadm_state(sata_hba_inst_t *, int32_t,
256     devctl_ap_state_t *);
257 static	dev_info_t *sata_get_target_dip(dev_info_t *, uint8_t, uint8_t);
258 static	dev_info_t *sata_get_scsi_target_dip(dev_info_t *, sata_address_t *);
259 static	dev_info_t *sata_devt_to_devinfo(dev_t);
260 static	int sata_ioctl_connect(sata_hba_inst_t *, sata_device_t *);
261 static	int sata_ioctl_disconnect(sata_hba_inst_t *, sata_device_t *);
262 static	int sata_ioctl_configure(sata_hba_inst_t *, sata_device_t *);
263 static	int sata_ioctl_unconfigure(sata_hba_inst_t *, sata_device_t *);
264 static	int sata_ioctl_activate(sata_hba_inst_t *, sata_device_t *);
265 static	int sata_ioctl_deactivate(sata_hba_inst_t *, sata_device_t *);
266 static	int sata_ioctl_reset_port(sata_hba_inst_t *, sata_device_t *);
267 static	int sata_ioctl_reset_device(sata_hba_inst_t *, sata_device_t *);
268 static	int sata_ioctl_reset_all(sata_hba_inst_t *);
269 static	int sata_ioctl_port_self_test(sata_hba_inst_t *, sata_device_t *);
270 static	int sata_ioctl_get_device_path(sata_hba_inst_t *, sata_device_t *,
271     sata_ioctl_data_t *, int mode);
272 static	int sata_ioctl_get_ap_type(sata_hba_inst_t *, sata_device_t *,
273     sata_ioctl_data_t *, int mode);
274 static	int sata_ioctl_get_model_info(sata_hba_inst_t *, sata_device_t *,
275     sata_ioctl_data_t *, int mode);
276 static	int sata_ioctl_get_revfirmware_info(sata_hba_inst_t *, sata_device_t *,
277     sata_ioctl_data_t *, int mode);
278 static	int sata_ioctl_get_serialnumber_info(sata_hba_inst_t *,
279     sata_device_t *, sata_ioctl_data_t *, int mode);
280 
281 /*
282  * Local functions
283  */
284 static	void sata_remove_hba_instance(dev_info_t *);
285 static	int sata_validate_sata_hba_tran(dev_info_t *, sata_hba_tran_t *);
286 static	void sata_probe_ports(sata_hba_inst_t *);
287 static	void sata_probe_pmports(sata_hba_inst_t *, uint8_t);
288 static	int sata_reprobe_port(sata_hba_inst_t *, sata_device_t *, int);
289 static	int sata_reprobe_pmult(sata_hba_inst_t *, sata_device_t *, int);
290 static	int sata_reprobe_pmport(sata_hba_inst_t *, sata_device_t *, int);
291 static	int sata_alloc_pmult(sata_hba_inst_t *, sata_device_t *);
292 static	void sata_free_pmult(sata_hba_inst_t *, sata_device_t *);
293 static	int sata_add_device(dev_info_t *, sata_hba_inst_t *, sata_device_t *);
294 static	int sata_offline_device(sata_hba_inst_t *, sata_device_t *,
295     sata_drive_info_t *);
296 static	dev_info_t *sata_create_target_node(dev_info_t *, sata_hba_inst_t *,
297     sata_address_t *);
298 static	void sata_remove_target_node(sata_hba_inst_t *,
299     sata_address_t *);
300 static	int sata_validate_scsi_address(sata_hba_inst_t *,
301     struct scsi_address *, sata_device_t *);
302 static	int sata_validate_sata_address(sata_hba_inst_t *, int, int, int);
303 static	sata_pkt_t *sata_pkt_alloc(sata_pkt_txlate_t *, int (*)(caddr_t));
304 static	void sata_pkt_free(sata_pkt_txlate_t *);
305 static	int sata_dma_buf_setup(sata_pkt_txlate_t *, int, int (*)(caddr_t),
306     caddr_t, ddi_dma_attr_t *);
307 static	void sata_common_free_dma_rsrcs(sata_pkt_txlate_t *);
308 static	int sata_probe_device(sata_hba_inst_t *, sata_device_t *);
309 static	sata_drive_info_t *sata_get_device_info(sata_hba_inst_t *,
310     sata_device_t *);
311 static	int sata_identify_device(sata_hba_inst_t *, sata_drive_info_t *);
312 static	void sata_reidentify_device(sata_pkt_txlate_t *);
313 static	struct buf *sata_alloc_local_buffer(sata_pkt_txlate_t *, int);
314 static	void sata_free_local_buffer(sata_pkt_txlate_t *);
315 static	uint64_t sata_check_capacity(sata_drive_info_t *);
316 void	sata_adjust_dma_attr(sata_drive_info_t *, ddi_dma_attr_t *,
317     ddi_dma_attr_t *);
318 static	int sata_fetch_device_identify_data(sata_hba_inst_t *,
319     sata_drive_info_t *);
320 static	void sata_update_port_info(sata_hba_inst_t *, sata_device_t *);
321 static	void sata_update_pmport_info(sata_hba_inst_t *, sata_device_t *);
322 static	void sata_update_port_scr(sata_port_scr_t *, sata_device_t *);
323 static	int sata_set_dma_mode(sata_hba_inst_t *, sata_drive_info_t *);
324 static	int sata_set_cache_mode(sata_hba_inst_t *, sata_drive_info_t *, int);
325 static	int sata_set_rmsn(sata_hba_inst_t *, sata_drive_info_t *, int);
326 static	int sata_set_drive_features(sata_hba_inst_t *,
327     sata_drive_info_t *, int flag);
328 static	void sata_init_write_cache_mode(sata_drive_info_t *sdinfo);
329 static	int sata_initialize_device(sata_hba_inst_t *, sata_drive_info_t *);
330 static	void sata_identdev_to_inquiry(sata_hba_inst_t *, sata_drive_info_t *,
331     uint8_t *);
332 static	int sata_get_atapi_inquiry_data(sata_hba_inst_t *, sata_address_t *,
333     struct scsi_inquiry *);
334 static	int sata_build_msense_page_1(sata_drive_info_t *, int, uint8_t *);
335 static	int sata_build_msense_page_8(sata_drive_info_t *, int, uint8_t *);
336 static	int sata_build_msense_page_1a(sata_drive_info_t *, int, uint8_t *);
337 static	int sata_build_msense_page_1c(sata_drive_info_t *, int, uint8_t *);
338 static	int sata_build_msense_page_30(sata_drive_info_t *, int, uint8_t *);
339 static	int sata_mode_select_page_8(sata_pkt_txlate_t *,
340     struct mode_cache_scsi3 *, int, int *, int *, int *);
341 static	int sata_mode_select_page_1a(sata_pkt_txlate_t *,
342     struct mode_info_power_cond *, int, int *, int *, int *);
343 static	int sata_mode_select_page_1c(sata_pkt_txlate_t *,
344     struct mode_info_excpt_page *, int, int *, int *, int *);
345 static	int sata_mode_select_page_30(sata_pkt_txlate_t *,
346     struct mode_acoustic_management *, int, int *, int *, int *);
347 
348 static	int sata_build_lsense_page_0(sata_drive_info_t *, uint8_t *);
349 static	int sata_build_lsense_page_10(sata_drive_info_t *, uint8_t *,
350     sata_hba_inst_t *);
351 static	int sata_build_lsense_page_2f(sata_drive_info_t *, uint8_t *,
352     sata_hba_inst_t *);
353 static	int sata_build_lsense_page_30(sata_drive_info_t *, uint8_t *,
354     sata_hba_inst_t *);
355 static	int sata_build_lsense_page_0e(sata_drive_info_t *, uint8_t *,
356     sata_pkt_txlate_t *);
357 
358 static	void sata_set_arq_data(sata_pkt_t *);
359 static	void sata_build_read_verify_cmd(sata_cmd_t *, uint16_t, uint64_t);
360 static	void sata_build_generic_cmd(sata_cmd_t *, uint8_t);
361 static	uint8_t sata_get_standby_timer(uint8_t *timer);
362 
363 static	void sata_save_drive_settings(sata_drive_info_t *);
364 static	void sata_show_drive_info(sata_hba_inst_t *, sata_drive_info_t *);
365 static	void sata_show_pmult_info(sata_hba_inst_t *, sata_device_t *);
366 static	void sata_log(sata_hba_inst_t *, uint_t, char *fmt, ...);
367 static	void sata_trace_log(sata_hba_inst_t *, uint_t, const char *fmt, ...);
368 static	int sata_fetch_smart_return_status(sata_hba_inst_t *,
369     sata_drive_info_t *);
370 static	int sata_fetch_smart_data(sata_hba_inst_t *, sata_drive_info_t *,
371     struct smart_data *);
372 static	int sata_smart_selftest_log(sata_hba_inst_t *,
373     sata_drive_info_t *,
374     struct smart_selftest_log *);
375 static	int sata_ext_smart_selftest_read_log(sata_hba_inst_t *,
376     sata_drive_info_t *, struct smart_ext_selftest_log *, uint16_t);
377 static	int sata_smart_read_log(sata_hba_inst_t *, sata_drive_info_t *,
378     uint8_t *, uint8_t, uint8_t);
379 static	int sata_read_log_ext_directory(sata_hba_inst_t *, sata_drive_info_t *,
380     struct read_log_ext_directory *);
381 static	void sata_gen_sysevent(sata_hba_inst_t *, sata_address_t *, int);
382 static	void sata_xlate_errors(sata_pkt_txlate_t *);
383 static	void sata_decode_device_error(sata_pkt_txlate_t *,
384     struct scsi_extended_sense *);
385 static	void sata_set_device_removed(dev_info_t *);
386 static	boolean_t sata_check_device_removed(dev_info_t *);
387 static	void sata_set_target_node_cleanup(sata_hba_inst_t *, sata_address_t *);
388 static	int sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *,
389     sata_drive_info_t *);
390 static	int sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *,
391     sata_drive_info_t *);
392 static	void sata_atapi_packet_cmd_setup(sata_cmd_t *, sata_drive_info_t *);
393 static	void sata_fixed_sense_data_preset(struct scsi_extended_sense *);
394 static  void sata_target_devid_register(dev_info_t *, sata_drive_info_t *);
395 static  int sata_check_modser(char *, int);
396 
397 /*
398  * FMA
399  */
400 static boolean_t sata_check_for_dma_error(dev_info_t *, sata_pkt_txlate_t *);
401 
402 
403 /*
404  * SATA Framework will ignore SATA HBA driver cb_ops structure and
405  * register following one with SCSA framework.
406  * Open & close are provided, so scsi framework will not use its own
407  */
408 static struct cb_ops sata_cb_ops = {
409 	sata_hba_open,			/* open */
410 	sata_hba_close,			/* close */
411 	nodev,				/* strategy */
412 	nodev,				/* print */
413 	nodev,				/* dump */
414 	nodev,				/* read */
415 	nodev,				/* write */
416 	sata_hba_ioctl,			/* ioctl */
417 	nodev,				/* devmap */
418 	nodev,				/* mmap */
419 	nodev,				/* segmap */
420 	nochpoll,			/* chpoll */
421 	ddi_prop_op,			/* cb_prop_op */
422 	0,				/* streamtab */
423 	D_NEW | D_MP,			/* cb_flag */
424 	CB_REV,				/* rev */
425 	nodev,				/* aread */
426 	nodev				/* awrite */
427 };
428 
429 
430 extern struct mod_ops mod_miscops;
431 extern uchar_t	scsi_cdb_size[];
432 
433 static struct modlmisc modlmisc = {
434 	&mod_miscops,			/* Type of module */
435 	"SATA Module"			/* module name */
436 };
437 
438 
439 static struct modlinkage modlinkage = {
440 	MODREV_1,
441 	(void *)&modlmisc,
442 	NULL
443 };
444 
445 /*
446  * Default sata pkt timeout. Used when a target driver scsi_pkt time is zero,
447  * i.e. when scsi_pkt has not timeout specified.
448  */
449 static int sata_default_pkt_time = 60;	/* 60 seconds */
450 
451 /*
452  * Intermediate buffer device access attributes - they are required,
453  * but not necessarily used.
454  */
455 static ddi_device_acc_attr_t sata_acc_attr = {
456 	DDI_DEVICE_ATTR_V0,
457 	DDI_STRUCTURE_LE_ACC,
458 	DDI_STRICTORDER_ACC
459 };
460 
461 
462 /*
463  * Mutexes protecting structures in multithreaded operations.
464  * Because events are relatively rare, a single global mutex protecting
465  * data structures should be sufficient. To increase performance, add
466  * separate mutex per each sata port and use global mutex only to protect
467  * common data structures.
468  */
469 static	kmutex_t sata_mutex;		/* protects sata_hba_list */
470 static	kmutex_t sata_log_mutex;	/* protects log */
471 
472 static	char sata_log_buf[256];
473 
474 /*
475  * sata trace debug
476  */
477 static	sata_trace_rbuf_t *sata_debug_rbuf;
478 static	sata_trace_dmsg_t *sata_trace_dmsg_alloc(void);
479 static	void sata_trace_dmsg_free(void);
480 static	void sata_trace_rbuf_alloc(void);
481 static	void sata_trace_rbuf_free(void);
482 
483 int	dmsg_ring_size = DMSG_RING_SIZE;
484 
485 /* Default write cache setting for SATA hard disks */
486 int	sata_write_cache = 1;		/* enabled */
487 
488 /* Default write cache setting for SATA ATAPI CD/DVD */
489 int	sata_atapicdvd_write_cache = 1; /* enabled */
490 
491 /* Default write cache setting for SATA ATAPI tape */
492 int	sata_atapitape_write_cache = 1; /* enabled */
493 
494 /* Default write cache setting for SATA ATAPI disk */
495 int	sata_atapidisk_write_cache = 1;	/* enabled */
496 
497 /*
498  * Linked list of HBA instances
499  */
500 static	sata_hba_inst_t *sata_hba_list = NULL;
501 static	sata_hba_inst_t *sata_hba_list_tail = NULL;
502 /*
503  * Pointer to per-instance SATA HBA soft structure is stored in sata_hba_tran
504  * structure and in sata soft state.
505  */
506 
507 /*
508  * Event daemon related variables
509  */
510 static	kmutex_t sata_event_mutex;
511 static	kcondvar_t sata_event_cv;
512 static	kthread_t *sata_event_thread = NULL;
513 static	int sata_event_thread_terminate = 0;
514 static	int sata_event_pending = 0;
515 static	int sata_event_thread_active = 0;
516 extern	pri_t minclsyspri;
517 
518 /*
519  * NCQ error recovery command
520  */
521 static const sata_cmd_t sata_rle_cmd = {
522 	SATA_CMD_REV,
523 	NULL,
524 	{
525 		SATA_DIR_READ
526 	},
527 	ATA_ADDR_LBA48,
528 	0,
529 	0,
530 	0,
531 	0,
532 	0,
533 	1,
534 	READ_LOG_EXT_NCQ_ERROR_RECOVERY,
535 	0,
536 	0,
537 	0,
538 	SATAC_READ_LOG_EXT,
539 	0,
540 	0,
541 	0,
542 };
543 
544 /*
545  * ATAPI error recovery CDB
546  */
547 static const uint8_t sata_rqsense_cdb[SATA_ATAPI_RQSENSE_CDB_LEN] = {
548 	SCMD_REQUEST_SENSE,
549 	0,			/* Only fixed RQ format is supported */
550 	0,
551 	0,
552 	SATA_ATAPI_MIN_RQSENSE_LEN, /* Less data may be returned */
553 	0
554 };
555 
556 
557 /* Warlock directives */
558 
559 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran))
560 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_device))
561 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_ops))
562 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_extended_sense))
563 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_arq_status))
564 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_attr))
565 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_cookie_t))
566 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", devctl_ap_state))
567 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_info::devi_state))
568 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_list))
569 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_list))
570 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_next))
571 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_prev))
572 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", \
573     sata_hba_inst::satahba_scsi_tran))
574 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_tran))
575 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_dip))
576 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_hba_inst::satahba_attached))
577 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_inst::satahba_dev_port))
578 _NOTE(MUTEX_PROTECTS_DATA(sata_hba_inst::satahba_mutex,
579     sata_hba_inst::satahba_event_flags))
580 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
581     sata_cport_info::cport_devp))
582 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_devp))
583 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_cport_info::cport_addr))
584 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
585     sata_cport_info::cport_dev_type))
586 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_dev_type))
587 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
588     sata_cport_info::cport_state))
589 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_state))
590 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
591     sata_pmport_info::pmport_state))
592 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_state))
593 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
594     sata_pmport_info::pmport_dev_type))
595 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_dev_type))
596 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
597     sata_pmport_info::pmport_sata_drive))
598 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
599     sata_pmport_info::pmport_tgtnode_clean))
600 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
601     sata_pmport_info::pmport_event_flags))
602 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_sata_drive))
603 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_dev_port))
604 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_num_dev_ports))
605 #ifdef SATA_DEBUG
606 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuf_count))
607 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuffail_count))
608 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace))
609 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace_index))
610 #endif
611 
612 /* End of warlock directives */
613 
614 /* ************** loadable module configuration functions ************** */
615 
616 int
617 _init()
618 {
619 	int rval;
620 
621 	mutex_init(&sata_mutex, NULL, MUTEX_DRIVER, NULL);
622 	mutex_init(&sata_event_mutex, NULL, MUTEX_DRIVER, NULL);
623 	mutex_init(&sata_log_mutex, NULL, MUTEX_DRIVER, NULL);
624 	cv_init(&sata_event_cv, NULL, CV_DRIVER, NULL);
625 	sata_trace_rbuf_alloc();
626 	if ((rval = mod_install(&modlinkage)) != 0) {
627 #ifdef SATA_DEBUG
628 		cmn_err(CE_WARN, "sata: _init: mod_install failed\n");
629 #endif
630 		sata_trace_rbuf_free();
631 		mutex_destroy(&sata_log_mutex);
632 		cv_destroy(&sata_event_cv);
633 		mutex_destroy(&sata_event_mutex);
634 		mutex_destroy(&sata_mutex);
635 	}
636 	return (rval);
637 }
638 
639 int
640 _fini()
641 {
642 	int rval;
643 
644 	if ((rval = mod_remove(&modlinkage)) != 0)
645 		return (rval);
646 
647 	sata_trace_rbuf_free();
648 	mutex_destroy(&sata_log_mutex);
649 	cv_destroy(&sata_event_cv);
650 	mutex_destroy(&sata_event_mutex);
651 	mutex_destroy(&sata_mutex);
652 	return (rval);
653 }
654 
655 int
656 _info(struct modinfo *modinfop)
657 {
658 	return (mod_info(&modlinkage, modinfop));
659 }
660 
661 
662 
663 /* ********************* SATA HBA entry points ********************* */
664 
665 
666 /*
667  * Called by SATA HBA from _init().
668  * Registers HBA driver instance/sata framework pair with scsi framework, by
669  * calling scsi_hba_init().
670  *
671  * SATA HBA driver cb_ops are ignored - SATA HBA framework cb_ops are used
672  * instead. SATA HBA framework cb_ops pointer overwrites SATA HBA driver
673  * cb_ops pointer in SATA HBA driver dev_ops structure.
674  * SATA HBA framework cb_ops supplies cb_open cb_close and cb_ioctl vectors.
675  *
676  * Return status of the scsi_hba_init() is returned to a calling SATA HBA
677  * driver.
678  */
679 int
680 sata_hba_init(struct modlinkage *modlp)
681 {
682 	int rval;
683 	struct dev_ops *hba_ops;
684 
685 	SATADBG1(SATA_DBG_HBA_IF, NULL,
686 	    "sata_hba_init: name %s \n",
687 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
688 	/*
689 	 * Fill-up cb_ops and dev_ops when necessary
690 	 */
691 	hba_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
692 	/*
693 	 * Provide pointer to SATA dev_ops
694 	 */
695 	hba_ops->devo_cb_ops = &sata_cb_ops;
696 
697 	/*
698 	 * Register SATA HBA with SCSI framework
699 	 */
700 	if ((rval = scsi_hba_init(modlp)) != 0) {
701 		SATADBG1(SATA_DBG_HBA_IF, NULL,
702 		    "sata_hba_init: scsi hba init failed\n", NULL);
703 		return (rval);
704 	}
705 
706 	return (0);
707 }
708 
709 
710 /* HBA attach stages */
711 #define	HBA_ATTACH_STAGE_SATA_HBA_INST	1
712 #define	HBA_ATTACH_STAGE_SCSI_ATTACHED	2
713 #define	HBA_ATTACH_STAGE_SETUP		4
714 #define	HBA_ATTACH_STAGE_LINKED		8
715 
716 
717 /*
718  *
719  * Called from SATA HBA driver's attach routine to attach an instance of
720  * the HBA.
721  *
722  * For DDI_ATTACH command:
723  * sata_hba_inst structure is allocated here and initialized with pointers to
724  * SATA framework implementation of required scsi tran functions.
725  * The scsi_tran's tran_hba_private field is used by SATA Framework to point
726  * to the soft structure (sata_hba_inst) allocated by SATA framework for
727  * SATA HBA instance related data.
728  * The scsi_tran's tran_hba_private field is used by SATA framework to
729  * store a pointer to per-HBA-instance of sata_hba_inst structure.
730  * The sata_hba_inst structure is cross-linked to scsi tran structure.
731  * Among other info, a pointer to sata_hba_tran structure is stored in
732  * sata_hba_inst. The sata_hba_inst structures for different HBA instances are
733  * linked together into the list, pointed to by sata_hba_list.
734  * On the first HBA instance attach the sata event thread is initialized.
735  * Attachment points are created for all SATA ports of the HBA being attached.
736  * All HBA instance's SATA ports are probed and type of plugged devices is
737  * determined. For each device of a supported type, a target node is created.
738  *
739  * DDI_SUCCESS is returned when attachment process is successful,
740  * DDI_FAILURE is returned otherwise.
741  *
742  * For DDI_RESUME command:
743  * Not implemented at this time (postponed until phase 2 of the development).
744  */
745 int
746 sata_hba_attach(dev_info_t *dip, sata_hba_tran_t *sata_tran,
747     ddi_attach_cmd_t cmd)
748 {
749 	sata_hba_inst_t	*sata_hba_inst;
750 	scsi_hba_tran_t *scsi_tran = NULL;
751 	int hba_attach_state = 0;
752 	char taskq_name[MAXPATHLEN];
753 
754 	SATADBG3(SATA_DBG_HBA_IF, NULL,
755 	    "sata_hba_attach: node %s (%s%d)\n",
756 	    ddi_node_name(dip), ddi_driver_name(dip),
757 	    ddi_get_instance(dip));
758 
759 	if (cmd == DDI_RESUME) {
760 		/*
761 		 * Postponed until phase 2 of the development
762 		 */
763 		return (DDI_FAILURE);
764 	}
765 
766 	if (cmd != DDI_ATTACH) {
767 		return (DDI_FAILURE);
768 	}
769 
770 	/* cmd == DDI_ATTACH */
771 
772 	if (sata_validate_sata_hba_tran(dip, sata_tran) != SATA_SUCCESS) {
773 		SATA_LOG_D((NULL, CE_WARN,
774 		    "sata_hba_attach: invalid sata_hba_tran"));
775 		return (DDI_FAILURE);
776 	}
777 	/*
778 	 * Allocate and initialize SCSI tran structure.
779 	 * SATA copy of tran_bus_config is provided to create port nodes.
780 	 */
781 	scsi_tran = scsi_hba_tran_alloc(dip, SCSI_HBA_CANSLEEP);
782 	if (scsi_tran == NULL)
783 		return (DDI_FAILURE);
784 	/*
785 	 * Allocate soft structure for SATA HBA instance.
786 	 * There is a separate softstate for each HBA instance.
787 	 */
788 	sata_hba_inst = kmem_zalloc(sizeof (struct sata_hba_inst), KM_SLEEP);
789 	ASSERT(sata_hba_inst != NULL); /* this should not fail */
790 	mutex_init(&sata_hba_inst->satahba_mutex, NULL, MUTEX_DRIVER, NULL);
791 	hba_attach_state |= HBA_ATTACH_STAGE_SATA_HBA_INST;
792 
793 	/*
794 	 * scsi_trans's tran_hba_private is used by SATA Framework to point to
795 	 * soft structure allocated by SATA framework for
796 	 * SATA HBA instance related data.
797 	 */
798 	scsi_tran->tran_hba_private	= sata_hba_inst;
799 	scsi_tran->tran_tgt_private	= NULL;
800 
801 	scsi_tran->tran_tgt_init	= sata_scsi_tgt_init;
802 	scsi_tran->tran_tgt_probe	= sata_scsi_tgt_probe;
803 	scsi_tran->tran_tgt_free	= sata_scsi_tgt_free;
804 
805 	scsi_tran->tran_start		= sata_scsi_start;
806 	scsi_tran->tran_reset		= sata_scsi_reset;
807 	scsi_tran->tran_abort		= sata_scsi_abort;
808 	scsi_tran->tran_getcap		= sata_scsi_getcap;
809 	scsi_tran->tran_setcap		= sata_scsi_setcap;
810 	scsi_tran->tran_init_pkt	= sata_scsi_init_pkt;
811 	scsi_tran->tran_destroy_pkt	= sata_scsi_destroy_pkt;
812 
813 	scsi_tran->tran_dmafree		= sata_scsi_dmafree;
814 	scsi_tran->tran_sync_pkt	= sata_scsi_sync_pkt;
815 
816 	scsi_tran->tran_reset_notify	= NULL;
817 	scsi_tran->tran_get_bus_addr	= NULL;
818 	scsi_tran->tran_quiesce		= NULL;
819 	scsi_tran->tran_unquiesce	= NULL;
820 	scsi_tran->tran_bus_reset	= NULL;
821 
822 	if (scsi_hba_attach_setup(dip, sata_tran->sata_tran_hba_dma_attr,
823 	    scsi_tran, 0) != DDI_SUCCESS) {
824 #ifdef SATA_DEBUG
825 		cmn_err(CE_WARN, "?SATA: %s%d hba scsi attach failed",
826 		    ddi_driver_name(dip), ddi_get_instance(dip));
827 #endif
828 		goto fail;
829 	}
830 	hba_attach_state |= HBA_ATTACH_STAGE_SCSI_ATTACHED;
831 
832 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "sata")) {
833 		if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
834 		    "sata", 1) != DDI_PROP_SUCCESS) {
835 			SATA_LOG_D((NULL, CE_WARN, "sata_hba_attach: "
836 			    "failed to create hba sata prop"));
837 			goto fail;
838 		}
839 	}
840 
841 	/*
842 	 * Save pointers in hba instance soft state.
843 	 */
844 	sata_hba_inst->satahba_scsi_tran = scsi_tran;
845 	sata_hba_inst->satahba_tran = sata_tran;
846 	sata_hba_inst->satahba_dip = dip;
847 
848 	/*
849 	 * Create a task queue to handle emulated commands completion
850 	 * Use node name, dash, instance number as the queue name.
851 	 */
852 	taskq_name[0] = '\0';
853 	(void) strlcat(taskq_name, DEVI(dip)->devi_node_name,
854 	    sizeof (taskq_name));
855 	(void) snprintf(taskq_name + strlen(taskq_name),
856 	    sizeof (taskq_name) - strlen(taskq_name),
857 	    "-%d", DEVI(dip)->devi_instance);
858 	sata_hba_inst->satahba_taskq = taskq_create(taskq_name, 1,
859 	    minclsyspri, 1, sata_tran->sata_tran_hba_num_cports * 4,
860 	    TASKQ_DYNAMIC);
861 
862 	hba_attach_state |= HBA_ATTACH_STAGE_SETUP;
863 
864 	/*
865 	 * Create events thread if not created yet.
866 	 */
867 	sata_event_thread_control(1);
868 
869 	/*
870 	 * Link this hba instance into the list.
871 	 */
872 	mutex_enter(&sata_mutex);
873 
874 	if (sata_hba_list == NULL) {
875 		/*
876 		 * The first instance of HBA is attached.
877 		 * Set current/active default maximum NCQ/TCQ queue depth for
878 		 * all SATA devices. It is done here and now, to eliminate the
879 		 * possibility of the dynamic, programatic modification of the
880 		 * queue depth via global (and public) sata_max_queue_depth
881 		 * variable (this would require special handling in HBA drivers)
882 		 */
883 		sata_current_max_qdepth = sata_max_queue_depth;
884 		if (sata_current_max_qdepth > 32)
885 			sata_current_max_qdepth = 32;
886 		else if (sata_current_max_qdepth < 1)
887 			sata_current_max_qdepth = 1;
888 	}
889 
890 	sata_hba_inst->satahba_next = NULL;
891 	sata_hba_inst->satahba_prev = sata_hba_list_tail;
892 	if (sata_hba_list == NULL) {
893 		sata_hba_list = sata_hba_inst;
894 	}
895 	if (sata_hba_list_tail != NULL) {
896 		sata_hba_list_tail->satahba_next = sata_hba_inst;
897 	}
898 	sata_hba_list_tail = sata_hba_inst;
899 	mutex_exit(&sata_mutex);
900 	hba_attach_state |= HBA_ATTACH_STAGE_LINKED;
901 
902 	/*
903 	 * Create SATA HBA devctl minor node for sata_hba_open, close, ioctl
904 	 * SATA HBA driver should not use its own open/close entry points.
905 	 *
906 	 * Make sure that instance number doesn't overflow
907 	 * when forming minor numbers.
908 	 */
909 	ASSERT(ddi_get_instance(dip) <= (L_MAXMIN >> INST_MINOR_SHIFT));
910 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
911 	    INST2DEVCTL(ddi_get_instance(dip)),
912 	    DDI_NT_SATA_NEXUS, 0) != DDI_SUCCESS) {
913 #ifdef SATA_DEBUG
914 		cmn_err(CE_WARN, "sata_hba_attach: "
915 		    "cannot create devctl minor node");
916 #endif
917 		goto fail;
918 	}
919 
920 
921 	/*
922 	 * Set-up kstats here, if necessary.
923 	 * (postponed until future phase of the development).
924 	 */
925 
926 	/*
927 	 * Indicate that HBA is attached. This will enable events processing
928 	 * for this HBA.
929 	 */
930 	sata_hba_inst->satahba_attached = 1;
931 	/*
932 	 * Probe controller ports. This operation will describe a current
933 	 * controller/port/multipliers/device configuration and will create
934 	 * attachment points.
935 	 * We may end-up with just a controller with no devices attached.
936 	 * For the ports with a supported device attached, device target nodes
937 	 * are created and devices are initialized.
938 	 */
939 	sata_probe_ports(sata_hba_inst);
940 
941 	return (DDI_SUCCESS);
942 
943 fail:
944 	if (hba_attach_state & HBA_ATTACH_STAGE_LINKED) {
945 		(void) sata_remove_hba_instance(dip);
946 		if (sata_hba_list == NULL)
947 			sata_event_thread_control(0);
948 	}
949 
950 	if (hba_attach_state & HBA_ATTACH_STAGE_SETUP) {
951 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
952 		taskq_destroy(sata_hba_inst->satahba_taskq);
953 	}
954 
955 	if (hba_attach_state & HBA_ATTACH_STAGE_SCSI_ATTACHED)
956 		(void) scsi_hba_detach(dip);
957 
958 	if (hba_attach_state & HBA_ATTACH_STAGE_SATA_HBA_INST) {
959 		mutex_destroy(&sata_hba_inst->satahba_mutex);
960 		kmem_free((void *)sata_hba_inst,
961 		    sizeof (struct sata_hba_inst));
962 		scsi_hba_tran_free(scsi_tran);
963 	}
964 
965 	sata_log(NULL, CE_WARN, "?SATA: %s%d hba attach failed",
966 	    ddi_driver_name(dip), ddi_get_instance(dip));
967 
968 	return (DDI_FAILURE);
969 }
970 
971 
972 /*
973  * Called by SATA HBA from to detach an instance of the driver.
974  *
975  * For DDI_DETACH command:
976  * Free local structures allocated for SATA HBA instance during
977  * sata_hba_attach processing.
978  *
979  * Returns DDI_SUCCESS when HBA was detached, DDI_FAILURE otherwise.
980  *
981  * For DDI_SUSPEND command:
982  * Not implemented at this time (postponed until phase 2 of the development)
983  * Returnd DDI_SUCCESS.
984  *
985  * When the last HBA instance is detached, the event daemon is terminated.
986  *
987  * NOTE: Port multiplier is supported.
988  */
989 int
990 sata_hba_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
991 {
992 	dev_info_t	*tdip;
993 	sata_hba_inst_t	*sata_hba_inst;
994 	scsi_hba_tran_t *scsi_hba_tran;
995 	sata_cport_info_t *cportinfo;
996 	sata_pmult_info_t *pminfo;
997 	sata_drive_info_t *sdinfo;
998 	sata_device_t	sdevice;
999 	int ncport, npmport;
1000 
1001 	SATADBG3(SATA_DBG_HBA_IF, NULL, "sata_hba_detach: node %s (%s%d)\n",
1002 	    ddi_node_name(dip), ddi_driver_name(dip), ddi_get_instance(dip));
1003 
1004 	switch (cmd) {
1005 	case DDI_DETACH:
1006 
1007 		if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1008 			return (DDI_FAILURE);
1009 
1010 		sata_hba_inst = scsi_hba_tran->tran_hba_private;
1011 		if (sata_hba_inst == NULL)
1012 			return (DDI_FAILURE);
1013 
1014 		if (scsi_hba_detach(dip) == DDI_FAILURE) {
1015 			sata_hba_inst->satahba_attached = 1;
1016 			return (DDI_FAILURE);
1017 		}
1018 
1019 		/*
1020 		 * Free all target nodes - at this point
1021 		 * devices should be at least offlined
1022 		 * otherwise scsi_hba_detach() should not be called.
1023 		 */
1024 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
1025 		    ncport++) {
1026 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
1027 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1028 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
1029 				if (sdinfo != NULL) {
1030 					tdip = sata_get_target_dip(dip,
1031 					    ncport, 0);
1032 					if (tdip != NULL) {
1033 						if (ndi_devi_offline(tdip,
1034 						    NDI_DEVI_REMOVE) !=
1035 						    NDI_SUCCESS) {
1036 							SATA_LOG_D((
1037 							    sata_hba_inst,
1038 							    CE_WARN,
1039 							    "sata_hba_detach: "
1040 							    "Target node not "
1041 							    "removed !"));
1042 							return (DDI_FAILURE);
1043 						}
1044 					}
1045 				}
1046 			} else { /* SATA_DTYPE_PMULT */
1047 				mutex_enter(&cportinfo->cport_mutex);
1048 				pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
1049 
1050 				if (pminfo == NULL) {
1051 					SATA_LOG_D((sata_hba_inst, CE_WARN,
1052 					    "sata_hba_detach: Port multiplier "
1053 					    "not ready yet!"));
1054 					mutex_exit(&cportinfo->cport_mutex);
1055 					return (DDI_FAILURE);
1056 				}
1057 
1058 				/*
1059 				 * Detach would fail if removal of any of the
1060 				 * target nodes is failed - albeit in that
1061 				 * case some of them may have been removed.
1062 				 */
1063 				for (npmport = 0; npmport < SATA_NUM_PMPORTS(
1064 				    sata_hba_inst, ncport); npmport++) {
1065 					tdip = sata_get_target_dip(dip, ncport,
1066 					    npmport);
1067 					if (tdip != NULL) {
1068 						if (ndi_devi_offline(tdip,
1069 						    NDI_DEVI_REMOVE) !=
1070 						    NDI_SUCCESS) {
1071 							SATA_LOG_D((
1072 							    sata_hba_inst,
1073 							    CE_WARN,
1074 							    "sata_hba_detach: "
1075 							    "Target node not "
1076 							    "removed !"));
1077 							mutex_exit(&cportinfo->
1078 							    cport_mutex);
1079 							return (DDI_FAILURE);
1080 						}
1081 					}
1082 				}
1083 				mutex_exit(&cportinfo->cport_mutex);
1084 			}
1085 		}
1086 		/*
1087 		 * Disable sata event daemon processing for this HBA
1088 		 */
1089 		sata_hba_inst->satahba_attached = 0;
1090 
1091 		/*
1092 		 * Remove event daemon thread, if it is last HBA instance.
1093 		 */
1094 
1095 		mutex_enter(&sata_mutex);
1096 		if (sata_hba_list->satahba_next == NULL) {
1097 			mutex_exit(&sata_mutex);
1098 			sata_event_thread_control(0);
1099 			mutex_enter(&sata_mutex);
1100 		}
1101 		mutex_exit(&sata_mutex);
1102 
1103 		/* Remove this HBA instance from the HBA list */
1104 		sata_remove_hba_instance(dip);
1105 
1106 		/*
1107 		 * At this point there should be no target nodes attached.
1108 		 * Detach and destroy device and port info structures.
1109 		 */
1110 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
1111 		    ncport++) {
1112 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
1113 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1114 				sdinfo =
1115 				    cportinfo->cport_devp.cport_sata_drive;
1116 				if (sdinfo != NULL) {
1117 					/* Release device structure */
1118 					kmem_free(sdinfo,
1119 					    sizeof (sata_drive_info_t));
1120 				}
1121 				/* Release cport info */
1122 				mutex_destroy(&cportinfo->cport_mutex);
1123 				kmem_free(cportinfo,
1124 				    sizeof (sata_cport_info_t));
1125 			} else { /* SATA_DTYPE_PMULT */
1126 				sdevice.satadev_addr.cport = (uint8_t)ncport;
1127 				sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
1128 				sata_free_pmult(sata_hba_inst, &sdevice);
1129 			}
1130 		}
1131 
1132 		scsi_hba_tran_free(sata_hba_inst->satahba_scsi_tran);
1133 
1134 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
1135 
1136 		taskq_destroy(sata_hba_inst->satahba_taskq);
1137 
1138 		mutex_destroy(&sata_hba_inst->satahba_mutex);
1139 		kmem_free((void *)sata_hba_inst,
1140 		    sizeof (struct sata_hba_inst));
1141 
1142 		return (DDI_SUCCESS);
1143 
1144 	case DDI_SUSPEND:
1145 		/*
1146 		 * Postponed until phase 2
1147 		 */
1148 		return (DDI_FAILURE);
1149 
1150 	default:
1151 		return (DDI_FAILURE);
1152 	}
1153 }
1154 
1155 
1156 /*
1157  * Called by an HBA drive from _fini() routine.
1158  * Unregisters SATA HBA instance/SATA framework pair from the scsi framework.
1159  */
1160 void
1161 sata_hba_fini(struct modlinkage *modlp)
1162 {
1163 	SATADBG1(SATA_DBG_HBA_IF, NULL,
1164 	    "sata_hba_fini: name %s\n",
1165 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
1166 
1167 	scsi_hba_fini(modlp);
1168 }
1169 
1170 
1171 /*
1172  * Default open and close routine for sata_hba framework.
1173  *
1174  */
1175 /*
1176  * Open devctl node.
1177  *
1178  * Returns:
1179  * 0 if node was open successfully, error code otherwise.
1180  *
1181  *
1182  */
1183 
1184 static int
1185 sata_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
1186 {
1187 #ifndef __lock_lint
1188 	_NOTE(ARGUNUSED(credp))
1189 #endif
1190 	int rv = 0;
1191 	dev_info_t *dip;
1192 	scsi_hba_tran_t *scsi_hba_tran;
1193 	sata_hba_inst_t	*sata_hba_inst;
1194 
1195 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_open: entered", NULL);
1196 
1197 	if (otyp != OTYP_CHR)
1198 		return (EINVAL);
1199 
1200 	dip = sata_devt_to_devinfo(*devp);
1201 	if (dip == NULL)
1202 		return (ENXIO);
1203 
1204 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1205 		return (ENXIO);
1206 
1207 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1208 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1209 		return (ENXIO);
1210 
1211 	mutex_enter(&sata_mutex);
1212 	if (flags & FEXCL) {
1213 		if (sata_hba_inst->satahba_open_flag != 0) {
1214 			rv = EBUSY;
1215 		} else {
1216 			sata_hba_inst->satahba_open_flag =
1217 			    SATA_DEVCTL_EXOPENED;
1218 		}
1219 	} else {
1220 		if (sata_hba_inst->satahba_open_flag == SATA_DEVCTL_EXOPENED) {
1221 			rv = EBUSY;
1222 		} else {
1223 			sata_hba_inst->satahba_open_flag =
1224 			    SATA_DEVCTL_SOPENED;
1225 		}
1226 	}
1227 	mutex_exit(&sata_mutex);
1228 
1229 	return (rv);
1230 }
1231 
1232 
1233 /*
1234  * Close devctl node.
1235  * Returns:
1236  * 0 if node was closed successfully, error code otherwise.
1237  *
1238  */
1239 
1240 static int
1241 sata_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
1242 {
1243 #ifndef __lock_lint
1244 	_NOTE(ARGUNUSED(credp))
1245 	_NOTE(ARGUNUSED(flag))
1246 #endif
1247 	dev_info_t *dip;
1248 	scsi_hba_tran_t *scsi_hba_tran;
1249 	sata_hba_inst_t	*sata_hba_inst;
1250 
1251 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_close: entered", NULL);
1252 
1253 	if (otyp != OTYP_CHR)
1254 		return (EINVAL);
1255 
1256 	dip = sata_devt_to_devinfo(dev);
1257 	if (dip == NULL)
1258 		return (ENXIO);
1259 
1260 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1261 		return (ENXIO);
1262 
1263 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1264 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1265 		return (ENXIO);
1266 
1267 	mutex_enter(&sata_mutex);
1268 	sata_hba_inst->satahba_open_flag = 0;
1269 	mutex_exit(&sata_mutex);
1270 	return (0);
1271 }
1272 
1273 
1274 
1275 /*
1276  * Standard IOCTL commands for SATA hotplugging.
1277  * Implemented DEVCTL_AP commands:
1278  * DEVCTL_AP_CONNECT
1279  * DEVCTL_AP_DISCONNECT
1280  * DEVCTL_AP_CONFIGURE
1281  * DEVCTL_UNCONFIGURE
1282  * DEVCTL_AP_CONTROL
1283  *
1284  * Commands passed to default ndi ioctl handler:
1285  * DEVCTL_DEVICE_GETSTATE
1286  * DEVCTL_DEVICE_ONLINE
1287  * DEVCTL_DEVICE_OFFLINE
1288  * DEVCTL_DEVICE_REMOVE
1289  * DEVCTL_DEVICE_INSERT
1290  * DEVCTL_BUS_GETSTATE
1291  *
1292  * All other cmds are passed to HBA if it provide ioctl handler, or failed
1293  * if not.
1294  *
1295  * Returns:
1296  * 0 if successful,
1297  * error code if operation failed.
1298  *
1299  * Port Multiplier support is supported now.
1300  *
1301  * NOTE: qual should be SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT
1302  */
1303 
1304 static int
1305 sata_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
1306     int *rvalp)
1307 {
1308 #ifndef __lock_lint
1309 	_NOTE(ARGUNUSED(credp))
1310 	_NOTE(ARGUNUSED(rvalp))
1311 #endif
1312 	int rv = 0;
1313 	int32_t	comp_port = -1;
1314 	dev_info_t *dip;
1315 	devctl_ap_state_t ap_state;
1316 	struct devctl_iocdata *dcp = NULL;
1317 	scsi_hba_tran_t *scsi_hba_tran;
1318 	sata_hba_inst_t *sata_hba_inst;
1319 	sata_device_t sata_device;
1320 	sata_cport_info_t *cportinfo;
1321 	int cport, pmport, qual;
1322 	int rval = SATA_SUCCESS;
1323 
1324 	dip = sata_devt_to_devinfo(dev);
1325 	if (dip == NULL)
1326 		return (ENXIO);
1327 
1328 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1329 		return (ENXIO);
1330 
1331 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1332 	if (sata_hba_inst == NULL)
1333 		return (ENXIO);
1334 
1335 	if (sata_hba_inst->satahba_tran == NULL)
1336 		return (ENXIO);
1337 
1338 	switch (cmd) {
1339 
1340 	case DEVCTL_DEVICE_GETSTATE:
1341 	case DEVCTL_DEVICE_ONLINE:
1342 	case DEVCTL_DEVICE_OFFLINE:
1343 	case DEVCTL_DEVICE_REMOVE:
1344 	case DEVCTL_BUS_GETSTATE:
1345 		/*
1346 		 * There may be more cases that we want to pass to default
1347 		 * handler rather than fail them.
1348 		 */
1349 		return (ndi_devctl_ioctl(dip, cmd, arg, mode, 0));
1350 	}
1351 
1352 	/* read devctl ioctl data */
1353 	if (cmd != DEVCTL_AP_CONTROL && cmd >= DEVCTL_IOC &&
1354 	    cmd <= DEVCTL_IOC_MAX) {
1355 		if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS)
1356 			return (EFAULT);
1357 
1358 		if ((comp_port = sata_get_port_num(sata_hba_inst, dcp)) ==
1359 		    -1) {
1360 			if (dcp)
1361 				ndi_dc_freehdl(dcp);
1362 			return (EINVAL);
1363 		}
1364 
1365 		/*
1366 		 * According to SCSI_TO_SATA_ADDR_QUAL, qual should be either
1367 		 * SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT.
1368 		 */
1369 		cport = SCSI_TO_SATA_CPORT(comp_port);
1370 		pmport = SCSI_TO_SATA_PMPORT(comp_port);
1371 		qual = SCSI_TO_SATA_ADDR_QUAL(comp_port);
1372 
1373 		if (sata_validate_sata_address(sata_hba_inst, cport, pmport,
1374 		    qual) != 0) {
1375 			ndi_dc_freehdl(dcp);
1376 			return (EINVAL);
1377 		}
1378 
1379 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1380 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1381 		    cport_mutex);
1382 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1383 			/*
1384 			 * Cannot process ioctl request now. Come back later.
1385 			 */
1386 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1387 			    cport_mutex);
1388 			ndi_dc_freehdl(dcp);
1389 			return (EBUSY);
1390 		}
1391 		/* Block event processing for this port */
1392 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1393 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1394 
1395 		sata_device.satadev_addr.cport = cport;
1396 		sata_device.satadev_addr.pmport = pmport;
1397 		sata_device.satadev_addr.qual = qual;
1398 		sata_device.satadev_rev = SATA_DEVICE_REV;
1399 	}
1400 
1401 	switch (cmd) {
1402 
1403 	case DEVCTL_AP_DISCONNECT:
1404 
1405 		/*
1406 		 * Normally, cfgadm sata plugin will try to offline
1407 		 * (unconfigure) device before this request. Nevertheless,
1408 		 * if a device is still configured, we need to
1409 		 * attempt to offline and unconfigure device first, and we will
1410 		 * deactivate the port regardless of the unconfigure
1411 		 * operation results.
1412 		 *
1413 		 */
1414 		rv = sata_ioctl_disconnect(sata_hba_inst, &sata_device);
1415 
1416 		break;
1417 
1418 	case DEVCTL_AP_UNCONFIGURE:
1419 
1420 		/*
1421 		 * The unconfigure operation uses generic nexus operation to
1422 		 * offline a device. It leaves a target device node attached.
1423 		 * and obviously sata_drive_info attached as well, because
1424 		 * from the hardware point of view nothing has changed.
1425 		 */
1426 		rv = sata_ioctl_unconfigure(sata_hba_inst, &sata_device);
1427 		break;
1428 
1429 	case DEVCTL_AP_CONNECT:
1430 	{
1431 		/*
1432 		 * The sata cfgadm pluging will invoke this operation only if
1433 		 * port was found in the disconnect state (failed state
1434 		 * is also treated as the disconnected state).
1435 		 * If port activation is successful and a device is found
1436 		 * attached to the port, the initialization sequence is
1437 		 * executed to probe the port and attach
1438 		 * a device structure to a port structure. The device is not
1439 		 * set in configured state (system-wise) by this operation.
1440 		 */
1441 
1442 		rv = sata_ioctl_connect(sata_hba_inst, &sata_device);
1443 
1444 		break;
1445 	}
1446 
1447 	case DEVCTL_AP_CONFIGURE:
1448 	{
1449 		/*
1450 		 * A port may be in an active or shutdown state.
1451 		 * If port is in a failed state, operation is aborted.
1452 		 * If a port is in a shutdown state, sata_tran_port_activate()
1453 		 * is invoked prior to any other operation.
1454 		 *
1455 		 * Onlining the device involves creating a new target node.
1456 		 * If there is an old target node present (belonging to
1457 		 * previously removed device), the operation is aborted - the
1458 		 * old node has to be released and removed before configure
1459 		 * operation is attempted.
1460 		 */
1461 
1462 		rv = sata_ioctl_configure(sata_hba_inst, &sata_device);
1463 
1464 		break;
1465 	}
1466 
1467 	case DEVCTL_AP_GETSTATE:
1468 
1469 		sata_cfgadm_state(sata_hba_inst, comp_port, &ap_state);
1470 
1471 		ap_state.ap_last_change = (time_t)-1;
1472 		ap_state.ap_error_code = 0;
1473 		ap_state.ap_in_transition = 0;
1474 
1475 		/* Copy the return AP-state information to the user space */
1476 		if (ndi_dc_return_ap_state(&ap_state, dcp) != NDI_SUCCESS) {
1477 			rv = EFAULT;
1478 		}
1479 		break;
1480 
1481 	case DEVCTL_AP_CONTROL:
1482 	{
1483 		/*
1484 		 * Generic devctl for hardware specific functionality
1485 		 */
1486 		sata_ioctl_data_t	ioc;
1487 
1488 		ASSERT(dcp == NULL);
1489 
1490 		/* Copy in user ioctl data first */
1491 #ifdef _MULTI_DATAMODEL
1492 		if (ddi_model_convert_from(mode & FMODELS) ==
1493 		    DDI_MODEL_ILP32) {
1494 
1495 			sata_ioctl_data_32_t	ioc32;
1496 
1497 			if (ddi_copyin((void *)arg, (void *)&ioc32,
1498 			    sizeof (ioc32), mode) != 0) {
1499 				rv = EFAULT;
1500 				break;
1501 			}
1502 			ioc.cmd		= (uint_t)ioc32.cmd;
1503 			ioc.port	= (uint_t)ioc32.port;
1504 			ioc.get_size	= (uint_t)ioc32.get_size;
1505 			ioc.buf		= (caddr_t)(uintptr_t)ioc32.buf;
1506 			ioc.bufsiz	= (uint_t)ioc32.bufsiz;
1507 			ioc.misc_arg	= (uint_t)ioc32.misc_arg;
1508 		} else
1509 #endif /* _MULTI_DATAMODEL */
1510 		if (ddi_copyin((void *)arg, (void *)&ioc, sizeof (ioc),
1511 		    mode) != 0) {
1512 			return (EFAULT);
1513 		}
1514 
1515 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
1516 		    "sata_hba_ioctl: DEVCTL_AP_CONTROL "
1517 		    "cmd 0x%x, port 0x%x", ioc.cmd, ioc.port);
1518 
1519 		/*
1520 		 * To avoid BE/LE and 32/64 issues, a get_size always returns
1521 		 * a 32-bit number.
1522 		 */
1523 		if (ioc.get_size != 0 && ioc.bufsiz != (sizeof (uint32_t))) {
1524 			return (EINVAL);
1525 		}
1526 		/* validate address */
1527 		cport = SCSI_TO_SATA_CPORT(ioc.port);
1528 		pmport = SCSI_TO_SATA_PMPORT(ioc.port);
1529 		qual = SCSI_TO_SATA_ADDR_QUAL(ioc.port);
1530 
1531 		SATADBG3(SATA_DBG_IOCTL_IF, sata_hba_inst,
1532 		    "sata_hba_ioctl: target port is %d:%d (%d)",
1533 		    cport, pmport, qual);
1534 
1535 		if (sata_validate_sata_address(sata_hba_inst, cport,
1536 		    pmport, qual) != 0)
1537 			return (EINVAL);
1538 
1539 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1540 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1541 		    cport_mutex);
1542 		/* Is the port locked by event processing daemon ? */
1543 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1544 			/*
1545 			 * Cannot process ioctl request now. Come back later
1546 			 */
1547 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1548 			    cport_mutex);
1549 			return (EBUSY);
1550 		}
1551 		/* Block event processing for this port */
1552 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1553 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1554 
1555 
1556 		sata_device.satadev_addr.cport = cport;
1557 		sata_device.satadev_addr.pmport = pmport;
1558 		sata_device.satadev_addr.qual = qual;
1559 		sata_device.satadev_rev = SATA_DEVICE_REV;
1560 
1561 		switch (ioc.cmd) {
1562 
1563 		case SATA_CFGA_RESET_PORT:
1564 			/*
1565 			 * There is no protection for configured device.
1566 			 */
1567 			rv = sata_ioctl_reset_port(sata_hba_inst, &sata_device);
1568 			break;
1569 
1570 		case SATA_CFGA_RESET_DEVICE:
1571 			/*
1572 			 * There is no protection for configured device.
1573 			 */
1574 			rv = sata_ioctl_reset_device(sata_hba_inst,
1575 			    &sata_device);
1576 			break;
1577 
1578 		case SATA_CFGA_RESET_ALL:
1579 			/*
1580 			 * There is no protection for configured devices.
1581 			 */
1582 			rv = sata_ioctl_reset_all(sata_hba_inst);
1583 			/*
1584 			 * We return here, because common return is for
1585 			 * a single port operation - we have already unlocked
1586 			 * all ports and no dc handle was allocated.
1587 			 */
1588 			return (rv);
1589 
1590 		case SATA_CFGA_PORT_DEACTIVATE:
1591 			/*
1592 			 * Arbitrarily unconfigure attached device, if any.
1593 			 * Even if the unconfigure fails, proceed with the
1594 			 * port deactivation.
1595 			 */
1596 			rv = sata_ioctl_deactivate(sata_hba_inst, &sata_device);
1597 
1598 			break;
1599 
1600 		case SATA_CFGA_PORT_ACTIVATE:
1601 
1602 			rv = sata_ioctl_activate(sata_hba_inst, &sata_device);
1603 			break;
1604 
1605 		case SATA_CFGA_PORT_SELF_TEST:
1606 
1607 			rv = sata_ioctl_port_self_test(sata_hba_inst,
1608 			    &sata_device);
1609 			break;
1610 
1611 		case SATA_CFGA_GET_DEVICE_PATH:
1612 
1613 			rv = sata_ioctl_get_device_path(sata_hba_inst,
1614 			    &sata_device, &ioc, mode);
1615 			break;
1616 
1617 		case SATA_CFGA_GET_AP_TYPE:
1618 
1619 			rv = sata_ioctl_get_ap_type(sata_hba_inst,
1620 			    &sata_device, &ioc, mode);
1621 			break;
1622 
1623 		case SATA_CFGA_GET_MODEL_INFO:
1624 
1625 			rv = sata_ioctl_get_model_info(sata_hba_inst,
1626 			    &sata_device, &ioc, mode);
1627 			break;
1628 
1629 		case SATA_CFGA_GET_REVFIRMWARE_INFO:
1630 
1631 			rv = sata_ioctl_get_revfirmware_info(sata_hba_inst,
1632 			    &sata_device, &ioc, mode);
1633 			break;
1634 
1635 		case SATA_CFGA_GET_SERIALNUMBER_INFO:
1636 
1637 			rv = sata_ioctl_get_serialnumber_info(sata_hba_inst,
1638 			    &sata_device, &ioc, mode);
1639 			break;
1640 
1641 		default:
1642 			rv = EINVAL;
1643 			break;
1644 
1645 		} /* End of DEVCTL_AP_CONTROL cmd switch */
1646 
1647 		break;
1648 	}
1649 
1650 	default:
1651 	{
1652 		/*
1653 		 * If we got here, we got an IOCTL that SATA HBA Framework
1654 		 * does not recognize. Pass ioctl to HBA driver, in case
1655 		 * it could process it.
1656 		 */
1657 		sata_hba_tran_t *sata_tran = sata_hba_inst->satahba_tran;
1658 		dev_info_t	*mydip = SATA_DIP(sata_hba_inst);
1659 
1660 		SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1661 		    "IOCTL 0x%2x not supported in SATA framework, "
1662 		    "passthrough to HBA", cmd);
1663 
1664 		if (sata_tran->sata_tran_ioctl == NULL) {
1665 			rv = EINVAL;
1666 			break;
1667 		}
1668 		rval = (*sata_tran->sata_tran_ioctl)(mydip, cmd, arg);
1669 		if (rval != 0) {
1670 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1671 			    "IOCTL 0x%2x failed in HBA", cmd);
1672 			rv = rval;
1673 		}
1674 		break;
1675 	}
1676 
1677 	} /* End of main IOCTL switch */
1678 
1679 	if (dcp) {
1680 		ndi_dc_freehdl(dcp);
1681 	}
1682 
1683 	if (cmd >= DEVCTL_IOC && cmd <= DEVCTL_IOC_MAX) {
1684 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
1685 		    cport)->cport_mutex);
1686 		cportinfo->cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
1687 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1688 	}
1689 
1690 	return (rv);
1691 }
1692 
1693 
1694 /*
1695  * Create error retrieval sata packet
1696  *
1697  * A sata packet is allocated and set-up to contain specified error retrieval
1698  * command and appropriate dma-able data buffer.
1699  * No association with any scsi packet is made and no callback routine is
1700  * specified.
1701  *
1702  * Returns a pointer to sata packet upon successful packet creation.
1703  * Returns NULL, if packet cannot be created.
1704  */
1705 sata_pkt_t *
1706 sata_get_error_retrieval_pkt(dev_info_t *dip, sata_device_t *sata_device,
1707     int pkt_type)
1708 {
1709 	sata_hba_inst_t	*sata_hba_inst;
1710 	sata_pkt_txlate_t *spx;
1711 	sata_pkt_t *spkt;
1712 	sata_drive_info_t *sdinfo;
1713 
1714 	mutex_enter(&sata_mutex);
1715 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1716 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1717 		if (SATA_DIP(sata_hba_inst) == dip)
1718 			break;
1719 	}
1720 	mutex_exit(&sata_mutex);
1721 	ASSERT(sata_hba_inst != NULL);
1722 
1723 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
1724 	if (sdinfo == NULL) {
1725 		sata_log(sata_hba_inst, CE_WARN,
1726 		    "sata: error recovery request for non-attached device at "
1727 		    "cport %d", sata_device->satadev_addr.cport);
1728 		return (NULL);
1729 	}
1730 
1731 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1732 	spx->txlt_sata_hba_inst = sata_hba_inst;
1733 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
1734 	spkt = sata_pkt_alloc(spx, NULL);
1735 	if (spkt == NULL) {
1736 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1737 		return (NULL);
1738 	}
1739 	/* address is needed now */
1740 	spkt->satapkt_device.satadev_addr = sata_device->satadev_addr;
1741 
1742 	switch (pkt_type) {
1743 	case SATA_ERR_RETR_PKT_TYPE_NCQ:
1744 		if (sata_ncq_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS) {
1745 			if (sata_check_for_dma_error(dip, spx)) {
1746 				ddi_fm_service_impact(dip,
1747 				    DDI_SERVICE_UNAFFECTED);
1748 				break;
1749 			}
1750 			return (spkt);
1751 		}
1752 		break;
1753 
1754 	case SATA_ERR_RETR_PKT_TYPE_ATAPI:
1755 		if (sata_atapi_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS) {
1756 			if (sata_check_for_dma_error(dip, spx)) {
1757 				ddi_fm_service_impact(dip,
1758 				    DDI_SERVICE_UNAFFECTED);
1759 				break;
1760 			}
1761 			return (spkt);
1762 		}
1763 		break;
1764 
1765 	default:
1766 		break;
1767 	}
1768 
1769 	sata_pkt_free(spx);
1770 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1771 	return (NULL);
1772 
1773 }
1774 
1775 
1776 /*
1777  * Free error retrieval sata packet
1778  *
1779  * Free sata packet and any associated resources allocated previously by
1780  * sata_get_error_retrieval_pkt().
1781  *
1782  * Void return.
1783  */
1784 void
1785 sata_free_error_retrieval_pkt(sata_pkt_t *sata_pkt)
1786 {
1787 	sata_pkt_txlate_t *spx =
1788 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1789 
1790 	ASSERT(sata_pkt != NULL);
1791 
1792 	sata_free_local_buffer(spx);
1793 	sata_pkt_free(spx);
1794 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1795 
1796 }
1797 
1798 /*
1799  * Create READ PORT MULTIPLIER and WRITE PORT MULTIPLIER sata packet
1800  *
1801  * No association with any scsi packet is made and no callback routine is
1802  * specified.
1803  *
1804  * Returns a pointer to sata packet upon successful packet creation.
1805  * Returns NULL, if packet cannot be created.
1806  *
1807  * NOTE: Input/Output value includes 64 bits accoring to SATA Spec 2.6,
1808  * only lower 32 bits are available currently.
1809  */
1810 sata_pkt_t *
1811 sata_get_rdwr_pmult_pkt(dev_info_t *dip, sata_device_t *sd,
1812     uint8_t regn, uint32_t regv, uint32_t type)
1813 {
1814 	sata_hba_inst_t	*sata_hba_inst;
1815 	sata_pkt_txlate_t *spx;
1816 	sata_pkt_t *spkt;
1817 	sata_cmd_t *scmd;
1818 
1819 	/* Only READ/WRITE commands are accepted. */
1820 	ASSERT(type == SATA_RDWR_PMULT_PKT_TYPE_READ ||
1821 	    type == SATA_RDWR_PMULT_PKT_TYPE_WRITE);
1822 
1823 	mutex_enter(&sata_mutex);
1824 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1825 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1826 		if (SATA_DIP(sata_hba_inst) == dip)
1827 			break;
1828 	}
1829 	mutex_exit(&sata_mutex);
1830 	ASSERT(sata_hba_inst != NULL);
1831 
1832 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1833 	spx->txlt_sata_hba_inst = sata_hba_inst;
1834 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
1835 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
1836 	if (spkt == NULL) {
1837 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1838 		return (NULL);
1839 	}
1840 
1841 	/*
1842 	 * NOTE: We need to send this command to the port multiplier,
1843 	 * that means send to SATA_PMULT_HOSTPORT(0xf) pmport
1844 	 *
1845 	 * sata_device contains the address of actual target device, and the
1846 	 * pmport number in the command comes from the sata_device structure.
1847 	 */
1848 	spkt->satapkt_device.satadev_addr = sd->satadev_addr;
1849 	spkt->satapkt_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
1850 	spkt->satapkt_device.satadev_addr.qual = SATA_ADDR_PMULT;
1851 
1852 	/* Fill sata_pkt */
1853 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_POLLING;
1854 	spkt->satapkt_comp = NULL; /* Synchronous mode, no callback */
1855 	spkt->satapkt_time = 10; /* Timeout 10s */
1856 
1857 	/* Build READ PORT MULTIPLIER cmd in the sata_pkt */
1858 	scmd = &spkt->satapkt_cmd;
1859 	scmd->satacmd_features_reg = regn & 0xff;
1860 	scmd->satacmd_features_reg_ext = (regn >> 8) & 0xff;
1861 	scmd->satacmd_device_reg = sd->satadev_addr.pmport;
1862 	scmd->satacmd_addr_type = 0;		/* N/A */
1863 
1864 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
1865 
1866 	if (type == SATA_RDWR_PMULT_PKT_TYPE_READ) {
1867 		scmd->satacmd_cmd_reg = SATAC_READ_PORTMULT;
1868 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
1869 		scmd->satacmd_flags.sata_special_regs = 1;
1870 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
1871 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
1872 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
1873 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
1874 	} else if (type == SATA_RDWR_PMULT_PKT_TYPE_WRITE) {
1875 		scmd->satacmd_cmd_reg = SATAC_WRITE_PORTMULT;
1876 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
1877 		scmd->satacmd_sec_count_lsb = regv & 0xff;
1878 		scmd->satacmd_lba_low_lsb = regv >> 8 & 0xff;
1879 		scmd->satacmd_lba_mid_lsb = regv >> 16 & 0xff;
1880 		scmd->satacmd_lba_high_lsb = regv >> 24 & 0xff;
1881 	}
1882 
1883 	return (spkt);
1884 }
1885 
1886 /*
1887  * Free sata packet and any associated resources allocated previously by
1888  * sata_get_rdwr_pmult_pkt().
1889  *
1890  * Void return.
1891  */
1892 void
1893 sata_free_rdwr_pmult_pkt(sata_pkt_t *sata_pkt)
1894 {
1895 	sata_pkt_txlate_t *spx =
1896 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1897 
1898 	/* Free allocated resources */
1899 	sata_pkt_free(spx);
1900 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1901 }
1902 
1903 /*
1904  * Register a port multiplier to framework.
1905  * 1) Store the GSCR values in the previous allocated pmult_info strctures.
1906  * 2) Search in the blacklist and update the number of the device ports of the
1907  * port multiplier.
1908  *
1909  * Void return.
1910  */
1911 void
1912 sata_register_pmult(dev_info_t *dip, sata_device_t *sd, sata_pmult_gscr_t *sg)
1913 {
1914 	sata_hba_inst_t *sata_hba_inst = NULL;
1915 	sata_pmult_info_t *pmultinfo;
1916 	sata_pmult_bl_t *blp;
1917 	int cport = sd->satadev_addr.cport;
1918 
1919 	mutex_enter(&sata_mutex);
1920 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1921 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1922 		if (SATA_DIP(sata_hba_inst) == dip)
1923 			if (sata_hba_inst->satahba_attached == 1)
1924 				break;
1925 	}
1926 	mutex_exit(&sata_mutex);
1927 	/* HBA not attached? */
1928 	if (sata_hba_inst == NULL)
1929 		return;
1930 
1931 	/* Number of pmports */
1932 	sd->satadev_add_info = sg->gscr2 & SATA_PMULT_PORTNUM_MASK;
1933 
1934 	/* Check the blacklist */
1935 	for (blp = sata_pmult_blacklist; blp->bl_gscr0; blp++) {
1936 		if (sg->gscr0 != blp->bl_gscr0 && blp->bl_gscr0)
1937 			continue;
1938 		if (sg->gscr1 != blp->bl_gscr1 && blp->bl_gscr1)
1939 			continue;
1940 		if (sg->gscr2 != blp->bl_gscr2 && blp->bl_gscr2)
1941 			continue;
1942 
1943 		cmn_err(CE_WARN, "!Port multiplier is on the blacklist.");
1944 		sd->satadev_add_info = blp->bl_flags;
1945 		break;
1946 	}
1947 
1948 	/* Register the port multiplier GSCR */
1949 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
1950 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
1951 	if (pmultinfo != NULL) {
1952 		pmultinfo->pmult_gscr = *sg;
1953 		pmultinfo->pmult_num_dev_ports =
1954 		    sd->satadev_add_info & SATA_PMULT_PORTNUM_MASK;
1955 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
1956 		    "Port multiplier registered at port %d", cport);
1957 	}
1958 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
1959 }
1960 
1961 /*
1962  * sata_split_model splits the model ID into vendor and product IDs.
1963  * It assumes that a vendor ID cannot be longer than 8 characters, and
1964  * that vendor and product ID are separated by a whitespace.
1965  */
1966 void
1967 sata_split_model(char *model, char **vendor, char **product)
1968 {
1969 	int i, modlen;
1970 	char *vid, *pid;
1971 
1972 	/*
1973 	 * remove whitespace at the end of model
1974 	 */
1975 	for (i = SATA_ID_MODEL_LEN; i > 0; i--)
1976 		if (model[i] == ' ' || model[i] == '\t' || model[i] == '\0')
1977 			model[i] = '\0';
1978 		else
1979 			break;
1980 
1981 	/*
1982 	 * try to split model into into vid/pid
1983 	 */
1984 	modlen = strlen(model);
1985 	for (i = 0, pid = model; i < modlen; i++, pid++)
1986 		if ((*pid == ' ') || (*pid == '\t'))
1987 			break;
1988 
1989 	/*
1990 	 * only use vid if it is less than 8 chars (as in SCSI)
1991 	 */
1992 	if (i < modlen && i <= 8) {
1993 		vid = model;
1994 		/*
1995 		 * terminate vid, establish pid
1996 		 */
1997 		*pid++ = '\0';
1998 	} else {
1999 		/*
2000 		 * vid will stay "ATA     "
2001 		 */
2002 		vid = NULL;
2003 		/*
2004 		 * model is all pid
2005 		 */
2006 		pid = model;
2007 	}
2008 
2009 	*vendor = vid;
2010 	*product = pid;
2011 }
2012 
2013 /*
2014  * sata_name_child is for composing the name of the node
2015  * the format of the name is "target,0".
2016  */
2017 static int
2018 sata_name_child(dev_info_t *dip, char *name, int namelen)
2019 {
2020 	int target;
2021 
2022 	target = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
2023 	    DDI_PROP_DONTPASS, "target", -1);
2024 	if (target == -1)
2025 		return (DDI_FAILURE);
2026 	(void) snprintf(name, namelen, "%x,0", target);
2027 	return (DDI_SUCCESS);
2028 }
2029 
2030 
2031 
2032 /* ****************** SCSA required entry points *********************** */
2033 
2034 /*
2035  * Implementation of scsi tran_tgt_init.
2036  * sata_scsi_tgt_init() initializes scsi_device structure
2037  *
2038  * If successful, DDI_SUCCESS is returned.
2039  * DDI_FAILURE is returned if addressed device does not exist
2040  */
2041 
2042 static int
2043 sata_scsi_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
2044     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
2045 {
2046 #ifndef __lock_lint
2047 	_NOTE(ARGUNUSED(hba_dip))
2048 	_NOTE(ARGUNUSED(tgt_dip))
2049 #endif
2050 	sata_device_t		sata_device;
2051 	sata_drive_info_t	*sdinfo;
2052 	struct sata_id		*sid;
2053 	sata_hba_inst_t		*sata_hba_inst;
2054 	char			model[SATA_ID_MODEL_LEN + 1];
2055 	char			fw[SATA_ID_FW_LEN + 1];
2056 	char			*vid, *pid;
2057 
2058 	/*
2059 	 * Fail tran_tgt_init for .conf stub node
2060 	 */
2061 	if (ndi_dev_is_persistent_node(tgt_dip) == 0) {
2062 		(void) ndi_merge_node(tgt_dip, sata_name_child);
2063 		ddi_set_name_addr(tgt_dip, NULL);
2064 		return (DDI_FAILURE);
2065 	}
2066 
2067 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
2068 
2069 	/* Validate scsi device address */
2070 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
2071 	    &sata_device) != 0)
2072 		return (DDI_FAILURE);
2073 
2074 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2075 	    sata_device.satadev_addr.cport)));
2076 
2077 	/* sata_device now contains a valid sata address */
2078 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
2079 	if (sdinfo == NULL) {
2080 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2081 		    sata_device.satadev_addr.cport)));
2082 		return (DDI_FAILURE);
2083 	}
2084 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2085 	    sata_device.satadev_addr.cport)));
2086 
2087 	/*
2088 	 * Check if we need to create a legacy devid (i.e cmdk style) for
2089 	 * the target disks.
2090 	 *
2091 	 * HBA devinfo node will have the property "use-cmdk-devid-format"
2092 	 * if we need to create cmdk-style devid for all the disk devices
2093 	 * attached to this controller. This property may have been set
2094 	 * from HBA driver's .conf file or by the HBA driver in its
2095 	 * attach(9F) function.
2096 	 */
2097 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
2098 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
2099 	    "use-cmdk-devid-format", 0) == 1)) {
2100 		/* register a legacy devid for this target node */
2101 		sata_target_devid_register(tgt_dip, sdinfo);
2102 	}
2103 
2104 
2105 	/*
2106 	 * 'Identify Device Data' does not always fit in standard SCSI
2107 	 * INQUIRY data, so establish INQUIRY_* properties with full-form
2108 	 * of information.
2109 	 */
2110 	sid = &sdinfo->satadrv_id;
2111 #ifdef	_LITTLE_ENDIAN
2112 	swab(sid->ai_model, model, SATA_ID_MODEL_LEN);
2113 	swab(sid->ai_fw, fw, SATA_ID_FW_LEN);
2114 #else	/* _LITTLE_ENDIAN */
2115 	bcopy(sid->ai_model, model, SATA_ID_MODEL_LEN);
2116 	bcopy(sid->ai_fw, fw, SATA_ID_FW_LEN);
2117 #endif	/* _LITTLE_ENDIAN */
2118 	model[SATA_ID_MODEL_LEN] = 0;
2119 	fw[SATA_ID_FW_LEN] = 0;
2120 
2121 	sata_split_model(model, &vid, &pid);
2122 
2123 	if (vid)
2124 		(void) scsi_device_prop_update_inqstring(sd, INQUIRY_VENDOR_ID,
2125 		    vid, strlen(vid));
2126 	if (pid)
2127 		(void) scsi_device_prop_update_inqstring(sd, INQUIRY_PRODUCT_ID,
2128 		    pid, strlen(pid));
2129 	(void) scsi_device_prop_update_inqstring(sd, INQUIRY_REVISION_ID,
2130 	    fw, strlen(fw));
2131 
2132 	return (DDI_SUCCESS);
2133 }
2134 
2135 /*
2136  * Implementation of scsi tran_tgt_probe.
2137  * Probe target, by calling default scsi routine scsi_hba_probe()
2138  */
2139 static int
2140 sata_scsi_tgt_probe(struct scsi_device *sd, int (*callback)(void))
2141 {
2142 	sata_hba_inst_t *sata_hba_inst =
2143 	    (sata_hba_inst_t *)(sd->sd_address.a_hba_tran->tran_hba_private);
2144 	int rval;
2145 	uint32_t pm_cap;
2146 
2147 	rval = scsi_hba_probe(sd, callback);
2148 	pm_cap = SATA_CAP_POWER_CONDITON | SATA_CAP_SMART_PAGE |
2149 	    SATA_CAP_LOG_SENSE;
2150 
2151 	if (rval == SCSIPROBE_EXISTS) {
2152 		/*
2153 		 * Set property "pm-capable" on the target device node, so that
2154 		 * the target driver will not try to fetch scsi cycle counters
2155 		 * before enabling device power-management.
2156 		 */
2157 		if ((ddi_prop_update_int(DDI_DEV_T_NONE, sd->sd_dev,
2158 		    "pm-capable", pm_cap)) != DDI_PROP_SUCCESS) {
2159 			sata_log(sata_hba_inst, CE_WARN,
2160 			    "SATA device at port %d: "
2161 			    "will not be power-managed ",
2162 			    SCSI_TO_SATA_CPORT(sd->sd_address.a_target));
2163 			SATA_LOG_D((sata_hba_inst, CE_WARN,
2164 			    "failure updating pm-capable property"));
2165 		}
2166 	}
2167 	return (rval);
2168 }
2169 
2170 /*
2171  * Implementation of scsi tran_tgt_free.
2172  * Release all resources allocated for scsi_device
2173  */
2174 static void
2175 sata_scsi_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
2176     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
2177 {
2178 #ifndef __lock_lint
2179 	_NOTE(ARGUNUSED(hba_dip))
2180 #endif
2181 	sata_device_t		sata_device;
2182 	sata_drive_info_t	*sdinfo;
2183 	sata_hba_inst_t		*sata_hba_inst;
2184 	ddi_devid_t		devid;
2185 
2186 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
2187 
2188 	/* Validate scsi device address */
2189 	/*
2190 	 * Note: tgt_free relates to the SCSA view of a device. If called, there
2191 	 * was a device at this address, so even if the sata framework internal
2192 	 * resources were alredy released because a device was detached,
2193 	 * this function should be executed as long as its actions do
2194 	 * not require the internal sata view of a device and the address
2195 	 * refers to a valid sata address.
2196 	 * Validating the address here means that we do not trust SCSA...
2197 	 */
2198 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
2199 	    &sata_device) == -1)
2200 		return;
2201 
2202 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2203 	    sata_device.satadev_addr.cport)));
2204 
2205 	/* sata_device now should contain a valid sata address */
2206 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
2207 	if (sdinfo == NULL) {
2208 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2209 		    sata_device.satadev_addr.cport)));
2210 		return;
2211 	}
2212 	/*
2213 	 * We did not allocate any resources in sata_scsi_tgt_init()
2214 	 * other than few properties.
2215 	 * Free them.
2216 	 */
2217 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2218 	    sata_device.satadev_addr.cport)));
2219 	(void) ndi_prop_remove(DDI_DEV_T_NONE, tgt_dip, "pm-capable");
2220 
2221 	/*
2222 	 * If devid was previously created but not freed up from
2223 	 * sd(7D) driver (i.e during detach(9F)) then do it here.
2224 	 */
2225 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
2226 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
2227 	    "use-cmdk-devid-format", 0) == 1) &&
2228 	    (ddi_devid_get(tgt_dip, &devid) == DDI_SUCCESS)) {
2229 		ddi_devid_unregister(tgt_dip);
2230 		ddi_devid_free(devid);
2231 	}
2232 }
2233 
2234 /*
2235  * Implementation of scsi tran_init_pkt
2236  * Upon successful return, scsi pkt buffer has DMA resources allocated.
2237  *
2238  * It seems that we should always allocate pkt, even if the address is
2239  * for non-existing device - just use some default for dma_attr.
2240  * The reason is that there is no way to communicate this to a caller here.
2241  * Subsequent call to sata_scsi_start may fail appropriately.
2242  * Simply returning NULL does not seem to discourage a target driver...
2243  *
2244  * Returns a pointer to initialized scsi_pkt, or NULL otherwise.
2245  */
2246 static struct scsi_pkt *
2247 sata_scsi_init_pkt(struct scsi_address *ap, struct scsi_pkt *pkt,
2248     struct buf *bp, int cmdlen, int statuslen, int tgtlen, int flags,
2249     int (*callback)(caddr_t), caddr_t arg)
2250 {
2251 	sata_hba_inst_t *sata_hba_inst =
2252 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2253 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
2254 	sata_device_t sata_device;
2255 	sata_drive_info_t *sdinfo;
2256 	sata_pkt_txlate_t *spx;
2257 	ddi_dma_attr_t cur_dma_attr;
2258 	int rval;
2259 	boolean_t new_pkt = B_TRUE;
2260 
2261 	ASSERT(ap->a_hba_tran->tran_hba_dip == dip);
2262 
2263 	/*
2264 	 * We need to translate the address, even if it could be
2265 	 * a bogus one, for a non-existing device
2266 	 */
2267 	sata_device.satadev_addr.qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
2268 	sata_device.satadev_addr.cport = SCSI_TO_SATA_CPORT(ap->a_target);
2269 	sata_device.satadev_addr.pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2270 	sata_device.satadev_rev = SATA_DEVICE_REV;
2271 
2272 	if (pkt == NULL) {
2273 		/*
2274 		 * Have to allocate a brand new scsi packet.
2275 		 * We need to operate with auto request sense enabled.
2276 		 */
2277 		pkt = scsi_hba_pkt_alloc(dip, ap, cmdlen,
2278 		    MAX(statuslen, SATA_MAX_SENSE_LEN),
2279 		    tgtlen, sizeof (sata_pkt_txlate_t), callback, arg);
2280 
2281 		if (pkt == NULL)
2282 			return (NULL);
2283 
2284 		/* Fill scsi packet structure */
2285 		pkt->pkt_comp		= (void (*)())NULL;
2286 		pkt->pkt_time		= 0;
2287 		pkt->pkt_resid		= 0;
2288 		pkt->pkt_statistics	= 0;
2289 		pkt->pkt_reason		= 0;
2290 
2291 		/*
2292 		 * pkt_hba_private will point to sata pkt txlate structure
2293 		 */
2294 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2295 		bzero(spx, sizeof (sata_pkt_txlate_t));
2296 
2297 		spx->txlt_scsi_pkt = pkt;
2298 		spx->txlt_sata_hba_inst = sata_hba_inst;
2299 
2300 		/* Allocate sata_pkt */
2301 		spx->txlt_sata_pkt = sata_pkt_alloc(spx, callback);
2302 		if (spx->txlt_sata_pkt == NULL) {
2303 			/* Could not allocate sata pkt */
2304 			scsi_hba_pkt_free(ap, pkt);
2305 			return (NULL);
2306 		}
2307 		/* Set sata address */
2308 		spx->txlt_sata_pkt->satapkt_device.satadev_addr =
2309 		    sata_device.satadev_addr;
2310 		spx->txlt_sata_pkt->satapkt_device.satadev_rev =
2311 		    sata_device.satadev_rev;
2312 
2313 		if ((bp == NULL) || (bp->b_bcount == 0))
2314 			return (pkt);
2315 
2316 		spx->txlt_total_residue = bp->b_bcount;
2317 	} else {
2318 		new_pkt = B_FALSE;
2319 		/*
2320 		 * Packet was preallocated/initialized by previous call
2321 		 */
2322 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2323 
2324 		if ((bp == NULL) || (bp->b_bcount == 0)) {
2325 			return (pkt);
2326 		}
2327 
2328 		/* Pkt is available already: spx->txlt_scsi_pkt == pkt; */
2329 	}
2330 
2331 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
2332 
2333 	/*
2334 	 * We use an adjusted version of the dma_attr, to account
2335 	 * for device addressing limitations.
2336 	 * sata_adjust_dma_attr() will handle sdinfo == NULL which may
2337 	 * happen when a device is not yet configured.
2338 	 */
2339 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2340 	    sata_device.satadev_addr.cport)));
2341 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
2342 	    &spx->txlt_sata_pkt->satapkt_device);
2343 	/* NULL sdinfo may be passsed to sata_adjust_dma_attr() */
2344 	sata_adjust_dma_attr(sdinfo,
2345 	    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
2346 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2347 	    sata_device.satadev_addr.cport)));
2348 	/*
2349 	 * Allocate necessary DMA resources for the packet's data buffer
2350 	 * NOTE:
2351 	 * In case of read/write commands, DMA resource allocation here is
2352 	 * based on the premise that the transfer length specified in
2353 	 * the read/write scsi cdb will match exactly DMA resources -
2354 	 * returning correct packet residue is crucial.
2355 	 */
2356 	if ((rval = sata_dma_buf_setup(spx, flags, callback, arg,
2357 	    &cur_dma_attr)) != DDI_SUCCESS) {
2358 		/*
2359 		 * If a DMA allocation request fails with
2360 		 * DDI_DMA_NOMAPPING, indicate the error by calling
2361 		 * bioerror(9F) with bp and an error code of EFAULT.
2362 		 * If a DMA allocation request fails with
2363 		 * DDI_DMA_TOOBIG, indicate the error by calling
2364 		 * bioerror(9F) with bp and an error code of EINVAL.
2365 		 * For DDI_DMA_NORESOURCES, we may have some of them allocated.
2366 		 * Request may be repeated later - there is no real error.
2367 		 */
2368 		switch (rval) {
2369 		case DDI_DMA_NORESOURCES:
2370 			bioerror(bp, 0);
2371 			break;
2372 		case DDI_DMA_NOMAPPING:
2373 		case DDI_DMA_BADATTR:
2374 			bioerror(bp, EFAULT);
2375 			break;
2376 		case DDI_DMA_TOOBIG:
2377 		default:
2378 			bioerror(bp, EINVAL);
2379 			break;
2380 		}
2381 		goto fail;
2382 	}
2383 
2384 	if (sata_check_for_dma_error(dip, spx)) {
2385 		ddi_fm_service_impact(dip, DDI_SERVICE_UNAFFECTED);
2386 		bioerror(bp, EFAULT);
2387 		goto fail;
2388 	}
2389 
2390 success:
2391 	/* Set number of bytes that are not yet accounted for */
2392 	pkt->pkt_resid = spx->txlt_total_residue;
2393 	ASSERT(pkt->pkt_resid >= 0);
2394 
2395 	return (pkt);
2396 
2397 fail:
2398 	if (new_pkt == B_TRUE) {
2399 		/*
2400 		 * Since this is a new packet, we can clean-up
2401 		 * everything
2402 		 */
2403 		sata_scsi_destroy_pkt(ap, pkt);
2404 	} else {
2405 		/*
2406 		 * This is a re-used packet. It will be target driver's
2407 		 * responsibility to eventually destroy it (which
2408 		 * will free allocated resources).
2409 		 * Here, we just "complete" the request, leaving
2410 		 * allocated resources intact, so the request may
2411 		 * be retried.
2412 		 */
2413 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2414 		sata_pkt_free(spx);
2415 	}
2416 	return (NULL);
2417 }
2418 
2419 /*
2420  * Implementation of scsi tran_start.
2421  * Translate scsi cmd into sata operation and return status.
2422  * ATAPI CDBs are passed to ATAPI devices - the device determines what commands
2423  * are supported.
2424  * For SATA hard disks, supported scsi commands:
2425  * SCMD_INQUIRY
2426  * SCMD_TEST_UNIT_READY
2427  * SCMD_START_STOP
2428  * SCMD_READ_CAPACITY
2429  * SCMD_SVC_ACTION_IN_G4 (READ CAPACITY (16))
2430  * SCMD_REQUEST_SENSE
2431  * SCMD_LOG_SENSE_G1
2432  * SCMD_LOG_SELECT_G1
2433  * SCMD_MODE_SENSE	(specific pages)
2434  * SCMD_MODE_SENSE_G1	(specific pages)
2435  * SCMD_MODE_SELECT	(specific pages)
2436  * SCMD_MODE_SELECT_G1	(specific pages)
2437  * SCMD_SYNCHRONIZE_CACHE
2438  * SCMD_SYNCHRONIZE_CACHE_G1
2439  * SCMD_READ
2440  * SCMD_READ_G1
2441  * SCMD_READ_G4
2442  * SCMD_READ_G5
2443  * SCMD_WRITE
2444  * SCMD_WRITE_BUFFER
2445  * SCMD_WRITE_G1
2446  * SCMD_WRITE_G4
2447  * SCMD_WRITE_G5
2448  * SCMD_SEEK		(noop)
2449  * SCMD_SDIAG
2450  *
2451  * All other commands are rejected as unsupported.
2452  *
2453  * Returns:
2454  * TRAN_ACCEPT if command was executed successfully or accepted by HBA driver
2455  * for execution. TRAN_ACCEPT may be returned also if device was removed but
2456  * a callback could be scheduled.
2457  * TRAN_BADPKT if cmd was directed to invalid address.
2458  * TRAN_FATAL_ERROR is command was rejected due to hardware error, including
2459  * some unspecified error. TRAN_FATAL_ERROR may be also returned if a device
2460  * was removed and there was no callback specified in scsi pkt.
2461  * TRAN_BUSY if command could not be executed becasue HBA driver or SATA
2462  * framework was busy performing some other operation(s).
2463  *
2464  */
2465 static int
2466 sata_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
2467 {
2468 	sata_hba_inst_t *sata_hba_inst =
2469 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2470 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2471 	sata_device_t *sdevice = &spx->txlt_sata_pkt->satapkt_device;
2472 	sata_drive_info_t *sdinfo;
2473 	struct buf *bp;
2474 	uint8_t cport, pmport;
2475 	boolean_t dev_gone = B_FALSE;
2476 	int rval;
2477 
2478 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2479 	    "sata_scsi_start: cmd 0x%02x\n", pkt->pkt_cdbp[0]);
2480 
2481 	ASSERT(spx != NULL &&
2482 	    spx->txlt_scsi_pkt == pkt && spx->txlt_sata_pkt != NULL);
2483 
2484 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
2485 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2486 
2487 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2488 
2489 	if (sdevice->satadev_addr.qual == SATA_ADDR_DCPORT) {
2490 		sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2491 		if (sdinfo == NULL ||
2492 		    SATA_CPORT_INFO(sata_hba_inst, cport)->
2493 		    cport_tgtnode_clean == B_FALSE ||
2494 		    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2495 			dev_gone = B_TRUE;
2496 		}
2497 	} else if (sdevice->satadev_addr.qual == SATA_ADDR_DPMPORT) {
2498 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
2499 		    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
2500 		    cport) == NULL) {
2501 			dev_gone = B_TRUE;
2502 		} else if (SATA_PMPORT_INFO(sata_hba_inst, cport,
2503 		    pmport) == NULL) {
2504 			dev_gone = B_TRUE;
2505 		} else {
2506 			mutex_enter(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2507 			    cport, pmport)));
2508 			sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2509 			if (sdinfo == NULL ||
2510 			    SATA_PMPORT_INFO(sata_hba_inst, cport, pmport)->
2511 			    pmport_tgtnode_clean == B_FALSE ||
2512 			    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2513 				dev_gone = B_TRUE;
2514 			}
2515 			mutex_exit(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2516 			    cport, pmport)));
2517 		}
2518 	}
2519 
2520 	if (dev_gone == B_TRUE) {
2521 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2522 		pkt->pkt_reason = CMD_DEV_GONE;
2523 		/*
2524 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
2525 		 * only in callback function (for normal requests) and
2526 		 * in the dump code path.
2527 		 * So, if the callback is available, we need to do
2528 		 * the callback rather than returning TRAN_FATAL_ERROR here.
2529 		 */
2530 		if (pkt->pkt_comp != NULL) {
2531 			/* scsi callback required */
2532 			if (servicing_interrupt()) {
2533 				if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2534 				    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2535 				    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
2536 				    TASKQID_INVALID) {
2537 					return (TRAN_BUSY);
2538 				}
2539 			} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2540 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2541 			    spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
2542 				/* Scheduling the callback failed */
2543 				return (TRAN_BUSY);
2544 			}
2545 			return (TRAN_ACCEPT);
2546 		}
2547 		/* No callback available */
2548 		return (TRAN_FATAL_ERROR);
2549 	}
2550 
2551 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
2552 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2553 		rval = sata_txlt_atapi(spx);
2554 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2555 		    "sata_scsi_start atapi: rval %d\n", rval);
2556 		return (rval);
2557 	}
2558 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2559 
2560 	/*
2561 	 * Checking for power state, if it was on
2562 	 * STOPPED state, then the drive is not capable
2563 	 * of processing media access command.  And
2564 	 * TEST_UNIT_READY, REQUEST_SENSE has special handling
2565 	 * in the function for different power state.
2566 	 */
2567 	if (((sdinfo->satadrv_power_level == SATA_POWER_STANDBY) ||
2568 	    (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)) &&
2569 	    (SATA_IS_MEDIUM_ACCESS_CMD(pkt->pkt_cdbp[0]))) {
2570 		return (sata_txlt_check_condition(spx, KEY_NOT_READY,
2571 		    SD_SCSI_ASC_LU_NOT_READY));
2572 	}
2573 
2574 	/* ATA Disk commands processing starts here */
2575 
2576 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2577 
2578 	switch (pkt->pkt_cdbp[0]) {
2579 
2580 	case SCMD_INQUIRY:
2581 		/* Mapped to identify device */
2582 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2583 			bp_mapin(bp);
2584 		rval = sata_txlt_inquiry(spx);
2585 		break;
2586 
2587 	case SCMD_TEST_UNIT_READY:
2588 		/*
2589 		 * SAT "SATA to ATA Translation" doc specifies translation
2590 		 * to ATA CHECK POWER MODE.
2591 		 */
2592 		rval = sata_txlt_test_unit_ready(spx);
2593 		break;
2594 
2595 	case SCMD_START_STOP:
2596 		/* Mapping depends on the command */
2597 		rval = sata_txlt_start_stop_unit(spx);
2598 		break;
2599 
2600 	case SCMD_READ_CAPACITY:
2601 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2602 			bp_mapin(bp);
2603 		rval = sata_txlt_read_capacity(spx);
2604 		break;
2605 
2606 	case SCMD_SVC_ACTION_IN_G4:		/* READ CAPACITY (16) */
2607 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2608 			bp_mapin(bp);
2609 		rval = sata_txlt_read_capacity16(spx);
2610 		break;
2611 
2612 	case SCMD_REQUEST_SENSE:
2613 		/*
2614 		 * Always No Sense, since we force ARQ
2615 		 */
2616 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2617 			bp_mapin(bp);
2618 		rval = sata_txlt_request_sense(spx);
2619 		break;
2620 
2621 	case SCMD_LOG_SENSE_G1:
2622 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2623 			bp_mapin(bp);
2624 		rval = sata_txlt_log_sense(spx);
2625 		break;
2626 
2627 	case SCMD_LOG_SELECT_G1:
2628 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2629 			bp_mapin(bp);
2630 		rval = sata_txlt_log_select(spx);
2631 		break;
2632 
2633 	case SCMD_MODE_SENSE:
2634 	case SCMD_MODE_SENSE_G1:
2635 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2636 			bp_mapin(bp);
2637 		rval = sata_txlt_mode_sense(spx);
2638 		break;
2639 
2640 
2641 	case SCMD_MODE_SELECT:
2642 	case SCMD_MODE_SELECT_G1:
2643 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2644 			bp_mapin(bp);
2645 		rval = sata_txlt_mode_select(spx);
2646 		break;
2647 
2648 	case SCMD_SYNCHRONIZE_CACHE:
2649 	case SCMD_SYNCHRONIZE_CACHE_G1:
2650 		rval = sata_txlt_synchronize_cache(spx);
2651 		break;
2652 
2653 	case SCMD_READ:
2654 	case SCMD_READ_G1:
2655 	case SCMD_READ_G4:
2656 	case SCMD_READ_G5:
2657 		rval = sata_txlt_read(spx);
2658 		break;
2659 	case SCMD_WRITE_BUFFER:
2660 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2661 			bp_mapin(bp);
2662 		rval = sata_txlt_write_buffer(spx);
2663 		break;
2664 
2665 	case SCMD_WRITE:
2666 	case SCMD_WRITE_G1:
2667 	case SCMD_WRITE_G4:
2668 	case SCMD_WRITE_G5:
2669 		rval = sata_txlt_write(spx);
2670 		break;
2671 
2672 	case SCMD_SEEK:
2673 		rval = sata_txlt_nodata_cmd_immediate(spx);
2674 		break;
2675 
2676 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
2677 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
2678 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2679 			bp_mapin(bp);
2680 		rval = sata_txlt_ata_pass_thru(spx);
2681 		break;
2682 
2683 		/* Other cases will be filed later */
2684 		/* postponed until phase 2 of the development */
2685 	case SPC3_CMD_UNMAP:
2686 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2687 			bp_mapin(bp);
2688 		rval = sata_txlt_unmap(spx);
2689 		break;
2690 	default:
2691 		rval = sata_txlt_invalid_command(spx);
2692 		break;
2693 	}
2694 
2695 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2696 	    "sata_scsi_start: rval %d\n", rval);
2697 
2698 	return (rval);
2699 }
2700 
2701 /*
2702  * Implementation of scsi tran_abort.
2703  * Abort specific pkt or all packets.
2704  *
2705  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2706  *
2707  * May be called from an interrupt level.
2708  */
2709 static int
2710 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2711 {
2712 	sata_hba_inst_t *sata_hba_inst =
2713 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2714 	sata_device_t	sata_device;
2715 	sata_pkt_t	*sata_pkt;
2716 
2717 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2718 	    "sata_scsi_abort: %s at target: 0x%x\n",
2719 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2720 
2721 	/* Validate address */
2722 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2723 		/* Invalid address */
2724 		return (0);
2725 
2726 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2727 	    sata_device.satadev_addr.cport)));
2728 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2729 		/* invalid address */
2730 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2731 		    sata_device.satadev_addr.cport)));
2732 		return (0);
2733 	}
2734 	if (scsi_pkt == NULL) {
2735 		/*
2736 		 * Abort all packets.
2737 		 * Although we do not have specific packet, we still need
2738 		 * dummy packet structure to pass device address to HBA.
2739 		 * Allocate one, without sleeping. Fail if pkt cannot be
2740 		 * allocated.
2741 		 */
2742 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2743 		if (sata_pkt == NULL) {
2744 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2745 			    sata_device.satadev_addr.cport)));
2746 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2747 			    "could not allocate sata_pkt"));
2748 			return (0);
2749 		}
2750 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2751 		sata_pkt->satapkt_device = sata_device;
2752 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2753 	} else {
2754 		if (scsi_pkt->pkt_ha_private == NULL) {
2755 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2756 			    sata_device.satadev_addr.cport)));
2757 			return (0); /* Bad scsi pkt */
2758 		}
2759 		/* extract pointer to sata pkt */
2760 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2761 		    txlt_sata_pkt;
2762 	}
2763 
2764 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2765 	    sata_device.satadev_addr.cport)));
2766 	/* Send abort request to HBA */
2767 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2768 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2769 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2770 	    SATA_SUCCESS) {
2771 		if (scsi_pkt == NULL)
2772 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2773 		/* Success */
2774 		return (1);
2775 	}
2776 	/* Else, something did not go right */
2777 	if (scsi_pkt == NULL)
2778 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
2779 	/* Failure */
2780 	return (0);
2781 }
2782 
2783 
2784 /*
2785  * Implementation of scsi tran_reset.
2786  * RESET_ALL request is translated into port reset.
2787  * RESET_TARGET requests is translated into a device reset,
2788  * RESET_LUN request is accepted only for LUN 0 and translated into
2789  * device reset.
2790  * The target reset should cause all HBA active and queued packets to
2791  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
2792  * the return. HBA should report reset event for the device.
2793  *
2794  * Returns 1 upon success, 0 upon failure.
2795  */
2796 static int
2797 sata_scsi_reset(struct scsi_address *ap, int level)
2798 {
2799 	sata_hba_inst_t	*sata_hba_inst =
2800 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2801 	sata_device_t	sata_device;
2802 	int		val;
2803 
2804 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2805 	    "sata_scsi_reset: level %d target: 0x%x\n",
2806 	    level, ap->a_target);
2807 
2808 	/* Validate address */
2809 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
2810 	if (val == -1)
2811 		/* Invalid address */
2812 		return (0);
2813 
2814 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2815 	    sata_device.satadev_addr.cport)));
2816 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2817 		/* invalid address */
2818 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2819 		    sata_device.satadev_addr.cport)));
2820 		return (0);
2821 	}
2822 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2823 	    sata_device.satadev_addr.cport)));
2824 	if (level == RESET_ALL) {
2825 		/* port reset */
2826 		if (sata_device.satadev_addr.qual == SATA_ADDR_DCPORT)
2827 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2828 		else
2829 			sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
2830 
2831 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2832 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2833 			return (1);
2834 		else
2835 			return (0);
2836 
2837 	} else if (val == 0 &&
2838 	    (level == RESET_TARGET || level == RESET_LUN)) {
2839 		/* reset device (device attached) */
2840 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2841 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2842 			return (1);
2843 		else
2844 			return (0);
2845 	}
2846 	return (0);
2847 }
2848 
2849 
2850 /*
2851  * Implementation of scsi tran_getcap (get transport/device capabilities).
2852  * Supported capabilities for SATA hard disks:
2853  * auto-rqsense		(always supported)
2854  * tagged-qing		(supported if HBA supports it)
2855  * untagged-qing	(could be supported if disk supports it, but because
2856  *			 caching behavior allowing untagged queuing actually
2857  *			 results in reduced performance.  sd tries to throttle
2858  *			 back to only 3 outstanding commands, which may
2859  *			 work for real SCSI disks, but with read ahead
2860  *			 caching, having more than 1 outstanding command
2861  *			 results in cache thrashing.)
2862  * sector_size
2863  * dma_max
2864  * interconnect-type	(INTERCONNECT_SATA)
2865  *
2866  * Supported capabilities for ATAPI CD/DVD devices:
2867  * auto-rqsense		(always supported)
2868  * sector_size
2869  * dma_max
2870  * max-cdb-length
2871  * interconnect-type	(INTERCONNECT_SATA)
2872  *
2873  * Supported capabilities for ATAPI TAPE devices:
2874  * auto-rqsense		(always supported)
2875  * dma_max
2876  * max-cdb-length
2877  *
2878  * Supported capabilities for SATA ATAPI hard disks:
2879  * auto-rqsense		(always supported)
2880  * interconnect-type	(INTERCONNECT_SATA)
2881  * max-cdb-length
2882  *
2883  * Request for other capabilities is rejected as unsupported.
2884  *
2885  * Returns supported capability value, or -1 if capability is unsuppported or
2886  * the address is invalid - no device.
2887  */
2888 
2889 static int
2890 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
2891 {
2892 
2893 	sata_hba_inst_t		*sata_hba_inst =
2894 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2895 	sata_device_t		sata_device;
2896 	sata_drive_info_t	*sdinfo;
2897 	ddi_dma_attr_t		adj_dma_attr;
2898 	int			rval;
2899 
2900 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2901 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
2902 	    ap->a_target, cap);
2903 
2904 	/*
2905 	 * We want to process the capabilities on per port granularity.
2906 	 * So, we are specifically restricting ourselves to whom != 0
2907 	 * to exclude the controller wide handling.
2908 	 */
2909 	if (cap == NULL || whom == 0)
2910 		return (-1);
2911 
2912 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2913 		/* Invalid address */
2914 		return (-1);
2915 	}
2916 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2917 	    sata_device.satadev_addr.cport)));
2918 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
2919 	    NULL) {
2920 		/* invalid address */
2921 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2922 		    sata_device.satadev_addr.cport)));
2923 		return (-1);
2924 	}
2925 
2926 	switch (scsi_hba_lookup_capstr(cap)) {
2927 	case SCSI_CAP_ARQ:
2928 		rval = 1;		/* ARQ supported, turned on */
2929 		break;
2930 
2931 	case SCSI_CAP_SECTOR_SIZE:
2932 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
2933 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
2934 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
2935 			rval = SATA_ATAPI_SECTOR_SIZE;
2936 		else rval = -1;
2937 		break;
2938 
2939 	/*
2940 	 * untagged queuing cause a performance inversion because of
2941 	 * the way sd operates.  Because of this reason we do not
2942 	 * use it when available.
2943 	 */
2944 	case SCSI_CAP_UNTAGGED_QING:
2945 		if (sdinfo->satadrv_features_enabled &
2946 		    SATA_DEV_F_E_UNTAGGED_QING)
2947 			rval = 1;	/* Untagged queuing available */
2948 		else
2949 			rval = -1;	/* Untagged queuing not available */
2950 		break;
2951 
2952 	case SCSI_CAP_TAGGED_QING:
2953 		if ((sdinfo->satadrv_features_enabled &
2954 		    SATA_DEV_F_E_TAGGED_QING) &&
2955 		    (sdinfo->satadrv_max_queue_depth > 1))
2956 			rval = 1;	/* Tagged queuing available */
2957 		else
2958 			rval = -1;	/* Tagged queuing not available */
2959 		break;
2960 
2961 	case SCSI_CAP_DMA_MAX:
2962 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
2963 		    &adj_dma_attr);
2964 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
2965 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
2966 		break;
2967 
2968 	case SCSI_CAP_INTERCONNECT_TYPE:
2969 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
2970 		break;
2971 
2972 	case SCSI_CAP_CDB_LEN:
2973 		if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI)
2974 			rval = sdinfo->satadrv_atapi_cdb_len;
2975 		else
2976 			rval = -1;
2977 		break;
2978 
2979 	default:
2980 		rval = -1;
2981 		break;
2982 	}
2983 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2984 	    sata_device.satadev_addr.cport)));
2985 	return (rval);
2986 }
2987 
2988 /*
2989  * Implementation of scsi tran_setcap
2990  *
2991  * Only SCSI_CAP_UNTAGGED_QING and  SCSI_CAP_TAGGED_QING are changeable.
2992  *
2993  */
2994 static int
2995 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
2996 {
2997 	sata_hba_inst_t	*sata_hba_inst =
2998 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2999 	sata_device_t	sata_device;
3000 	sata_drive_info_t	*sdinfo;
3001 	int		rval;
3002 
3003 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
3004 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
3005 
3006 	/*
3007 	 * We want to process the capabilities on per port granularity.
3008 	 * So, we are specifically restricting ourselves to whom != 0
3009 	 * to exclude the controller wide handling.
3010 	 */
3011 	if (cap == NULL || whom == 0) {
3012 		return (-1);
3013 	}
3014 
3015 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
3016 		/* Invalid address */
3017 		return (-1);
3018 	}
3019 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
3020 	    sata_device.satadev_addr.cport)));
3021 	if ((sdinfo = sata_get_device_info(sata_hba_inst,
3022 	    &sata_device)) == NULL) {
3023 		/* invalid address */
3024 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
3025 		    sata_device.satadev_addr.cport)));
3026 		return (-1);
3027 	}
3028 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
3029 	    sata_device.satadev_addr.cport)));
3030 
3031 	switch (scsi_hba_lookup_capstr(cap)) {
3032 	case SCSI_CAP_ARQ:
3033 	case SCSI_CAP_SECTOR_SIZE:
3034 	case SCSI_CAP_DMA_MAX:
3035 	case SCSI_CAP_INTERCONNECT_TYPE:
3036 		rval = 0;
3037 		break;
3038 	case SCSI_CAP_UNTAGGED_QING:
3039 		if (SATA_QDEPTH(sata_hba_inst) > 1) {
3040 			rval = 1;
3041 			if (value == 1) {
3042 				sdinfo->satadrv_features_enabled |=
3043 				    SATA_DEV_F_E_UNTAGGED_QING;
3044 			} else if (value == 0) {
3045 				sdinfo->satadrv_features_enabled &=
3046 				    ~SATA_DEV_F_E_UNTAGGED_QING;
3047 			} else {
3048 				rval = -1;
3049 			}
3050 		} else {
3051 			rval = 0;
3052 		}
3053 		break;
3054 	case SCSI_CAP_TAGGED_QING:
3055 		/* This can TCQ or NCQ */
3056 		if (sata_func_enable & SATA_ENABLE_QUEUING &&
3057 		    ((sdinfo->satadrv_features_support & SATA_DEV_F_TCQ &&
3058 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_QCMD) ||
3059 		    (sata_func_enable & SATA_ENABLE_NCQ &&
3060 		    sdinfo->satadrv_features_support & SATA_DEV_F_NCQ &&
3061 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_NCQ)) &&
3062 		    (sdinfo->satadrv_max_queue_depth > 1)) {
3063 			rval = 1;
3064 			if (value == 1) {
3065 				sdinfo->satadrv_features_enabled |=
3066 				    SATA_DEV_F_E_TAGGED_QING;
3067 			} else if (value == 0) {
3068 				sdinfo->satadrv_features_enabled &=
3069 				    ~SATA_DEV_F_E_TAGGED_QING;
3070 			} else {
3071 				rval = -1;
3072 			}
3073 		} else {
3074 			rval = 0;
3075 		}
3076 		break;
3077 	default:
3078 		rval = -1;
3079 		break;
3080 	}
3081 	return (rval);
3082 }
3083 
3084 /*
3085  * Implementations of scsi tran_destroy_pkt.
3086  * Free resources allocated by sata_scsi_init_pkt()
3087  */
3088 static void
3089 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3090 {
3091 	sata_pkt_txlate_t *spx;
3092 
3093 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3094 
3095 	sata_common_free_dma_rsrcs(spx);
3096 
3097 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
3098 	sata_pkt_free(spx);
3099 
3100 	scsi_hba_pkt_free(ap, pkt);
3101 }
3102 
3103 /*
3104  * Implementation of scsi tran_dmafree.
3105  * Free DMA resources allocated by sata_scsi_init_pkt()
3106  */
3107 
3108 static void
3109 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
3110 {
3111 #ifndef __lock_lint
3112 	_NOTE(ARGUNUSED(ap))
3113 #endif
3114 	sata_pkt_txlate_t *spx;
3115 
3116 	ASSERT(pkt != NULL);
3117 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3118 
3119 	sata_common_free_dma_rsrcs(spx);
3120 }
3121 
3122 /*
3123  * Implementation of scsi tran_sync_pkt.
3124  *
3125  * The assumption below is that pkt is unique - there is no need to check ap
3126  *
3127  * Synchronize DMA buffer and, if the intermediate buffer is used, copy data
3128  * into/from the real buffer.
3129  */
3130 static void
3131 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3132 {
3133 #ifndef __lock_lint
3134 	_NOTE(ARGUNUSED(ap))
3135 #endif
3136 	int rval;
3137 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3138 	struct buf *bp;
3139 	int direction;
3140 
3141 	ASSERT(spx != NULL);
3142 	if (spx->txlt_buf_dma_handle != NULL) {
3143 		direction = spx->txlt_sata_pkt->
3144 		    satapkt_cmd.satacmd_flags.sata_data_direction;
3145 		if (spx->txlt_sata_pkt != NULL &&
3146 		    direction != SATA_DIR_NODATA_XFER) {
3147 			if (spx->txlt_tmp_buf != NULL) {
3148 				/* Intermediate DMA buffer used */
3149 				bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3150 
3151 				if (direction & SATA_DIR_WRITE) {
3152 					bcopy(bp->b_un.b_addr,
3153 					    spx->txlt_tmp_buf, bp->b_bcount);
3154 				}
3155 			}
3156 			/* Sync the buffer for device or for CPU */
3157 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle,   0, 0,
3158 			    (direction & SATA_DIR_WRITE) ?
3159 			    DDI_DMA_SYNC_FORDEV :  DDI_DMA_SYNC_FORCPU);
3160 			ASSERT(rval == DDI_SUCCESS);
3161 			if (spx->txlt_tmp_buf != NULL &&
3162 			    !(direction & SATA_DIR_WRITE)) {
3163 				/* Intermediate DMA buffer used for read */
3164 				bcopy(spx->txlt_tmp_buf,
3165 				    bp->b_un.b_addr, bp->b_bcount);
3166 			}
3167 
3168 		}
3169 	}
3170 }
3171 
3172 
3173 
3174 /* *******************  SATA - SCSI Translation functions **************** */
3175 /*
3176  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
3177  * translation.
3178  */
3179 
3180 /*
3181  * Checks if a device exists and can be access and translates common
3182  * scsi_pkt data to sata_pkt data.
3183  *
3184  * Flag argument indicates that a non-read/write ATA command may be sent
3185  * to HBA in arbitrary SYNC mode to execute this packet.
3186  *
3187  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_CMPLT if device exists and
3188  * sata_pkt was set-up.
3189  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_DEV_GONE if device does not
3190  * exist and pkt_comp callback was scheduled.
3191  * Returns other TRAN_XXXXX values when error occured and command should be
3192  * rejected with the returned TRAN_XXXXX value.
3193  *
3194  * This function should be called with port mutex held.
3195  */
3196 static int
3197 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx, int *reason, int flag)
3198 {
3199 	sata_drive_info_t *sdinfo;
3200 	sata_device_t sata_device;
3201 	const struct sata_cmd_flags sata_initial_cmd_flags = {
3202 		SATA_DIR_NODATA_XFER,
3203 		/* all other values to 0/FALSE */
3204 	};
3205 	/*
3206 	 * Pkt_reason has to be set if the pkt_comp callback is invoked,
3207 	 * and that implies TRAN_ACCEPT return value. Any other returned value
3208 	 * indicates that the scsi packet was not accepted (the reason will not
3209 	 * be checked by the scsi target driver).
3210 	 * To make debugging easier, we set pkt_reason to know value here.
3211 	 * It may be changed later when different completion reason is
3212 	 * determined.
3213 	 */
3214 	spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
3215 	*reason = CMD_TRAN_ERR;
3216 
3217 	/* Validate address */
3218 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
3219 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
3220 
3221 	case -1:
3222 		/* Invalid address or invalid device type */
3223 		return (TRAN_BADPKT);
3224 	case 2:
3225 		/*
3226 		 * Valid address but device type is unknown - Chack if it is
3227 		 * in the reset state and therefore in an indeterminate state.
3228 		 */
3229 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3230 		    &spx->txlt_sata_pkt->satapkt_device);
3231 		if (sdinfo != NULL && (sdinfo->satadrv_event_flags &
3232 		    (SATA_EVNT_DEVICE_RESET |
3233 		    SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3234 			if (!ddi_in_panic()) {
3235 				spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3236 				*reason = CMD_INCOMPLETE;
3237 				SATADBG1(SATA_DBG_SCSI_IF,
3238 				    spx->txlt_sata_hba_inst,
3239 				    "sata_scsi_start: rejecting command "
3240 				    "because of device reset state\n", NULL);
3241 				return (TRAN_BUSY);
3242 			}
3243 		}
3244 		/* FALLTHROUGH */
3245 	case 1:
3246 		/* valid address but no valid device - it has disappeared */
3247 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
3248 		*reason = CMD_DEV_GONE;
3249 		/*
3250 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
3251 		 * only in callback function (for normal requests) and
3252 		 * in the dump code path.
3253 		 * So, if the callback is available, we need to do
3254 		 * the callback rather than returning TRAN_FATAL_ERROR here.
3255 		 */
3256 		if (spx->txlt_scsi_pkt->pkt_comp != NULL) {
3257 			/* scsi callback required */
3258 			if (servicing_interrupt()) {
3259 				if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3260 				    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3261 				    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
3262 				    TASKQID_INVALID) {
3263 					return (TRAN_BUSY);
3264 				}
3265 			} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3266 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3267 			    spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
3268 				/* Scheduling the callback failed */
3269 				return (TRAN_BUSY);
3270 			}
3271 
3272 			return (TRAN_ACCEPT);
3273 		}
3274 		return (TRAN_FATAL_ERROR);
3275 	default:
3276 		/* all OK; pkt reason will be overwritten later */
3277 		break;
3278 	}
3279 	/*
3280 	 * If pkt is to be executed in polling mode and a command will not be
3281 	 * emulated in SATA module (requires sending a non-read/write ATA
3282 	 * command to HBA driver in arbitrary SYNC mode) and we are in the
3283 	 * interrupt context and not in the panic dump, then reject the packet
3284 	 * to avoid a possible interrupt stack overrun or hang caused by
3285 	 * a potentially blocked interrupt.
3286 	 */
3287 	if (((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0 || flag != 0) &&
3288 	    servicing_interrupt() && !ddi_in_panic()) {
3289 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
3290 		    "sata_scsi_start: rejecting synchronous command because "
3291 		    "of interrupt context\n", NULL);
3292 		return (TRAN_BUSY);
3293 	}
3294 
3295 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3296 	    &spx->txlt_sata_pkt->satapkt_device);
3297 
3298 	/*
3299 	 * If device is in reset condition, reject the packet with
3300 	 * TRAN_BUSY, unless:
3301 	 * 1. system is panicking (dumping)
3302 	 * In such case only one thread is running and there is no way to
3303 	 * process reset.
3304 	 * 2. cfgadm operation is is progress (internal APCTL lock is set)
3305 	 * Some cfgadm operations involve drive commands, so reset condition
3306 	 * needs to be ignored for IOCTL operations.
3307 	 */
3308 	if ((sdinfo->satadrv_event_flags &
3309 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3310 
3311 		if (!ddi_in_panic() &&
3312 		    ((SATA_CPORT_EVENT_FLAGS(spx->txlt_sata_hba_inst,
3313 		    sata_device.satadev_addr.cport) &
3314 		    SATA_APCTL_LOCK_PORT_BUSY) == 0)) {
3315 			spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3316 			*reason = CMD_INCOMPLETE;
3317 			SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3318 			    "sata_scsi_start: rejecting command because "
3319 			    "of device reset state\n", NULL);
3320 			return (TRAN_BUSY);
3321 		}
3322 	}
3323 
3324 	/*
3325 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
3326 	 * sata_scsi_pkt_init() because pkt init had to work also with
3327 	 * non-existing devices.
3328 	 * Now we know that the packet was set-up for a real device, so its
3329 	 * type is known.
3330 	 */
3331 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
3332 
3333 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
3334 	if ((SATA_CPORT_INFO(spx->txlt_sata_hba_inst,
3335 	    sata_device.satadev_addr.cport)->cport_event_flags &
3336 	    SATA_APCTL_LOCK_PORT_BUSY) != 0) {
3337 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3338 		    sata_ignore_dev_reset = B_TRUE;
3339 	}
3340 	/*
3341 	 * At this point the generic translation routine determined that the
3342 	 * scsi packet should be accepted. Packet completion reason may be
3343 	 * changed later when a different completion reason is determined.
3344 	 */
3345 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3346 	*reason = CMD_CMPLT;
3347 
3348 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3349 		/* Synchronous execution */
3350 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
3351 		    SATA_OPMODE_POLLING;
3352 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3353 		    sata_ignore_dev_reset = ddi_in_panic();
3354 	} else {
3355 		/* Asynchronous execution */
3356 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
3357 		    SATA_OPMODE_INTERRUPTS;
3358 	}
3359 	/* Convert queuing information */
3360 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
3361 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
3362 		    B_TRUE;
3363 	else if (spx->txlt_scsi_pkt->pkt_flags &
3364 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
3365 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
3366 		    B_TRUE;
3367 
3368 	/* Always limit pkt time */
3369 	if (spx->txlt_scsi_pkt->pkt_time == 0)
3370 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
3371 	else
3372 		/* Pass on scsi_pkt time */
3373 		spx->txlt_sata_pkt->satapkt_time =
3374 		    spx->txlt_scsi_pkt->pkt_time;
3375 
3376 	return (TRAN_ACCEPT);
3377 }
3378 
3379 
3380 /*
3381  * Translate ATA Identify Device data to SCSI Inquiry data.
3382  * This function may be called only for ATA devices.
3383  * This function should not be called for ATAPI devices - they
3384  * respond directly to SCSI Inquiry command.
3385  *
3386  * SATA Identify Device data has to be valid in sata_drive_info.
3387  * Buffer has to accomodate the inquiry length (36 bytes).
3388  *
3389  * This function should be called with a port mutex held.
3390  */
3391 static	void
3392 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
3393     sata_drive_info_t *sdinfo, uint8_t *buf)
3394 {
3395 
3396 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
3397 	struct sata_id *sid = &sdinfo->satadrv_id;
3398 
3399 	/* Start with a nice clean slate */
3400 	bzero((void *)inq, sizeof (struct scsi_inquiry));
3401 
3402 	/*
3403 	 * Rely on the dev_type for setting paripheral qualifier.
3404 	 * Assume that  DTYPE_RODIRECT applies to CD/DVD R/W devices.
3405 	 * It could be that DTYPE_OPTICAL could also qualify in the future.
3406 	 * ATAPI Inquiry may provide more data to the target driver.
3407 	 */
3408 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3409 	    DTYPE_DIRECT : DTYPE_RODIRECT; /* DTYPE_UNKNOWN; */
3410 
3411 	/* CFA type device is not a removable media device */
3412 	inq->inq_rmb = ((sid->ai_config != SATA_CFA_TYPE) &&
3413 	    (sid->ai_config & SATA_REM_MEDIA)) ? 1 : 0;
3414 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
3415 	inq->inq_iso = 0;	/* ISO version */
3416 	inq->inq_ecma = 0;	/* ECMA version */
3417 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
3418 	inq->inq_aenc = 0;	/* Async event notification cap. */
3419 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg - NO */
3420 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
3421 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
3422 	inq->inq_len = 31;	/* Additional length */
3423 	inq->inq_dualp = 0;	/* dual port device - NO */
3424 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
3425 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
3426 	inq->inq_linked = 0;	/* Supports linked commands - NO */
3427 				/*
3428 				 * Queuing support - controller has to
3429 				 * support some sort of command queuing.
3430 				 */
3431 	if (SATA_QDEPTH(sata_hba_inst) > 1)
3432 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
3433 	else
3434 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
3435 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
3436 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
3437 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
3438 
3439 #ifdef	_LITTLE_ENDIAN
3440 	/* Swap text fields to match SCSI format */
3441 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3442 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3443 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3444 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
3445 	else
3446 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
3447 #else	/* _LITTLE_ENDIAN */
3448 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3449 	bcopy(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3450 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3451 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
3452 	else
3453 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
3454 #endif	/* _LITTLE_ENDIAN */
3455 }
3456 
3457 
3458 /*
3459  * Scsi response set up for invalid command (command not supported)
3460  *
3461  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3462  */
3463 static int
3464 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
3465 {
3466 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3467 	struct scsi_extended_sense *sense;
3468 
3469 	scsipkt->pkt_reason = CMD_CMPLT;
3470 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3471 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3472 
3473 	*scsipkt->pkt_scbp = STATUS_CHECK;
3474 
3475 	sense = sata_arq_sense(spx);
3476 	sense->es_key = KEY_ILLEGAL_REQUEST;
3477 	sense->es_add_code = SD_SCSI_ASC_INVALID_COMMAND_CODE;
3478 
3479 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3480 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3481 
3482 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3483 	    scsipkt->pkt_comp != NULL) {
3484 		/* scsi callback required */
3485 		if (servicing_interrupt()) {
3486 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3487 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3488 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
3489 			    TASKQID_INVALID) {
3490 				return (TRAN_BUSY);
3491 			}
3492 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3493 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3494 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
3495 			/* Scheduling the callback failed */
3496 			return (TRAN_BUSY);
3497 		}
3498 	}
3499 	return (TRAN_ACCEPT);
3500 }
3501 
3502 /*
3503  * Scsi response set up for check condition with special sense key
3504  * and additional sense code.
3505  *
3506  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3507  */
3508 static int
3509 sata_txlt_check_condition(sata_pkt_txlate_t *spx, uchar_t key, uchar_t code)
3510 {
3511 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3512 	int cport = SATA_TXLT_CPORT(spx);
3513 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3514 	struct scsi_extended_sense *sense;
3515 
3516 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3517 	scsipkt->pkt_reason = CMD_CMPLT;
3518 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3519 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3520 
3521 	*scsipkt->pkt_scbp = STATUS_CHECK;
3522 
3523 	sense = sata_arq_sense(spx);
3524 	sense->es_key = key;
3525 	sense->es_add_code = code;
3526 
3527 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3528 
3529 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3530 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3531 
3532 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3533 	    scsipkt->pkt_comp != NULL) {
3534 		/* scsi callback required */
3535 		if (servicing_interrupt()) {
3536 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3537 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3538 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
3539 			    TASKQID_INVALID) {
3540 				return (TRAN_BUSY);
3541 			}
3542 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3543 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3544 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
3545 			/* Scheduling the callback failed */
3546 			return (TRAN_BUSY);
3547 		}
3548 	}
3549 	return (TRAN_ACCEPT);
3550 }
3551 
3552 /*
3553  * Scsi response setup for
3554  * emulated non-data command that requires no action/return data
3555  *
3556  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3557  */
3558 static	int
3559 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3560 {
3561 	int rval;
3562 	int reason;
3563 	kmutex_t *cport_mutex =  &(SATA_TXLT_CPORT_MUTEX(spx));
3564 
3565 	mutex_enter(cport_mutex);
3566 
3567 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3568 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3569 		mutex_exit(cport_mutex);
3570 		return (rval);
3571 	}
3572 	mutex_exit(cport_mutex);
3573 
3574 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3575 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3576 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3577 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3578 
3579 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3580 	    "Scsi_pkt completion reason %x\n",
3581 	    spx->txlt_scsi_pkt->pkt_reason);
3582 
3583 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3584 	    spx->txlt_scsi_pkt->pkt_comp != NULL) {
3585 		/* scsi callback required */
3586 		if (servicing_interrupt()) {
3587 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3588 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3589 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
3590 			    TASKQID_INVALID) {
3591 				return (TRAN_BUSY);
3592 			}
3593 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3594 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3595 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
3596 			/* Scheduling the callback failed */
3597 			return (TRAN_BUSY);
3598 		}
3599 	}
3600 	return (TRAN_ACCEPT);
3601 }
3602 
3603 
3604 /*
3605  * SATA translate command: Inquiry / Identify Device
3606  * Use cached Identify Device data for now, rather than issuing actual
3607  * Device Identify cmd request. If device is detached and re-attached,
3608  * asynchronous event processing should fetch and refresh Identify Device
3609  * data.
3610  * VPD pages supported now:
3611  * Vital Product Data page
3612  * Unit Serial Number page
3613  * Block Device Characteristics Page
3614  * ATA Information Page
3615  *
3616  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3617  */
3618 
3619 #define	EVPD			1	/* Extended Vital Product Data flag */
3620 #define	CMDDT			2	/* Command Support Data - Obsolete */
3621 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VPD Pages Page Code */
3622 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3623 #define	INQUIRY_BDC_PAGE	0xB1	/* Block Device Characteristics Page */
3624 					/* Code */
3625 #define	INQUIRY_ATA_INFO_PAGE	0x89	/* ATA Information Page Code */
3626 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3627 
3628 static int
3629 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3630 {
3631 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3632 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3633 	sata_drive_info_t *sdinfo;
3634 	struct scsi_extended_sense *sense;
3635 	int count;
3636 	uint8_t *p;
3637 	int i, j;
3638 	uint8_t page_buf[1024]; /* Max length */
3639 	int rval, reason;
3640 	ushort_t rate;
3641 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
3642 
3643 	mutex_enter(cport_mutex);
3644 
3645 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3646 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3647 		mutex_exit(cport_mutex);
3648 		return (rval);
3649 	}
3650 
3651 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3652 	    &spx->txlt_sata_pkt->satapkt_device);
3653 
3654 	ASSERT(sdinfo != NULL);
3655 
3656 	scsipkt->pkt_reason = CMD_CMPLT;
3657 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3658 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3659 
3660 	/* Reject not supported request */
3661 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3662 		*scsipkt->pkt_scbp = STATUS_CHECK;
3663 		sense = sata_arq_sense(spx);
3664 		sense->es_key = KEY_ILLEGAL_REQUEST;
3665 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3666 		goto done;
3667 	}
3668 
3669 	/* Valid Inquiry request */
3670 	*scsipkt->pkt_scbp = STATUS_GOOD;
3671 
3672 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3673 
3674 		/*
3675 		 * Because it is fully emulated command storing data
3676 		 * programatically in the specified buffer, release
3677 		 * preallocated DMA resources before storing data in the buffer,
3678 		 * so no unwanted DMA sync would take place.
3679 		 */
3680 		sata_scsi_dmafree(NULL, scsipkt);
3681 
3682 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3683 			/* Standard Inquiry Data request */
3684 			struct scsi_inquiry inq;
3685 			unsigned int bufsize;
3686 
3687 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3688 			    sdinfo, (uint8_t *)&inq);
3689 			/* Copy no more than requested */
3690 			count = MIN(bp->b_bcount,
3691 			    sizeof (struct scsi_inquiry));
3692 			bufsize = scsipkt->pkt_cdbp[4];
3693 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3694 			count = MIN(count, bufsize);
3695 			bcopy(&inq, bp->b_un.b_addr, count);
3696 
3697 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3698 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3699 			    bufsize - count : 0;
3700 		} else {
3701 			/*
3702 			 * peripheral_qualifier = 0;
3703 			 *
3704 			 * We are dealing only with HD and will be
3705 			 * dealing with CD/DVD devices soon
3706 			 */
3707 			uint8_t peripheral_device_type =
3708 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3709 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3710 
3711 			bzero(page_buf, sizeof (page_buf));
3712 
3713 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3714 			case INQUIRY_SUP_VPD_PAGE:
3715 				/*
3716 				 * Request for supported Vital Product Data
3717 				 * pages.
3718 				 */
3719 				page_buf[0] = peripheral_device_type;
3720 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3721 				page_buf[2] = 0;
3722 				page_buf[3] = 4; /* page length */
3723 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3724 				page_buf[5] = INQUIRY_USN_PAGE;
3725 				page_buf[6] = INQUIRY_BDC_PAGE;
3726 				page_buf[7] = INQUIRY_ATA_INFO_PAGE;
3727 				/* Copy no more than requested */
3728 				count = MIN(bp->b_bcount, 8);
3729 				bcopy(page_buf, bp->b_un.b_addr, count);
3730 				break;
3731 
3732 			case INQUIRY_USN_PAGE:
3733 				/*
3734 				 * Request for Unit Serial Number page.
3735 				 * Set-up the page.
3736 				 */
3737 				page_buf[0] = peripheral_device_type;
3738 				page_buf[1] = INQUIRY_USN_PAGE;
3739 				page_buf[2] = 0;
3740 				/* remaining page length */
3741 				page_buf[3] = SATA_ID_SERIAL_LEN;
3742 
3743 				/*
3744 				 * Copy serial number from Identify Device data
3745 				 * words into the inquiry page and swap bytes
3746 				 * when necessary.
3747 				 */
3748 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3749 #ifdef	_LITTLE_ENDIAN
3750 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3751 #else
3752 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3753 #endif
3754 				/*
3755 				 * Least significant character of the serial
3756 				 * number shall appear as the last byte,
3757 				 * according to SBC-3 spec.
3758 				 * Count trailing spaces to determine the
3759 				 * necessary shift length.
3760 				 */
3761 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3762 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3763 					if (*(p - j) != '\0' &&
3764 					    *(p - j) != '\040')
3765 						break;
3766 				}
3767 
3768 				/*
3769 				 * Shift SN string right, so that the last
3770 				 * non-blank character would appear in last
3771 				 * byte of SN field in the page.
3772 				 * 'j' is the shift length.
3773 				 */
3774 				for (i = 0;
3775 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3776 				    i++, p--)
3777 					*p = *(p - j);
3778 
3779 				/*
3780 				 * Add leading spaces - same number as the
3781 				 * shift size
3782 				 */
3783 				for (; j > 0; j--)
3784 					page_buf[4 + j - 1] = '\040';
3785 
3786 				count = MIN(bp->b_bcount,
3787 				    SATA_ID_SERIAL_LEN + 4);
3788 				bcopy(page_buf, bp->b_un.b_addr, count);
3789 				break;
3790 
3791 			case INQUIRY_BDC_PAGE:
3792 				/*
3793 				 * Request for Block Device Characteristics
3794 				 * page.  Set-up the page.
3795 				 */
3796 				page_buf[0] = peripheral_device_type;
3797 				page_buf[1] = INQUIRY_BDC_PAGE;
3798 				page_buf[2] = 0;
3799 				/* remaining page length */
3800 				page_buf[3] = SATA_ID_BDC_LEN;
3801 
3802 				rate = sdinfo->satadrv_id.ai_medrotrate;
3803 				page_buf[4] = (rate >> 8) & 0xff;
3804 				page_buf[5] = rate & 0xff;
3805 				page_buf[6] = 0;
3806 				page_buf[7] = sdinfo->satadrv_id.
3807 				    ai_nomformfactor & 0xf;
3808 
3809 				count = MIN(bp->b_bcount,
3810 				    SATA_ID_BDC_LEN + 4);
3811 				bcopy(page_buf, bp->b_un.b_addr, count);
3812 				break;
3813 
3814 			case INQUIRY_ATA_INFO_PAGE:
3815 				/*
3816 				 * Request for ATA Information page.
3817 				 */
3818 				page_buf[0] = peripheral_device_type;
3819 				page_buf[1] = INQUIRY_ATA_INFO_PAGE;
3820 				page_buf[2] = (SATA_ID_ATA_INFO_LEN >> 8) &
3821 				    0xff;
3822 				page_buf[3] = SATA_ID_ATA_INFO_LEN & 0xff;
3823 				/* page_buf[4-7] reserved */
3824 #ifdef  _LITTLE_ENDIAN
3825 				bcopy("ATA     ", &page_buf[8], 8);
3826 				swab(sdinfo->satadrv_id.ai_model,
3827 				    &page_buf[16], 16);
3828 				if (strncmp(&sdinfo->satadrv_id.ai_fw[4],
3829 				    "    ", 4) == 0) {
3830 					swab(sdinfo->satadrv_id.ai_fw,
3831 					    &page_buf[32], 4);
3832 				} else {
3833 					swab(&sdinfo->satadrv_id.ai_fw[4],
3834 					    &page_buf[32], 4);
3835 				}
3836 #else   /* _LITTLE_ENDIAN */
3837 				bcopy("ATA     ", &page_buf[8], 8);
3838 				bcopy(sdinfo->satadrv_id.ai_model,
3839 				    &page_buf[16], 16);
3840 				if (strncmp(&sdinfo->satadrv_id.ai_fw[4],
3841 				    "    ", 4) == 0) {
3842 					bcopy(sdinfo->satadrv_id.ai_fw,
3843 					    &page_buf[32], 4);
3844 				} else {
3845 					bcopy(&sdinfo->satadrv_id.ai_fw[4],
3846 					    &page_buf[32], 4);
3847 				}
3848 #endif  /* _LITTLE_ENDIAN */
3849 				/*
3850 				 * page_buf[36-55] which defines the device
3851 				 * signature is not defined at this
3852 				 * time.
3853 				 */
3854 
3855 				/* Set the command code */
3856 				if (sdinfo->satadrv_type ==
3857 				    SATA_DTYPE_ATADISK) {
3858 					page_buf[56] = SATAC_ID_DEVICE;
3859 				} else if (sdinfo->satadrv_type ==
3860 				    SATA_DTYPE_ATAPI) {
3861 					page_buf[56] = SATAC_ID_PACKET_DEVICE;
3862 				}
3863 				/*
3864 				 * If the command code, page_buf[56], is not
3865 				 * zero and if one of the identify commands
3866 				 * succeeds, return the identify data.
3867 				 */
3868 				if ((page_buf[56] != 0) &&
3869 				    (sata_fetch_device_identify_data(
3870 				    spx->txlt_sata_hba_inst, sdinfo) ==
3871 				    SATA_SUCCESS)) {
3872 					bcopy(&sdinfo->satadrv_id,
3873 					    &page_buf[60], sizeof (sata_id_t));
3874 				}
3875 
3876 				/* Need to copy out the page_buf to bp */
3877 				count = MIN(bp->b_bcount,
3878 				    SATA_ID_ATA_INFO_LEN + 4);
3879 				bcopy(page_buf, bp->b_un.b_addr, count);
3880 				break;
3881 
3882 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3883 				/*
3884 				 * We may want to implement this page, when
3885 				 * identifiers are common for SATA devices
3886 				 * But not now.
3887 				 */
3888 				/*FALLTHROUGH*/
3889 
3890 			default:
3891 				/* Request for unsupported VPD page */
3892 				*scsipkt->pkt_scbp = STATUS_CHECK;
3893 				sense = sata_arq_sense(spx);
3894 				sense->es_key = KEY_ILLEGAL_REQUEST;
3895 				sense->es_add_code =
3896 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3897 				goto done;
3898 			}
3899 		}
3900 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3901 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3902 		    scsipkt->pkt_cdbp[4] - count : 0;
3903 	}
3904 done:
3905 	mutex_exit(cport_mutex);
3906 
3907 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3908 	    "Scsi_pkt completion reason %x\n",
3909 	    scsipkt->pkt_reason);
3910 
3911 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3912 	    scsipkt->pkt_comp != NULL) {
3913 		/* scsi callback required */
3914 		if (servicing_interrupt()) {
3915 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3916 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3917 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
3918 			    TASKQID_INVALID) {
3919 				return (TRAN_BUSY);
3920 			}
3921 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3922 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3923 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
3924 			/* Scheduling the callback failed */
3925 			return (TRAN_BUSY);
3926 		}
3927 	}
3928 	return (TRAN_ACCEPT);
3929 }
3930 
3931 /*
3932  * SATA translate command: Request Sense.
3933  *
3934  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3935  * At the moment this is an emulated command (ATA version for SATA hard disks).
3936  * May be translated into Check Power Mode command in the future.
3937  *
3938  * Note: There is a mismatch between already implemented Informational
3939  * Exception Mode Select page 0x1C and this function.
3940  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3941  * NO SENSE and set additional sense code to the exception code - this is not
3942  * implemented here.
3943  */
3944 static int
3945 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3946 {
3947 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3948 	struct scsi_extended_sense sense;
3949 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3950 	sata_drive_info_t *sdinfo;
3951 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3952 	int rval, reason, power_state = 0;
3953 	kmutex_t *cport_mutex;
3954 
3955 	cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
3956 	mutex_enter(cport_mutex);
3957 
3958 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3959 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3960 		mutex_exit(cport_mutex);
3961 		return (rval);
3962 	}
3963 
3964 	scsipkt->pkt_reason = CMD_CMPLT;
3965 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3966 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3967 	*scsipkt->pkt_scbp = STATUS_GOOD;
3968 
3969 	/*
3970 	 * when CONTROL field's NACA bit == 1
3971 	 * return ILLEGAL_REQUEST
3972 	 */
3973 	if (scsipkt->pkt_cdbp[5] & CTL_BYTE_NACA_MASK) {
3974 		mutex_exit(cport_mutex);
3975 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3976 		    SD_SCSI_ASC_CMD_SEQUENCE_ERR));
3977 	}
3978 
3979 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3980 	    &spx->txlt_sata_pkt->satapkt_device);
3981 	ASSERT(sdinfo != NULL);
3982 
3983 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3984 
3985 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3986 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3987 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3988 	if (sata_hba_start(spx, &rval) != 0) {
3989 		mutex_exit(cport_mutex);
3990 		return (rval);
3991 	}
3992 	if (scmd->satacmd_error_reg != 0) {
3993 		mutex_exit(cport_mutex);
3994 		return (sata_txlt_check_condition(spx, KEY_NO_SENSE,
3995 		    SD_SCSI_ASC_NO_ADD_SENSE));
3996 	}
3997 
3998 	switch (scmd->satacmd_sec_count_lsb) {
3999 	case SATA_PWRMODE_STANDBY: /* device in standby mode */
4000 		if (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)
4001 			power_state = SATA_POWER_STOPPED;
4002 		else {
4003 			power_state = SATA_POWER_STANDBY;
4004 			sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4005 		}
4006 		break;
4007 	case SATA_PWRMODE_IDLE: /* device in idle mode */
4008 		power_state = SATA_POWER_IDLE;
4009 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4010 		break;
4011 	case SATA_PWRMODE_ACTIVE: /* device in active or idle mode */
4012 	default:		  /* 0x40, 0x41 active mode */
4013 		if (sdinfo->satadrv_power_level == SATA_POWER_IDLE)
4014 			power_state = SATA_POWER_IDLE;
4015 		else {
4016 			power_state = SATA_POWER_ACTIVE;
4017 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4018 		}
4019 		break;
4020 	}
4021 
4022 	mutex_exit(cport_mutex);
4023 
4024 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4025 		/*
4026 		 * Because it is fully emulated command storing data
4027 		 * programatically in the specified buffer, release
4028 		 * preallocated DMA resources before storing data in the buffer,
4029 		 * so no unwanted DMA sync would take place.
4030 		 */
4031 		int count = MIN(bp->b_bcount,
4032 		    sizeof (struct scsi_extended_sense));
4033 		sata_scsi_dmafree(NULL, scsipkt);
4034 		bzero(&sense, sizeof (struct scsi_extended_sense));
4035 		sense.es_valid = 0;	/* Valid LBA */
4036 		sense.es_class = 7;	/* Response code 0x70 - current err */
4037 		sense.es_key = KEY_NO_SENSE;
4038 		sense.es_add_len = 6;	/* Additional length */
4039 		/* Copy no more than requested */
4040 		bcopy(&sense, bp->b_un.b_addr, count);
4041 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4042 		scsipkt->pkt_resid = 0;
4043 		switch (power_state) {
4044 		case SATA_POWER_IDLE:
4045 		case SATA_POWER_STANDBY:
4046 			sense.es_add_code =
4047 			    SD_SCSI_ASC_LOW_POWER_CONDITION_ON;
4048 			break;
4049 		case SATA_POWER_STOPPED:
4050 			sense.es_add_code = SD_SCSI_ASC_NO_ADD_SENSE;
4051 			break;
4052 		case SATA_POWER_ACTIVE:
4053 		default:
4054 			break;
4055 		}
4056 	}
4057 
4058 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4059 	    "Scsi_pkt completion reason %x\n",
4060 	    scsipkt->pkt_reason);
4061 
4062 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4063 	    scsipkt->pkt_comp != NULL) {
4064 		/* scsi callback required */
4065 		if (servicing_interrupt()) {
4066 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4067 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4068 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
4069 			    TASKQID_INVALID) {
4070 				return (TRAN_BUSY);
4071 			}
4072 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4073 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4074 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
4075 			/* Scheduling the callback failed */
4076 			return (TRAN_BUSY);
4077 		}
4078 	}
4079 	return (TRAN_ACCEPT);
4080 }
4081 
4082 /*
4083  * SATA translate command: Test Unit Ready
4084  * (ATA version for SATA hard disks).
4085  * It is translated into the Check Power Mode command.
4086  *
4087  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4088  */
4089 static int
4090 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
4091 {
4092 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4093 	struct scsi_extended_sense *sense;
4094 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4095 	sata_drive_info_t *sdinfo;
4096 	int power_state;
4097 	int rval, reason;
4098 	kmutex_t *cport_mutex =  &(SATA_TXLT_CPORT_MUTEX(spx));
4099 
4100 	mutex_enter(cport_mutex);
4101 
4102 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4103 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4104 		mutex_exit(cport_mutex);
4105 		return (rval);
4106 	}
4107 
4108 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4109 	    &spx->txlt_sata_pkt->satapkt_device);
4110 	ASSERT(sdinfo != NULL);
4111 
4112 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
4113 
4114 	/* send CHECK POWER MODE command */
4115 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4116 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4117 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4118 	if (sata_hba_start(spx, &rval) != 0) {
4119 		mutex_exit(cport_mutex);
4120 		return (rval);
4121 	}
4122 
4123 	if (scmd->satacmd_error_reg != 0) {
4124 		mutex_exit(cport_mutex);
4125 		return (sata_txlt_check_condition(spx, KEY_NOT_READY,
4126 		    SD_SCSI_ASC_LU_NOT_RESPONSE));
4127 	}
4128 
4129 	power_state = scmd->satacmd_sec_count_lsb;
4130 
4131 	/*
4132 	 * return NOT READY when device in STOPPED mode
4133 	 */
4134 	if (power_state == SATA_PWRMODE_STANDBY &&
4135 	    sdinfo->satadrv_power_level == SATA_POWER_STOPPED) {
4136 		*scsipkt->pkt_scbp = STATUS_CHECK;
4137 		sense = sata_arq_sense(spx);
4138 		sense->es_key = KEY_NOT_READY;
4139 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
4140 	} else {
4141 		/*
4142 		 * For other power mode, return GOOD status
4143 		 */
4144 		*scsipkt->pkt_scbp = STATUS_GOOD;
4145 	}
4146 
4147 	scsipkt->pkt_reason = CMD_CMPLT;
4148 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4149 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4150 
4151 	mutex_exit(cport_mutex);
4152 
4153 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4154 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4155 
4156 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4157 	    scsipkt->pkt_comp != NULL) {
4158 		/* scsi callback required */
4159 		if (servicing_interrupt()) {
4160 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4161 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4162 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
4163 			    TASKQID_INVALID) {
4164 				return (TRAN_BUSY);
4165 			}
4166 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4167 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4168 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
4169 			/* Scheduling the callback failed */
4170 			return (TRAN_BUSY);
4171 		}
4172 	}
4173 
4174 	return (TRAN_ACCEPT);
4175 }
4176 
4177 /*
4178  * SATA translate command: Start Stop Unit
4179  * Translation depends on a command:
4180  *
4181  * Power condition bits will be supported
4182  * and the power level should be maintained by SATL,
4183  * When SATL received a command, it will check the
4184  * power level firstly, and return the status according
4185  * to SAT2 v2.6 and SAT-2 Standby Modifications
4186  *
4187  * SPC-4/SBC-3      SATL    ATA power condition  SATL      SPC/SBC
4188  * -----------------------------------------------------------------------
4189  * SSU_PC1 Active   <==>     ATA  Active         <==>     SSU:start_bit =1
4190  * SSU_PC2 Idle     <==>     ATA  Idle           <==>     N/A
4191  * SSU_PC3 Standby  <==>     ATA  Standby        <==>     N/A
4192  * SSU_PC4 Stopped  <==>     ATA  Standby        <==>     SSU:start_bit = 0
4193  *
4194  *	Unload Media / NOT SUPPORTED YET
4195  *	Load Media / NOT SUPPROTED YET
4196  *	Immediate bit / NOT SUPPORTED YET (deferred error)
4197  *
4198  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4199  * appropriate values in scsi_pkt fields.
4200  */
4201 static int
4202 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
4203 {
4204 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4205 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4206 	int rval, reason;
4207 	sata_drive_info_t *sdinfo;
4208 	sata_id_t *sata_id;
4209 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
4210 
4211 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4212 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
4213 
4214 	mutex_enter(cport_mutex);
4215 
4216 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4217 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4218 		mutex_exit(cport_mutex);
4219 		return (rval);
4220 	}
4221 
4222 	if (scsipkt->pkt_cdbp[1] & START_STOP_IMMED_MASK) {
4223 		/* IMMED bit - not supported */
4224 		mutex_exit(cport_mutex);
4225 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4226 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4227 	}
4228 
4229 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
4230 	spx->txlt_sata_pkt->satapkt_comp = NULL;
4231 
4232 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4233 	    &spx->txlt_sata_pkt->satapkt_device);
4234 	ASSERT(sdinfo != NULL);
4235 	sata_id = &sdinfo->satadrv_id;
4236 
4237 	switch ((scsipkt->pkt_cdbp[4] & START_STOP_POWER_COND_MASK) >> 4) {
4238 	case 0:
4239 		if (scsipkt->pkt_cdbp[4] & START_STOP_LOEJ_MASK) {
4240 			/* Load/Unload Media - invalid request */
4241 			goto err_out;
4242 		}
4243 		if (scsipkt->pkt_cdbp[4] & START_STOP_START_MASK) {
4244 			/* Start Unit */
4245 			sata_build_read_verify_cmd(scmd, 1, 5);
4246 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4247 			/* Transfer command to HBA */
4248 			if (sata_hba_start(spx, &rval) != 0) {
4249 				/* Pkt not accepted for execution */
4250 				mutex_exit(cport_mutex);
4251 				return (rval);
4252 			}
4253 			if (scmd->satacmd_error_reg != 0) {
4254 				goto err_out;
4255 			}
4256 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4257 		} else {
4258 			/* Stop Unit */
4259 			sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4260 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4261 			if (sata_hba_start(spx, &rval) != 0) {
4262 				mutex_exit(cport_mutex);
4263 				return (rval);
4264 			} else {
4265 				if (scmd->satacmd_error_reg != 0) {
4266 					goto err_out;
4267 				}
4268 			}
4269 			/* ata standby immediate command */
4270 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4271 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4272 			if (sata_hba_start(spx, &rval) != 0) {
4273 				mutex_exit(cport_mutex);
4274 				return (rval);
4275 			}
4276 			if (scmd->satacmd_error_reg != 0) {
4277 				goto err_out;
4278 			}
4279 			sdinfo->satadrv_power_level = SATA_POWER_STOPPED;
4280 		}
4281 		break;
4282 	case 0x1:
4283 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4284 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4285 		if (sata_hba_start(spx, &rval) != 0) {
4286 			mutex_exit(cport_mutex);
4287 			return (rval);
4288 		}
4289 		if (scmd->satacmd_error_reg != 0) {
4290 			goto err_out;
4291 		}
4292 		sata_build_read_verify_cmd(scmd, 1, 5);
4293 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4294 		/* Transfer command to HBA */
4295 		if (sata_hba_start(spx, &rval) != 0) {
4296 			/* Pkt not accepted for execution */
4297 			mutex_exit(cport_mutex);
4298 			return (rval);
4299 		} else {
4300 			if (scmd->satacmd_error_reg != 0) {
4301 				goto err_out;
4302 			}
4303 		}
4304 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4305 		break;
4306 	case 0x2:
4307 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4308 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4309 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4310 			if (sata_hba_start(spx, &rval) != 0) {
4311 				mutex_exit(cport_mutex);
4312 				return (rval);
4313 			}
4314 			if (scmd->satacmd_error_reg != 0) {
4315 				goto err_out;
4316 			}
4317 		}
4318 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4319 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4320 		if (sata_hba_start(spx, &rval) != 0) {
4321 			mutex_exit(cport_mutex);
4322 			return (rval);
4323 		}
4324 		if (scmd->satacmd_error_reg != 0) {
4325 			goto err_out;
4326 		}
4327 		if ((scsipkt->pkt_cdbp[3] & START_STOP_MODIFIER_MASK)) {
4328 			/*
4329 			 *  POWER CONDITION MODIFIER bit set
4330 			 *  to 0x1 or larger it will be handled
4331 			 *  on the same way as bit = 0x1
4332 			 */
4333 			if (!(sata_id->ai_cmdset84 &
4334 			    SATA_IDLE_UNLOAD_SUPPORTED)) {
4335 				sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4336 				break;
4337 			}
4338 			sata_build_generic_cmd(scmd, SATAC_IDLE_IM);
4339 			scmd->satacmd_features_reg = 0x44;
4340 			scmd->satacmd_lba_low_lsb = 0x4c;
4341 			scmd->satacmd_lba_mid_lsb = 0x4e;
4342 			scmd->satacmd_lba_high_lsb = 0x55;
4343 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4344 			if (sata_hba_start(spx, &rval) != 0) {
4345 				mutex_exit(cport_mutex);
4346 				return (rval);
4347 			}
4348 			if (scmd->satacmd_error_reg != 0) {
4349 				goto err_out;
4350 			}
4351 		}
4352 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4353 		break;
4354 	case 0x3:
4355 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4356 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4357 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4358 			if (sata_hba_start(spx, &rval) != 0) {
4359 				mutex_exit(cport_mutex);
4360 				return (rval);
4361 			}
4362 			if (scmd->satacmd_error_reg != 0) {
4363 				goto err_out;
4364 			}
4365 		}
4366 		sata_build_generic_cmd(scmd, SATAC_STANDBY);
4367 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4368 		if (sata_hba_start(spx, &rval) != 0) {
4369 			mutex_exit(cport_mutex);
4370 			return (rval);
4371 		}
4372 		if (scmd->satacmd_error_reg != 0) {
4373 			goto err_out;
4374 		}
4375 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4376 		break;
4377 	case 0x7:
4378 		sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4379 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4380 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4381 		if (sata_hba_start(spx, &rval) != 0) {
4382 			mutex_exit(cport_mutex);
4383 			return (rval);
4384 		}
4385 		if (scmd->satacmd_error_reg != 0) {
4386 			goto err_out;
4387 		}
4388 		switch (scmd->satacmd_sec_count_lsb) {
4389 		case SATA_PWRMODE_STANDBY:
4390 			sata_build_generic_cmd(scmd, SATAC_STANDBY);
4391 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4392 			    sdinfo->satadrv_standby_timer);
4393 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4394 			if (sata_hba_start(spx, &rval) != 0) {
4395 				mutex_exit(cport_mutex);
4396 				return (rval);
4397 			} else {
4398 				if (scmd->satacmd_error_reg != 0) {
4399 					goto err_out;
4400 				}
4401 			}
4402 			break;
4403 		case SATA_PWRMODE_IDLE:
4404 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4405 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4406 			    sdinfo->satadrv_standby_timer);
4407 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4408 			if (sata_hba_start(spx, &rval) != 0) {
4409 				mutex_exit(cport_mutex);
4410 				return (rval);
4411 			} else {
4412 				if (scmd->satacmd_error_reg != 0) {
4413 					goto err_out;
4414 				}
4415 			}
4416 			break;
4417 		case SATA_PWRMODE_ACTIVE_SPINDOWN:
4418 		case SATA_PWRMODE_ACTIVE_SPINUP:
4419 		case SATA_PWRMODE_ACTIVE:
4420 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4421 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4422 			    sdinfo->satadrv_standby_timer);
4423 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4424 			if (sata_hba_start(spx, &rval) != 0) {
4425 				mutex_exit(cport_mutex);
4426 				return (rval);
4427 			}
4428 			if (scmd->satacmd_error_reg != 0) {
4429 				goto err_out;
4430 			}
4431 			sata_build_read_verify_cmd(scmd, 1, 5);
4432 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4433 			if (sata_hba_start(spx, &rval) != 0) {
4434 				mutex_exit(cport_mutex);
4435 				return (rval);
4436 			}
4437 			if (scmd->satacmd_error_reg != 0) {
4438 				goto err_out;
4439 			}
4440 			break;
4441 		default:
4442 			goto err_out;
4443 		}
4444 		break;
4445 	case 0xb:
4446 		if ((sata_get_standby_timer(sdinfo->satadrv_standby_timer) ==
4447 		    0) || (!(sata_id->ai_cap & SATA_STANDBYTIMER))) {
4448 			mutex_exit(cport_mutex);
4449 			return (sata_txlt_check_condition(spx,
4450 			    KEY_ILLEGAL_REQUEST,
4451 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4452 		}
4453 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4454 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4455 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4456 			if (sata_hba_start(spx, &rval) != 0) {
4457 				mutex_exit(cport_mutex);
4458 				return (rval);
4459 			}
4460 			if (scmd->satacmd_error_reg != 0) {
4461 				goto err_out;
4462 			}
4463 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4464 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4465 			if (sata_hba_start(spx, &rval) != 0) {
4466 				mutex_exit(cport_mutex);
4467 				return (rval);
4468 			}
4469 			if (scmd->satacmd_error_reg != 0) {
4470 				goto err_out;
4471 			}
4472 		}
4473 		bzero(sdinfo->satadrv_standby_timer, sizeof (uchar_t) * 4);
4474 		break;
4475 	default:
4476 err_out:
4477 		mutex_exit(cport_mutex);
4478 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4479 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4480 	}
4481 
4482 	/*
4483 	 * Since it was a synchronous command,
4484 	 * a callback function will be called directly.
4485 	 */
4486 	mutex_exit(cport_mutex);
4487 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4488 	    "synchronous execution status %x\n",
4489 	    spx->txlt_sata_pkt->satapkt_reason);
4490 
4491 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4492 	    scsipkt->pkt_comp != NULL) {
4493 		sata_set_arq_data(spx->txlt_sata_pkt);
4494 		if (servicing_interrupt()) {
4495 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4496 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4497 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
4498 			    TASKQID_INVALID) {
4499 				return (TRAN_BUSY);
4500 			}
4501 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4502 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4503 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
4504 			/* Scheduling the callback failed */
4505 			return (TRAN_BUSY);
4506 		}
4507 	}
4508 	else
4509 
4510 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
4511 
4512 	return (TRAN_ACCEPT);
4513 
4514 }
4515 
4516 /*
4517  * SATA translate command:  Read Capacity.
4518  * Emulated command for SATA disks.
4519  * Capacity is retrieved from cached Idenifty Device data.
4520  * Identify Device data shows effective disk capacity, not the native
4521  * capacity, which may be limitted by Set Max Address command.
4522  * This is ATA version for SATA hard disks.
4523  *
4524  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4525  */
4526 static int
4527 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
4528 {
4529 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4530 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4531 	sata_drive_info_t *sdinfo;
4532 	uint64_t val;
4533 	uint32_t lbsize = DEV_BSIZE;
4534 	uchar_t *rbuf;
4535 	int rval, reason;
4536 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
4537 
4538 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4539 	    "sata_txlt_read_capacity: ", NULL);
4540 
4541 	mutex_enter(cport_mutex);
4542 
4543 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4544 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4545 		mutex_exit(cport_mutex);
4546 		return (rval);
4547 	}
4548 
4549 	scsipkt->pkt_reason = CMD_CMPLT;
4550 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4551 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4552 	*scsipkt->pkt_scbp = STATUS_GOOD;
4553 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4554 		/*
4555 		 * Because it is fully emulated command storing data
4556 		 * programatically in the specified buffer, release
4557 		 * preallocated DMA resources before storing data in the buffer,
4558 		 * so no unwanted DMA sync would take place.
4559 		 */
4560 		sata_scsi_dmafree(NULL, scsipkt);
4561 
4562 		sdinfo = sata_get_device_info(
4563 		    spx->txlt_sata_hba_inst,
4564 		    &spx->txlt_sata_pkt->satapkt_device);
4565 
4566 		/*
4567 		 * As per SBC-3, the "returned LBA" is either the highest
4568 		 * addressable LBA or 0xffffffff, whichever is smaller.
4569 		 */
4570 		val = MIN(sdinfo->satadrv_capacity - 1, UINT32_MAX);
4571 
4572 		if (sdinfo->satadrv_id.ai_phys_sect_sz & SATA_L2PS_CHECK_BIT) {
4573 			/* physical/logical sector size word is valid */
4574 
4575 			if (sdinfo->satadrv_id.ai_phys_sect_sz &
4576 			    SATA_L2PS_BIG_SECTORS) {
4577 				/* if this set 117-118 words are valid */
4578 				lbsize = sdinfo->satadrv_id.ai_words_lsec[0] |
4579 				    (sdinfo->satadrv_id.ai_words_lsec[1] << 16);
4580 				lbsize <<= 1; /* convert from words to bytes */
4581 			}
4582 		}
4583 		rbuf = (uchar_t *)bp->b_un.b_addr;
4584 		/* Need to swap endians to match scsi format */
4585 		rbuf[0] = (val >> 24) & 0xff;
4586 		rbuf[1] = (val >> 16) & 0xff;
4587 		rbuf[2] = (val >> 8) & 0xff;
4588 		rbuf[3] = val & 0xff;
4589 		rbuf[4] = (lbsize >> 24) & 0xff;
4590 		rbuf[5] = (lbsize >> 16) & 0xff;
4591 		rbuf[6] = (lbsize >> 8) & 0xff;
4592 		rbuf[7] = lbsize & 0xff;
4593 
4594 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4595 		scsipkt->pkt_resid = 0;
4596 
4597 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
4598 		    sdinfo->satadrv_capacity -1);
4599 	}
4600 	mutex_exit(cport_mutex);
4601 	/*
4602 	 * If a callback was requested, do it now.
4603 	 */
4604 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4605 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4606 
4607 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4608 	    scsipkt->pkt_comp != NULL) {
4609 		/* scsi callback required */
4610 		if (servicing_interrupt()) {
4611 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4612 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4613 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
4614 			    TASKQID_INVALID) {
4615 				return (TRAN_BUSY);
4616 			}
4617 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4618 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4619 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
4620 			/* Scheduling the callback failed */
4621 			return (TRAN_BUSY);
4622 		}
4623 	}
4624 
4625 	return (TRAN_ACCEPT);
4626 }
4627 
4628 /*
4629  * SATA translate command:  Read Capacity (16).
4630  * Emulated command for SATA disks.
4631  * Info is retrieved from cached Identify Device data.
4632  * Implemented to SBC-3 (draft 21) and SAT-2 (final) specifications.
4633  *
4634  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4635  */
4636 static int
4637 sata_txlt_read_capacity16(sata_pkt_txlate_t *spx)
4638 {
4639 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4640 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4641 	sata_drive_info_t *sdinfo;
4642 	uint64_t val;
4643 	uint16_t l2p_exp;
4644 	uint32_t lbsize = DEV_BSIZE;
4645 	uchar_t *rbuf;
4646 	int rval, reason;
4647 #define	TPE	0x80
4648 #define	TPRZ	0x40
4649 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
4650 
4651 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4652 	    "sata_txlt_read_capacity: ", NULL);
4653 
4654 	mutex_enter(cport_mutex);
4655 
4656 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4657 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4658 		mutex_exit(cport_mutex);
4659 		return (rval);
4660 	}
4661 
4662 	scsipkt->pkt_reason = CMD_CMPLT;
4663 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4664 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4665 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4666 		/*
4667 		 * Because it is fully emulated command storing data
4668 		 * programatically in the specified buffer, release
4669 		 * preallocated DMA resources before storing data in the buffer,
4670 		 * so no unwanted DMA sync would take place.
4671 		 */
4672 		sata_scsi_dmafree(NULL, scsipkt);
4673 
4674 		/* Check SERVICE ACTION field */
4675 		if ((scsipkt->pkt_cdbp[1] & 0x1f) !=
4676 		    SSVC_ACTION_READ_CAPACITY_G4) {
4677 			mutex_exit(cport_mutex);
4678 			return (sata_txlt_check_condition(spx,
4679 			    KEY_ILLEGAL_REQUEST,
4680 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4681 		}
4682 
4683 		/* Check LBA field */
4684 		if ((scsipkt->pkt_cdbp[2] != 0) ||
4685 		    (scsipkt->pkt_cdbp[3] != 0) ||
4686 		    (scsipkt->pkt_cdbp[4] != 0) ||
4687 		    (scsipkt->pkt_cdbp[5] != 0) ||
4688 		    (scsipkt->pkt_cdbp[6] != 0) ||
4689 		    (scsipkt->pkt_cdbp[7] != 0) ||
4690 		    (scsipkt->pkt_cdbp[8] != 0) ||
4691 		    (scsipkt->pkt_cdbp[9] != 0)) {
4692 			mutex_exit(cport_mutex);
4693 			return (sata_txlt_check_condition(spx,
4694 			    KEY_ILLEGAL_REQUEST,
4695 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4696 		}
4697 
4698 		/* Check PMI bit */
4699 		if (scsipkt->pkt_cdbp[14] & 0x1) {
4700 			mutex_exit(cport_mutex);
4701 			return (sata_txlt_check_condition(spx,
4702 			    KEY_ILLEGAL_REQUEST,
4703 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4704 		}
4705 
4706 		*scsipkt->pkt_scbp = STATUS_GOOD;
4707 
4708 		sdinfo = sata_get_device_info(
4709 		    spx->txlt_sata_hba_inst,
4710 		    &spx->txlt_sata_pkt->satapkt_device);
4711 
4712 		/* last logical block address */
4713 		val = MIN(sdinfo->satadrv_capacity - 1,
4714 		    SCSI_READ_CAPACITY16_MAX_LBA);
4715 
4716 		/* logical to physical block size exponent */
4717 		l2p_exp = 0;
4718 		if (sdinfo->satadrv_id.ai_phys_sect_sz & SATA_L2PS_CHECK_BIT) {
4719 			/* physical/logical sector size word is valid */
4720 
4721 			if (sdinfo->satadrv_id.ai_phys_sect_sz &
4722 			    SATA_L2PS_HAS_MULT) {
4723 				/* multiple logical sectors per phys sectors */
4724 				l2p_exp =
4725 				    sdinfo->satadrv_id.ai_phys_sect_sz &
4726 				    SATA_L2PS_EXP_MASK;
4727 			}
4728 
4729 			if (sdinfo->satadrv_id.ai_phys_sect_sz &
4730 			    SATA_L2PS_BIG_SECTORS) {
4731 				/* if this set 117-118 words are valid */
4732 				lbsize = sdinfo->satadrv_id.ai_words_lsec[0] |
4733 				    (sdinfo->satadrv_id.ai_words_lsec[1] << 16);
4734 				lbsize <<= 1; /* convert from words to bytes */
4735 			}
4736 		}
4737 
4738 		rbuf = (uchar_t *)bp->b_un.b_addr;
4739 		bzero(rbuf, bp->b_bcount);
4740 
4741 		/* returned logical block address */
4742 		rbuf[0] = (val >> 56) & 0xff;
4743 		rbuf[1] = (val >> 48) & 0xff;
4744 		rbuf[2] = (val >> 40) & 0xff;
4745 		rbuf[3] = (val >> 32) & 0xff;
4746 		rbuf[4] = (val >> 24) & 0xff;
4747 		rbuf[5] = (val >> 16) & 0xff;
4748 		rbuf[6] = (val >> 8) & 0xff;
4749 		rbuf[7] = val & 0xff;
4750 		rbuf[8] = (lbsize >> 24) & 0xff;
4751 		rbuf[9] = (lbsize >> 16) & 0xff;
4752 		rbuf[10] = (lbsize >> 8) & 0xff;
4753 		rbuf[11] = lbsize & 0xff;
4754 
4755 		/* p_type, prot_en, unspecified by SAT-2 */
4756 		/* rbuf[12] = 0; */
4757 
4758 		/* p_i_exponent, undefined by SAT-2 */
4759 		/* logical blocks per physical block exponent */
4760 		rbuf[13] = l2p_exp;
4761 
4762 		/* lowest aligned logical block address = 0 (for now) */
4763 		/* tpe and tprz as defined in T10/10-079 r0 */
4764 		if (sdinfo->satadrv_id.ai_addsupported &
4765 		    SATA_DETERMINISTIC_READ) {
4766 			if (sdinfo->satadrv_id.ai_addsupported &
4767 			    SATA_READ_ZERO) {
4768 				rbuf[14] |= TPRZ;
4769 			} else {
4770 				rbuf[14] |= TPE;
4771 			}
4772 		}
4773 		/* rbuf[15] = 0; */
4774 
4775 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4776 		scsipkt->pkt_resid = 0;
4777 
4778 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%llu\n",
4779 		    sdinfo->satadrv_capacity -1);
4780 	}
4781 
4782 	mutex_exit(cport_mutex);
4783 
4784 	/*
4785 	 * If a callback was requested, do it now.
4786 	 */
4787 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4788 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4789 
4790 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4791 	    scsipkt->pkt_comp != NULL) {
4792 		/* scsi callback required */
4793 		if (servicing_interrupt()) {
4794 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4795 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4796 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
4797 			    TASKQID_INVALID) {
4798 				return (TRAN_BUSY);
4799 			}
4800 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4801 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4802 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
4803 			/* Scheduling the callback failed */
4804 			return (TRAN_BUSY);
4805 		}
4806 	}
4807 
4808 	return (TRAN_ACCEPT);
4809 }
4810 
4811 /*
4812  * Translate command: UNMAP
4813  *
4814  * The function cannot be called in interrupt context since it may sleep.
4815  */
4816 static int
4817 sata_txlt_unmap(sata_pkt_txlate_t *spx)
4818 {
4819 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4820 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4821 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4822 	uint16_t count = 0;
4823 	int synch;
4824 	int rval, reason;
4825 	int i, x;
4826 	int bdlen = 0;
4827 	int ranges = 0;
4828 	int paramlen = 8;
4829 	uint8_t *data, *tmpbd;
4830 	sata_drive_info_t *sdinfo;
4831 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
4832 #define	TRIM	0x1
4833 
4834 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4835 	    "sata_txlt_unmap: ", NULL);
4836 
4837 	mutex_enter(cport_mutex);
4838 
4839 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4840 	    &spx->txlt_sata_pkt->satapkt_device);
4841 	if (sdinfo != NULL) {
4842 		SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4843 		    "DSM support 0x%x, max number of 512 byte blocks of LBA "
4844 		    "range entries 0x%x\n", sdinfo->satadrv_id.ai_dsm,
4845 		    sdinfo->satadrv_id.ai_maxcount);
4846 	}
4847 
4848 	rval = sata_txlt_generic_pkt_info(spx, &reason, 1);
4849 	if ((rval != TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4850 		mutex_exit(cport_mutex);
4851 		return (rval);
4852 	}
4853 
4854 	/*
4855 	 * Need to modify bp to have TRIM data instead of UNMAP data.
4856 	 * Start by getting the block descriptor data length by subtracting
4857 	 * the 8 byte parameter list header from the parameter list length.
4858 	 * The block descriptor size has to be a multiple of 16 bytes.
4859 	 */
4860 	bdlen = scsipkt->pkt_cdbp[7];
4861 	bdlen = (bdlen << 8) + scsipkt->pkt_cdbp[8] - paramlen;
4862 	if ((bdlen < 0) || ((bdlen % 16) != 0) ||
4863 	    ((bp != NULL) && (bdlen > (bp->b_bcount - paramlen)))) {
4864 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4865 		    "sata_txlt_unmap: invalid block descriptor length", NULL);
4866 		mutex_exit(cport_mutex);
4867 		return ((sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4868 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB)));
4869 	}
4870 	/*
4871 	 * If there are no parameter data or block descriptors, it is not
4872 	 * considered an error so just complete the command without sending
4873 	 * TRIM.
4874 	 */
4875 	if ((bdlen == 0) || (bp == NULL) || (bp->b_un.b_addr == NULL) ||
4876 	    (bp->b_bcount == 0)) {
4877 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4878 		    "sata_txlt_unmap: no parameter data or block descriptors",
4879 		    NULL);
4880 		mutex_exit(cport_mutex);
4881 		return (sata_txlt_unmap_nodata_cmd(spx));
4882 	}
4883 	tmpbd = (uint8_t *)bp->b_un.b_addr + paramlen;
4884 	data = kmem_zalloc(bdlen, KM_SLEEP);
4885 
4886 	/*
4887 	 * Loop through all the UNMAP block descriptors and convert the data
4888 	 * into TRIM format.
4889 	 */
4890 	for (i = 0, x = 0; i < bdlen; i += 16, x += 8) {
4891 		/* get range length */
4892 		data[x] = tmpbd[i+7];
4893 		data[x+1] = tmpbd[i+6];
4894 		/* get LBA */
4895 		data[x+2] = tmpbd[i+5];
4896 		data[x+3] = tmpbd[i+4];
4897 		data[x+4] = tmpbd[i+3];
4898 		data[x+5] = tmpbd[i+2];
4899 		data[x+6] = tmpbd[i+11];
4900 		data[x+7] = tmpbd[i+10];
4901 
4902 		ranges++;
4903 	}
4904 
4905 	/*
4906 	 * The TRIM command expects the data buffer to be a multiple of
4907 	 * 512-byte blocks of range entries.  This means that the UNMAP buffer
4908 	 * may be too small.  Free the original DMA resources and create a
4909 	 * local buffer.
4910 	 */
4911 	sata_common_free_dma_rsrcs(spx);
4912 
4913 	/*
4914 	 * Get count of 512-byte blocks of range entries.  The length
4915 	 * of a range entry is 8 bytes which means one count has 64 range
4916 	 * entries.
4917 	 */
4918 	count = (ranges + 63)/64;
4919 
4920 	/* Allocate a buffer that is a multiple of 512 bytes. */
4921 	mutex_exit(cport_mutex);
4922 	bp = sata_alloc_local_buffer(spx, count * 512);
4923 	if (bp == NULL) {
4924 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
4925 		    "sata_txlt_unmap: "
4926 		    "cannot allocate buffer for TRIM command", NULL);
4927 		kmem_free(data, bdlen);
4928 		return (TRAN_BUSY);
4929 	}
4930 	bp_mapin(bp); /* make data buffer accessible */
4931 	mutex_enter(cport_mutex);
4932 
4933 	bzero(bp->b_un.b_addr, bp->b_bcount);
4934 	bcopy(data, bp->b_un.b_addr, x);
4935 	kmem_free(data, bdlen);
4936 	rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
4937 	    DDI_DMA_SYNC_FORDEV);
4938 	ASSERT(rval == DDI_SUCCESS);
4939 
4940 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
4941 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
4942 	scmd->satacmd_cmd_reg = SATAC_DSM;
4943 	scmd->satacmd_sec_count_msb = (count >> 8) & 0xff;
4944 	scmd->satacmd_sec_count_lsb = count & 0xff;
4945 	scmd->satacmd_features_reg = TRIM;
4946 	scmd->satacmd_device_reg = SATA_ADH_LBA;
4947 	scmd->satacmd_status_reg = 0;
4948 	scmd->satacmd_error_reg = 0;
4949 
4950 	/* Start processing command */
4951 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
4952 		spx->txlt_sata_pkt->satapkt_comp =
4953 		    sata_txlt_unmap_completion;
4954 		synch = FALSE;
4955 	} else {
4956 		synch = TRUE;
4957 	}
4958 
4959 	if (sata_hba_start(spx, &rval) != 0) {
4960 		mutex_exit(cport_mutex);
4961 		return (rval);
4962 	}
4963 
4964 	mutex_exit(cport_mutex);
4965 
4966 	if (synch) {
4967 		sata_txlt_unmap_completion(spx->txlt_sata_pkt);
4968 	}
4969 
4970 	return (TRAN_ACCEPT);
4971 }
4972 
4973 /*
4974  * SATA translate command: Mode Sense.
4975  * Translated into appropriate SATA command or emulated.
4976  * Saved Values Page Control (03) are not supported.
4977  *
4978  * NOTE: only caching mode sense page is currently implemented.
4979  *
4980  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4981  */
4982 
4983 #define	LLBAA	0x10	/* Long LBA Accepted */
4984 
4985 static int
4986 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4987 {
4988 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4989 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4990 	sata_drive_info_t *sdinfo;
4991 	sata_id_t *sata_id;
4992 	struct scsi_extended_sense *sense;
4993 	int		len, bdlen, count, alc_len;
4994 	int		pc;	/* Page Control code */
4995 	uint8_t		*buf;	/* mode sense buffer */
4996 	int		rval, reason;
4997 	kmutex_t	*cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
4998 
4999 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5000 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
5001 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5002 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5003 
5004 	if (servicing_interrupt()) {
5005 		buf = kmem_zalloc(1024, KM_NOSLEEP);
5006 		if (buf == NULL) {
5007 			return (TRAN_BUSY);
5008 		}
5009 	} else {
5010 		buf = kmem_zalloc(1024, KM_SLEEP);
5011 	}
5012 
5013 	mutex_enter(cport_mutex);
5014 
5015 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
5016 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5017 		mutex_exit(cport_mutex);
5018 		kmem_free(buf, 1024);
5019 		return (rval);
5020 	}
5021 
5022 	scsipkt->pkt_reason = CMD_CMPLT;
5023 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5024 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5025 
5026 	pc = scsipkt->pkt_cdbp[2] >> 6;
5027 
5028 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
5029 		/*
5030 		 * Because it is fully emulated command storing data
5031 		 * programatically in the specified buffer, release
5032 		 * preallocated DMA resources before storing data in the buffer,
5033 		 * so no unwanted DMA sync would take place.
5034 		 */
5035 		sata_scsi_dmafree(NULL, scsipkt);
5036 
5037 		len = 0;
5038 		bdlen = 0;
5039 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
5040 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
5041 			    (scsipkt->pkt_cdbp[1] & LLBAA))
5042 				bdlen = 16;
5043 			else
5044 				bdlen = 8;
5045 		}
5046 		/* Build mode parameter header */
5047 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
5048 			/* 4-byte mode parameter header */
5049 			buf[len++] = 0;		/* mode data length */
5050 			buf[len++] = 0;		/* medium type */
5051 			buf[len++] = 0;		/* dev-specific param */
5052 			buf[len++] = bdlen;	/* Block Descriptor length */
5053 		} else {
5054 			/* 8-byte mode parameter header */
5055 			buf[len++] = 0;		/* mode data length */
5056 			buf[len++] = 0;
5057 			buf[len++] = 0;		/* medium type */
5058 			buf[len++] = 0;		/* dev-specific param */
5059 			if (bdlen == 16)
5060 				buf[len++] = 1;	/* long lba descriptor */
5061 			else
5062 				buf[len++] = 0;
5063 			buf[len++] = 0;
5064 			buf[len++] = 0;		/* Block Descriptor length */
5065 			buf[len++] = bdlen;
5066 		}
5067 
5068 		sdinfo = sata_get_device_info(
5069 		    spx->txlt_sata_hba_inst,
5070 		    &spx->txlt_sata_pkt->satapkt_device);
5071 
5072 		/* Build block descriptor only if not disabled (DBD) */
5073 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
5074 			/* Block descriptor - direct-access device format */
5075 			if (bdlen == 8) {
5076 				/* build regular block descriptor */
5077 				buf[len++] =
5078 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
5079 				buf[len++] =
5080 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
5081 				buf[len++] =
5082 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
5083 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
5084 				buf[len++] = 0; /* density code */
5085 				buf[len++] = 0;
5086 				if (sdinfo->satadrv_type ==
5087 				    SATA_DTYPE_ATADISK)
5088 					buf[len++] = 2;
5089 				else
5090 					/* ATAPI */
5091 					buf[len++] = 8;
5092 				buf[len++] = 0;
5093 			} else if (bdlen == 16) {
5094 				/* Long LBA Accepted */
5095 				/* build long lba block descriptor */
5096 #ifndef __lock_lint
5097 				buf[len++] =
5098 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
5099 				buf[len++] =
5100 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
5101 				buf[len++] =
5102 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
5103 				buf[len++] =
5104 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
5105 #endif
5106 				buf[len++] =
5107 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
5108 				buf[len++] =
5109 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
5110 				buf[len++] =
5111 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
5112 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
5113 				buf[len++] = 0;
5114 				buf[len++] = 0; /* density code */
5115 				buf[len++] = 0;
5116 				buf[len++] = 0;
5117 				if (sdinfo->satadrv_type ==
5118 				    SATA_DTYPE_ATADISK)
5119 					buf[len++] = 2;
5120 				else
5121 					/* ATAPI */
5122 					buf[len++] = 8;
5123 				buf[len++] = 0;
5124 			}
5125 		}
5126 
5127 		sata_id = &sdinfo->satadrv_id;
5128 
5129 		/*
5130 		 * Add requested pages.
5131 		 * Page 3 and 4 are obsolete and we are not supporting them.
5132 		 * We deal now with:
5133 		 * caching (read/write cache control).
5134 		 * We should eventually deal with following mode pages:
5135 		 * error recovery  (0x01),
5136 		 * power condition (0x1a),
5137 		 * exception control page (enables SMART) (0x1c),
5138 		 * enclosure management (ses),
5139 		 * protocol-specific port mode (port control).
5140 		 */
5141 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
5142 		case MODEPAGE_RW_ERRRECOV:
5143 			/* DAD_MODE_ERR_RECOV */
5144 			/* R/W recovery */
5145 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
5146 			break;
5147 		case MODEPAGE_CACHING:
5148 			/* DAD_MODE_CACHE */
5149 			/* Reject not supported request for saved parameters */
5150 			if (pc == 3) {
5151 				*scsipkt->pkt_scbp = STATUS_CHECK;
5152 				sense = sata_arq_sense(spx);
5153 				sense->es_key = KEY_ILLEGAL_REQUEST;
5154 				sense->es_add_code =
5155 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
5156 				goto done;
5157 			}
5158 
5159 			/* caching */
5160 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
5161 			break;
5162 		case MODEPAGE_INFO_EXCPT:
5163 			/* exception cntrl */
5164 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
5165 				len += sata_build_msense_page_1c(sdinfo, pc,
5166 				    buf+len);
5167 			}
5168 			else
5169 				goto err;
5170 			break;
5171 		case MODEPAGE_POWER_COND:
5172 			/* DAD_MODE_POWER_COND */
5173 			/* power condition */
5174 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
5175 			break;
5176 
5177 		case MODEPAGE_ACOUSTIC_MANAG:
5178 			/* acoustic management */
5179 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
5180 			break;
5181 		case MODEPAGE_ALLPAGES:
5182 			/* all pages */
5183 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
5184 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
5185 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
5186 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
5187 				len += sata_build_msense_page_1c(sdinfo, pc,
5188 				    buf+len);
5189 			}
5190 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
5191 			break;
5192 		default:
5193 		err:
5194 			/* Invalid request */
5195 			*scsipkt->pkt_scbp = STATUS_CHECK;
5196 			sense = sata_arq_sense(spx);
5197 			sense->es_key = KEY_ILLEGAL_REQUEST;
5198 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5199 			goto done;
5200 		}
5201 
5202 		/* fix total mode data length */
5203 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
5204 			/* 4-byte mode parameter header */
5205 			buf[0] = len - 1;	/* mode data length */
5206 		} else {
5207 			buf[0] = (len -2) >> 8;
5208 			buf[1] = (len -2) & 0xff;
5209 		}
5210 
5211 
5212 		/* Check allocation length */
5213 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
5214 			alc_len = scsipkt->pkt_cdbp[4];
5215 		} else {
5216 			alc_len = scsipkt->pkt_cdbp[7];
5217 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
5218 		}
5219 		/*
5220 		 * We do not check for possible parameters truncation
5221 		 * (alc_len < len) assuming that the target driver works
5222 		 * correctly. Just avoiding overrun.
5223 		 * Copy no more than requested and possible, buffer-wise.
5224 		 */
5225 		count = MIN(alc_len, len);
5226 		count = MIN(bp->b_bcount, count);
5227 		bcopy(buf, bp->b_un.b_addr, count);
5228 
5229 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5230 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
5231 	}
5232 	*scsipkt->pkt_scbp = STATUS_GOOD;
5233 done:
5234 	mutex_exit(cport_mutex);
5235 	(void) kmem_free(buf, 1024);
5236 
5237 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5238 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5239 
5240 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5241 	    scsipkt->pkt_comp != NULL) {
5242 		/* scsi callback required */
5243 		if (servicing_interrupt()) {
5244 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5245 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5246 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
5247 			    TASKQID_INVALID) {
5248 				return (TRAN_BUSY);
5249 			}
5250 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5251 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5252 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
5253 			/* Scheduling the callback failed */
5254 			return (TRAN_BUSY);
5255 		}
5256 	}
5257 
5258 	return (TRAN_ACCEPT);
5259 }
5260 
5261 
5262 /*
5263  * SATA translate command: Mode Select.
5264  * Translated into appropriate SATA command or emulated.
5265  * Saving parameters is not supported.
5266  * Changing device capacity is not supported (although theoretically
5267  * possible by executing SET FEATURES/SET MAX ADDRESS)
5268  *
5269  * Assumption is that the target driver is working correctly.
5270  *
5271  * More than one SATA command may be executed to perform operations specified
5272  * by mode select pages. The first error terminates further execution.
5273  * Operations performed successully are not backed-up in such case.
5274  *
5275  * NOTE: Implemented pages:
5276  * - caching page
5277  * - informational exception page
5278  * - acoustic management page
5279  * - power condition page
5280  * Caching setup is remembered so it could be re-stored in case of
5281  * an unexpected device reset.
5282  *
5283  * Returns TRAN_XXXX.
5284  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
5285  */
5286 
5287 static int
5288 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
5289 {
5290 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5291 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5292 	struct scsi_extended_sense *sense;
5293 	int len, pagelen, count, pllen;
5294 	uint8_t *buf;	/* mode select buffer */
5295 	int rval, stat, reason;
5296 	uint_t nointr_flag;
5297 	int dmod = 0;
5298 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
5299 
5300 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5301 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
5302 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5303 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5304 
5305 	mutex_enter(cport_mutex);
5306 
5307 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5308 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5309 		mutex_exit(cport_mutex);
5310 		return (rval);
5311 	}
5312 
5313 	rval = TRAN_ACCEPT;
5314 
5315 	scsipkt->pkt_reason = CMD_CMPLT;
5316 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5317 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5318 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
5319 
5320 	/* Reject not supported request */
5321 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
5322 		*scsipkt->pkt_scbp = STATUS_CHECK;
5323 		sense = sata_arq_sense(spx);
5324 		sense->es_key = KEY_ILLEGAL_REQUEST;
5325 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5326 		goto done;
5327 	}
5328 
5329 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
5330 		pllen = scsipkt->pkt_cdbp[4];
5331 	} else {
5332 		pllen = scsipkt->pkt_cdbp[7];
5333 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
5334 	}
5335 
5336 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
5337 
5338 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
5339 		buf = (uint8_t *)bp->b_un.b_addr;
5340 		count = MIN(bp->b_bcount, pllen);
5341 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5342 		scsipkt->pkt_resid = 0;
5343 		pllen = count;
5344 
5345 		/*
5346 		 * Check the header to skip the block descriptor(s) - we
5347 		 * do not support setting device capacity.
5348 		 * Existing macros do not recognize long LBA dscriptor,
5349 		 * hence manual calculation.
5350 		 */
5351 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
5352 			/* 6-bytes CMD, 4 bytes header */
5353 			if (count <= 4)
5354 				goto done;		/* header only */
5355 			len = buf[3] + 4;
5356 		} else {
5357 			/* 10-bytes CMD, 8 bytes header */
5358 			if (count <= 8)
5359 				goto done;		/* header only */
5360 			len = buf[6];
5361 			len = (len << 8) + buf[7] + 8;
5362 		}
5363 		if (len >= count)
5364 			goto done;	/* header + descriptor(s) only */
5365 
5366 		pllen -= len;		/* remaining data length */
5367 
5368 		/*
5369 		 * We may be executing SATA command and want to execute it
5370 		 * in SYNCH mode, regardless of scsi_pkt setting.
5371 		 * Save scsi_pkt setting and indicate SYNCH mode
5372 		 */
5373 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5374 		    scsipkt->pkt_comp != NULL) {
5375 			scsipkt->pkt_flags |= FLAG_NOINTR;
5376 		}
5377 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
5378 
5379 		/*
5380 		 * len is now the offset to a first mode select page
5381 		 * Process all pages
5382 		 */
5383 		while (pllen > 0) {
5384 			switch ((int)buf[len]) {
5385 			case MODEPAGE_CACHING:
5386 				/* No support for SP (saving) */
5387 				if (scsipkt->pkt_cdbp[1] & 0x01) {
5388 					*scsipkt->pkt_scbp = STATUS_CHECK;
5389 					sense = sata_arq_sense(spx);
5390 					sense->es_key = KEY_ILLEGAL_REQUEST;
5391 					sense->es_add_code =
5392 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5393 					goto done;
5394 				}
5395 				stat = sata_mode_select_page_8(spx,
5396 				    (struct mode_cache_scsi3 *)&buf[len],
5397 				    pllen, &pagelen, &rval, &dmod);
5398 				/*
5399 				 * The pagelen value indicates the number of
5400 				 * parameter bytes already processed.
5401 				 * The rval is the return value from
5402 				 * sata_tran_start().
5403 				 * The stat indicates the overall status of
5404 				 * the operation(s).
5405 				 */
5406 				if (stat != SATA_SUCCESS)
5407 					/*
5408 					 * Page processing did not succeed -
5409 					 * all error info is already set-up,
5410 					 * just return
5411 					 */
5412 					pllen = 0; /* this breaks the loop */
5413 				else {
5414 					len += pagelen;
5415 					pllen -= pagelen;
5416 				}
5417 				break;
5418 
5419 			case MODEPAGE_INFO_EXCPT:
5420 				stat = sata_mode_select_page_1c(spx,
5421 				    (struct mode_info_excpt_page *)&buf[len],
5422 				    pllen, &pagelen, &rval, &dmod);
5423 				/*
5424 				 * The pagelen value indicates the number of
5425 				 * parameter bytes already processed.
5426 				 * The rval is the return value from
5427 				 * sata_tran_start().
5428 				 * The stat indicates the overall status of
5429 				 * the operation(s).
5430 				 */
5431 				if (stat != SATA_SUCCESS)
5432 					/*
5433 					 * Page processing did not succeed -
5434 					 * all error info is already set-up,
5435 					 * just return
5436 					 */
5437 					pllen = 0; /* this breaks the loop */
5438 				else {
5439 					len += pagelen;
5440 					pllen -= pagelen;
5441 				}
5442 				break;
5443 
5444 			case MODEPAGE_ACOUSTIC_MANAG:
5445 				stat = sata_mode_select_page_30(spx,
5446 				    (struct mode_acoustic_management *)
5447 				    &buf[len], pllen, &pagelen, &rval, &dmod);
5448 				/*
5449 				 * The pagelen value indicates the number of
5450 				 * parameter bytes already processed.
5451 				 * The rval is the return value from
5452 				 * sata_tran_start().
5453 				 * The stat indicates the overall status of
5454 				 * the operation(s).
5455 				 */
5456 				if (stat != SATA_SUCCESS)
5457 					/*
5458 					 * Page processing did not succeed -
5459 					 * all error info is already set-up,
5460 					 * just return
5461 					 */
5462 					pllen = 0; /* this breaks the loop */
5463 				else {
5464 					len += pagelen;
5465 					pllen -= pagelen;
5466 				}
5467 
5468 				break;
5469 			case MODEPAGE_POWER_COND:
5470 				stat = sata_mode_select_page_1a(spx,
5471 				    (struct mode_info_power_cond *)&buf[len],
5472 				    pllen, &pagelen, &rval, &dmod);
5473 				/*
5474 				 * The pagelen value indicates the number of
5475 				 * parameter bytes already processed.
5476 				 * The rval is the return value from
5477 				 * sata_tran_start().
5478 				 * The stat indicates the overall status of
5479 				 * the operation(s).
5480 				 */
5481 				if (stat != SATA_SUCCESS)
5482 					/*
5483 					 * Page processing did not succeed -
5484 					 * all error info is already set-up,
5485 					 * just return
5486 					 */
5487 					pllen = 0; /* this breaks the loop */
5488 				else {
5489 					len += pagelen;
5490 					pllen -= pagelen;
5491 				}
5492 				break;
5493 			default:
5494 				*scsipkt->pkt_scbp = STATUS_CHECK;
5495 				sense = sata_arq_sense(spx);
5496 				sense->es_key = KEY_ILLEGAL_REQUEST;
5497 				sense->es_add_code =
5498 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
5499 				goto done;
5500 			}
5501 		}
5502 	}
5503 done:
5504 	mutex_exit(cport_mutex);
5505 	/*
5506 	 * If device parameters were modified, fetch and store the new
5507 	 * Identify Device data. Since port mutex could have been released
5508 	 * for accessing HBA driver, we need to re-check device existence.
5509 	 */
5510 	if (dmod != 0) {
5511 		sata_drive_info_t new_sdinfo, *sdinfo;
5512 		int rv = 0;
5513 
5514 		/*
5515 		 * Following statement has to be changed if this function is
5516 		 * used for devices other than SATA hard disks.
5517 		 */
5518 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
5519 
5520 		new_sdinfo.satadrv_addr =
5521 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
5522 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
5523 		    &new_sdinfo);
5524 
5525 		mutex_enter(cport_mutex);
5526 		/*
5527 		 * Since port mutex could have been released when
5528 		 * accessing HBA driver, we need to re-check that the
5529 		 * framework still holds the device info structure.
5530 		 */
5531 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5532 		    &spx->txlt_sata_pkt->satapkt_device);
5533 		if (sdinfo != NULL) {
5534 			/*
5535 			 * Device still has info structure in the
5536 			 * sata framework. Copy newly fetched info
5537 			 */
5538 			if (rv == 0) {
5539 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
5540 				sata_save_drive_settings(sdinfo);
5541 			} else {
5542 				/*
5543 				 * Could not fetch new data - invalidate
5544 				 * sata_drive_info. That makes device
5545 				 * unusable.
5546 				 */
5547 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
5548 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
5549 			}
5550 		}
5551 		if (rv != 0 || sdinfo == NULL) {
5552 			/*
5553 			 * This changes the overall mode select completion
5554 			 * reason to a failed one !!!!!
5555 			 */
5556 			*scsipkt->pkt_scbp = STATUS_CHECK;
5557 			sense = sata_arq_sense(spx);
5558 			scsipkt->pkt_reason = CMD_INCOMPLETE;
5559 			rval = TRAN_ACCEPT;
5560 		}
5561 		mutex_exit(cport_mutex);
5562 	}
5563 	/* Restore the scsi pkt flags */
5564 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
5565 	scsipkt->pkt_flags |= nointr_flag;
5566 
5567 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5568 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5569 
5570 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5571 	    scsipkt->pkt_comp != NULL) {
5572 		/* scsi callback required */
5573 		if (servicing_interrupt()) {
5574 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5575 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5576 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
5577 			    TASKQID_INVALID) {
5578 				return (TRAN_BUSY);
5579 			}
5580 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5581 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5582 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
5583 			/* Scheduling the callback failed */
5584 			return (TRAN_BUSY);
5585 		}
5586 	}
5587 
5588 	return (rval);
5589 }
5590 
5591 /*
5592  * Translate command: ATA Pass Through
5593  * Incomplete implementation.  Only supports No-Data, PIO Data-In, and
5594  * PIO Data-Out protocols.  Also supports CK_COND bit.
5595  *
5596  * Mapping of the incoming CDB bytes to the outgoing satacmd bytes is
5597  * described in Table 111 of SAT-2 (Draft 9).
5598  */
5599 static  int
5600 sata_txlt_ata_pass_thru(sata_pkt_txlate_t *spx)
5601 {
5602 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5603 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5604 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5605 	int extend;
5606 	uint64_t lba;
5607 	uint16_t feature, sec_count;
5608 	int t_len, synch;
5609 	int rval, reason;
5610 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
5611 
5612 	mutex_enter(cport_mutex);
5613 
5614 	rval = sata_txlt_generic_pkt_info(spx, &reason, 1);
5615 	if ((rval != TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5616 		mutex_exit(cport_mutex);
5617 		return (rval);
5618 	}
5619 
5620 	/* T_DIR bit */
5621 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_T_DIR)
5622 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5623 	else
5624 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5625 
5626 	/* MULTIPLE_COUNT field.  If non-zero, invalid command (for now). */
5627 	if (((scsipkt->pkt_cdbp[1] >> 5) & 0x7) != 0) {
5628 		mutex_exit(cport_mutex);
5629 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5630 	}
5631 
5632 	/* OFFLINE field. If non-zero, invalid command (for now). */
5633 	if (((scsipkt->pkt_cdbp[2] >> 6) & 0x3) != 0) {
5634 		mutex_exit(cport_mutex);
5635 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5636 	}
5637 
5638 	/* PROTOCOL field */
5639 	switch ((scsipkt->pkt_cdbp[1] >> 1) & 0xf) {
5640 	case SATL_APT_P_HW_RESET:
5641 	case SATL_APT_P_SRST:
5642 	case SATL_APT_P_DMA:
5643 	case SATL_APT_P_DMA_QUEUED:
5644 	case SATL_APT_P_DEV_DIAG:
5645 	case SATL_APT_P_DEV_RESET:
5646 	case SATL_APT_P_UDMA_IN:
5647 	case SATL_APT_P_UDMA_OUT:
5648 	case SATL_APT_P_FPDMA:
5649 	case SATL_APT_P_RET_RESP:
5650 		/* Not yet implemented */
5651 	default:
5652 		mutex_exit(cport_mutex);
5653 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5654 
5655 	case SATL_APT_P_NON_DATA:
5656 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
5657 		break;
5658 
5659 	case SATL_APT_P_PIO_DATA_IN:
5660 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5661 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_WRITE) {
5662 			mutex_exit(cport_mutex);
5663 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5664 		}
5665 
5666 		/* if there is a buffer, release its DMA resources */
5667 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5668 			sata_scsi_dmafree(NULL, scsipkt);
5669 		} else {
5670 			/* if there is no buffer, how do you PIO in? */
5671 			mutex_exit(cport_mutex);
5672 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5673 		}
5674 
5675 		break;
5676 
5677 	case SATL_APT_P_PIO_DATA_OUT:
5678 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5679 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_READ) {
5680 			mutex_exit(cport_mutex);
5681 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5682 		}
5683 
5684 		/* if there is a buffer, release its DMA resources */
5685 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5686 			sata_scsi_dmafree(NULL, scsipkt);
5687 		} else {
5688 			/* if there is no buffer, how do you PIO out? */
5689 			mutex_exit(cport_mutex);
5690 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5691 		}
5692 
5693 		break;
5694 	}
5695 
5696 	/* Parse the ATA cmd fields, transfer some straight to the satacmd */
5697 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5698 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
5699 		feature = scsipkt->pkt_cdbp[3];
5700 
5701 		sec_count = scsipkt->pkt_cdbp[4];
5702 
5703 		lba = scsipkt->pkt_cdbp[8] & 0xf;
5704 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5705 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5706 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5707 
5708 		scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] & 0xf0;
5709 		scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[9];
5710 
5711 		break;
5712 
5713 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
5714 		if (scsipkt->pkt_cdbp[1] & SATL_APT_BM_EXTEND) {
5715 			extend = 1;
5716 
5717 			feature = scsipkt->pkt_cdbp[3];
5718 			feature = (feature << 8) | scsipkt->pkt_cdbp[4];
5719 
5720 			sec_count = scsipkt->pkt_cdbp[5];
5721 			sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[6];
5722 
5723 			lba = scsipkt->pkt_cdbp[11];
5724 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5725 			lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5726 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5727 			lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5728 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5729 
5730 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13];
5731 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5732 		} else {
5733 			feature = scsipkt->pkt_cdbp[3];
5734 
5735 			sec_count = scsipkt->pkt_cdbp[5];
5736 
5737 			lba = scsipkt->pkt_cdbp[13] & 0xf;
5738 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5739 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5740 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5741 
5742 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] &
5743 			    0xf0;
5744 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5745 		}
5746 
5747 		break;
5748 	}
5749 
5750 	/* CK_COND bit */
5751 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
5752 		if (extend) {
5753 			scmd->satacmd_flags.sata_copy_out_sec_count_msb = 1;
5754 			scmd->satacmd_flags.sata_copy_out_lba_low_msb = 1;
5755 			scmd->satacmd_flags.sata_copy_out_lba_mid_msb = 1;
5756 			scmd->satacmd_flags.sata_copy_out_lba_high_msb = 1;
5757 		}
5758 
5759 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
5760 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
5761 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
5762 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
5763 		scmd->satacmd_flags.sata_copy_out_device_reg = 1;
5764 		scmd->satacmd_flags.sata_copy_out_error_reg = 1;
5765 	}
5766 
5767 	/* Transfer remaining parsed ATA cmd values to the satacmd */
5768 	if (extend) {
5769 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5770 
5771 		scmd->satacmd_features_reg_ext = (feature >> 8) & 0xff;
5772 		scmd->satacmd_sec_count_msb = (sec_count >> 8) & 0xff;
5773 		scmd->satacmd_lba_low_msb = (lba >> 8) & 0xff;
5774 		scmd->satacmd_lba_mid_msb = (lba >> 8) & 0xff;
5775 		scmd->satacmd_lba_high_msb = lba >> 40;
5776 	} else {
5777 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5778 
5779 		scmd->satacmd_features_reg_ext = 0;
5780 		scmd->satacmd_sec_count_msb = 0;
5781 		scmd->satacmd_lba_low_msb = 0;
5782 		scmd->satacmd_lba_mid_msb = 0;
5783 		scmd->satacmd_lba_high_msb = 0;
5784 	}
5785 
5786 	scmd->satacmd_features_reg = feature & 0xff;
5787 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5788 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5789 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5790 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5791 
5792 	/* Determine transfer length */
5793 	switch (scsipkt->pkt_cdbp[2] & 0x3) {		/* T_LENGTH field */
5794 	case 1:
5795 		t_len = feature;
5796 		break;
5797 	case 2:
5798 		t_len = sec_count;
5799 		break;
5800 	default:
5801 		t_len = 0;
5802 		break;
5803 	}
5804 
5805 	/* Adjust transfer length for the Byte Block bit */
5806 	if ((scsipkt->pkt_cdbp[2] >> 2) & 1)
5807 		t_len *= SATA_DISK_SECTOR_SIZE;
5808 
5809 	/* Start processing command */
5810 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5811 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_apt_completion;
5812 		synch = FALSE;
5813 	} else {
5814 		synch = TRUE;
5815 	}
5816 
5817 	if (sata_hba_start(spx, &rval) != 0) {
5818 		mutex_exit(cport_mutex);
5819 		return (rval);
5820 	}
5821 
5822 	mutex_exit(cport_mutex);
5823 
5824 	if (synch) {
5825 		sata_txlt_apt_completion(spx->txlt_sata_pkt);
5826 	}
5827 
5828 	return (TRAN_ACCEPT);
5829 }
5830 
5831 /*
5832  * Translate command: Log Sense
5833  */
5834 static int
5835 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
5836 {
5837 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
5838 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5839 	sata_drive_info_t *sdinfo;
5840 	struct scsi_extended_sense *sense;
5841 	int		len, count, alc_len;
5842 	int		pc;	/* Page Control code */
5843 	int		page_code;	/* Page code */
5844 	uint8_t		*buf;	/* log sense buffer */
5845 	int		rval, reason;
5846 #define	MAX_LOG_SENSE_PAGE_SIZE	512
5847 	kmutex_t	*cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
5848 
5849 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5850 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
5851 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5852 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5853 
5854 	if (servicing_interrupt()) {
5855 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_NOSLEEP);
5856 		if (buf == NULL) {
5857 			return (TRAN_BUSY);
5858 		}
5859 	} else {
5860 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
5861 	}
5862 
5863 	mutex_enter(cport_mutex);
5864 
5865 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5866 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5867 		mutex_exit(cport_mutex);
5868 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5869 		return (rval);
5870 	}
5871 
5872 	scsipkt->pkt_reason = CMD_CMPLT;
5873 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5874 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5875 
5876 	pc = scsipkt->pkt_cdbp[2] >> 6;
5877 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
5878 
5879 	/* Reject not supported request for all but cumulative values */
5880 	switch (pc) {
5881 	case PC_CUMULATIVE_VALUES:
5882 		break;
5883 	default:
5884 		*scsipkt->pkt_scbp = STATUS_CHECK;
5885 		sense = sata_arq_sense(spx);
5886 		sense->es_key = KEY_ILLEGAL_REQUEST;
5887 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5888 		goto done;
5889 	}
5890 
5891 	switch (page_code) {
5892 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5893 	case PAGE_CODE_SELF_TEST_RESULTS:
5894 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
5895 	case PAGE_CODE_SMART_READ_DATA:
5896 	case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5897 		break;
5898 	default:
5899 		*scsipkt->pkt_scbp = STATUS_CHECK;
5900 		sense = sata_arq_sense(spx);
5901 		sense->es_key = KEY_ILLEGAL_REQUEST;
5902 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5903 		goto done;
5904 	}
5905 
5906 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
5907 		/*
5908 		 * Because log sense uses local buffers for data retrieval from
5909 		 * the devices and sets the data programatically in the
5910 		 * original specified buffer, release preallocated DMA
5911 		 * resources before storing data in the original buffer,
5912 		 * so no unwanted DMA sync would take place.
5913 		 */
5914 		sata_id_t *sata_id;
5915 
5916 		sata_scsi_dmafree(NULL, scsipkt);
5917 
5918 		len = 0;
5919 
5920 		/* Build log parameter header */
5921 		buf[len++] = page_code;	/* page code as in the CDB */
5922 		buf[len++] = 0;		/* reserved */
5923 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
5924 		buf[len++] = 0;		/* (LSB) */
5925 
5926 		sdinfo = sata_get_device_info(
5927 		    spx->txlt_sata_hba_inst,
5928 		    &spx->txlt_sata_pkt->satapkt_device);
5929 
5930 		/*
5931 		 * Add requested pages.
5932 		 */
5933 		switch (page_code) {
5934 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5935 			len = sata_build_lsense_page_0(sdinfo, buf + len);
5936 			break;
5937 		case PAGE_CODE_SELF_TEST_RESULTS:
5938 			sata_id = &sdinfo->satadrv_id;
5939 			if ((! (sata_id->ai_cmdset84 &
5940 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
5941 			    (! (sata_id->ai_features87 &
5942 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
5943 				*scsipkt->pkt_scbp = STATUS_CHECK;
5944 				sense = sata_arq_sense(spx);
5945 				sense->es_key = KEY_ILLEGAL_REQUEST;
5946 				sense->es_add_code =
5947 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5948 
5949 				goto done;
5950 			}
5951 			len = sata_build_lsense_page_10(sdinfo, buf + len,
5952 			    spx->txlt_sata_hba_inst);
5953 			break;
5954 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
5955 			sata_id = &sdinfo->satadrv_id;
5956 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5957 				*scsipkt->pkt_scbp = STATUS_CHECK;
5958 				sense = sata_arq_sense(spx);
5959 				sense->es_key = KEY_ILLEGAL_REQUEST;
5960 				sense->es_add_code =
5961 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5962 
5963 				goto done;
5964 			}
5965 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5966 				*scsipkt->pkt_scbp = STATUS_CHECK;
5967 				sense = sata_arq_sense(spx);
5968 				sense->es_key = KEY_ABORTED_COMMAND;
5969 				sense->es_add_code =
5970 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5971 				sense->es_qual_code =
5972 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5973 
5974 				goto done;
5975 			}
5976 
5977 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
5978 			    spx->txlt_sata_hba_inst);
5979 			break;
5980 		case PAGE_CODE_SMART_READ_DATA:
5981 			sata_id = &sdinfo->satadrv_id;
5982 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5983 				*scsipkt->pkt_scbp = STATUS_CHECK;
5984 				sense = sata_arq_sense(spx);
5985 				sense->es_key = KEY_ILLEGAL_REQUEST;
5986 				sense->es_add_code =
5987 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5988 
5989 				goto done;
5990 			}
5991 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5992 				*scsipkt->pkt_scbp = STATUS_CHECK;
5993 				sense = sata_arq_sense(spx);
5994 				sense->es_key = KEY_ABORTED_COMMAND;
5995 				sense->es_add_code =
5996 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5997 				sense->es_qual_code =
5998 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5999 
6000 				goto done;
6001 			}
6002 
6003 			/* This page doesn't include a page header */
6004 			len = sata_build_lsense_page_30(sdinfo, buf,
6005 			    spx->txlt_sata_hba_inst);
6006 			goto no_header;
6007 		case PAGE_CODE_START_STOP_CYCLE_COUNTER:
6008 			sata_id = &sdinfo->satadrv_id;
6009 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
6010 				*scsipkt->pkt_scbp = STATUS_CHECK;
6011 				sense = sata_arq_sense(spx);
6012 				sense->es_key = KEY_ILLEGAL_REQUEST;
6013 				sense->es_add_code =
6014 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6015 
6016 				goto done;
6017 			}
6018 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
6019 				*scsipkt->pkt_scbp = STATUS_CHECK;
6020 				sense = sata_arq_sense(spx);
6021 				sense->es_key = KEY_ABORTED_COMMAND;
6022 				sense->es_add_code =
6023 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
6024 				sense->es_qual_code =
6025 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
6026 
6027 				goto done;
6028 			}
6029 			len = sata_build_lsense_page_0e(sdinfo, buf, spx);
6030 			goto no_header;
6031 		default:
6032 			/* Invalid request */
6033 			*scsipkt->pkt_scbp = STATUS_CHECK;
6034 			sense = sata_arq_sense(spx);
6035 			sense->es_key = KEY_ILLEGAL_REQUEST;
6036 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6037 			goto done;
6038 		}
6039 
6040 		/* set parameter log sense data length */
6041 		buf[2] = len >> 8;	/* log sense length (MSB) */
6042 		buf[3] = len & 0xff;	/* log sense length (LSB) */
6043 
6044 		len += SCSI_LOG_PAGE_HDR_LEN;
6045 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
6046 
6047 no_header:
6048 		/* Check allocation length */
6049 		alc_len = scsipkt->pkt_cdbp[7];
6050 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
6051 
6052 		/*
6053 		 * We do not check for possible parameters truncation
6054 		 * (alc_len < len) assuming that the target driver works
6055 		 * correctly. Just avoiding overrun.
6056 		 * Copy no more than requested and possible, buffer-wise.
6057 		 */
6058 		count = MIN(alc_len, len);
6059 		count = MIN(bp->b_bcount, count);
6060 		bcopy(buf, bp->b_un.b_addr, count);
6061 
6062 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
6063 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
6064 	}
6065 	*scsipkt->pkt_scbp = STATUS_GOOD;
6066 done:
6067 	mutex_exit(cport_mutex);
6068 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
6069 
6070 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6071 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6072 
6073 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6074 	    scsipkt->pkt_comp != NULL) {
6075 		/* scsi callback required */
6076 		if (servicing_interrupt()) {
6077 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6078 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6079 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
6080 			    TASKQID_INVALID) {
6081 				return (TRAN_BUSY);
6082 			}
6083 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6084 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6085 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
6086 			/* Scheduling the callback failed */
6087 			return (TRAN_BUSY);
6088 		}
6089 	}
6090 
6091 	return (TRAN_ACCEPT);
6092 }
6093 
6094 /*
6095  * Translate command: Log Select
6096  * Not implemented at this time - returns invalid command response.
6097  */
6098 static	int
6099 sata_txlt_log_select(sata_pkt_txlate_t *spx)
6100 {
6101 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6102 	    "sata_txlt_log_select\n", NULL);
6103 
6104 	return (sata_txlt_invalid_command(spx));
6105 }
6106 
6107 
6108 /*
6109  * Translate command: Read (various types).
6110  * Translated into appropriate type of ATA READ command
6111  * for SATA hard disks.
6112  * Both the device capabilities and requested operation mode are
6113  * considered.
6114  *
6115  * Following scsi cdb fields are ignored:
6116  * rdprotect, dpo, fua, fua_nv, group_number.
6117  *
6118  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
6119  * enable variable sata_func_enable), the capability of the controller and
6120  * capability of a device are checked and if both support queueing, read
6121  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
6122  * command rather than plain READ_XXX command.
6123  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
6124  * both the controller and device suport such functionality, the read
6125  * request will be translated to READ_FPDMA_QUEUED command.
6126  * In both cases the maximum queue depth is derived as minimum of:
6127  * HBA capability,device capability and sata_max_queue_depth variable setting.
6128  * The value passed to HBA driver is decremented by 1, because only 5 bits are
6129  * used to pass max queue depth value, and the maximum possible queue depth
6130  * is 32.
6131  *
6132  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6133  * appropriate values in scsi_pkt fields.
6134  */
6135 static int
6136 sata_txlt_read(sata_pkt_txlate_t *spx)
6137 {
6138 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6139 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6140 	sata_drive_info_t *sdinfo;
6141 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6142 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
6143 	uint16_t sec_count;
6144 	uint64_t lba;
6145 	int rval, reason;
6146 	int synch;
6147 
6148 	mutex_enter(cport_mutex);
6149 
6150 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
6151 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6152 		mutex_exit(cport_mutex);
6153 		return (rval);
6154 	}
6155 
6156 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6157 	    &spx->txlt_sata_pkt->satapkt_device);
6158 
6159 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
6160 	/*
6161 	 * Extract LBA and sector count from scsi CDB.
6162 	 */
6163 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
6164 	case SCMD_READ:
6165 		/* 6-byte scsi read cmd : 0x08 */
6166 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
6167 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
6168 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6169 		sec_count = scsipkt->pkt_cdbp[4];
6170 		/* sec_count 0 will be interpreted as 256 by a device */
6171 		break;
6172 	case SCMD_READ_G1:
6173 		/* 10-bytes scsi read command : 0x28 */
6174 		lba = scsipkt->pkt_cdbp[2];
6175 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6176 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6177 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6178 		sec_count = scsipkt->pkt_cdbp[7];
6179 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
6180 		break;
6181 	case SCMD_READ_G5:
6182 		/* 12-bytes scsi read command : 0xA8 */
6183 		lba = scsipkt->pkt_cdbp[2];
6184 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6185 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6186 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6187 		sec_count = scsipkt->pkt_cdbp[6];
6188 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
6189 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
6190 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
6191 		break;
6192 	case SCMD_READ_G4:
6193 		/* 16-bytes scsi read command : 0x88 */
6194 		lba = scsipkt->pkt_cdbp[2];
6195 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6196 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6197 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6198 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
6199 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
6200 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
6201 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
6202 		sec_count = scsipkt->pkt_cdbp[10];
6203 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
6204 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
6205 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
6206 		break;
6207 	default:
6208 		/* Unsupported command */
6209 		mutex_exit(cport_mutex);
6210 		return (sata_txlt_invalid_command(spx));
6211 	}
6212 
6213 	/*
6214 	 * Check if specified address exceeds device capacity
6215 	 */
6216 	if ((lba >= sdinfo->satadrv_capacity) ||
6217 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
6218 		/* LBA out of range */
6219 		mutex_exit(cport_mutex);
6220 		return (sata_txlt_lba_out_of_range(spx));
6221 	}
6222 
6223 	/*
6224 	 * For zero-length transfer, emulate good completion of the command
6225 	 * (reasons for rejecting the command were already checked).
6226 	 * No DMA resources were allocated.
6227 	 */
6228 	if (spx->txlt_dma_cookie_list == NULL) {
6229 		mutex_exit(cport_mutex);
6230 		return (sata_emul_rw_completion(spx));
6231 	}
6232 
6233 	/*
6234 	 * Build cmd block depending on the device capability and
6235 	 * requested operation mode.
6236 	 * Do not bother with non-dma mode - we are working only with
6237 	 * devices supporting DMA.
6238 	 */
6239 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
6240 	scmd->satacmd_device_reg = SATA_ADH_LBA;
6241 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
6242 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
6243 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
6244 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
6245 		scmd->satacmd_sec_count_msb = sec_count >> 8;
6246 #ifndef __lock_lint
6247 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
6248 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
6249 		scmd->satacmd_lba_high_msb = lba >> 40;
6250 #endif
6251 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
6252 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
6253 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
6254 	}
6255 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
6256 	scmd->satacmd_lba_low_lsb = lba & 0xff;
6257 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
6258 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
6259 	scmd->satacmd_features_reg = 0;
6260 	scmd->satacmd_status_reg = 0;
6261 	scmd->satacmd_error_reg = 0;
6262 
6263 	/*
6264 	 * Check if queueing commands should be used and switch
6265 	 * to appropriate command if possible
6266 	 */
6267 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
6268 		boolean_t using_queuing;
6269 
6270 		/* Queuing supported by controller and device? */
6271 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
6272 		    (sdinfo->satadrv_features_support &
6273 		    SATA_DEV_F_NCQ) &&
6274 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6275 		    SATA_CTLF_NCQ)) {
6276 			using_queuing = B_TRUE;
6277 
6278 			/* NCQ supported - use FPDMA READ */
6279 			scmd->satacmd_cmd_reg =
6280 			    SATAC_READ_FPDMA_QUEUED;
6281 			scmd->satacmd_features_reg_ext =
6282 			    scmd->satacmd_sec_count_msb;
6283 			scmd->satacmd_sec_count_msb = 0;
6284 		} else if ((sdinfo->satadrv_features_support &
6285 		    SATA_DEV_F_TCQ) &&
6286 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6287 		    SATA_CTLF_QCMD)) {
6288 			using_queuing = B_TRUE;
6289 
6290 			/* Legacy queueing */
6291 			if (sdinfo->satadrv_features_support &
6292 			    SATA_DEV_F_LBA48) {
6293 				scmd->satacmd_cmd_reg =
6294 				    SATAC_READ_DMA_QUEUED_EXT;
6295 				scmd->satacmd_features_reg_ext =
6296 				    scmd->satacmd_sec_count_msb;
6297 				scmd->satacmd_sec_count_msb = 0;
6298 			} else {
6299 				scmd->satacmd_cmd_reg =
6300 				    SATAC_READ_DMA_QUEUED;
6301 			}
6302 		} else	/* NCQ nor legacy queuing not supported */
6303 			using_queuing = B_FALSE;
6304 
6305 		/*
6306 		 * If queuing, the sector count goes in the features register
6307 		 * and the secount count will contain the tag.
6308 		 */
6309 		if (using_queuing) {
6310 			scmd->satacmd_features_reg =
6311 			    scmd->satacmd_sec_count_lsb;
6312 			scmd->satacmd_sec_count_lsb = 0;
6313 			scmd->satacmd_flags.sata_queued = B_TRUE;
6314 
6315 			/* Set-up maximum queue depth */
6316 			scmd->satacmd_flags.sata_max_queue_depth =
6317 			    sdinfo->satadrv_max_queue_depth - 1;
6318 		} else if (sdinfo->satadrv_features_enabled &
6319 		    SATA_DEV_F_E_UNTAGGED_QING) {
6320 			/*
6321 			 * Although NCQ/TCQ is not enabled, untagged queuing
6322 			 * may be still used.
6323 			 * Set-up the maximum untagged queue depth.
6324 			 * Use controller's queue depth from sata_hba_tran.
6325 			 * SATA HBA drivers may ignore this value and rely on
6326 			 * the internal limits.For drivers that do not
6327 			 * ignore untaged queue depth, limit the value to
6328 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
6329 			 * largest value that can be passed via
6330 			 * satacmd_flags.sata_max_queue_depth.
6331 			 */
6332 			scmd->satacmd_flags.sata_max_queue_depth =
6333 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
6334 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
6335 
6336 		} else {
6337 			scmd->satacmd_flags.sata_max_queue_depth = 0;
6338 		}
6339 	} else
6340 		scmd->satacmd_flags.sata_max_queue_depth = 0;
6341 
6342 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
6343 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
6344 	    scmd->satacmd_cmd_reg, lba, sec_count);
6345 
6346 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6347 		/* Need callback function */
6348 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
6349 		synch = FALSE;
6350 	} else
6351 		synch = TRUE;
6352 
6353 	/* Transfer command to HBA */
6354 	if (sata_hba_start(spx, &rval) != 0) {
6355 		/* Pkt not accepted for execution */
6356 		mutex_exit(cport_mutex);
6357 		return (rval);
6358 	}
6359 	mutex_exit(cport_mutex);
6360 	/*
6361 	 * If execution is non-synchronous,
6362 	 * a callback function will handle potential errors, translate
6363 	 * the response and will do a callback to a target driver.
6364 	 * If it was synchronous, check execution status using the same
6365 	 * framework callback.
6366 	 */
6367 	if (synch) {
6368 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6369 		    "synchronous execution status %x\n",
6370 		    spx->txlt_sata_pkt->satapkt_reason);
6371 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
6372 	}
6373 	return (TRAN_ACCEPT);
6374 }
6375 
6376 
6377 /*
6378  * SATA translate command: Write (various types)
6379  * Translated into appropriate type of ATA WRITE command
6380  * for SATA hard disks.
6381  * Both the device capabilities and requested operation mode are
6382  * considered.
6383  *
6384  * Following scsi cdb fields are ignored:
6385  * rwprotect, dpo, fua, fua_nv, group_number.
6386  *
6387  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
6388  * enable variable sata_func_enable), the capability of the controller and
6389  * capability of a device are checked and if both support queueing, write
6390  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
6391  * command rather than plain WRITE_XXX command.
6392  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
6393  * both the controller and device suport such functionality, the write
6394  * request will be translated to WRITE_FPDMA_QUEUED command.
6395  * In both cases the maximum queue depth is derived as minimum of:
6396  * HBA capability,device capability and sata_max_queue_depth variable setting.
6397  * The value passed to HBA driver is decremented by 1, because only 5 bits are
6398  * used to pass max queue depth value, and the maximum possible queue depth
6399  * is 32.
6400  *
6401  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6402  * appropriate values in scsi_pkt fields.
6403  */
6404 static int
6405 sata_txlt_write(sata_pkt_txlate_t *spx)
6406 {
6407 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6408 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6409 	sata_drive_info_t *sdinfo;
6410 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6411 	uint16_t sec_count;
6412 	uint64_t lba;
6413 	int rval, reason;
6414 	int synch;
6415 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
6416 
6417 	mutex_enter(cport_mutex);
6418 
6419 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
6420 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6421 		mutex_exit(cport_mutex);
6422 		return (rval);
6423 	}
6424 
6425 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6426 	    &spx->txlt_sata_pkt->satapkt_device);
6427 
6428 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
6429 	/*
6430 	 * Extract LBA and sector count from scsi CDB
6431 	 */
6432 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
6433 	case SCMD_WRITE:
6434 		/* 6-byte scsi read cmd : 0x0A */
6435 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
6436 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
6437 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6438 		sec_count = scsipkt->pkt_cdbp[4];
6439 		/* sec_count 0 will be interpreted as 256 by a device */
6440 		break;
6441 	case SCMD_WRITE_G1:
6442 		/* 10-bytes scsi write command : 0x2A */
6443 		lba = scsipkt->pkt_cdbp[2];
6444 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6445 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6446 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6447 		sec_count = scsipkt->pkt_cdbp[7];
6448 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
6449 		break;
6450 	case SCMD_WRITE_G5:
6451 		/* 12-bytes scsi read command : 0xAA */
6452 		lba = scsipkt->pkt_cdbp[2];
6453 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6454 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6455 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6456 		sec_count = scsipkt->pkt_cdbp[6];
6457 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
6458 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
6459 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
6460 		break;
6461 	case SCMD_WRITE_G4:
6462 		/* 16-bytes scsi write command : 0x8A */
6463 		lba = scsipkt->pkt_cdbp[2];
6464 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6465 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6466 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6467 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
6468 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
6469 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
6470 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
6471 		sec_count = scsipkt->pkt_cdbp[10];
6472 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
6473 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
6474 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
6475 		break;
6476 	default:
6477 		/* Unsupported command */
6478 		mutex_exit(cport_mutex);
6479 		return (sata_txlt_invalid_command(spx));
6480 	}
6481 
6482 	/*
6483 	 * Check if specified address and length exceeds device capacity
6484 	 */
6485 	if ((lba >= sdinfo->satadrv_capacity) ||
6486 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
6487 		/* LBA out of range */
6488 		mutex_exit(cport_mutex);
6489 		return (sata_txlt_lba_out_of_range(spx));
6490 	}
6491 
6492 	/*
6493 	 * For zero-length transfer, emulate good completion of the command
6494 	 * (reasons for rejecting the command were already checked).
6495 	 * No DMA resources were allocated.
6496 	 */
6497 	if (spx->txlt_dma_cookie_list == NULL) {
6498 		mutex_exit(cport_mutex);
6499 		return (sata_emul_rw_completion(spx));
6500 	}
6501 
6502 	/*
6503 	 * Build cmd block depending on the device capability and
6504 	 * requested operation mode.
6505 	 * Do not bother with non-dma mode- we are working only with
6506 	 * devices supporting DMA.
6507 	 */
6508 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
6509 	scmd->satacmd_device_reg = SATA_ADH_LBA;
6510 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
6511 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
6512 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
6513 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
6514 		scmd->satacmd_sec_count_msb = sec_count >> 8;
6515 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
6516 #ifndef __lock_lint
6517 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
6518 		scmd->satacmd_lba_high_msb = lba >> 40;
6519 #endif
6520 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
6521 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
6522 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
6523 	}
6524 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
6525 	scmd->satacmd_lba_low_lsb = lba & 0xff;
6526 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
6527 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
6528 	scmd->satacmd_features_reg = 0;
6529 	scmd->satacmd_status_reg = 0;
6530 	scmd->satacmd_error_reg = 0;
6531 
6532 	/*
6533 	 * Check if queueing commands should be used and switch
6534 	 * to appropriate command if possible
6535 	 */
6536 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
6537 		boolean_t using_queuing;
6538 
6539 		/* Queuing supported by controller and device? */
6540 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
6541 		    (sdinfo->satadrv_features_support &
6542 		    SATA_DEV_F_NCQ) &&
6543 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6544 		    SATA_CTLF_NCQ)) {
6545 			using_queuing = B_TRUE;
6546 
6547 			/* NCQ supported - use FPDMA WRITE */
6548 			scmd->satacmd_cmd_reg =
6549 			    SATAC_WRITE_FPDMA_QUEUED;
6550 			scmd->satacmd_features_reg_ext =
6551 			    scmd->satacmd_sec_count_msb;
6552 			scmd->satacmd_sec_count_msb = 0;
6553 		} else if ((sdinfo->satadrv_features_support &
6554 		    SATA_DEV_F_TCQ) &&
6555 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6556 		    SATA_CTLF_QCMD)) {
6557 			using_queuing = B_TRUE;
6558 
6559 			/* Legacy queueing */
6560 			if (sdinfo->satadrv_features_support &
6561 			    SATA_DEV_F_LBA48) {
6562 				scmd->satacmd_cmd_reg =
6563 				    SATAC_WRITE_DMA_QUEUED_EXT;
6564 				scmd->satacmd_features_reg_ext =
6565 				    scmd->satacmd_sec_count_msb;
6566 				scmd->satacmd_sec_count_msb = 0;
6567 			} else {
6568 				scmd->satacmd_cmd_reg =
6569 				    SATAC_WRITE_DMA_QUEUED;
6570 			}
6571 		} else	/*  NCQ nor legacy queuing not supported */
6572 			using_queuing = B_FALSE;
6573 
6574 		if (using_queuing) {
6575 			scmd->satacmd_features_reg =
6576 			    scmd->satacmd_sec_count_lsb;
6577 			scmd->satacmd_sec_count_lsb = 0;
6578 			scmd->satacmd_flags.sata_queued = B_TRUE;
6579 			/* Set-up maximum queue depth */
6580 			scmd->satacmd_flags.sata_max_queue_depth =
6581 			    sdinfo->satadrv_max_queue_depth - 1;
6582 		} else if (sdinfo->satadrv_features_enabled &
6583 		    SATA_DEV_F_E_UNTAGGED_QING) {
6584 			/*
6585 			 * Although NCQ/TCQ is not enabled, untagged queuing
6586 			 * may be still used.
6587 			 * Set-up the maximum untagged queue depth.
6588 			 * Use controller's queue depth from sata_hba_tran.
6589 			 * SATA HBA drivers may ignore this value and rely on
6590 			 * the internal limits. For drivera that do not
6591 			 * ignore untaged queue depth, limit the value to
6592 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
6593 			 * largest value that can be passed via
6594 			 * satacmd_flags.sata_max_queue_depth.
6595 			 */
6596 			scmd->satacmd_flags.sata_max_queue_depth =
6597 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
6598 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
6599 
6600 		} else {
6601 			scmd->satacmd_flags.sata_max_queue_depth = 0;
6602 		}
6603 	} else
6604 		scmd->satacmd_flags.sata_max_queue_depth = 0;
6605 
6606 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6607 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
6608 	    scmd->satacmd_cmd_reg, lba, sec_count);
6609 
6610 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6611 		/* Need callback function */
6612 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
6613 		synch = FALSE;
6614 	} else
6615 		synch = TRUE;
6616 
6617 	/* Transfer command to HBA */
6618 	if (sata_hba_start(spx, &rval) != 0) {
6619 		/* Pkt not accepted for execution */
6620 		mutex_exit(cport_mutex);
6621 		return (rval);
6622 	}
6623 	mutex_exit(cport_mutex);
6624 
6625 	/*
6626 	 * If execution is non-synchronous,
6627 	 * a callback function will handle potential errors, translate
6628 	 * the response and will do a callback to a target driver.
6629 	 * If it was synchronous, check execution status using the same
6630 	 * framework callback.
6631 	 */
6632 	if (synch) {
6633 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6634 		    "synchronous execution status %x\n",
6635 		    spx->txlt_sata_pkt->satapkt_reason);
6636 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
6637 	}
6638 	return (TRAN_ACCEPT);
6639 }
6640 
6641 
6642 /*
6643  * Implements SCSI SBC WRITE BUFFER command download microcode option
6644  */
6645 static int
6646 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
6647 {
6648 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
6649 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
6650 
6651 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6652 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
6653 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6654 
6655 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6656 	struct scsi_extended_sense *sense;
6657 	int rval, mode, sector_count, reason;
6658 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
6659 
6660 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
6661 
6662 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6663 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
6664 
6665 	mutex_enter(cport_mutex);
6666 
6667 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6668 	    TRAN_ACCEPT) {
6669 		mutex_exit(cport_mutex);
6670 		return (rval);
6671 	}
6672 
6673 	/* Use synchronous mode */
6674 	spx->txlt_sata_pkt->satapkt_op_mode
6675 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
6676 
6677 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
6678 
6679 	scsipkt->pkt_reason = CMD_CMPLT;
6680 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6681 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6682 
6683 	/*
6684 	 * The SCSI to ATA translation specification only calls
6685 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
6686 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
6687 	 * ATA 8 (draft) got rid of download microcode for temp
6688 	 * and it is even optional for ATA 7, so it may be aborted.
6689 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
6690 	 * it is not specified and the buffer offset for SCSI is a 16-bit
6691 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
6692 	 * sectors.  Thus the offset really doesn't buy us anything.
6693 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
6694 	 * is revised, this can be revisisted.
6695 	 */
6696 	/* Reject not supported request */
6697 	switch (mode) {
6698 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
6699 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
6700 		break;
6701 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
6702 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
6703 		break;
6704 	default:
6705 		goto bad_param;
6706 	}
6707 
6708 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
6709 
6710 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
6711 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
6712 		goto bad_param;
6713 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
6714 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
6715 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
6716 	scmd->satacmd_lba_mid_lsb = 0;
6717 	scmd->satacmd_lba_high_lsb = 0;
6718 	scmd->satacmd_device_reg = 0;
6719 	spx->txlt_sata_pkt->satapkt_comp = NULL;
6720 	scmd->satacmd_addr_type = 0;
6721 
6722 	/* Transfer command to HBA */
6723 	if (sata_hba_start(spx, &rval) != 0) {
6724 		/* Pkt not accepted for execution */
6725 		mutex_exit(cport_mutex);
6726 		return (rval);
6727 	}
6728 
6729 	mutex_exit(cport_mutex);
6730 
6731 	/* Then we need synchronous check the status of the disk */
6732 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6733 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6734 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6735 		scsipkt->pkt_reason = CMD_CMPLT;
6736 
6737 		/* Download commmand succeed, so probe and identify device */
6738 		sata_reidentify_device(spx);
6739 	} else {
6740 		/* Something went wrong, microcode download command failed */
6741 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6742 		*scsipkt->pkt_scbp = STATUS_CHECK;
6743 		sense = sata_arq_sense(spx);
6744 		switch (sata_pkt->satapkt_reason) {
6745 		case SATA_PKT_PORT_ERROR:
6746 			/*
6747 			 * We have no device data. Assume no data transfered.
6748 			 */
6749 			sense->es_key = KEY_HARDWARE_ERROR;
6750 			break;
6751 
6752 		case SATA_PKT_DEV_ERROR:
6753 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6754 			    SATA_STATUS_ERR) {
6755 				/*
6756 				 * determine dev error reason from error
6757 				 * reg content
6758 				 */
6759 				sata_decode_device_error(spx, sense);
6760 				break;
6761 			}
6762 			/* No extended sense key - no info available */
6763 			break;
6764 
6765 		case SATA_PKT_TIMEOUT:
6766 			scsipkt->pkt_reason = CMD_TIMEOUT;
6767 			scsipkt->pkt_statistics |=
6768 			    STAT_TIMEOUT | STAT_DEV_RESET;
6769 			/* No extended sense key ? */
6770 			break;
6771 
6772 		case SATA_PKT_ABORTED:
6773 			scsipkt->pkt_reason = CMD_ABORTED;
6774 			scsipkt->pkt_statistics |= STAT_ABORTED;
6775 			/* No extended sense key ? */
6776 			break;
6777 
6778 		case SATA_PKT_RESET:
6779 			/* pkt aborted by an explicit reset from a host */
6780 			scsipkt->pkt_reason = CMD_RESET;
6781 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6782 			break;
6783 
6784 		default:
6785 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6786 			    "sata_txlt_nodata_cmd_completion: "
6787 			    "invalid packet completion reason %d",
6788 			    sata_pkt->satapkt_reason));
6789 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6790 			break;
6791 		}
6792 
6793 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6794 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6795 
6796 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6797 			/* scsi callback required */
6798 			scsi_hba_pkt_comp(scsipkt);
6799 	}
6800 	return (TRAN_ACCEPT);
6801 
6802 bad_param:
6803 	mutex_exit(cport_mutex);
6804 	*scsipkt->pkt_scbp = STATUS_CHECK;
6805 	sense = sata_arq_sense(spx);
6806 	sense->es_key = KEY_ILLEGAL_REQUEST;
6807 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6808 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6809 	    scsipkt->pkt_comp != NULL) {
6810 		/* scsi callback required */
6811 		if (servicing_interrupt()) {
6812 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6813 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6814 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
6815 			    TASKQID_INVALID) {
6816 				return (TRAN_BUSY);
6817 			}
6818 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6819 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6820 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
6821 			/* Scheduling the callback failed */
6822 			return (TRAN_BUSY);
6823 		}
6824 	}
6825 	return (rval);
6826 }
6827 
6828 /*
6829  * Re-identify device after doing a firmware download.
6830  */
6831 static void
6832 sata_reidentify_device(sata_pkt_txlate_t *spx)
6833 {
6834 #define	DOWNLOAD_WAIT_TIME_SECS	60
6835 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
6836 	int rval;
6837 	int retry_cnt;
6838 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6839 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6840 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
6841 	sata_drive_info_t *sdinfo;
6842 
6843 	/*
6844 	 * Before returning good status, probe device.
6845 	 * Device probing will get IDENTIFY DEVICE data, if possible.
6846 	 * The assumption is that the new microcode is applied by the
6847 	 * device. It is a caller responsibility to verify this.
6848 	 */
6849 	for (retry_cnt = 0;
6850 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
6851 	    retry_cnt++) {
6852 		rval = sata_probe_device(sata_hba_inst, &sata_device);
6853 
6854 		if (rval == SATA_SUCCESS) { /* Set default features */
6855 			sdinfo = sata_get_device_info(sata_hba_inst,
6856 			    &sata_device);
6857 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
6858 			    SATA_SUCCESS) {
6859 				/* retry */
6860 				rval = sata_initialize_device(sata_hba_inst,
6861 				    sdinfo);
6862 				if (rval == SATA_RETRY)
6863 					sata_log(sata_hba_inst, CE_WARN,
6864 					    "SATA device at port %d pmport %d -"
6865 					    " default device features could not"
6866 					    " be set. Device may not operate "
6867 					    "as expected.",
6868 					    sata_device.satadev_addr.cport,
6869 					    sata_device.satadev_addr.pmport);
6870 			}
6871 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6872 				scsi_hba_pkt_comp(scsipkt);
6873 			return;
6874 		} else if (rval == SATA_RETRY) {
6875 			delay(drv_usectohz(1000000 *
6876 			    DOWNLOAD_WAIT_INTERVAL_SECS));
6877 			continue;
6878 		} else	/* failed - no reason to retry */
6879 			break;
6880 	}
6881 
6882 	/*
6883 	 * Something went wrong, device probing failed.
6884 	 */
6885 	SATA_LOG_D((sata_hba_inst, CE_WARN,
6886 	    "Cannot probe device after downloading microcode\n"));
6887 
6888 	/* Reset device to force retrying the probe. */
6889 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
6890 	    (SATA_DIP(sata_hba_inst), &sata_device);
6891 
6892 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6893 		scsi_hba_pkt_comp(scsipkt);
6894 }
6895 
6896 
6897 /*
6898  * Translate command: Synchronize Cache.
6899  * Translates into Flush Cache command for SATA hard disks.
6900  *
6901  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6902  * appropriate values in scsi_pkt fields.
6903  */
6904 static int
6905 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
6906 {
6907 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6908 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
6909 	int rval, reason;
6910 	int synch;
6911 
6912 	mutex_enter(cport_mutex);
6913 
6914 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6915 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6916 		mutex_exit(cport_mutex);
6917 		return (rval);
6918 	}
6919 
6920 	scmd->satacmd_addr_type = 0;
6921 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
6922 	scmd->satacmd_device_reg = 0;
6923 	scmd->satacmd_sec_count_lsb = 0;
6924 	scmd->satacmd_lba_low_lsb = 0;
6925 	scmd->satacmd_lba_mid_lsb = 0;
6926 	scmd->satacmd_lba_high_lsb = 0;
6927 	scmd->satacmd_features_reg = 0;
6928 	scmd->satacmd_status_reg = 0;
6929 	scmd->satacmd_error_reg = 0;
6930 
6931 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6932 	    "sata_txlt_synchronize_cache\n", NULL);
6933 
6934 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6935 		/* Need to set-up a callback function */
6936 		spx->txlt_sata_pkt->satapkt_comp =
6937 		    sata_txlt_nodata_cmd_completion;
6938 		synch = FALSE;
6939 	} else
6940 		synch = TRUE;
6941 
6942 	/* Transfer command to HBA */
6943 	if (sata_hba_start(spx, &rval) != 0) {
6944 		/* Pkt not accepted for execution */
6945 		mutex_exit(cport_mutex);
6946 		return (rval);
6947 	}
6948 	mutex_exit(cport_mutex);
6949 
6950 	/*
6951 	 * If execution non-synchronous, it had to be completed
6952 	 * a callback function will handle potential errors, translate
6953 	 * the response and will do a callback to a target driver.
6954 	 * If it was synchronous, check status, using the same
6955 	 * framework callback.
6956 	 */
6957 	if (synch) {
6958 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6959 		    "synchronous execution status %x\n",
6960 		    spx->txlt_sata_pkt->satapkt_reason);
6961 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
6962 	}
6963 	return (TRAN_ACCEPT);
6964 }
6965 
6966 
6967 /*
6968  * Send pkt to SATA HBA driver
6969  *
6970  * This function may be called only if the operation is requested by scsi_pkt,
6971  * i.e. scsi_pkt is not NULL.
6972  *
6973  * This function has to be called with cport mutex held. It does release
6974  * the mutex when it calls HBA driver sata_tran_start function and
6975  * re-acquires it afterwards.
6976  *
6977  * If return value is 0, pkt was accepted, -1 otherwise
6978  * rval is set to appropriate sata_scsi_start return value.
6979  *
6980  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
6981  * have called the sata_pkt callback function for this packet.
6982  *
6983  * The scsi callback has to be performed by the caller of this routine.
6984  */
6985 static int
6986 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
6987 {
6988 	int stat;
6989 	uint8_t cport = SATA_TXLT_CPORT(spx);
6990 	uint8_t pmport = SATA_TXLT_PMPORT(spx);
6991 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6992 	sata_drive_info_t *sdinfo;
6993 	sata_pmult_info_t *pminfo;
6994 	sata_pmport_info_t *pmportinfo = NULL;
6995 	sata_device_t *sata_device = NULL;
6996 	uint8_t cmd;
6997 	struct sata_cmd_flags cmd_flags;
6998 
6999 	ASSERT(spx->txlt_sata_pkt != NULL);
7000 
7001 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
7002 
7003 	sdinfo = sata_get_device_info(sata_hba_inst,
7004 	    &spx->txlt_sata_pkt->satapkt_device);
7005 	ASSERT(sdinfo != NULL);
7006 
7007 	/* Clear device reset state? */
7008 	/* qual should be XXX_DPMPORT, but add XXX_PMPORT in case */
7009 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT ||
7010 	    sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT) {
7011 
7012 		/*
7013 		 * Get the pmult_info of the its parent port multiplier, all
7014 		 * sub-devices share a common device reset flags on in
7015 		 * pmult_info.
7016 		 */
7017 		pminfo = SATA_PMULT_INFO(sata_hba_inst, cport);
7018 		pmportinfo = pminfo->pmult_dev_port[pmport];
7019 		ASSERT(pminfo != NULL);
7020 		if (pminfo->pmult_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
7021 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
7022 			    sata_clear_dev_reset = B_TRUE;
7023 			pminfo->pmult_event_flags &=
7024 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
7025 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
7026 			    "sata_hba_start: clearing device reset state"
7027 			    "on pmult.\n", NULL);
7028 		}
7029 	} else {
7030 		if (sdinfo->satadrv_event_flags &
7031 		    SATA_EVNT_CLEAR_DEVICE_RESET) {
7032 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
7033 			    sata_clear_dev_reset = B_TRUE;
7034 			sdinfo->satadrv_event_flags &=
7035 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
7036 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
7037 			    "sata_hba_start: clearing device reset state\n",
7038 			    NULL);
7039 		}
7040 	}
7041 
7042 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
7043 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
7044 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
7045 
7046 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
7047 
7048 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7049 	    "Sata cmd 0x%2x\n", cmd);
7050 
7051 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
7052 	    spx->txlt_sata_pkt);
7053 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
7054 	/*
7055 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
7056 	 * with the sata callback, the sata_pkt could be already destroyed
7057 	 * by the time we check ther return status from the hba_start()
7058 	 * function, because sata_scsi_destroy_pkt() could have been already
7059 	 * called (perhaps in the interrupt context). So, in such case, there
7060 	 * should be no references to it. In other cases, sata_pkt still
7061 	 * exists.
7062 	 */
7063 	if (stat == SATA_TRAN_ACCEPTED) {
7064 		/*
7065 		 * pkt accepted for execution.
7066 		 * If it was executed synchronously, it is already completed
7067 		 * and pkt completion_reason indicates completion status.
7068 		 */
7069 		*rval = TRAN_ACCEPT;
7070 		return (0);
7071 	}
7072 
7073 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
7074 	switch (stat) {
7075 	case SATA_TRAN_QUEUE_FULL:
7076 		/*
7077 		 * Controller detected queue full condition.
7078 		 */
7079 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
7080 		    "sata_hba_start: queue full\n", NULL);
7081 
7082 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
7083 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
7084 
7085 		*rval = TRAN_BUSY;
7086 		break;
7087 
7088 	case SATA_TRAN_PORT_ERROR:
7089 		/*
7090 		 * Communication/link with device or general port error
7091 		 * detected before pkt execution begun.
7092 		 */
7093 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
7094 		    SATA_ADDR_CPORT ||
7095 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
7096 		    SATA_ADDR_DCPORT)
7097 			sata_log(sata_hba_inst, CE_CONT,
7098 			    "SATA port %d error",
7099 			    sata_device->satadev_addr.cport);
7100 		else
7101 			sata_log(sata_hba_inst, CE_CONT,
7102 			    "SATA port %d:%d error\n",
7103 			    sata_device->satadev_addr.cport,
7104 			    sata_device->satadev_addr.pmport);
7105 
7106 		/*
7107 		 * Update the port/device structure.
7108 		 * sata_pkt should be still valid. Since port error is
7109 		 * returned, sata_device content should reflect port
7110 		 * state - it means, that sata address have been changed,
7111 		 * because original packet's sata address refered to a device
7112 		 * attached to some port.
7113 		 */
7114 		if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT ||
7115 		    sata_device->satadev_addr.qual == SATA_ADDR_PMPORT) {
7116 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
7117 			mutex_enter(&pmportinfo->pmport_mutex);
7118 			sata_update_pmport_info(sata_hba_inst, sata_device);
7119 			mutex_exit(&pmportinfo->pmport_mutex);
7120 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
7121 		} else {
7122 			sata_update_port_info(sata_hba_inst, sata_device);
7123 		}
7124 
7125 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
7126 		*rval = TRAN_FATAL_ERROR;
7127 		break;
7128 
7129 	case SATA_TRAN_CMD_UNSUPPORTED:
7130 		/*
7131 		 * Command rejected by HBA as unsupported. It was HBA driver
7132 		 * that rejected the command, command was not sent to
7133 		 * an attached device.
7134 		 */
7135 		if ((sdinfo != NULL) &&
7136 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
7137 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
7138 			    "sat_hba_start: cmd 0x%2x rejected "
7139 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
7140 
7141 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
7142 		(void) sata_txlt_invalid_command(spx);
7143 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
7144 
7145 		*rval = TRAN_ACCEPT;
7146 		break;
7147 
7148 	case SATA_TRAN_BUSY:
7149 		/*
7150 		 * Command rejected by HBA because other operation prevents
7151 		 * accepting the packet, or device is in RESET condition.
7152 		 */
7153 		if (sdinfo != NULL) {
7154 			sdinfo->satadrv_state =
7155 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
7156 
7157 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
7158 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
7159 				    "sata_hba_start: cmd 0x%2x rejected "
7160 				    "because of device reset condition\n",
7161 				    cmd);
7162 			} else {
7163 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
7164 				    "sata_hba_start: cmd 0x%2x rejected "
7165 				    "with SATA_TRAN_BUSY status\n",
7166 				    cmd);
7167 			}
7168 		}
7169 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
7170 		*rval = TRAN_BUSY;
7171 		break;
7172 
7173 	default:
7174 		/* Unrecognized HBA response */
7175 		SATA_LOG_D((sata_hba_inst, CE_WARN,
7176 		    "sata_hba_start: unrecognized HBA response "
7177 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
7178 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
7179 		*rval = TRAN_FATAL_ERROR;
7180 		break;
7181 	}
7182 
7183 	/*
7184 	 * If we got here, the packet was rejected.
7185 	 * Check if we need to remember reset state clearing request
7186 	 */
7187 	if (cmd_flags.sata_clear_dev_reset) {
7188 		/*
7189 		 * Check if device is still configured - it may have
7190 		 * disapeared from the configuration
7191 		 */
7192 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
7193 		if (sdinfo != NULL) {
7194 			/*
7195 			 * Restore the flag that requests clearing of
7196 			 * the device reset state,
7197 			 * so the next sata packet may carry it to HBA.
7198 			 */
7199 			if (sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT ||
7200 			    sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT) {
7201 				pminfo->pmult_event_flags |=
7202 				    SATA_EVNT_CLEAR_DEVICE_RESET;
7203 			} else {
7204 				sdinfo->satadrv_event_flags |=
7205 				    SATA_EVNT_CLEAR_DEVICE_RESET;
7206 			}
7207 		}
7208 	}
7209 	return (-1);
7210 }
7211 
7212 /*
7213  * Scsi response setup for invalid LBA
7214  *
7215  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
7216  */
7217 static int
7218 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
7219 {
7220 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7221 	struct scsi_extended_sense *sense;
7222 
7223 	scsipkt->pkt_reason = CMD_CMPLT;
7224 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7225 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7226 	*scsipkt->pkt_scbp = STATUS_CHECK;
7227 
7228 	*scsipkt->pkt_scbp = STATUS_CHECK;
7229 	sense = sata_arq_sense(spx);
7230 	sense->es_key = KEY_ILLEGAL_REQUEST;
7231 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
7232 
7233 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7234 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7235 
7236 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
7237 	    scsipkt->pkt_comp != NULL) {
7238 		/* scsi callback required */
7239 		if (servicing_interrupt()) {
7240 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7241 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7242 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
7243 			    TASKQID_INVALID) {
7244 				return (TRAN_BUSY);
7245 			}
7246 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7247 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7248 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
7249 			/* Scheduling the callback failed */
7250 			return (TRAN_BUSY);
7251 		}
7252 	}
7253 	return (TRAN_ACCEPT);
7254 }
7255 
7256 
7257 /*
7258  * Analyze device status and error registers and translate them into
7259  * appropriate scsi sense codes.
7260  * NOTE: non-packet commands only for now
7261  */
7262 static void
7263 sata_decode_device_error(sata_pkt_txlate_t *spx,
7264     struct scsi_extended_sense *sense)
7265 {
7266 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
7267 
7268 	ASSERT(sense != NULL);
7269 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
7270 	    SATA_STATUS_ERR);
7271 
7272 
7273 	if (err_reg & SATA_ERROR_ICRC) {
7274 		sense->es_key = KEY_ABORTED_COMMAND;
7275 		sense->es_add_code = 0x08; /* Communication failure */
7276 		return;
7277 	}
7278 
7279 	if (err_reg & SATA_ERROR_UNC) {
7280 		sense->es_key = KEY_MEDIUM_ERROR;
7281 		/* Information bytes (LBA) need to be set by a caller */
7282 		return;
7283 	}
7284 
7285 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
7286 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
7287 		sense->es_key = KEY_UNIT_ATTENTION;
7288 		sense->es_add_code = 0x3a; /* No media present */
7289 		return;
7290 	}
7291 
7292 	if (err_reg & SATA_ERROR_IDNF) {
7293 		if (err_reg & SATA_ERROR_ABORT) {
7294 			sense->es_key = KEY_ABORTED_COMMAND;
7295 		} else {
7296 			sense->es_key = KEY_ILLEGAL_REQUEST;
7297 			sense->es_add_code = 0x21; /* LBA out of range */
7298 		}
7299 		return;
7300 	}
7301 
7302 	if (err_reg & SATA_ERROR_ABORT) {
7303 		ASSERT(spx->txlt_sata_pkt != NULL);
7304 		sense->es_key = KEY_ABORTED_COMMAND;
7305 		return;
7306 	}
7307 }
7308 
7309 /*
7310  * Extract error LBA from sata_pkt.satapkt_cmd register fields
7311  */
7312 static void
7313 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
7314 {
7315 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
7316 
7317 	*lba = 0;
7318 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
7319 		*lba = sata_cmd->satacmd_lba_high_msb;
7320 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
7321 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
7322 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
7323 		*lba = sata_cmd->satacmd_device_reg & 0xf;
7324 	}
7325 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
7326 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
7327 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
7328 }
7329 
7330 /*
7331  * This is fixed sense format - if LBA exceeds the info field size,
7332  * no valid info will be returned (valid bit in extended sense will
7333  * be set to 0).
7334  */
7335 static struct scsi_extended_sense *
7336 sata_arq_sense(sata_pkt_txlate_t *spx)
7337 {
7338 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7339 	struct scsi_arq_status *arqs;
7340 	struct scsi_extended_sense *sense;
7341 
7342 	/* Fill ARQ sense data */
7343 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7344 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
7345 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
7346 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
7347 	arqs->sts_rqpkt_reason = CMD_CMPLT;
7348 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7349 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7350 	arqs->sts_rqpkt_resid = 0;
7351 	sense = &arqs->sts_sensedata;
7352 	bzero(sense, sizeof (struct scsi_extended_sense));
7353 	sata_fixed_sense_data_preset(sense);
7354 	return (sense);
7355 }
7356 
7357 /*
7358  * ATA Pass Through support
7359  * Sets flags indicating that an invalid value was found in some
7360  * field in the command.  It could be something illegal according to
7361  * the SAT-2 spec or it could be a feature that is not (yet?)
7362  * supported.
7363  */
7364 static int
7365 sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *spx)
7366 {
7367 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7368 	struct scsi_extended_sense *sense = sata_arq_sense(spx);
7369 
7370 	scsipkt->pkt_reason = CMD_CMPLT;
7371 	*scsipkt->pkt_scbp = STATUS_CHECK;
7372 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7373 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7374 
7375 	sense = sata_arq_sense(spx);
7376 	sense->es_key = KEY_ILLEGAL_REQUEST;
7377 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7378 
7379 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
7380 	    scsipkt->pkt_comp != NULL) {
7381 		/* scsi callback required */
7382 		if (servicing_interrupt()) {
7383 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7384 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7385 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
7386 			    TASKQID_INVALID) {
7387 				return (TRAN_BUSY);
7388 			}
7389 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7390 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7391 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
7392 			/* Scheduling the callback failed */
7393 			return (TRAN_BUSY);
7394 		}
7395 	}
7396 
7397 	return (TRAN_ACCEPT);
7398 }
7399 
7400 /*
7401  * The UNMAP command considers it not to be an error if the parameter length
7402  * or block descriptor length is 0.  For this case, there is nothing for TRIM
7403  * to do so just complete the command.
7404  */
7405 static int
7406 sata_txlt_unmap_nodata_cmd(sata_pkt_txlate_t *spx)
7407 {
7408 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7409 
7410 	scsipkt->pkt_reason = CMD_CMPLT;
7411 	*scsipkt->pkt_scbp = STATUS_GOOD;
7412 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7413 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7414 
7415 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
7416 	    scsipkt->pkt_comp != NULL) {
7417 		/* scsi callback required */
7418 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7419 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7420 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
7421 			/* Scheduling the callback failed */
7422 			return (TRAN_BUSY);
7423 		}
7424 	}
7425 
7426 	return (TRAN_ACCEPT);
7427 }
7428 
7429 /*
7430  * Emulated SATA Read/Write command completion for zero-length requests.
7431  * This request always succedes, so in synchronous mode it always returns
7432  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
7433  * callback cannot be scheduled.
7434  */
7435 static int
7436 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
7437 {
7438 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7439 
7440 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7441 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7442 	scsipkt->pkt_reason = CMD_CMPLT;
7443 	*scsipkt->pkt_scbp = STATUS_GOOD;
7444 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
7445 		/* scsi callback required - have to schedule it */
7446 		if (servicing_interrupt()) {
7447 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7448 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7449 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
7450 			    TASKQID_INVALID) {
7451 				return (TRAN_BUSY);
7452 			}
7453 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7454 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7455 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == TASKQID_INVALID) {
7456 			/* Scheduling the callback failed */
7457 			return (TRAN_BUSY);
7458 		}
7459 	}
7460 	return (TRAN_ACCEPT);
7461 }
7462 
7463 
7464 /*
7465  * Translate completion status of SATA read/write commands into scsi response.
7466  * pkt completion_reason is checked to determine the completion status.
7467  * Do scsi callback if necessary.
7468  *
7469  * Note: this function may be called also for synchronously executed
7470  * commands.
7471  * This function may be used only if scsi_pkt is non-NULL.
7472  */
7473 static void
7474 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
7475 {
7476 	sata_pkt_txlate_t *spx =
7477 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7478 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7479 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7480 	struct scsi_extended_sense *sense;
7481 	uint64_t lba;
7482 	struct buf *bp;
7483 	int rval;
7484 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7485 		/* Normal completion */
7486 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7487 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
7488 		scsipkt->pkt_reason = CMD_CMPLT;
7489 		*scsipkt->pkt_scbp = STATUS_GOOD;
7490 		if (spx->txlt_tmp_buf != NULL) {
7491 			/* Temporary buffer was used */
7492 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7493 			if (bp->b_flags & B_READ) {
7494 				rval = ddi_dma_sync(
7495 				    spx->txlt_buf_dma_handle, 0, 0,
7496 				    DDI_DMA_SYNC_FORCPU);
7497 				ASSERT(rval == DDI_SUCCESS);
7498 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7499 				    bp->b_bcount);
7500 			}
7501 		}
7502 	} else {
7503 		/*
7504 		 * Something went wrong - analyze return
7505 		 */
7506 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7507 		    STATE_SENT_CMD | STATE_GOT_STATUS;
7508 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7509 		*scsipkt->pkt_scbp = STATUS_CHECK;
7510 		sense = sata_arq_sense(spx);
7511 		ASSERT(sense != NULL);
7512 
7513 		/*
7514 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
7515 		 * extract from device registers the failing LBA.
7516 		 */
7517 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
7518 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
7519 			    (scmd->satacmd_lba_mid_msb != 0 ||
7520 			    scmd->satacmd_lba_high_msb != 0)) {
7521 				/*
7522 				 * We have problem reporting this cmd LBA
7523 				 * in fixed sense data format, because of
7524 				 * the size of the scsi LBA fields.
7525 				 */
7526 				sense->es_valid = 0;
7527 			} else {
7528 				sata_extract_error_lba(spx, &lba);
7529 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
7530 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
7531 				sense->es_info_3 = (lba & 0xFF00) >> 8;
7532 				sense->es_info_4 = lba & 0xFF;
7533 			}
7534 		} else {
7535 			/* Invalid extended sense info */
7536 			sense->es_valid = 0;
7537 		}
7538 
7539 		switch (sata_pkt->satapkt_reason) {
7540 		case SATA_PKT_PORT_ERROR:
7541 			/* We may want to handle DEV GONE state as well */
7542 			/*
7543 			 * We have no device data. Assume no data transfered.
7544 			 */
7545 			sense->es_key = KEY_HARDWARE_ERROR;
7546 			break;
7547 
7548 		case SATA_PKT_DEV_ERROR:
7549 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7550 			    SATA_STATUS_ERR) {
7551 				/*
7552 				 * determine dev error reason from error
7553 				 * reg content
7554 				 */
7555 				sata_decode_device_error(spx, sense);
7556 				if (sense->es_key == KEY_MEDIUM_ERROR) {
7557 					switch (scmd->satacmd_cmd_reg) {
7558 					case SATAC_READ_DMA:
7559 					case SATAC_READ_DMA_EXT:
7560 					case SATAC_READ_DMA_QUEUED:
7561 					case SATAC_READ_DMA_QUEUED_EXT:
7562 					case SATAC_READ_FPDMA_QUEUED:
7563 						/* Unrecovered read error */
7564 						sense->es_add_code =
7565 						    SD_SCSI_ASC_UNREC_READ_ERR;
7566 						break;
7567 					case SATAC_WRITE_DMA:
7568 					case SATAC_WRITE_DMA_EXT:
7569 					case SATAC_WRITE_DMA_QUEUED:
7570 					case SATAC_WRITE_DMA_QUEUED_EXT:
7571 					case SATAC_WRITE_FPDMA_QUEUED:
7572 						/* Write error */
7573 						sense->es_add_code =
7574 						    SD_SCSI_ASC_WRITE_ERR;
7575 						break;
7576 					default:
7577 						/* Internal error */
7578 						SATA_LOG_D((
7579 						    spx->txlt_sata_hba_inst,
7580 						    CE_WARN,
7581 						    "sata_txlt_rw_completion :"
7582 						    "internal error - invalid "
7583 						    "command 0x%2x",
7584 						    scmd->satacmd_cmd_reg));
7585 						break;
7586 					}
7587 				}
7588 				break;
7589 			}
7590 			/* No extended sense key - no info available */
7591 			scsipkt->pkt_reason = CMD_INCOMPLETE;
7592 			break;
7593 
7594 		case SATA_PKT_TIMEOUT:
7595 			scsipkt->pkt_reason = CMD_TIMEOUT;
7596 			scsipkt->pkt_statistics |=
7597 			    STAT_TIMEOUT | STAT_DEV_RESET;
7598 			sense->es_key = KEY_ABORTED_COMMAND;
7599 			break;
7600 
7601 		case SATA_PKT_ABORTED:
7602 			scsipkt->pkt_reason = CMD_ABORTED;
7603 			scsipkt->pkt_statistics |= STAT_ABORTED;
7604 			sense->es_key = KEY_ABORTED_COMMAND;
7605 			break;
7606 
7607 		case SATA_PKT_RESET:
7608 			scsipkt->pkt_reason = CMD_RESET;
7609 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7610 			sense->es_key = KEY_ABORTED_COMMAND;
7611 			break;
7612 
7613 		default:
7614 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7615 			    "sata_txlt_rw_completion: "
7616 			    "invalid packet completion reason"));
7617 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7618 			break;
7619 		}
7620 	}
7621 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7622 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7623 
7624 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7625 		/* scsi callback required */
7626 		scsi_hba_pkt_comp(scsipkt);
7627 }
7628 
7629 
7630 /*
7631  * Translate completion status of non-data commands (i.e. commands returning
7632  * no data).
7633  * pkt completion_reason is checked to determine the completion status.
7634  * Do scsi callback if necessary (FLAG_NOINTR == 0)
7635  *
7636  * Note: this function may be called also for synchronously executed
7637  * commands.
7638  * This function may be used only if scsi_pkt is non-NULL.
7639  */
7640 
7641 static	void
7642 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
7643 {
7644 	sata_pkt_txlate_t *spx =
7645 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7646 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7647 
7648 	sata_set_arq_data(sata_pkt);
7649 
7650 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7651 		/* scsi callback required */
7652 		scsi_hba_pkt_comp(scsipkt);
7653 }
7654 
7655 /*
7656  * Completion handler for ATA Pass Through command
7657  */
7658 static void
7659 sata_txlt_apt_completion(sata_pkt_t *sata_pkt)
7660 {
7661 	sata_pkt_txlate_t *spx =
7662 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7663 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7664 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7665 	struct buf *bp;
7666 	uint8_t sense_key = 0, addl_sense_code = 0, addl_sense_qual = 0;
7667 
7668 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7669 		/* Normal completion */
7670 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7671 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
7672 		scsipkt->pkt_reason = CMD_CMPLT;
7673 		*scsipkt->pkt_scbp = STATUS_GOOD;
7674 
7675 		/*
7676 		 * If the command has CK_COND set
7677 		 */
7678 		if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
7679 			*scsipkt->pkt_scbp = STATUS_CHECK;
7680 			sata_fill_ata_return_desc(sata_pkt,
7681 			    KEY_RECOVERABLE_ERROR,
7682 			    SD_SCSI_ASC_APT_INFO_AVAIL, 0x1d);
7683 		}
7684 
7685 		if (spx->txlt_tmp_buf != NULL) {
7686 			/* Temporary buffer was used */
7687 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7688 			if (bp->b_flags & B_READ) {
7689 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7690 				    bp->b_bcount);
7691 			}
7692 		}
7693 	} else {
7694 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7695 		    STATE_SENT_CMD | STATE_GOT_STATUS;
7696 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7697 		*scsipkt->pkt_scbp = STATUS_CHECK;
7698 
7699 		/*
7700 		 * If DF or ERR was set, the HBA should have copied out the
7701 		 * status and error registers to the satacmd structure.
7702 		 */
7703 		if (scmd->satacmd_status_reg & SATA_STATUS_DF) {
7704 			sense_key = KEY_HARDWARE_ERROR;
7705 			addl_sense_code = SD_SCSI_ASC_INTERNAL_TARGET_FAILURE;
7706 			addl_sense_qual = 0;
7707 		} else if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
7708 			if (scmd->satacmd_error_reg & SATA_ERROR_NM) {
7709 				sense_key = KEY_NOT_READY;
7710 				addl_sense_code =
7711 				    SD_SCSI_ASC_MEDIUM_NOT_PRESENT;
7712 				addl_sense_qual = 0;
7713 			} else if (scmd->satacmd_error_reg & SATA_ERROR_UNC) {
7714 				sense_key = KEY_MEDIUM_ERROR;
7715 				addl_sense_code = SD_SCSI_ASC_UNREC_READ_ERR;
7716 				addl_sense_qual = 0;
7717 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ILI) {
7718 				sense_key = KEY_DATA_PROTECT;
7719 				addl_sense_code = SD_SCSI_ASC_WRITE_PROTECTED;
7720 				addl_sense_qual = 0;
7721 			} else if (scmd->satacmd_error_reg & SATA_ERROR_IDNF) {
7722 				sense_key = KEY_ILLEGAL_REQUEST;
7723 				addl_sense_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
7724 				addl_sense_qual = 0;
7725 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
7726 				sense_key = KEY_ABORTED_COMMAND;
7727 				addl_sense_code = SD_SCSI_ASC_NO_ADD_SENSE;
7728 				addl_sense_qual = 0;
7729 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MC) {
7730 				sense_key = KEY_UNIT_ATTENTION;
7731 				addl_sense_code =
7732 				    SD_SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED;
7733 				addl_sense_qual = 0;
7734 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MCR) {
7735 				sense_key = KEY_UNIT_ATTENTION;
7736 				addl_sense_code = SD_SCSI_ASC_OP_MEDIUM_REM_REQ;
7737 				addl_sense_qual = 0;
7738 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ICRC) {
7739 				sense_key = KEY_ABORTED_COMMAND;
7740 				addl_sense_code =
7741 				    SD_SCSI_ASC_INFO_UNIT_IUCRC_ERR;
7742 				addl_sense_qual = 0;
7743 			}
7744 		}
7745 
7746 		sata_fill_ata_return_desc(sata_pkt, sense_key, addl_sense_code,
7747 		    addl_sense_qual);
7748 	}
7749 
7750 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7751 		/* scsi callback required */
7752 		scsi_hba_pkt_comp(scsipkt);
7753 }
7754 
7755 /*
7756  * Completion handler for unmap translation command
7757  */
7758 static void
7759 sata_txlt_unmap_completion(sata_pkt_t *sata_pkt)
7760 {
7761 	sata_pkt_txlate_t *spx =
7762 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7763 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7764 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7765 	struct buf *bp;
7766 	uint8_t sense_key = 0, addl_sense_code = 0, addl_sense_qual = 0;
7767 
7768 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7769 		/* Normal completion */
7770 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7771 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
7772 		scsipkt->pkt_reason = CMD_CMPLT;
7773 		*scsipkt->pkt_scbp = STATUS_GOOD;
7774 
7775 		if (spx->txlt_tmp_buf != NULL) {
7776 			/* Temporary buffer was used */
7777 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7778 			if (bp->b_flags & B_READ) {
7779 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7780 				    bp->b_bcount);
7781 			}
7782 		}
7783 	} else {
7784 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7785 		    STATE_SENT_CMD | STATE_GOT_STATUS;
7786 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7787 		*scsipkt->pkt_scbp = STATUS_CHECK;
7788 
7789 		/*
7790 		 * If DF or ERR was set, the HBA should have copied out the
7791 		 * status and error registers to the satacmd structure.
7792 		 */
7793 		if (scmd->satacmd_status_reg & SATA_STATUS_DF) {
7794 			sense_key = KEY_HARDWARE_ERROR;
7795 			addl_sense_code = SD_SCSI_ASC_INTERNAL_TARGET_FAILURE;
7796 			addl_sense_qual = 0;
7797 		} else if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
7798 			if (scmd->satacmd_error_reg & SATA_ERROR_NM) {
7799 				sense_key = KEY_NOT_READY;
7800 				addl_sense_code =
7801 				    SD_SCSI_ASC_MEDIUM_NOT_PRESENT;
7802 				addl_sense_qual = 0;
7803 			} else if (scmd->satacmd_error_reg & SATA_ERROR_UNC) {
7804 				sense_key = KEY_MEDIUM_ERROR;
7805 				addl_sense_code = SD_SCSI_ASC_WRITE_ERR;
7806 				addl_sense_qual = 0;
7807 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ILI) {
7808 				sense_key = KEY_DATA_PROTECT;
7809 				addl_sense_code = SD_SCSI_ASC_WRITE_PROTECTED;
7810 				addl_sense_qual = 0;
7811 			} else if (scmd->satacmd_error_reg & SATA_ERROR_IDNF) {
7812 				sense_key = KEY_ILLEGAL_REQUEST;
7813 				addl_sense_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
7814 				addl_sense_qual = 0;
7815 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
7816 				sense_key = KEY_ABORTED_COMMAND;
7817 				addl_sense_code = SD_SCSI_ASC_NO_ADD_SENSE;
7818 				addl_sense_qual = 0;
7819 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MC) {
7820 				sense_key = KEY_UNIT_ATTENTION;
7821 				addl_sense_code =
7822 				    SD_SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED;
7823 				addl_sense_qual = 0;
7824 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MCR) {
7825 				sense_key = KEY_UNIT_ATTENTION;
7826 				addl_sense_code = SD_SCSI_ASC_OP_MEDIUM_REM_REQ;
7827 				addl_sense_qual = 0;
7828 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ICRC) {
7829 				sense_key = KEY_ABORTED_COMMAND;
7830 				addl_sense_code =
7831 				    SD_SCSI_ASC_INFO_UNIT_IUCRC_ERR;
7832 				addl_sense_qual = 0;
7833 			}
7834 		}
7835 
7836 		sata_fill_ata_return_desc(sata_pkt, sense_key, addl_sense_code,
7837 		    addl_sense_qual);
7838 	}
7839 
7840 	sata_free_local_buffer(spx);
7841 
7842 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7843 		/* scsi callback required */
7844 		scsi_hba_pkt_comp(scsipkt);
7845 }
7846 
7847 /*
7848  *
7849  */
7850 static void
7851 sata_fill_ata_return_desc(sata_pkt_t *sata_pkt, uint8_t sense_key,
7852     uint8_t addl_sense_code, uint8_t addl_sense_qual)
7853 {
7854 	sata_pkt_txlate_t *spx =
7855 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7856 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7857 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7858 	struct sata_apt_sense_data *apt_sd =
7859 	    (struct sata_apt_sense_data *)scsipkt->pkt_scbp;
7860 	struct scsi_descr_sense_hdr *sds = &(apt_sd->apt_sd_hdr);
7861 	struct scsi_ata_status_ret_sense_descr *ata_ret_desc =
7862 	    &(apt_sd->apt_sd_sense);
7863 	int extend = 0;
7864 
7865 	if ((scsipkt->pkt_cdbp[0] == SPC3_CMD_ATA_COMMAND_PASS_THROUGH16) &&
7866 	    (scsipkt->pkt_cdbp[2] & SATL_APT_BM_EXTEND))
7867 		extend = 1;
7868 
7869 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7870 
7871 	/* update the residual count */
7872 	*(uchar_t *)&apt_sd->apt_status = STATUS_CHECK;
7873 	*(uchar_t *)&apt_sd->apt_rqpkt_status = STATUS_GOOD;
7874 	apt_sd->apt_rqpkt_reason = CMD_CMPLT;
7875 	apt_sd->apt_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7876 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7877 	apt_sd->apt_rqpkt_resid = scsipkt->pkt_scblen -
7878 	    sizeof (struct sata_apt_sense_data);
7879 
7880 	/*
7881 	 * Fill in the Descriptor sense header
7882 	 */
7883 	bzero(sds, sizeof (struct scsi_descr_sense_hdr));
7884 	sds->ds_code = CODE_FMT_DESCR_CURRENT;
7885 	sds->ds_class = CLASS_EXTENDED_SENSE;
7886 	sds->ds_key = sense_key & 0xf;
7887 	sds->ds_add_code = addl_sense_code;
7888 	sds->ds_qual_code = addl_sense_qual;
7889 	sds->ds_addl_sense_length =
7890 	    sizeof (struct scsi_ata_status_ret_sense_descr);
7891 
7892 	/*
7893 	 * Fill in the ATA Return descriptor sense data
7894 	 */
7895 	bzero(ata_ret_desc, sizeof (struct scsi_ata_status_ret_sense_descr));
7896 	ata_ret_desc->ars_descr_type = DESCR_ATA_STATUS_RETURN;
7897 	ata_ret_desc->ars_addl_length = 0xc;
7898 	ata_ret_desc->ars_error = scmd->satacmd_error_reg;
7899 	ata_ret_desc->ars_sec_count_lsb = scmd->satacmd_sec_count_lsb;
7900 	ata_ret_desc->ars_lba_low_lsb = scmd->satacmd_lba_low_lsb;
7901 	ata_ret_desc->ars_lba_mid_lsb = scmd->satacmd_lba_mid_lsb;
7902 	ata_ret_desc->ars_lba_high_lsb = scmd->satacmd_lba_high_lsb;
7903 	ata_ret_desc->ars_device = scmd->satacmd_device_reg;
7904 	ata_ret_desc->ars_status = scmd->satacmd_status_reg;
7905 
7906 	if (extend == 1) {
7907 		ata_ret_desc->ars_extend = 1;
7908 		ata_ret_desc->ars_sec_count_msb = scmd->satacmd_sec_count_msb;
7909 		ata_ret_desc->ars_lba_low_msb = scmd->satacmd_lba_low_msb;
7910 		ata_ret_desc->ars_lba_mid_msb = scmd->satacmd_lba_mid_msb;
7911 		ata_ret_desc->ars_lba_high_msb = scmd->satacmd_lba_high_msb;
7912 	} else {
7913 		ata_ret_desc->ars_extend = 0;
7914 		ata_ret_desc->ars_sec_count_msb = 0;
7915 		ata_ret_desc->ars_lba_low_msb = 0;
7916 		ata_ret_desc->ars_lba_mid_msb = 0;
7917 		ata_ret_desc->ars_lba_high_msb = 0;
7918 	}
7919 }
7920 
7921 static	void
7922 sata_set_arq_data(sata_pkt_t *sata_pkt)
7923 {
7924 	sata_pkt_txlate_t *spx =
7925 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7926 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7927 	struct scsi_extended_sense *sense;
7928 
7929 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7930 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7931 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7932 		/* Normal completion */
7933 		scsipkt->pkt_reason = CMD_CMPLT;
7934 		*scsipkt->pkt_scbp = STATUS_GOOD;
7935 	} else {
7936 		/* Something went wrong */
7937 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7938 		*scsipkt->pkt_scbp = STATUS_CHECK;
7939 		sense = sata_arq_sense(spx);
7940 		switch (sata_pkt->satapkt_reason) {
7941 		case SATA_PKT_PORT_ERROR:
7942 			/*
7943 			 * We have no device data. Assume no data transfered.
7944 			 */
7945 			sense->es_key = KEY_HARDWARE_ERROR;
7946 			break;
7947 
7948 		case SATA_PKT_DEV_ERROR:
7949 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7950 			    SATA_STATUS_ERR) {
7951 				/*
7952 				 * determine dev error reason from error
7953 				 * reg content
7954 				 */
7955 				sata_decode_device_error(spx, sense);
7956 				break;
7957 			}
7958 			/* No extended sense key - no info available */
7959 			break;
7960 
7961 		case SATA_PKT_TIMEOUT:
7962 			scsipkt->pkt_reason = CMD_TIMEOUT;
7963 			scsipkt->pkt_statistics |=
7964 			    STAT_TIMEOUT | STAT_DEV_RESET;
7965 			/* No extended sense key ? */
7966 			break;
7967 
7968 		case SATA_PKT_ABORTED:
7969 			scsipkt->pkt_reason = CMD_ABORTED;
7970 			scsipkt->pkt_statistics |= STAT_ABORTED;
7971 			/* No extended sense key ? */
7972 			break;
7973 
7974 		case SATA_PKT_RESET:
7975 			/* pkt aborted by an explicit reset from a host */
7976 			scsipkt->pkt_reason = CMD_RESET;
7977 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7978 			break;
7979 
7980 		default:
7981 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7982 			    "sata_txlt_nodata_cmd_completion: "
7983 			    "invalid packet completion reason %d",
7984 			    sata_pkt->satapkt_reason));
7985 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7986 			break;
7987 		}
7988 
7989 	}
7990 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7991 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7992 }
7993 
7994 
7995 /*
7996  * Build Mode sense R/W recovery page
7997  * NOT IMPLEMENTED
7998  */
7999 
8000 static int
8001 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
8002 {
8003 #ifndef __lock_lint
8004 	_NOTE(ARGUNUSED(sdinfo))
8005 	_NOTE(ARGUNUSED(pcntrl))
8006 	_NOTE(ARGUNUSED(buf))
8007 #endif
8008 	return (0);
8009 }
8010 
8011 /*
8012  * Build Mode sense caching page  -  scsi-3 implementation.
8013  * Page length distinguishes previous format from scsi-3 format.
8014  * buf must have space for 0x12 bytes.
8015  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
8016  *
8017  */
8018 static int
8019 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
8020 {
8021 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
8022 	sata_id_t *sata_id = &sdinfo->satadrv_id;
8023 
8024 	/*
8025 	 * Most of the fields are set to 0, being not supported and/or disabled
8026 	 */
8027 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
8028 
8029 	/* Saved paramters not supported */
8030 	if (pcntrl == 3)
8031 		return (0);
8032 	if (pcntrl == 0 || pcntrl == 2) {
8033 		/*
8034 		 * For now treat current and default parameters as same
8035 		 * That may have to change, if target driver will complain
8036 		 */
8037 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
8038 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
8039 
8040 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
8041 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
8042 			page->dra = 1;		/* Read Ahead disabled */
8043 			page->rcd = 1;		/* Read Cache disabled */
8044 		}
8045 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
8046 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
8047 			page->wce = 1;		/* Write Cache enabled */
8048 	} else {
8049 		/* Changeable parameters */
8050 		page->mode_page.code = MODEPAGE_CACHING;
8051 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
8052 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
8053 			page->dra = 1;
8054 			page->rcd = 1;
8055 		}
8056 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
8057 			page->wce = 1;
8058 	}
8059 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
8060 	    sizeof (struct mode_page));
8061 }
8062 
8063 /*
8064  * Build Mode sense exception cntrl page
8065  */
8066 static int
8067 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
8068 {
8069 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
8070 	sata_id_t *sata_id = &sdinfo->satadrv_id;
8071 
8072 	/*
8073 	 * Most of the fields are set to 0, being not supported and/or disabled
8074 	 */
8075 	bzero(buf, PAGELENGTH_INFO_EXCPT);
8076 
8077 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
8078 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
8079 
8080 	/* Indicate that this is page is saveable */
8081 	page->mode_page.ps = 1;
8082 
8083 	/*
8084 	 * We will return the same data for default, current and saved page.
8085 	 * The only changeable bit is dexcpt and that bit is required
8086 	 * by the ATA specification to be preserved across power cycles.
8087 	 */
8088 	if (pcntrl != 1) {
8089 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
8090 		page->mrie = MRIE_ONLY_ON_REQUEST;
8091 	}
8092 	else
8093 		page->dexcpt = 1;	/* Only changeable parameter */
8094 
8095 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page));
8096 }
8097 
8098 
8099 static int
8100 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
8101 {
8102 	struct mode_acoustic_management *page =
8103 	    (struct mode_acoustic_management *)buf;
8104 	sata_id_t *sata_id = &sdinfo->satadrv_id;
8105 
8106 	/*
8107 	 * Most of the fields are set to 0, being not supported and/or disabled
8108 	 */
8109 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
8110 
8111 	switch (pcntrl) {
8112 	case P_CNTRL_DEFAULT:
8113 		/*  default paramters not supported */
8114 		return (0);
8115 
8116 	case P_CNTRL_CURRENT:
8117 	case P_CNTRL_SAVED:
8118 		/* Saved and current are supported and are identical */
8119 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
8120 		page->mode_page.length =
8121 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
8122 		page->mode_page.ps = 1;
8123 
8124 		/* Word 83 indicates if feature is supported */
8125 		/* If feature is not supported */
8126 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
8127 			page->acoustic_manag_enable =
8128 			    ACOUSTIC_DISABLED;
8129 		} else {
8130 			page->acoustic_manag_enable =
8131 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
8132 			    != 0);
8133 			/* Word 94 inidicates the value */
8134 #ifdef	_LITTLE_ENDIAN
8135 			page->acoustic_manag_level =
8136 			    (uchar_t)sata_id->ai_acoustic;
8137 			page->vendor_recommended_value =
8138 			    sata_id->ai_acoustic >> 8;
8139 #else
8140 			page->acoustic_manag_level =
8141 			    sata_id->ai_acoustic >> 8;
8142 			page->vendor_recommended_value =
8143 			    (uchar_t)sata_id->ai_acoustic;
8144 #endif
8145 		}
8146 		break;
8147 
8148 	case P_CNTRL_CHANGEABLE:
8149 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
8150 		page->mode_page.length =
8151 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
8152 		page->mode_page.ps = 1;
8153 
8154 		/* Word 83 indicates if the feature is supported */
8155 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
8156 			page->acoustic_manag_enable =
8157 			    ACOUSTIC_ENABLED;
8158 			page->acoustic_manag_level = 0xff;
8159 		}
8160 		break;
8161 	}
8162 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
8163 	    sizeof (struct mode_page));
8164 }
8165 
8166 
8167 /*
8168  * Build Mode sense power condition page.
8169  */
8170 static int
8171 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
8172 {
8173 	struct mode_info_power_cond *page = (struct mode_info_power_cond *)buf;
8174 	sata_id_t *sata_id = &sdinfo->satadrv_id;
8175 
8176 	/*
8177 	 * Most of the fields are set to 0, being not supported and/or disabled
8178 	 * power condition page length was 0x0a
8179 	 */
8180 	bzero(buf, sizeof (struct mode_info_power_cond));
8181 
8182 	if (pcntrl == P_CNTRL_DEFAULT) {
8183 		/*  default paramters not supported */
8184 		return (0);
8185 	}
8186 
8187 	page->mode_page.code = MODEPAGE_POWER_COND;
8188 	page->mode_page.length = sizeof (struct mode_info_power_cond);
8189 
8190 	if (sata_id->ai_cap & SATA_STANDBYTIMER) {
8191 		page->standby = 1;
8192 		bcopy(sdinfo->satadrv_standby_timer, page->standby_cond_timer,
8193 		    sizeof (uchar_t) * 4);
8194 	}
8195 
8196 	return (sizeof (struct mode_info_power_cond));
8197 }
8198 
8199 /*
8200  * Process mode select caching page 8 (scsi3 format only).
8201  * Read Ahead (same as read cache) and Write Cache may be turned on and off
8202  * if these features are supported by the device. If these features are not
8203  * supported, the command will be terminated with STATUS_CHECK.
8204  * This function fails only if the SET FEATURE command sent to
8205  * the device fails. The page format is not verified, assuming that the
8206  * target driver operates correctly - if parameters length is too short,
8207  * we just drop the page.
8208  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
8209  * setting have to be changed.
8210  * SET FEATURE command is executed synchronously, i.e. we wait here until
8211  * it is completed, regardless of the scsi pkt directives.
8212  *
8213  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
8214  * changing DRA will change RCD.
8215  *
8216  * More than one SATA command may be executed to perform operations specified
8217  * by mode select pages. The first error terminates further execution.
8218  * Operations performed successully are not backed-up in such case.
8219  *
8220  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
8221  * If operation resulted in changing device setup, dmod flag should be set to
8222  * one (1). If parameters were not changed, dmod flag should be set to 0.
8223  * Upon return, if operation required sending command to the device, the rval
8224  * should be set to the value returned by sata_hba_start. If operation
8225  * did not require device access, rval should be set to TRAN_ACCEPT.
8226  * The pagelen should be set to the length of the page.
8227  *
8228  * This function has to be called with a port mutex held.
8229  *
8230  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
8231  */
8232 int
8233 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
8234     int parmlen, int *pagelen, int *rval, int *dmod)
8235 {
8236 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8237 	sata_drive_info_t *sdinfo;
8238 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8239 	sata_id_t *sata_id;
8240 	struct scsi_extended_sense *sense;
8241 	int wce, dra;	/* Current settings */
8242 
8243 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
8244 	    &spx->txlt_sata_pkt->satapkt_device);
8245 	sata_id = &sdinfo->satadrv_id;
8246 	*dmod = 0;
8247 
8248 	/* Verify parameters length. If too short, drop it */
8249 	if ((PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
8250 	    sizeof (struct mode_page)) > parmlen) {
8251 		*scsipkt->pkt_scbp = STATUS_CHECK;
8252 		sense = sata_arq_sense(spx);
8253 		sense->es_key = KEY_ILLEGAL_REQUEST;
8254 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8255 		*pagelen = parmlen;
8256 		*rval = TRAN_ACCEPT;
8257 		return (SATA_FAILURE);
8258 	}
8259 
8260 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
8261 
8262 	/* Current setting of Read Ahead (and Read Cache) */
8263 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
8264 		dra = 0;	/* 0 == not disabled */
8265 	else
8266 		dra = 1;
8267 	/* Current setting of Write Cache */
8268 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
8269 		wce = 1;
8270 	else
8271 		wce = 0;
8272 
8273 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
8274 		/* nothing to do */
8275 		*rval = TRAN_ACCEPT;
8276 		return (SATA_SUCCESS);
8277 	}
8278 
8279 	/*
8280 	 * Need to flip some setting
8281 	 * Set-up Internal SET FEATURES command(s)
8282 	 */
8283 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
8284 	scmd->satacmd_addr_type = 0;
8285 	scmd->satacmd_device_reg = 0;
8286 	scmd->satacmd_status_reg = 0;
8287 	scmd->satacmd_error_reg = 0;
8288 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
8289 	if (page->dra != dra || page->rcd != dra) {
8290 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
8291 			/* Need to flip read ahead setting */
8292 			if (dra == 0)
8293 				/* Disable read ahead / read cache */
8294 				scmd->satacmd_features_reg =
8295 				    SATAC_SF_DISABLE_READ_AHEAD;
8296 			else
8297 				/* Enable read ahead  / read cache */
8298 				scmd->satacmd_features_reg =
8299 				    SATAC_SF_ENABLE_READ_AHEAD;
8300 
8301 			/* Transfer command to HBA */
8302 			if (sata_hba_start(spx, rval) != 0)
8303 				/*
8304 				 * Pkt not accepted for execution.
8305 				 */
8306 				return (SATA_FAILURE);
8307 
8308 			*dmod = 1;
8309 
8310 			/* Now process return */
8311 			if (spx->txlt_sata_pkt->satapkt_reason !=
8312 			    SATA_PKT_COMPLETED) {
8313 				goto failure;	/* Terminate */
8314 			}
8315 		} else {
8316 			*scsipkt->pkt_scbp = STATUS_CHECK;
8317 			sense = sata_arq_sense(spx);
8318 			sense->es_key = KEY_ILLEGAL_REQUEST;
8319 			sense->es_add_code =
8320 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8321 			*pagelen = parmlen;
8322 			*rval = TRAN_ACCEPT;
8323 			return (SATA_FAILURE);
8324 		}
8325 	}
8326 
8327 	/* Note that the packet is not removed, so it could be re-used */
8328 	if (page->wce != wce) {
8329 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
8330 			/* Need to flip Write Cache setting */
8331 			if (page->wce == 1)
8332 				/* Enable write cache */
8333 				scmd->satacmd_features_reg =
8334 				    SATAC_SF_ENABLE_WRITE_CACHE;
8335 			else
8336 				/* Disable write cache */
8337 				scmd->satacmd_features_reg =
8338 				    SATAC_SF_DISABLE_WRITE_CACHE;
8339 
8340 			/* Transfer command to HBA */
8341 			if (sata_hba_start(spx, rval) != 0)
8342 				/*
8343 				 * Pkt not accepted for execution.
8344 				 */
8345 				return (SATA_FAILURE);
8346 
8347 			*dmod = 1;
8348 
8349 			/* Now process return */
8350 			if (spx->txlt_sata_pkt->satapkt_reason !=
8351 			    SATA_PKT_COMPLETED) {
8352 				goto failure;
8353 			}
8354 		} else {
8355 			*scsipkt->pkt_scbp = STATUS_CHECK;
8356 			sense = sata_arq_sense(spx);
8357 			sense->es_key = KEY_ILLEGAL_REQUEST;
8358 			sense->es_add_code =
8359 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8360 			*pagelen = parmlen;
8361 			*rval = TRAN_ACCEPT;
8362 			return (SATA_FAILURE);
8363 		}
8364 	}
8365 	return (SATA_SUCCESS);
8366 
8367 failure:
8368 	sata_xlate_errors(spx);
8369 
8370 	return (SATA_FAILURE);
8371 }
8372 
8373 /*
8374  * Process mode select informational exceptions control page 0x1c
8375  *
8376  * The only changeable bit is dexcpt (disable exceptions).
8377  * MRIE (method of reporting informational exceptions) must be
8378  * "only on request".
8379  * This page applies to informational exceptions that report
8380  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
8381  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
8382  * Informational exception conditions occur as the result of background scan
8383  * errors, background self-test errors, or vendor specific events within a
8384  * logical unit. An informational exception condition may occur asynchronous
8385  * to any commands.
8386  *
8387  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
8388  * If operation resulted in changing device setup, dmod flag should be set to
8389  * one (1). If parameters were not changed, dmod flag should be set to 0.
8390  * Upon return, if operation required sending command to the device, the rval
8391  * should be set to the value returned by sata_hba_start. If operation
8392  * did not require device access, rval should be set to TRAN_ACCEPT.
8393  * The pagelen should be set to the length of the page.
8394  *
8395  * This function has to be called with a port mutex held.
8396  *
8397  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
8398  *
8399  * Cannot be called in the interrupt context.
8400  */
8401 static	int
8402 sata_mode_select_page_1c(
8403 	sata_pkt_txlate_t *spx,
8404 	struct mode_info_excpt_page *page,
8405 	int parmlen,
8406 	int *pagelen,
8407 	int *rval,
8408 	int *dmod)
8409 {
8410 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8411 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8412 	sata_drive_info_t *sdinfo;
8413 	sata_id_t *sata_id;
8414 	struct scsi_extended_sense *sense;
8415 
8416 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
8417 	    &spx->txlt_sata_pkt->satapkt_device);
8418 	sata_id = &sdinfo->satadrv_id;
8419 
8420 	*dmod = 0;
8421 
8422 	/* Verify parameters length. If too short, drop it */
8423 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) > parmlen) ||
8424 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
8425 		*scsipkt->pkt_scbp = STATUS_CHECK;
8426 		sense = sata_arq_sense(spx);
8427 		sense->es_key = KEY_ILLEGAL_REQUEST;
8428 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8429 		*pagelen = parmlen;
8430 		*rval = TRAN_ACCEPT;
8431 		return (SATA_FAILURE);
8432 	}
8433 
8434 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
8435 
8436 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
8437 		*scsipkt->pkt_scbp = STATUS_CHECK;
8438 		sense = sata_arq_sense(spx);
8439 		sense->es_key = KEY_ILLEGAL_REQUEST;
8440 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
8441 		*pagelen = parmlen;
8442 		*rval = TRAN_ACCEPT;
8443 		return (SATA_FAILURE);
8444 	}
8445 
8446 	/* If already in the state requested, we are done */
8447 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
8448 		/* nothing to do */
8449 		*rval = TRAN_ACCEPT;
8450 		return (SATA_SUCCESS);
8451 	}
8452 
8453 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
8454 
8455 	/* Build SMART_ENABLE or SMART_DISABLE command */
8456 	scmd->satacmd_addr_type = 0;		/* N/A */
8457 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
8458 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
8459 	scmd->satacmd_features_reg = page->dexcpt ?
8460 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
8461 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
8462 	scmd->satacmd_cmd_reg = SATAC_SMART;
8463 
8464 	/* Transfer command to HBA */
8465 	if (sata_hba_start(spx, rval) != 0)
8466 		/*
8467 		 * Pkt not accepted for execution.
8468 		 */
8469 		return (SATA_FAILURE);
8470 
8471 	*dmod = 1;	/* At least may have been modified */
8472 
8473 	/* Now process return */
8474 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
8475 		return (SATA_SUCCESS);
8476 
8477 	/* Packet did not complete successfully */
8478 	sata_xlate_errors(spx);
8479 
8480 	return (SATA_FAILURE);
8481 }
8482 
8483 /*
8484  * Process mode select acoustic management control page 0x30
8485  *
8486  *
8487  * This function has to be called with a port mutex held.
8488  *
8489  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
8490  *
8491  * Cannot be called in the interrupt context.
8492  */
8493 int
8494 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
8495     mode_acoustic_management *page, int parmlen, int *pagelen,
8496     int *rval, int *dmod)
8497 {
8498 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8499 	sata_drive_info_t *sdinfo;
8500 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8501 	sata_id_t *sata_id;
8502 	struct scsi_extended_sense *sense;
8503 
8504 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
8505 	    &spx->txlt_sata_pkt->satapkt_device);
8506 	sata_id = &sdinfo->satadrv_id;
8507 	*dmod = 0;
8508 
8509 	/* If parmlen is too short or the feature is not supported, drop it */
8510 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
8511 	    sizeof (struct mode_page)) > parmlen) ||
8512 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
8513 		*scsipkt->pkt_scbp = STATUS_CHECK;
8514 		sense = sata_arq_sense(spx);
8515 		sense->es_key = KEY_ILLEGAL_REQUEST;
8516 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8517 		*pagelen = parmlen;
8518 		*rval = TRAN_ACCEPT;
8519 		return (SATA_FAILURE);
8520 	}
8521 
8522 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
8523 	    sizeof (struct mode_page);
8524 
8525 	/*
8526 	 * We can enable and disable acoustice management and
8527 	 * set the acoustic management level.
8528 	 */
8529 
8530 	/*
8531 	 * Set-up Internal SET FEATURES command(s)
8532 	 */
8533 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
8534 	scmd->satacmd_addr_type = 0;
8535 	scmd->satacmd_device_reg = 0;
8536 	scmd->satacmd_status_reg = 0;
8537 	scmd->satacmd_error_reg = 0;
8538 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
8539 	if (page->acoustic_manag_enable) {
8540 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
8541 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
8542 	} else {	/* disabling acoustic management */
8543 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
8544 	}
8545 
8546 	/* Transfer command to HBA */
8547 	if (sata_hba_start(spx, rval) != 0)
8548 		/*
8549 		 * Pkt not accepted for execution.
8550 		 */
8551 		return (SATA_FAILURE);
8552 
8553 	/* Now process return */
8554 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
8555 		sata_xlate_errors(spx);
8556 		return (SATA_FAILURE);
8557 	}
8558 
8559 	*dmod = 1;
8560 
8561 	return (SATA_SUCCESS);
8562 }
8563 
8564 /*
8565  * Process mode select power condition page 0x1a
8566  *
8567  * This function has to be called with a port mutex held.
8568  *
8569  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
8570  *
8571  * Cannot be called in the interrupt context.
8572  */
8573 int
8574 sata_mode_select_page_1a(sata_pkt_txlate_t *spx, struct
8575     mode_info_power_cond *page, int parmlen, int *pagelen,
8576     int *rval, int *dmod)
8577 {
8578 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8579 	sata_drive_info_t *sdinfo;
8580 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8581 	sata_id_t *sata_id;
8582 	struct scsi_extended_sense *sense;
8583 	uint8_t ata_count;
8584 	int i, len;
8585 
8586 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
8587 	    &spx->txlt_sata_pkt->satapkt_device);
8588 	sata_id = &sdinfo->satadrv_id;
8589 	*dmod = 0;
8590 
8591 	len = sizeof (struct mode_info_power_cond);
8592 	len += sizeof (struct mode_page);
8593 
8594 	/* If parmlen is too short or the feature is not supported, drop it */
8595 	if ((len < parmlen) || (page->idle == 1) ||
8596 	    (!(sata_id->ai_cap & SATA_STANDBYTIMER) && page->standby == 1)) {
8597 		*scsipkt->pkt_scbp = STATUS_CHECK;
8598 		sense = sata_arq_sense(spx);
8599 		sense->es_key = KEY_ILLEGAL_REQUEST;
8600 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8601 		*pagelen = parmlen;
8602 		*rval = TRAN_ACCEPT;
8603 		return (SATA_FAILURE);
8604 	}
8605 
8606 	*pagelen = len;
8607 
8608 	/*
8609 	 * Set-up Internal STANDBY command(s)
8610 	 */
8611 	if (page->standby == 0)
8612 		goto out;
8613 
8614 	ata_count = sata_get_standby_timer(page->standby_cond_timer);
8615 
8616 	scmd->satacmd_addr_type = 0;
8617 	scmd->satacmd_sec_count_lsb = ata_count;
8618 	scmd->satacmd_lba_low_lsb = 0;
8619 	scmd->satacmd_lba_mid_lsb = 0;
8620 	scmd->satacmd_lba_high_lsb = 0;
8621 	scmd->satacmd_features_reg = 0;
8622 	scmd->satacmd_device_reg = 0;
8623 	scmd->satacmd_status_reg = 0;
8624 	scmd->satacmd_cmd_reg = SATAC_STANDBY;
8625 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8626 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
8627 
8628 	/* Transfer command to HBA */
8629 	if (sata_hba_start(spx, rval) != 0) {
8630 		return (SATA_FAILURE);
8631 	} else {
8632 		if ((scmd->satacmd_error_reg != 0) ||
8633 		    (spx->txlt_sata_pkt->satapkt_reason !=
8634 		    SATA_PKT_COMPLETED)) {
8635 			sata_xlate_errors(spx);
8636 			return (SATA_FAILURE);
8637 		}
8638 	}
8639 
8640 	for (i = 0; i < 4; i++) {
8641 		sdinfo->satadrv_standby_timer[i] = page->standby_cond_timer[i];
8642 	}
8643 out:
8644 	*dmod = 1;
8645 	return (SATA_SUCCESS);
8646 }
8647 
8648 /*
8649  * sata_build_lsense_page0() is used to create the
8650  * SCSI LOG SENSE page 0 (supported log pages)
8651  *
8652  * Currently supported pages are 0, 0x10, 0x2f, 0x30 and 0x0e
8653  * (supported log pages, self-test results, informational exceptions
8654  * Sun vendor specific ATA SMART data, and start stop cycle counter).
8655  *
8656  * Takes a sata_drive_info t * and the address of a buffer
8657  * in which to create the page information.
8658  *
8659  * Returns the number of bytes valid in the buffer.
8660  */
8661 static	int
8662 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
8663 {
8664 	struct log_parameter *lpp = (struct log_parameter *)buf;
8665 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
8666 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
8667 	sata_id_t *sata_id = &sdinfo->satadrv_id;
8668 
8669 	lpp->param_code[0] = 0;
8670 	lpp->param_code[1] = 0;
8671 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8672 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
8673 
8674 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
8675 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
8676 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
8677 			++num_pages_supported;
8678 		}
8679 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
8680 		++num_pages_supported;
8681 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
8682 		++num_pages_supported;
8683 		*page_ptr++ = PAGE_CODE_START_STOP_CYCLE_COUNTER;
8684 		++num_pages_supported;
8685 	}
8686 
8687 	lpp->param_len = num_pages_supported;
8688 
8689 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
8690 	    num_pages_supported);
8691 }
8692 
8693 /*
8694  * sata_build_lsense_page_10() is used to create the
8695  * SCSI LOG SENSE page 0x10 (self-test results)
8696  *
8697  * Takes a sata_drive_info t * and the address of a buffer
8698  * in which to create the page information as well as a sata_hba_inst_t *.
8699  *
8700  * Returns the number of bytes valid in the buffer.
8701  *
8702  * Note: Self test and SMART data is accessible in device log pages.
8703  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
8704  * of data can be transferred by a single command), or by the General Purpose
8705  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
8706  * - approximately 33MB - can be transferred by a single command.
8707  * The SCT Command response (either error or command) is the same for both
8708  * the SMART and GPL methods of issuing commands.
8709  * This function uses READ LOG EXT command when drive supports LBA48, and
8710  * SMART READ command otherwise.
8711  *
8712  * Since above commands are executed in a synchronous mode, this function
8713  * should not be called in an interrupt context.
8714  */
8715 static	int
8716 sata_build_lsense_page_10(
8717 	sata_drive_info_t *sdinfo,
8718 	uint8_t *buf,
8719 	sata_hba_inst_t *sata_hba_inst)
8720 {
8721 	struct log_parameter *lpp = (struct log_parameter *)buf;
8722 	int rval;
8723 
8724 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
8725 		struct smart_ext_selftest_log *ext_selftest_log;
8726 
8727 		ext_selftest_log = kmem_zalloc(
8728 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
8729 
8730 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
8731 		    ext_selftest_log, 0);
8732 		if (rval == 0) {
8733 			int index, start_index;
8734 			struct smart_ext_selftest_log_entry *entry;
8735 			static const struct smart_ext_selftest_log_entry empty =
8736 			    {0};
8737 			uint16_t block_num;
8738 			int count;
8739 			boolean_t only_one_block = B_FALSE;
8740 
8741 			index = ext_selftest_log->
8742 			    smart_ext_selftest_log_index[0];
8743 			index |= ext_selftest_log->
8744 			    smart_ext_selftest_log_index[1] << 8;
8745 			if (index == 0)
8746 				goto out;
8747 
8748 			--index;	/* Correct for 0 origin */
8749 			start_index = index;	/* remember where we started */
8750 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8751 			if (block_num != 0) {
8752 				rval = sata_ext_smart_selftest_read_log(
8753 				    sata_hba_inst, sdinfo, ext_selftest_log,
8754 				    block_num);
8755 				if (rval != 0)
8756 					goto out;
8757 			}
8758 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8759 			entry =
8760 			    &ext_selftest_log->
8761 			    smart_ext_selftest_log_entries[index];
8762 
8763 			for (count = 1;
8764 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8765 			    ++count) {
8766 				uint8_t status;
8767 				uint8_t code;
8768 				uint8_t sense_key;
8769 				uint8_t add_sense_code;
8770 				uint8_t add_sense_code_qual;
8771 
8772 				/* If this is an unused entry, we are done */
8773 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
8774 					/* Broken firmware on some disks */
8775 					if (index + 1 ==
8776 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
8777 						--entry;
8778 						--index;
8779 						if (bcmp(entry, &empty,
8780 						    sizeof (empty)) == 0)
8781 							goto out;
8782 					} else
8783 						goto out;
8784 				}
8785 
8786 				if (only_one_block &&
8787 				    start_index == index)
8788 					goto out;
8789 
8790 				lpp->param_code[0] = 0;
8791 				lpp->param_code[1] = count;
8792 				lpp->param_ctrl_flags =
8793 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8794 				lpp->param_len =
8795 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8796 
8797 				status = entry->smart_ext_selftest_log_status;
8798 				status >>= 4;
8799 				switch (status) {
8800 				case 0:
8801 				default:
8802 					sense_key = KEY_NO_SENSE;
8803 					add_sense_code =
8804 					    SD_SCSI_ASC_NO_ADD_SENSE;
8805 					add_sense_code_qual = 0;
8806 					break;
8807 				case 1:
8808 					sense_key = KEY_ABORTED_COMMAND;
8809 					add_sense_code =
8810 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8811 					add_sense_code_qual = SCSI_COMPONENT_81;
8812 					break;
8813 				case 2:
8814 					sense_key = KEY_ABORTED_COMMAND;
8815 					add_sense_code =
8816 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8817 					add_sense_code_qual = SCSI_COMPONENT_82;
8818 					break;
8819 				case 3:
8820 					sense_key = KEY_ABORTED_COMMAND;
8821 					add_sense_code =
8822 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8823 					add_sense_code_qual = SCSI_COMPONENT_83;
8824 					break;
8825 				case 4:
8826 					sense_key = KEY_HARDWARE_ERROR;
8827 					add_sense_code =
8828 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8829 					add_sense_code_qual = SCSI_COMPONENT_84;
8830 					break;
8831 				case 5:
8832 					sense_key = KEY_HARDWARE_ERROR;
8833 					add_sense_code =
8834 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8835 					add_sense_code_qual = SCSI_COMPONENT_85;
8836 					break;
8837 				case 6:
8838 					sense_key = KEY_HARDWARE_ERROR;
8839 					add_sense_code =
8840 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8841 					add_sense_code_qual = SCSI_COMPONENT_86;
8842 					break;
8843 				case 7:
8844 					sense_key = KEY_MEDIUM_ERROR;
8845 					add_sense_code =
8846 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8847 					add_sense_code_qual = SCSI_COMPONENT_87;
8848 					break;
8849 				case 8:
8850 					sense_key = KEY_HARDWARE_ERROR;
8851 					add_sense_code =
8852 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8853 					add_sense_code_qual = SCSI_COMPONENT_88;
8854 					break;
8855 				}
8856 				code = 0;	/* unspecified */
8857 				status |= (code << 4);
8858 				lpp->param_values[0] = status;
8859 				lpp->param_values[1] = 0; /* unspecified */
8860 				lpp->param_values[2] = entry->
8861 				    smart_ext_selftest_log_timestamp[1];
8862 				lpp->param_values[3] = entry->
8863 				    smart_ext_selftest_log_timestamp[0];
8864 				if (status != 0) {
8865 					lpp->param_values[4] = 0;
8866 					lpp->param_values[5] = 0;
8867 					lpp->param_values[6] = entry->
8868 					    smart_ext_selftest_log_failing_lba
8869 					    [5];
8870 					lpp->param_values[7] = entry->
8871 					    smart_ext_selftest_log_failing_lba
8872 					    [4];
8873 					lpp->param_values[8] = entry->
8874 					    smart_ext_selftest_log_failing_lba
8875 					    [3];
8876 					lpp->param_values[9] = entry->
8877 					    smart_ext_selftest_log_failing_lba
8878 					    [2];
8879 					lpp->param_values[10] = entry->
8880 					    smart_ext_selftest_log_failing_lba
8881 					    [1];
8882 					lpp->param_values[11] = entry->
8883 					    smart_ext_selftest_log_failing_lba
8884 					    [0];
8885 				} else {	/* No bad block address */
8886 					lpp->param_values[4] = 0xff;
8887 					lpp->param_values[5] = 0xff;
8888 					lpp->param_values[6] = 0xff;
8889 					lpp->param_values[7] = 0xff;
8890 					lpp->param_values[8] = 0xff;
8891 					lpp->param_values[9] = 0xff;
8892 					lpp->param_values[10] = 0xff;
8893 					lpp->param_values[11] = 0xff;
8894 				}
8895 
8896 				lpp->param_values[12] = sense_key;
8897 				lpp->param_values[13] = add_sense_code;
8898 				lpp->param_values[14] = add_sense_code_qual;
8899 				lpp->param_values[15] = 0; /* undefined */
8900 
8901 				lpp = (struct log_parameter *)
8902 				    (((uint8_t *)lpp) +
8903 				    SCSI_LOG_PARAM_HDR_LEN +
8904 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8905 
8906 				--index;	/* Back up to previous entry */
8907 				if (index < 0) {
8908 					if (block_num > 0) {
8909 						--block_num;
8910 					} else {
8911 						struct read_log_ext_directory
8912 						    logdir;
8913 
8914 						rval =
8915 						    sata_read_log_ext_directory(
8916 						    sata_hba_inst, sdinfo,
8917 						    &logdir);
8918 						if (rval == -1)
8919 							goto out;
8920 						if ((logdir.read_log_ext_vers
8921 						    [0] == 0) &&
8922 						    (logdir.read_log_ext_vers
8923 						    [1] == 0))
8924 							goto out;
8925 						block_num =
8926 						    logdir.read_log_ext_nblks
8927 						    [EXT_SMART_SELFTEST_LOG_PAGE
8928 						    - 1][0];
8929 						block_num |= logdir.
8930 						    read_log_ext_nblks
8931 						    [EXT_SMART_SELFTEST_LOG_PAGE
8932 						    - 1][1] << 8;
8933 						--block_num;
8934 						only_one_block =
8935 						    (block_num == 0);
8936 					}
8937 					rval = sata_ext_smart_selftest_read_log(
8938 					    sata_hba_inst, sdinfo,
8939 					    ext_selftest_log, block_num);
8940 					if (rval != 0)
8941 						goto out;
8942 
8943 					index =
8944 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
8945 					    1;
8946 				}
8947 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8948 				entry = &ext_selftest_log->
8949 				    smart_ext_selftest_log_entries[index];
8950 			}
8951 		}
8952 out:
8953 		kmem_free(ext_selftest_log,
8954 		    sizeof (struct smart_ext_selftest_log));
8955 	} else {
8956 		struct smart_selftest_log *selftest_log;
8957 
8958 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
8959 		    KM_SLEEP);
8960 
8961 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
8962 		    selftest_log);
8963 
8964 		if (rval == 0) {
8965 			int index;
8966 			int count;
8967 			struct smart_selftest_log_entry *entry;
8968 			static const struct smart_selftest_log_entry empty =
8969 			    { 0 };
8970 
8971 			index = selftest_log->smart_selftest_log_index;
8972 			if (index == 0)
8973 				goto done;
8974 			--index;	/* Correct for 0 origin */
8975 			entry = &selftest_log->
8976 			    smart_selftest_log_entries[index];
8977 			for (count = 1;
8978 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8979 			    ++count) {
8980 				uint8_t status;
8981 				uint8_t code;
8982 				uint8_t sense_key;
8983 				uint8_t add_sense_code;
8984 				uint8_t add_sense_code_qual;
8985 
8986 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
8987 					goto done;
8988 
8989 				lpp->param_code[0] = 0;
8990 				lpp->param_code[1] = count;
8991 				lpp->param_ctrl_flags =
8992 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8993 				lpp->param_len =
8994 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8995 
8996 				status = entry->smart_selftest_log_status;
8997 				status >>= 4;
8998 				switch (status) {
8999 				case 0:
9000 				default:
9001 					sense_key = KEY_NO_SENSE;
9002 					add_sense_code =
9003 					    SD_SCSI_ASC_NO_ADD_SENSE;
9004 					break;
9005 				case 1:
9006 					sense_key = KEY_ABORTED_COMMAND;
9007 					add_sense_code =
9008 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9009 					add_sense_code_qual = SCSI_COMPONENT_81;
9010 					break;
9011 				case 2:
9012 					sense_key = KEY_ABORTED_COMMAND;
9013 					add_sense_code =
9014 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9015 					add_sense_code_qual = SCSI_COMPONENT_82;
9016 					break;
9017 				case 3:
9018 					sense_key = KEY_ABORTED_COMMAND;
9019 					add_sense_code =
9020 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9021 					add_sense_code_qual = SCSI_COMPONENT_83;
9022 					break;
9023 				case 4:
9024 					sense_key = KEY_HARDWARE_ERROR;
9025 					add_sense_code =
9026 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9027 					add_sense_code_qual = SCSI_COMPONENT_84;
9028 					break;
9029 				case 5:
9030 					sense_key = KEY_HARDWARE_ERROR;
9031 					add_sense_code =
9032 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9033 					add_sense_code_qual = SCSI_COMPONENT_85;
9034 					break;
9035 				case 6:
9036 					sense_key = KEY_HARDWARE_ERROR;
9037 					add_sense_code =
9038 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9039 					add_sense_code_qual = SCSI_COMPONENT_86;
9040 					break;
9041 				case 7:
9042 					sense_key = KEY_MEDIUM_ERROR;
9043 					add_sense_code =
9044 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9045 					add_sense_code_qual = SCSI_COMPONENT_87;
9046 					break;
9047 				case 8:
9048 					sense_key = KEY_HARDWARE_ERROR;
9049 					add_sense_code =
9050 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9051 					add_sense_code_qual = SCSI_COMPONENT_88;
9052 					break;
9053 				}
9054 				code = 0;	/* unspecified */
9055 				status |= (code << 4);
9056 				lpp->param_values[0] = status;
9057 				lpp->param_values[1] = 0; /* unspecified */
9058 				lpp->param_values[2] = entry->
9059 				    smart_selftest_log_timestamp[1];
9060 				lpp->param_values[3] = entry->
9061 				    smart_selftest_log_timestamp[0];
9062 				if (status != 0) {
9063 					lpp->param_values[4] = 0;
9064 					lpp->param_values[5] = 0;
9065 					lpp->param_values[6] = 0;
9066 					lpp->param_values[7] = 0;
9067 					lpp->param_values[8] = entry->
9068 					    smart_selftest_log_failing_lba[3];
9069 					lpp->param_values[9] = entry->
9070 					    smart_selftest_log_failing_lba[2];
9071 					lpp->param_values[10] = entry->
9072 					    smart_selftest_log_failing_lba[1];
9073 					lpp->param_values[11] = entry->
9074 					    smart_selftest_log_failing_lba[0];
9075 				} else {	/* No block address */
9076 					lpp->param_values[4] = 0xff;
9077 					lpp->param_values[5] = 0xff;
9078 					lpp->param_values[6] = 0xff;
9079 					lpp->param_values[7] = 0xff;
9080 					lpp->param_values[8] = 0xff;
9081 					lpp->param_values[9] = 0xff;
9082 					lpp->param_values[10] = 0xff;
9083 					lpp->param_values[11] = 0xff;
9084 				}
9085 				lpp->param_values[12] = sense_key;
9086 				lpp->param_values[13] = add_sense_code;
9087 				lpp->param_values[14] = add_sense_code_qual;
9088 				lpp->param_values[15] = 0; /* undefined */
9089 
9090 				lpp = (struct log_parameter *)
9091 				    (((uint8_t *)lpp) +
9092 				    SCSI_LOG_PARAM_HDR_LEN +
9093 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
9094 				--index;	/* back up to previous entry */
9095 				if (index < 0) {
9096 					index =
9097 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
9098 				}
9099 				entry = &selftest_log->
9100 				    smart_selftest_log_entries[index];
9101 			}
9102 		}
9103 done:
9104 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
9105 	}
9106 
9107 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
9108 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
9109 }
9110 
9111 /*
9112  * sata_build_lsense_page_2f() is used to create the
9113  * SCSI LOG SENSE page 0x2f (informational exceptions)
9114  *
9115  * Takes a sata_drive_info t * and the address of a buffer
9116  * in which to create the page information as well as a sata_hba_inst_t *.
9117  *
9118  * Returns the number of bytes valid in the buffer.
9119  *
9120  * Because it invokes function(s) that send synchronously executed command
9121  * to the HBA, it cannot be called in the interrupt context.
9122  */
9123 static	int
9124 sata_build_lsense_page_2f(
9125 	sata_drive_info_t *sdinfo,
9126 	uint8_t *buf,
9127 	sata_hba_inst_t *sata_hba_inst)
9128 {
9129 	struct log_parameter *lpp = (struct log_parameter *)buf;
9130 	int rval;
9131 	uint8_t *smart_data;
9132 	uint8_t temp;
9133 	sata_id_t *sata_id;
9134 #define	SMART_NO_TEMP	0xff
9135 
9136 	lpp->param_code[0] = 0;
9137 	lpp->param_code[1] = 0;
9138 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
9139 
9140 	/* Now get the SMART status w.r.t. threshold exceeded */
9141 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
9142 	switch (rval) {
9143 	case 1:
9144 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
9145 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
9146 		break;
9147 	case 0:
9148 	case -1:	/* failed to get data */
9149 		lpp->param_values[0] = 0;	/* No failure predicted */
9150 		lpp->param_values[1] = 0;
9151 		break;
9152 #if defined(SATA_DEBUG)
9153 	default:
9154 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
9155 		/* NOTREACHED */
9156 #endif
9157 	}
9158 
9159 	sata_id = &sdinfo->satadrv_id;
9160 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
9161 		temp = SMART_NO_TEMP;
9162 	else {
9163 		/* Now get the temperature */
9164 		smart_data = kmem_zalloc(512, KM_SLEEP);
9165 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
9166 		    SCT_STATUS_LOG_PAGE, 1);
9167 		if (rval == -1)
9168 			temp = SMART_NO_TEMP;
9169 		else {
9170 			temp = smart_data[200];
9171 			if (temp & 0x80) {
9172 				if (temp & 0x7f)
9173 					temp = 0;
9174 				else
9175 					temp = SMART_NO_TEMP;
9176 			}
9177 		}
9178 		kmem_free(smart_data, 512);
9179 	}
9180 
9181 	lpp->param_values[2] = temp;	/* most recent temperature */
9182 	lpp->param_values[3] = 0;	/* required vendor specific byte */
9183 
9184 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
9185 
9186 
9187 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
9188 }
9189 
9190 /*
9191  * sata_build_lsense_page_30() is used to create the
9192  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
9193  *
9194  * Takes a sata_drive_info t * and the address of a buffer
9195  * in which to create the page information as well as a sata_hba_inst_t *.
9196  *
9197  * Returns the number of bytes valid in the buffer.
9198  */
9199 static int
9200 sata_build_lsense_page_30(
9201 	sata_drive_info_t *sdinfo,
9202 	uint8_t *buf,
9203 	sata_hba_inst_t *sata_hba_inst)
9204 {
9205 	struct smart_data *smart_data = (struct smart_data *)buf;
9206 	int rval;
9207 
9208 	/* Now do the SMART READ DATA */
9209 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
9210 	if (rval == -1)
9211 		return (0);
9212 
9213 	return (sizeof (struct smart_data));
9214 }
9215 
9216 /*
9217  * sata_build_lsense_page_0e() is used to create the
9218  * SCSI LOG SENSE page 0e (start-stop cycle counter page)
9219  *
9220  * Date of Manufacture (0x0001)
9221  *	YEAR = "0000"
9222  *	WEEK = "00"
9223  * Accounting Date (0x0002)
9224  *	6 ASCII space character(20h)
9225  * Specified cycle count over device lifetime
9226  *	VALUE - THRESH - the delta between max and min;
9227  * Accumulated start-stop cycles
9228  *	VALUE - WORST - the accumulated cycles;
9229  *
9230  * ID FLAG THRESH VALUE WORST RAW on start/stop counter attribute
9231  *
9232  * Takes a sata_drive_info t * and the address of a buffer
9233  * in which to create the page information as well as a sata_hba_inst_t *.
9234  *
9235  * Returns the number of bytes valid in the buffer.
9236  */
9237 static	int
9238 sata_build_lsense_page_0e(sata_drive_info_t *sdinfo, uint8_t *buf,
9239     sata_pkt_txlate_t *spx)
9240 {
9241 	struct start_stop_cycle_counter_log *log_page;
9242 	int i, rval, index;
9243 	uint8_t smart_data[512], id, value, worst, thresh;
9244 	uint32_t max_count, cycles;
9245 
9246 	/* Now do the SMART READ DATA */
9247 	rval = sata_fetch_smart_data(spx->txlt_sata_hba_inst, sdinfo,
9248 	    (struct smart_data *)smart_data);
9249 	if (rval == -1)
9250 		return (0);
9251 	for (i = 0, id = 0; i < SMART_START_STOP_COUNT_ID * 2; i++) {
9252 		index = (i * 12) + 2;
9253 		id = smart_data[index];
9254 		if (id != SMART_START_STOP_COUNT_ID)
9255 			continue;
9256 		else {
9257 			thresh = smart_data[index + 2];
9258 			value = smart_data[index + 3];
9259 			worst = smart_data[index + 4];
9260 			break;
9261 		}
9262 	}
9263 	if (id != SMART_START_STOP_COUNT_ID)
9264 		return (0);
9265 	max_count = value - thresh;
9266 	cycles = value - worst;
9267 
9268 	log_page = (struct start_stop_cycle_counter_log *)buf;
9269 	bzero(log_page, sizeof (struct start_stop_cycle_counter_log));
9270 	log_page->code = 0x0e;
9271 	log_page->page_len_low = 0x24;
9272 
9273 	log_page->manufactor_date_low = 0x1;
9274 	log_page->param_1.fmt_link = 0x1; /* 01b */
9275 	log_page->param_len_1 = 0x06;
9276 	for (i = 0; i < 4; i++) {
9277 		log_page->year_manu[i] = 0x30;
9278 		if (i < 2)
9279 			log_page->week_manu[i] = 0x30;
9280 	}
9281 
9282 	log_page->account_date_low = 0x02;
9283 	log_page->param_2.fmt_link = 0x01; /* 01b */
9284 	log_page->param_len_2 = 0x06;
9285 	for (i = 0; i < 4; i++) {
9286 		log_page->year_account[i] = 0x20;
9287 		if (i < 2)
9288 			log_page->week_account[i] = 0x20;
9289 	}
9290 
9291 	log_page->lifetime_code_low = 0x03;
9292 	log_page->param_3.fmt_link = 0x03; /* 11b */
9293 	log_page->param_len_3 = 0x04;
9294 	/* VALUE - THRESH - the delta between max and min */
9295 	log_page->cycle_code_low = 0x04;
9296 	log_page->param_4.fmt_link = 0x03; /* 11b */
9297 	log_page->param_len_4 = 0x04;
9298 	/* WORST - THRESH - the distance from 'now' to min */
9299 
9300 	for (i = 0; i < 4; i++) {
9301 		log_page->cycle_lifetime[i] =
9302 		    (max_count >> (8 * (3 - i))) & 0xff;
9303 		log_page->cycle_accumulated[i] =
9304 		    (cycles >> (8 * (3 - i))) & 0xff;
9305 	}
9306 
9307 	return (sizeof (struct start_stop_cycle_counter_log));
9308 }
9309 
9310 /*
9311  * This function was used for build a ATA read verify sector command
9312  */
9313 static void
9314 sata_build_read_verify_cmd(sata_cmd_t *scmd, uint16_t sec, uint64_t lba)
9315 {
9316 	scmd->satacmd_cmd_reg = SATAC_RDVER;
9317 	scmd->satacmd_addr_type = ATA_ADDR_LBA28;
9318 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
9319 
9320 	scmd->satacmd_sec_count_lsb = sec & 0xff;
9321 	scmd->satacmd_lba_low_lsb = lba & 0xff;
9322 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
9323 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
9324 	scmd->satacmd_device_reg = (SATA_ADH_LBA | (lba >> 24) & 0xf);
9325 	scmd->satacmd_features_reg = 0;
9326 	scmd->satacmd_status_reg = 0;
9327 	scmd->satacmd_error_reg = 0;
9328 }
9329 
9330 /*
9331  * This function was used for building an ATA
9332  * command, and only command register need to
9333  * be defined, other register will be zero or na.
9334  */
9335 static void
9336 sata_build_generic_cmd(sata_cmd_t *scmd, uint8_t cmd)
9337 {
9338 	scmd->satacmd_addr_type = 0;
9339 	scmd->satacmd_cmd_reg = cmd;
9340 	scmd->satacmd_device_reg = 0;
9341 	scmd->satacmd_sec_count_lsb = 0;
9342 	scmd->satacmd_lba_low_lsb = 0;
9343 	scmd->satacmd_lba_mid_lsb = 0;
9344 	scmd->satacmd_lba_high_lsb = 0;
9345 	scmd->satacmd_features_reg = 0;
9346 	scmd->satacmd_status_reg = 0;
9347 	scmd->satacmd_error_reg = 0;
9348 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
9349 }
9350 
9351 /*
9352  * This function was used for changing the standby
9353  * timer format from SCSI to ATA.
9354  */
9355 static uint8_t
9356 sata_get_standby_timer(uint8_t *timer)
9357 {
9358 	uint32_t i = 0, count = 0;
9359 	uint8_t ata_count;
9360 
9361 	for (i = 0; i < 4; i++) {
9362 		count = count << 8 | timer[i];
9363 	}
9364 
9365 	if (count == 0)
9366 		return (0);
9367 
9368 	if (count >= 1 && count <= 12000)
9369 		ata_count = (count -1) / 50 + 1;
9370 	else if (count > 12000 && count <= 12600)
9371 		ata_count = 0xfc;
9372 	else if (count > 12601 && count <= 12750)
9373 		ata_count = 0xff;
9374 	else if (count > 12750 && count <= 17999)
9375 		ata_count = 0xf1;
9376 	else if (count > 18000 && count <= 198000)
9377 		ata_count = count / 18000 + 240;
9378 	else
9379 		ata_count = 0xfd;
9380 	return (ata_count);
9381 }
9382 
9383 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
9384 
9385 /*
9386  * Start command for ATAPI device.
9387  * This function processes scsi_pkt requests.
9388  * Now CD/DVD, tape and ATAPI disk devices are supported.
9389  * Most commands are packet without any translation into Packet Command.
9390  * Some may be trapped and executed as SATA commands (not clear which one).
9391  *
9392  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
9393  * execution).
9394  * Returns other TRAN_XXXX codes if command is not accepted or completed
9395  * (see return values for sata_hba_start()).
9396  *
9397  * Note:
9398  * Inquiry cdb format differs between transport version 2 and 3.
9399  * However, the transport version 3 devices that were checked did not adhere
9400  * to the specification (ignored MSB of the allocation length). Therefore,
9401  * the transport version is not checked, but Inquiry allocation length is
9402  * truncated to 255 bytes if the original allocation length set-up by the
9403  * target driver is greater than 255 bytes.
9404  */
9405 static int
9406 sata_txlt_atapi(sata_pkt_txlate_t *spx)
9407 {
9408 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
9409 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
9410 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
9411 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
9412 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
9413 	    &spx->txlt_sata_pkt->satapkt_device);
9414 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
9415 	int cdblen;
9416 	int rval, reason;
9417 	int synch;
9418 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
9419 
9420 	mutex_enter(cport_mutex);
9421 
9422 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
9423 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
9424 		mutex_exit(cport_mutex);
9425 		return (rval);
9426 	}
9427 
9428 	/*
9429 	 * ATAPI device executes some ATA commands in addition to those
9430 	 * commands sent via PACKET command. These ATA commands may be
9431 	 * executed by the regular SATA translation functions. None needs
9432 	 * to be captured now.
9433 	 *
9434 	 * Commands sent via PACKET command include:
9435 	 *	MMC command set for ATAPI CD/DVD device
9436 	 *	SSC command set for ATAPI TAPE device
9437 	 *	SBC command set for ATAPI disk device
9438 	 *
9439 	 */
9440 
9441 	/* Check the size of cdb */
9442 
9443 	switch (GETGROUP(cdbp)) {
9444 	case CDB_GROUPID_3:   /* Reserved, per SPC-4 */
9445 		/*
9446 		 * opcodes 0x7e and 0x7f identify variable-length CDBs and
9447 		 * therefore require special handling.  Return failure, for now.
9448 		 */
9449 		mutex_exit(cport_mutex);
9450 		return (TRAN_BADPKT);
9451 
9452 	case CDB_GROUPID_6:   /* Vendor-specific, per SPC-4 */
9453 	case CDB_GROUPID_7:   /* Vendor-specific, per SPC-4 */
9454 		/* obtain length from the scsi_pkt */
9455 		cdblen = scsipkt->pkt_cdblen;
9456 		break;
9457 
9458 	default:
9459 		/* CDB's length is statically known, per SPC-4 */
9460 		cdblen = scsi_cdb_size[GETGROUP(cdbp)];
9461 		break;
9462 	}
9463 
9464 	if (cdblen <= 0 || cdblen > sdinfo->satadrv_atapi_cdb_len) {
9465 		sata_log(NULL, CE_WARN,
9466 		    "sata: invalid ATAPI cdb length %d",
9467 		    cdblen);
9468 		mutex_exit(cport_mutex);
9469 		return (TRAN_BADPKT);
9470 	}
9471 
9472 	SATAATAPITRACE(spx, cdblen);
9473 
9474 	/*
9475 	 * For non-read/write commands we need to
9476 	 * map buffer
9477 	 */
9478 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
9479 	case SCMD_READ:
9480 	case SCMD_READ_G1:
9481 	case SCMD_READ_G5:
9482 	case SCMD_READ_G4:
9483 	case SCMD_WRITE:
9484 	case SCMD_WRITE_G1:
9485 	case SCMD_WRITE_G5:
9486 	case SCMD_WRITE_G4:
9487 		break;
9488 	default:
9489 		if (bp != NULL) {
9490 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
9491 				bp_mapin(bp);
9492 		}
9493 		break;
9494 	}
9495 	/*
9496 	 * scmd->satacmd_flags.sata_data_direction default -
9497 	 * SATA_DIR_NODATA_XFER - is set by
9498 	 * sata_txlt_generic_pkt_info().
9499 	 */
9500 	if (scmd->satacmd_bp) {
9501 		if (scmd->satacmd_bp->b_flags & B_READ) {
9502 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9503 		} else {
9504 			scmd->satacmd_flags.sata_data_direction =
9505 			    SATA_DIR_WRITE;
9506 		}
9507 	}
9508 
9509 	/*
9510 	 * Set up ATAPI packet command.
9511 	 */
9512 
9513 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9514 
9515 	/* Copy cdb into sata_cmd */
9516 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9517 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9518 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
9519 
9520 	/* See note in the command header */
9521 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
9522 		if (scmd->satacmd_acdb[3] != 0)
9523 			scmd->satacmd_acdb[4] = 255;
9524 	}
9525 
9526 #ifdef SATA_DEBUG
9527 	if (sata_debug_flags & SATA_DBG_ATAPI) {
9528 		uint8_t *p = scmd->satacmd_acdb;
9529 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
9530 
9531 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
9532 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
9533 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
9534 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9535 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9536 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
9537 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
9538 	}
9539 #endif
9540 
9541 	/*
9542 	 * Preset request sense data to NO SENSE.
9543 	 * If there is no way to get error information via Request Sense,
9544 	 * the packet request sense data would not have to be modified by HBA,
9545 	 * but it could be returned as is.
9546 	 */
9547 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
9548 	sata_fixed_sense_data_preset(
9549 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9550 
9551 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
9552 		/* Need callback function */
9553 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
9554 		synch = FALSE;
9555 	} else
9556 		synch = TRUE;
9557 
9558 	/* Transfer command to HBA */
9559 	if (sata_hba_start(spx, &rval) != 0) {
9560 		/* Pkt not accepted for execution */
9561 		mutex_exit(cport_mutex);
9562 		return (rval);
9563 	}
9564 	mutex_exit(cport_mutex);
9565 	/*
9566 	 * If execution is non-synchronous,
9567 	 * a callback function will handle potential errors, translate
9568 	 * the response and will do a callback to a target driver.
9569 	 * If it was synchronous, use the same framework callback to check
9570 	 * an execution status.
9571 	 */
9572 	if (synch) {
9573 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
9574 		    "synchronous execution status %x\n",
9575 		    spx->txlt_sata_pkt->satapkt_reason);
9576 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
9577 	}
9578 	return (TRAN_ACCEPT);
9579 }
9580 
9581 
9582 /*
9583  * ATAPI Packet command completion.
9584  *
9585  * Failure of the command passed via Packet command are considered device
9586  * error. SATA HBA driver would have to retrieve error data (via Request
9587  * Sense command delivered via error retrieval sata packet) and copy it
9588  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
9589  */
9590 static void
9591 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
9592 {
9593 	sata_pkt_txlate_t *spx =
9594 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
9595 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
9596 	struct scsi_extended_sense *sense;
9597 	struct buf *bp;
9598 	int rval;
9599 
9600 #ifdef SATA_DEBUG
9601 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
9602 #endif
9603 
9604 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
9605 	    STATE_SENT_CMD | STATE_GOT_STATUS;
9606 
9607 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
9608 		/* Normal completion */
9609 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
9610 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
9611 		scsipkt->pkt_reason = CMD_CMPLT;
9612 		*scsipkt->pkt_scbp = STATUS_GOOD;
9613 		if (spx->txlt_tmp_buf != NULL) {
9614 			/* Temporary buffer was used */
9615 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
9616 			if (bp->b_flags & B_READ) {
9617 				rval = ddi_dma_sync(
9618 				    spx->txlt_buf_dma_handle, 0, 0,
9619 				    DDI_DMA_SYNC_FORCPU);
9620 				ASSERT(rval == DDI_SUCCESS);
9621 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
9622 				    bp->b_bcount);
9623 			}
9624 		}
9625 	} else {
9626 		/*
9627 		 * Something went wrong - analyze return
9628 		 */
9629 		*scsipkt->pkt_scbp = STATUS_CHECK;
9630 		sense = sata_arq_sense(spx);
9631 
9632 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9633 			/*
9634 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
9635 			 * Under this condition ERR bit is set for ATA command,
9636 			 * and CHK bit set for ATAPI command.
9637 			 *
9638 			 * Please check st_intr & sdintr about how pkt_reason
9639 			 * is used.
9640 			 */
9641 			scsipkt->pkt_reason = CMD_CMPLT;
9642 
9643 			/*
9644 			 * We may not have ARQ data if there was a double
9645 			 * error. But sense data in sata packet was pre-set
9646 			 * with NO SENSE so it is valid even if HBA could
9647 			 * not retrieve a real sense data.
9648 			 * Just copy this sense data into scsi pkt sense area.
9649 			 */
9650 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
9651 			    SATA_ATAPI_MIN_RQSENSE_LEN);
9652 #ifdef SATA_DEBUG
9653 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
9654 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9655 				    "sata_txlt_atapi_completion: %02x\n"
9656 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
9657 				    "          %02x %02x %02x %02x %02x %02x "
9658 				    "          %02x %02x %02x %02x %02x %02x\n",
9659 				    scsipkt->pkt_reason,
9660 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9661 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9662 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9663 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9664 				    rqsp[16], rqsp[17]);
9665 			}
9666 #endif
9667 		} else {
9668 			switch (sata_pkt->satapkt_reason) {
9669 			case SATA_PKT_PORT_ERROR:
9670 				/*
9671 				 * We have no device data.
9672 				 */
9673 				scsipkt->pkt_reason = CMD_INCOMPLETE;
9674 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
9675 				    STATE_GOT_TARGET | STATE_SENT_CMD |
9676 				    STATE_GOT_STATUS);
9677 				sense->es_key = KEY_HARDWARE_ERROR;
9678 				break;
9679 
9680 			case SATA_PKT_TIMEOUT:
9681 				scsipkt->pkt_reason = CMD_TIMEOUT;
9682 				scsipkt->pkt_statistics |=
9683 				    STAT_TIMEOUT | STAT_DEV_RESET;
9684 				/*
9685 				 * Need to check if HARDWARE_ERROR/
9686 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
9687 				 * appropriate.
9688 				 */
9689 				break;
9690 
9691 			case SATA_PKT_ABORTED:
9692 				scsipkt->pkt_reason = CMD_ABORTED;
9693 				scsipkt->pkt_statistics |= STAT_ABORTED;
9694 				/* Should we set key COMMAND_ABPRTED? */
9695 				break;
9696 
9697 			case SATA_PKT_RESET:
9698 				scsipkt->pkt_reason = CMD_RESET;
9699 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
9700 				/*
9701 				 * May be we should set Unit Attention /
9702 				 * Reset. Perhaps the same should be
9703 				 * returned for disks....
9704 				 */
9705 				sense->es_key = KEY_UNIT_ATTENTION;
9706 				sense->es_add_code = SD_SCSI_ASC_RESET;
9707 				break;
9708 
9709 			default:
9710 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9711 				    "sata_txlt_atapi_completion: "
9712 				    "invalid packet completion reason"));
9713 				scsipkt->pkt_reason = CMD_TRAN_ERR;
9714 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
9715 				    STATE_GOT_TARGET | STATE_SENT_CMD |
9716 				    STATE_GOT_STATUS);
9717 				break;
9718 			}
9719 		}
9720 	}
9721 
9722 	SATAATAPITRACE(spx, 0);
9723 
9724 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
9725 	    scsipkt->pkt_comp != NULL) {
9726 		/* scsi callback required */
9727 		(*scsipkt->pkt_comp)(scsipkt);
9728 	}
9729 }
9730 
9731 /*
9732  * Set up error retrieval sata command for ATAPI Packet Command error data
9733  * recovery.
9734  *
9735  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
9736  * returns SATA_FAILURE otherwise.
9737  */
9738 
9739 static int
9740 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
9741 {
9742 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
9743 	sata_cmd_t *scmd;
9744 	struct buf *bp;
9745 
9746 	/*
9747 	 * Allocate dma-able buffer error data.
9748 	 * Buffer allocation will take care of buffer alignment and other DMA
9749 	 * attributes.
9750 	 */
9751 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
9752 	if (bp == NULL) {
9753 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
9754 		    "sata_get_err_retrieval_pkt: "
9755 		    "cannot allocate buffer for error data", NULL);
9756 		return (SATA_FAILURE);
9757 	}
9758 	bp_mapin(bp); /* make data buffer accessible */
9759 
9760 	/* Operation modes are up to the caller */
9761 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9762 
9763 	/* Synchronous mode, no callback - may be changed by the caller */
9764 	spkt->satapkt_comp = NULL;
9765 	spkt->satapkt_time = sata_default_pkt_time;
9766 
9767 	scmd = &spkt->satapkt_cmd;
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 	/*
9774 	 * Set-up acdb. Request Sense CDB (packet command content) is
9775 	 * not in DMA-able buffer. Its handling is HBA-specific (how
9776 	 * it is transfered into packet FIS).
9777 	 */
9778 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9779 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
9780 	/* Following zeroing of pad bytes may not be necessary */
9781 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
9782 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
9783 
9784 	/*
9785 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
9786 	 * before accessing it. Handle is in usual place in translate struct.
9787 	 */
9788 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
9789 
9790 	/*
9791 	 * Preset request sense data to NO SENSE.
9792 	 * Here it is redundant, only for a symetry with scsi-originated
9793 	 * packets. It should not be used for anything but debugging.
9794 	 */
9795 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
9796 	sata_fixed_sense_data_preset(
9797 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9798 
9799 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9800 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9801 
9802 	return (SATA_SUCCESS);
9803 }
9804 
9805 /*
9806  * Set-up ATAPI packet command.
9807  * Data transfer direction has to be set-up in sata_cmd structure prior to
9808  * calling this function.
9809  *
9810  * Returns void
9811  */
9812 
9813 static void
9814 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
9815 {
9816 	scmd->satacmd_addr_type = 0;		/* N/A */
9817 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
9818 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
9819 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
9820 	scmd->satacmd_lba_high_lsb =
9821 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
9822 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
9823 
9824 	/*
9825 	 * We want all data to be transfered via DMA.
9826 	 * But specify it only if drive supports DMA and DMA mode is
9827 	 * selected - some drives are sensitive about it.
9828 	 * Hopefully it wil work for all drives....
9829 	 */
9830 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
9831 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
9832 
9833 	/*
9834 	 * Features register requires special care for devices that use
9835 	 * Serial ATA bridge - they need an explicit specification of
9836 	 * the data transfer direction for Packet DMA commands.
9837 	 * Setting this bit is harmless if DMA is not used.
9838 	 *
9839 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
9840 	 * spec they follow.
9841 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
9842 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
9843 	 * ATA/ATAPI-7 support is explicitly indicated.
9844 	 */
9845 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
9846 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
9847 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
9848 		/*
9849 		 * Specification of major version is valid and version 7
9850 		 * is supported. It does automatically imply that all
9851 		 * spec features are supported. For now, we assume that
9852 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
9853 		 */
9854 		if ((sdinfo->satadrv_id.ai_dirdma &
9855 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
9856 			if (scmd->satacmd_flags.sata_data_direction ==
9857 			    SATA_DIR_READ)
9858 			scmd->satacmd_features_reg |=
9859 			    SATA_ATAPI_F_DATA_DIR_READ;
9860 		}
9861 	}
9862 }
9863 
9864 
9865 #ifdef SATA_DEBUG
9866 
9867 /* Display 18 bytes of Inquiry data */
9868 static void
9869 sata_show_inqry_data(uint8_t *buf)
9870 {
9871 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
9872 	uint8_t *p;
9873 
9874 	cmn_err(CE_NOTE, "Inquiry data:");
9875 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
9876 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
9877 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
9878 	cmn_err(CE_NOTE, "ATAPI transport version %d",
9879 	    SATA_ATAPI_TRANS_VERSION(inq));
9880 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
9881 	    inq->inq_rdf, inq->inq_aenc);
9882 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
9883 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
9884 	p = (uint8_t *)inq->inq_vid;
9885 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
9886 	    "%02x %02x %02x %02x",
9887 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9888 	p = (uint8_t *)inq->inq_vid;
9889 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
9890 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9891 
9892 	p = (uint8_t *)inq->inq_pid;
9893 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
9894 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
9895 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9896 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9897 	p = (uint8_t *)inq->inq_pid;
9898 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
9899 	    "%c %c %c %c %c %c %c %c",
9900 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9901 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9902 
9903 	p = (uint8_t *)inq->inq_revision;
9904 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
9905 	    p[0], p[1], p[2], p[3]);
9906 	p = (uint8_t *)inq->inq_revision;
9907 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
9908 	    p[0], p[1], p[2], p[3]);
9909 
9910 }
9911 
9912 
9913 static void
9914 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
9915 {
9916 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
9917 
9918 	if (scsi_pkt == NULL)
9919 		return;
9920 	if (count != 0) {
9921 		/* saving cdb */
9922 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
9923 		    SATA_ATAPI_MAX_CDB_LEN);
9924 		bcopy(scsi_pkt->pkt_cdbp,
9925 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
9926 	} else {
9927 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
9928 		    sts_sensedata,
9929 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
9930 		    SATA_ATAPI_MIN_RQSENSE_LEN);
9931 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
9932 		    scsi_pkt->pkt_reason;
9933 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
9934 		    spx->txlt_sata_pkt->satapkt_reason;
9935 
9936 		if (++sata_atapi_trace_index >= 64)
9937 			sata_atapi_trace_index = 0;
9938 	}
9939 }
9940 
9941 #endif
9942 
9943 /*
9944  * Fetch inquiry data from ATAPI device
9945  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
9946  *
9947  * Note:
9948  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
9949  * where the caller expects to see the inquiry data.
9950  *
9951  */
9952 
9953 static int
9954 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
9955     sata_address_t *saddr, struct scsi_inquiry *inq)
9956 {
9957 	sata_pkt_txlate_t *spx;
9958 	sata_pkt_t *spkt;
9959 	struct buf *bp;
9960 	sata_drive_info_t *sdinfo;
9961 	sata_cmd_t *scmd;
9962 	int rval;
9963 	uint8_t *rqsp;
9964 	dev_info_t *dip = SATA_DIP(sata_hba);
9965 #ifdef SATA_DEBUG
9966 	char msg_buf[MAXPATHLEN];
9967 #endif
9968 	kmutex_t *cport_mutex;
9969 
9970 	ASSERT(sata_hba != NULL);
9971 
9972 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9973 	spx->txlt_sata_hba_inst = sata_hba;
9974 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9975 	spkt = sata_pkt_alloc(spx, NULL);
9976 	if (spkt == NULL) {
9977 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9978 		return (SATA_FAILURE);
9979 	}
9980 	/* address is needed now */
9981 	spkt->satapkt_device.satadev_addr = *saddr;
9982 
9983 	/* scsi_inquiry size buffer */
9984 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
9985 	if (bp == NULL) {
9986 		sata_pkt_free(spx);
9987 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9988 		SATA_LOG_D((sata_hba, CE_WARN,
9989 		    "sata_get_atapi_inquiry_data: "
9990 		    "cannot allocate data buffer"));
9991 		return (SATA_FAILURE);
9992 	}
9993 	bp_mapin(bp); /* make data buffer accessible */
9994 
9995 	scmd = &spkt->satapkt_cmd;
9996 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9997 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9998 
9999 	/* Use synchronous mode */
10000 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10001 	spkt->satapkt_comp = NULL;
10002 	spkt->satapkt_time = sata_default_pkt_time;
10003 
10004 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
10005 
10006 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
10007 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10008 
10009 	cport_mutex = &(SATA_CPORT_MUTEX(sata_hba, saddr->cport));
10010 	mutex_enter(cport_mutex);
10011 	sdinfo = sata_get_device_info(sata_hba,
10012 	    &spx->txlt_sata_pkt->satapkt_device);
10013 	if (sdinfo == NULL) {
10014 		/* we have to be carefull about the disapearing device */
10015 		mutex_exit(cport_mutex);
10016 		rval = SATA_FAILURE;
10017 		goto cleanup;
10018 	}
10019 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
10020 
10021 	/*
10022 	 * Set-up acdb. This works for atapi transport version 2 and later.
10023 	 */
10024 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
10025 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
10026 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
10027 	scmd->satacmd_acdb[1] = 0x00;
10028 	scmd->satacmd_acdb[2] = 0x00;
10029 	scmd->satacmd_acdb[3] = 0x00;
10030 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
10031 	scmd->satacmd_acdb[5] = 0x00;
10032 
10033 	sata_fixed_sense_data_preset(
10034 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
10035 
10036 	/* Transfer command to HBA */
10037 	if (sata_hba_start(spx, &rval) != 0) {
10038 		/* Pkt not accepted for execution */
10039 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
10040 		    "sata_get_atapi_inquiry_data: "
10041 		    "Packet not accepted for execution - ret: %02x", rval);
10042 		mutex_exit(cport_mutex);
10043 		rval = SATA_FAILURE;
10044 		goto cleanup;
10045 	}
10046 	mutex_exit(cport_mutex);
10047 
10048 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
10049 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
10050 		    "sata_get_atapi_inquiry_data: "
10051 		    "Packet completed successfully - ret: %02x", rval);
10052 		if (spx->txlt_buf_dma_handle != NULL) {
10053 			/*
10054 			 * Sync buffer. Handle is in usual place in translate
10055 			 * struct.
10056 			 */
10057 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
10058 			    DDI_DMA_SYNC_FORCPU);
10059 			ASSERT(rval == DDI_SUCCESS);
10060 		}
10061 
10062 		if (sata_check_for_dma_error(dip, spx)) {
10063 			ddi_fm_service_impact(dip, DDI_SERVICE_UNAFFECTED);
10064 			rval = SATA_FAILURE;
10065 		} else {
10066 			/*
10067 			 * Normal completion - copy data into caller's buffer
10068 			 */
10069 			bcopy(bp->b_un.b_addr, (uint8_t *)inq,
10070 			    sizeof (struct scsi_inquiry));
10071 #ifdef SATA_DEBUG
10072 			if (sata_debug_flags & SATA_DBG_ATAPI) {
10073 				sata_show_inqry_data((uint8_t *)inq);
10074 			}
10075 #endif
10076 			rval = SATA_SUCCESS;
10077 		}
10078 	} else {
10079 		/*
10080 		 * Something went wrong - analyze return - check rqsense data
10081 		 */
10082 		rval = SATA_FAILURE;
10083 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
10084 			/*
10085 			 * ARQ data hopefull show something other than NO SENSE
10086 			 */
10087 			rqsp = scmd->satacmd_rqsense;
10088 #ifdef SATA_DEBUG
10089 			if (sata_debug_flags & SATA_DBG_ATAPI) {
10090 				msg_buf[0] = '\0';
10091 				(void) snprintf(msg_buf, MAXPATHLEN,
10092 				    "ATAPI packet completion reason: %02x\n"
10093 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
10094 				    "          %02x %02x %02x %02x %02x %02x\n"
10095 				    "          %02x %02x %02x %02x %02x %02x",
10096 				    spkt->satapkt_reason,
10097 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
10098 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
10099 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
10100 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
10101 				    rqsp[16], rqsp[17]);
10102 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
10103 				    "%s", msg_buf);
10104 			}
10105 #endif
10106 		} else {
10107 			switch (spkt->satapkt_reason) {
10108 			case SATA_PKT_PORT_ERROR:
10109 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
10110 				    "sata_get_atapi_inquiry_data: "
10111 				    "packet reason: port error", NULL);
10112 				break;
10113 
10114 			case SATA_PKT_TIMEOUT:
10115 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
10116 				    "sata_get_atapi_inquiry_data: "
10117 				    "packet reason: timeout", NULL);
10118 				break;
10119 
10120 			case SATA_PKT_ABORTED:
10121 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
10122 				    "sata_get_atapi_inquiry_data: "
10123 				    "packet reason: aborted", NULL);
10124 				break;
10125 
10126 			case SATA_PKT_RESET:
10127 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
10128 				    "sata_get_atapi_inquiry_data: "
10129 				    "packet reason: reset\n", NULL);
10130 				break;
10131 			default:
10132 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
10133 				    "sata_get_atapi_inquiry_data: "
10134 				    "invalid packet reason: %02x\n",
10135 				    spkt->satapkt_reason);
10136 				break;
10137 			}
10138 		}
10139 	}
10140 cleanup:
10141 	sata_free_local_buffer(spx);
10142 	sata_pkt_free(spx);
10143 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
10144 	return (rval);
10145 }
10146 
10147 
10148 
10149 
10150 
10151 #if 0
10152 #ifdef SATA_DEBUG
10153 
10154 /*
10155  * Test ATAPI packet command.
10156  * Single threaded test: send packet command in synch mode, process completion
10157  *
10158  */
10159 static void
10160 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
10161 {
10162 	sata_pkt_txlate_t *spx;
10163 	sata_pkt_t *spkt;
10164 	struct buf *bp;
10165 	sata_device_t sata_device;
10166 	sata_drive_info_t *sdinfo;
10167 	sata_cmd_t *scmd;
10168 	int rval;
10169 	uint8_t *rqsp;
10170 
10171 	ASSERT(sata_hba_inst != NULL);
10172 	sata_device.satadev_addr.cport = cport;
10173 	sata_device.satadev_addr.pmport = 0;
10174 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
10175 	sata_device.satadev_rev = SATA_DEVICE_REV;
10176 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10177 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
10178 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10179 	if (sdinfo == NULL) {
10180 		sata_log(sata_hba_inst, CE_WARN,
10181 		    "sata_test_atapi_packet_command: "
10182 		    "no device info for cport %d",
10183 		    sata_device.satadev_addr.cport);
10184 		return;
10185 	}
10186 
10187 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10188 	spx->txlt_sata_hba_inst = sata_hba_inst;
10189 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
10190 	spkt = sata_pkt_alloc(spx, NULL);
10191 	if (spkt == NULL) {
10192 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
10193 		return;
10194 	}
10195 	/* address is needed now */
10196 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
10197 
10198 	/* 1024k buffer */
10199 	bp = sata_alloc_local_buffer(spx, 1024);
10200 	if (bp == NULL) {
10201 		sata_pkt_free(spx);
10202 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
10203 		sata_log(sata_hba_inst, CE_WARN,
10204 		    "sata_test_atapi_packet_command: "
10205 		    "cannot allocate data buffer");
10206 		return;
10207 	}
10208 	bp_mapin(bp); /* make data buffer accessible */
10209 
10210 	scmd = &spkt->satapkt_cmd;
10211 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
10212 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
10213 
10214 	/* Use synchronous mode */
10215 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10216 
10217 	/* Synchronous mode, no callback - may be changed by the caller */
10218 	spkt->satapkt_comp = NULL;
10219 	spkt->satapkt_time = sata_default_pkt_time;
10220 
10221 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
10222 
10223 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
10224 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10225 
10226 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
10227 
10228 	/* Set-up acdb. */
10229 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
10230 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
10231 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
10232 	scmd->satacmd_acdb[1] = 0x00;
10233 	scmd->satacmd_acdb[2] = 0x00;
10234 	scmd->satacmd_acdb[3] = 0x00;
10235 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
10236 	scmd->satacmd_acdb[5] = 0x00;
10237 
10238 	sata_fixed_sense_data_preset(
10239 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
10240 
10241 	/* Transfer command to HBA */
10242 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10243 	if (sata_hba_start(spx, &rval) != 0) {
10244 		/* Pkt not accepted for execution */
10245 		sata_log(sata_hba_inst, CE_WARN,
10246 		    "sata_test_atapi_packet_command: "
10247 		    "Packet not accepted for execution - ret: %02x", rval);
10248 		mutex_exit(
10249 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10250 		goto cleanup;
10251 	}
10252 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10253 
10254 	if (spx->txlt_buf_dma_handle != NULL) {
10255 		/*
10256 		 * Sync buffer. Handle is in usual place in translate struct.
10257 		 */
10258 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
10259 		    DDI_DMA_SYNC_FORCPU);
10260 		ASSERT(rval == DDI_SUCCESS);
10261 	}
10262 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
10263 		sata_log(sata_hba_inst, CE_WARN,
10264 		    "sata_test_atapi_packet_command: "
10265 		    "Packet completed successfully");
10266 		/*
10267 		 * Normal completion - show inquiry data
10268 		 */
10269 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
10270 	} else {
10271 		/*
10272 		 * Something went wrong - analyze return - check rqsense data
10273 		 */
10274 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
10275 			/*
10276 			 * ARQ data hopefull show something other than NO SENSE
10277 			 */
10278 			rqsp = scmd->satacmd_rqsense;
10279 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
10280 			    "ATAPI packet completion reason: %02x\n"
10281 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
10282 			    "          %02x %02x %02x %02x %02x %02x "
10283 			    "          %02x %02x %02x %02x %02x %02x\n",
10284 			    spkt->satapkt_reason,
10285 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
10286 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
10287 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
10288 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
10289 			    rqsp[16], rqsp[17]);
10290 		} else {
10291 			switch (spkt->satapkt_reason) {
10292 			case SATA_PKT_PORT_ERROR:
10293 				sata_log(sata_hba_inst, CE_WARN,
10294 				    "sata_test_atapi_packet_command: "
10295 				    "packet reason: port error\n");
10296 				break;
10297 
10298 			case SATA_PKT_TIMEOUT:
10299 				sata_log(sata_hba_inst, CE_WARN,
10300 				    "sata_test_atapi_packet_command: "
10301 				    "packet reason: timeout\n");
10302 				break;
10303 
10304 			case SATA_PKT_ABORTED:
10305 				sata_log(sata_hba_inst, CE_WARN,
10306 				    "sata_test_atapi_packet_command: "
10307 				    "packet reason: aborted\n");
10308 				break;
10309 
10310 			case SATA_PKT_RESET:
10311 				sata_log(sata_hba_inst, CE_WARN,
10312 				    "sata_test_atapi_packet_command: "
10313 				    "packet reason: reset\n");
10314 				break;
10315 			default:
10316 				sata_log(sata_hba_inst, CE_WARN,
10317 				    "sata_test_atapi_packet_command: "
10318 				    "invalid packet reason: %02x\n",
10319 				    spkt->satapkt_reason);
10320 				break;
10321 			}
10322 		}
10323 	}
10324 cleanup:
10325 	sata_free_local_buffer(spx);
10326 	sata_pkt_free(spx);
10327 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
10328 }
10329 
10330 #endif /* SATA_DEBUG */
10331 #endif /* 1 */
10332 
10333 
10334 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
10335 
10336 /*
10337  * Validate sata_tran info
10338  * SATA_FAILURE returns if structure is inconsistent or structure revision
10339  * does not match one used by the framework.
10340  *
10341  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
10342  * required function pointers.
10343  * Returns SATA_FAILURE otherwise.
10344  */
10345 static int
10346 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
10347 {
10348 	/*
10349 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
10350 	 * of the SATA interface.
10351 	 */
10352 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
10353 		sata_log(NULL, CE_WARN,
10354 		    "sata: invalid sata_hba_tran version %d for driver %s",
10355 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
10356 		return (SATA_FAILURE);
10357 	}
10358 
10359 	if (dip != sata_tran->sata_tran_hba_dip) {
10360 		SATA_LOG_D((NULL, CE_WARN,
10361 		    "sata: inconsistent sata_tran_hba_dip "
10362 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
10363 		return (SATA_FAILURE);
10364 	}
10365 
10366 	if (sata_tran->sata_tran_probe_port == NULL ||
10367 	    sata_tran->sata_tran_start == NULL ||
10368 	    sata_tran->sata_tran_abort == NULL ||
10369 	    sata_tran->sata_tran_reset_dport == NULL ||
10370 	    sata_tran->sata_tran_hotplug_ops == NULL ||
10371 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
10372 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
10373 	    NULL) {
10374 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
10375 		    "required functions"));
10376 	}
10377 	return (SATA_SUCCESS);
10378 }
10379 
10380 /*
10381  * Remove HBA instance from sata_hba_list.
10382  */
10383 static void
10384 sata_remove_hba_instance(dev_info_t *dip)
10385 {
10386 	sata_hba_inst_t	*sata_hba_inst;
10387 
10388 	mutex_enter(&sata_mutex);
10389 	for (sata_hba_inst = sata_hba_list;
10390 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
10391 	    sata_hba_inst = sata_hba_inst->satahba_next) {
10392 		if (sata_hba_inst->satahba_dip == dip)
10393 			break;
10394 	}
10395 
10396 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
10397 #ifdef SATA_DEBUG
10398 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
10399 		    "unknown HBA instance\n");
10400 #endif
10401 		ASSERT(FALSE);
10402 	}
10403 	if (sata_hba_inst == sata_hba_list) {
10404 		sata_hba_list = sata_hba_inst->satahba_next;
10405 		if (sata_hba_list) {
10406 			sata_hba_list->satahba_prev =
10407 			    (struct sata_hba_inst *)NULL;
10408 		}
10409 		if (sata_hba_inst == sata_hba_list_tail) {
10410 			sata_hba_list_tail = NULL;
10411 		}
10412 	} else if (sata_hba_inst == sata_hba_list_tail) {
10413 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
10414 		if (sata_hba_list_tail) {
10415 			sata_hba_list_tail->satahba_next =
10416 			    (struct sata_hba_inst *)NULL;
10417 		}
10418 	} else {
10419 		sata_hba_inst->satahba_prev->satahba_next =
10420 		    sata_hba_inst->satahba_next;
10421 		sata_hba_inst->satahba_next->satahba_prev =
10422 		    sata_hba_inst->satahba_prev;
10423 	}
10424 	mutex_exit(&sata_mutex);
10425 }
10426 
10427 /*
10428  * Probe all SATA ports of the specified HBA instance.
10429  * The assumption is that there are no target and attachment point minor nodes
10430  * created by the boot subsystems, so we do not need to prune device tree.
10431  *
10432  * This function is called only from sata_hba_attach(). It does not have to
10433  * be protected by controller mutex, because the hba_attached flag is not set
10434  * yet and no one would be touching this HBA instance other than this thread.
10435  * Determines if port is active and what type of the device is attached
10436  * (if any). Allocates necessary structures for each port.
10437  *
10438  * An AP (Attachement Point) node is created for each SATA device port even
10439  * when there is no device attached.
10440  */
10441 
10442 static void
10443 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
10444 {
10445 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
10446 	int			ncport;
10447 	sata_cport_info_t	*cportinfo;
10448 	sata_drive_info_t	*drive;
10449 	sata_device_t		sata_device;
10450 	int			rval;
10451 	dev_t			minor_number;
10452 	char			name[16];
10453 	clock_t			start_time, cur_time;
10454 
10455 	/*
10456 	 * Probe controller ports first, to find port status and
10457 	 * any port multiplier attached.
10458 	 */
10459 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
10460 		/* allocate cport structure */
10461 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
10462 		ASSERT(cportinfo != NULL);
10463 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
10464 
10465 		mutex_enter(&cportinfo->cport_mutex);
10466 
10467 		cportinfo->cport_addr.cport = ncport;
10468 		cportinfo->cport_addr.pmport = 0;
10469 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
10470 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10471 		cportinfo->cport_state |= SATA_STATE_PROBING;
10472 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
10473 
10474 		/*
10475 		 * Regardless if a port is usable or not, create
10476 		 * an attachment point
10477 		 */
10478 		mutex_exit(&cportinfo->cport_mutex);
10479 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
10480 		    ncport, 0, SATA_ADDR_CPORT);
10481 		(void) sprintf(name, "%d", ncport);
10482 		if (ddi_create_minor_node(dip, name, S_IFCHR,
10483 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
10484 		    DDI_SUCCESS) {
10485 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
10486 			    "cannot create SATA attachment point for port %d",
10487 			    ncport);
10488 		}
10489 
10490 		/* Probe port */
10491 		start_time = ddi_get_lbolt();
10492 	reprobe_cport:
10493 		sata_device.satadev_addr.cport = ncport;
10494 		sata_device.satadev_addr.pmport = 0;
10495 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
10496 		sata_device.satadev_rev = SATA_DEVICE_REV;
10497 
10498 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10499 		    (dip, &sata_device);
10500 
10501 		mutex_enter(&cportinfo->cport_mutex);
10502 		cportinfo->cport_scr = sata_device.satadev_scr;
10503 		if (rval != SATA_SUCCESS) {
10504 			/* Something went wrong? Fail the port */
10505 			cportinfo->cport_state = SATA_PSTATE_FAILED;
10506 			mutex_exit(&cportinfo->cport_mutex);
10507 			continue;
10508 		}
10509 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
10510 		cportinfo->cport_state |= SATA_STATE_PROBED;
10511 		cportinfo->cport_dev_type = sata_device.satadev_type;
10512 
10513 		cportinfo->cport_state |= SATA_STATE_READY;
10514 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
10515 			mutex_exit(&cportinfo->cport_mutex);
10516 			continue;
10517 		}
10518 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
10519 			/*
10520 			 * There is some device attached.
10521 			 * Allocate device info structure
10522 			 */
10523 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
10524 				mutex_exit(&cportinfo->cport_mutex);
10525 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
10526 				    kmem_zalloc(sizeof (sata_drive_info_t),
10527 				    KM_SLEEP);
10528 				mutex_enter(&cportinfo->cport_mutex);
10529 			}
10530 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
10531 			drive->satadrv_addr = cportinfo->cport_addr;
10532 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
10533 			drive->satadrv_type = cportinfo->cport_dev_type;
10534 			drive->satadrv_state = SATA_STATE_UNKNOWN;
10535 
10536 			mutex_exit(&cportinfo->cport_mutex);
10537 			if (sata_add_device(dip, sata_hba_inst, &sata_device) !=
10538 			    SATA_SUCCESS) {
10539 				/*
10540 				 * Plugged device was not correctly identified.
10541 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
10542 				 */
10543 				cur_time = ddi_get_lbolt();
10544 				if ((cur_time - start_time) <
10545 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
10546 					/* sleep for a while */
10547 					delay(drv_usectohz(
10548 					    SATA_DEV_RETRY_DLY));
10549 					goto reprobe_cport;
10550 				}
10551 			}
10552 		} else { /* SATA_DTYPE_PMULT */
10553 			mutex_exit(&cportinfo->cport_mutex);
10554 
10555 			/* Allocate sata_pmult_info and sata_pmport_info */
10556 			if (sata_alloc_pmult(sata_hba_inst, &sata_device) !=
10557 			    SATA_SUCCESS)
10558 				continue;
10559 
10560 			/* Log the information of the port multiplier */
10561 			sata_show_pmult_info(sata_hba_inst, &sata_device);
10562 
10563 			/* Probe its pmports */
10564 			sata_probe_pmports(sata_hba_inst, ncport);
10565 		}
10566 	}
10567 }
10568 
10569 /*
10570  * Probe all device ports behind a port multiplier.
10571  *
10572  * PMult-related structure should be allocated before by sata_alloc_pmult().
10573  *
10574  * NOTE1: Only called from sata_probe_ports()
10575  * NOTE2: No mutex should be hold.
10576  */
10577 static void
10578 sata_probe_pmports(sata_hba_inst_t *sata_hba_inst, uint8_t ncport)
10579 {
10580 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
10581 	sata_pmult_info_t	*pmultinfo = NULL;
10582 	sata_pmport_info_t	*pmportinfo = NULL;
10583 	sata_drive_info_t	*drive = NULL;
10584 	sata_device_t		sata_device;
10585 
10586 	clock_t			start_time, cur_time;
10587 	int			npmport;
10588 	int			rval;
10589 
10590 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, ncport);
10591 
10592 	/* Probe Port Multiplier ports */
10593 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports; npmport++) {
10594 		pmportinfo = pmultinfo->pmult_dev_port[npmport];
10595 		start_time = ddi_get_lbolt();
10596 reprobe_pmport:
10597 		sata_device.satadev_addr.cport = ncport;
10598 		sata_device.satadev_addr.pmport = npmport;
10599 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
10600 		sata_device.satadev_rev = SATA_DEVICE_REV;
10601 
10602 		/* Let HBA driver probe it. */
10603 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10604 		    (dip, &sata_device);
10605 		mutex_enter(&pmportinfo->pmport_mutex);
10606 
10607 		pmportinfo->pmport_scr = sata_device.satadev_scr;
10608 
10609 		if (rval != SATA_SUCCESS) {
10610 			pmportinfo->pmport_state =
10611 			    SATA_PSTATE_FAILED;
10612 			mutex_exit(&pmportinfo->pmport_mutex);
10613 			continue;
10614 		}
10615 		pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
10616 		pmportinfo->pmport_state |= SATA_STATE_PROBED;
10617 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
10618 
10619 		pmportinfo->pmport_state |= SATA_STATE_READY;
10620 		if (pmportinfo->pmport_dev_type ==
10621 		    SATA_DTYPE_NONE) {
10622 			SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
10623 			    "no device found at port %d:%d", ncport, npmport);
10624 			mutex_exit(&pmportinfo->pmport_mutex);
10625 			continue;
10626 		}
10627 		/* Port multipliers cannot be chained */
10628 		ASSERT(pmportinfo->pmport_dev_type != SATA_DTYPE_PMULT);
10629 		/*
10630 		 * There is something attached to Port
10631 		 * Multiplier device port
10632 		 * Allocate device info structure
10633 		 */
10634 		if (pmportinfo->pmport_sata_drive == NULL) {
10635 			mutex_exit(&pmportinfo->pmport_mutex);
10636 			pmportinfo->pmport_sata_drive =
10637 			    kmem_zalloc(sizeof (sata_drive_info_t), KM_SLEEP);
10638 			mutex_enter(&pmportinfo->pmport_mutex);
10639 		}
10640 		drive = pmportinfo->pmport_sata_drive;
10641 		drive->satadrv_addr.cport = pmportinfo->pmport_addr.cport;
10642 		drive->satadrv_addr.pmport = npmport;
10643 		drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
10644 		drive->satadrv_type = pmportinfo-> pmport_dev_type;
10645 		drive->satadrv_state = SATA_STATE_UNKNOWN;
10646 
10647 		mutex_exit(&pmportinfo->pmport_mutex);
10648 		rval = sata_add_device(dip, sata_hba_inst, &sata_device);
10649 
10650 		if (rval != SATA_SUCCESS) {
10651 			/*
10652 			 * Plugged device was not correctly identified.
10653 			 * Retry, within the SATA_DEV_IDENTIFY_TIMEOUT
10654 			 */
10655 			cur_time = ddi_get_lbolt();
10656 			if ((cur_time - start_time) < drv_usectohz(
10657 			    SATA_DEV_IDENTIFY_TIMEOUT)) {
10658 				/* sleep for a while */
10659 				delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10660 				goto reprobe_pmport;
10661 			}
10662 		}
10663 	}
10664 }
10665 
10666 /*
10667  * Add SATA device for specified HBA instance & port (SCSI target
10668  * device nodes).
10669  * This function is called (indirectly) only from sata_hba_attach().
10670  * A target node is created when there is a supported type device attached,
10671  * but may be removed if it cannot be put online.
10672  *
10673  * This function cannot be called from an interrupt context.
10674  *
10675  * Create target nodes for disk, CD/DVD, Tape and ATAPI disk devices
10676  *
10677  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
10678  * device identification failed - adding a device could be retried.
10679  *
10680  */
10681 static int
10682 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst,
10683     sata_device_t *sata_device)
10684 {
10685 	sata_cport_info_t	*cportinfo;
10686 	sata_pmult_info_t	*pminfo;
10687 	sata_pmport_info_t	*pmportinfo;
10688 	dev_info_t		*cdip;		/* child dip */
10689 	sata_address_t		*saddr = &sata_device->satadev_addr;
10690 	uint8_t			cport, pmport;
10691 	int			rval;
10692 
10693 	cport = saddr->cport;
10694 	pmport = saddr->pmport;
10695 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10696 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
10697 
10698 	/*
10699 	 * Some device is attached to a controller port.
10700 	 * We rely on controllers distinquishing between no-device,
10701 	 * attached port multiplier and other kind of attached device.
10702 	 * We need to get Identify Device data and determine
10703 	 * positively the dev type before trying to attach
10704 	 * the target driver.
10705 	 */
10706 	sata_device->satadev_rev = SATA_DEVICE_REV;
10707 	switch (saddr->qual) {
10708 	case SATA_ADDR_CPORT:
10709 		/*
10710 		 * Add a non-port-multiplier device at controller port.
10711 		 */
10712 		saddr->qual = SATA_ADDR_DCPORT;
10713 
10714 		rval = sata_probe_device(sata_hba_inst, sata_device);
10715 		if (rval != SATA_SUCCESS ||
10716 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN)
10717 			return (SATA_FAILURE);
10718 
10719 		mutex_enter(&cportinfo->cport_mutex);
10720 		sata_show_drive_info(sata_hba_inst,
10721 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
10722 
10723 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10724 			/*
10725 			 * Could not determine device type or
10726 			 * a device is not supported.
10727 			 * Degrade this device to unknown.
10728 			 */
10729 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10730 			mutex_exit(&cportinfo->cport_mutex);
10731 			return (SATA_SUCCESS);
10732 		}
10733 		cportinfo->cport_dev_type = sata_device->satadev_type;
10734 		cportinfo->cport_tgtnode_clean = B_TRUE;
10735 		mutex_exit(&cportinfo->cport_mutex);
10736 
10737 		/*
10738 		 * Initialize device to the desired state. Even if it
10739 		 * fails, the device will still attach but syslog
10740 		 * will show the warning.
10741 		 */
10742 		if (sata_initialize_device(sata_hba_inst,
10743 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
10744 			/* Retry */
10745 			rval = sata_initialize_device(sata_hba_inst,
10746 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
10747 
10748 			if (rval == SATA_RETRY)
10749 				sata_log(sata_hba_inst, CE_WARN,
10750 				    "SATA device at port %d - "
10751 				    "default device features could not be set."
10752 				    " Device may not operate as expected.",
10753 				    cport);
10754 		}
10755 
10756 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10757 		if (cdip == NULL) {
10758 			/*
10759 			 * Attaching target node failed.
10760 			 * We retain sata_drive_info structure...
10761 			 */
10762 			return (SATA_SUCCESS);
10763 		}
10764 
10765 		mutex_enter(&cportinfo->cport_mutex);
10766 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
10767 		    satadrv_state = SATA_STATE_READY;
10768 		mutex_exit(&cportinfo->cport_mutex);
10769 
10770 		break;
10771 
10772 	case SATA_ADDR_PMPORT:
10773 		saddr->qual = SATA_ADDR_DPMPORT;
10774 
10775 		mutex_enter(&cportinfo->cport_mutex);
10776 		/* It must be a Port Multiplier at the controller port */
10777 		ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
10778 
10779 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
10780 		pmportinfo = pminfo->pmult_dev_port[saddr->pmport];
10781 		mutex_exit(&cportinfo->cport_mutex);
10782 
10783 		rval = sata_probe_device(sata_hba_inst, sata_device);
10784 		if (rval != SATA_SUCCESS ||
10785 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
10786 			return (SATA_FAILURE);
10787 		}
10788 
10789 		mutex_enter(&pmportinfo->pmport_mutex);
10790 		sata_show_drive_info(sata_hba_inst,
10791 		    SATA_PMPORTINFO_DRV_INFO(pmportinfo));
10792 
10793 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10794 			/*
10795 			 * Could not determine device type.
10796 			 * Degrade this device to unknown.
10797 			 */
10798 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
10799 			mutex_exit(&pmportinfo->pmport_mutex);
10800 			return (SATA_SUCCESS);
10801 		}
10802 		pmportinfo->pmport_dev_type = sata_device->satadev_type;
10803 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
10804 		mutex_exit(&pmportinfo->pmport_mutex);
10805 
10806 		/*
10807 		 * Initialize device to the desired state.
10808 		 * Even if it fails, the device will still
10809 		 * attach but syslog will show the warning.
10810 		 */
10811 		if (sata_initialize_device(sata_hba_inst,
10812 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
10813 			/* Retry */
10814 			rval = sata_initialize_device(sata_hba_inst,
10815 			    pmportinfo->pmport_sata_drive);
10816 
10817 			if (rval == SATA_RETRY)
10818 				sata_log(sata_hba_inst, CE_WARN,
10819 				    "SATA device at port %d:%d - "
10820 				    "default device features could not be set."
10821 				    " Device may not operate as expected.",
10822 				    cport, pmport);
10823 		}
10824 
10825 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10826 		if (cdip == NULL) {
10827 			/*
10828 			 * Attaching target node failed.
10829 			 * We retain sata_drive_info structure...
10830 			 */
10831 			return (SATA_SUCCESS);
10832 		}
10833 		mutex_enter(&pmportinfo->pmport_mutex);
10834 		pmportinfo->pmport_sata_drive->satadrv_state |=
10835 		    SATA_STATE_READY;
10836 		mutex_exit(&pmportinfo->pmport_mutex);
10837 
10838 		break;
10839 
10840 	default:
10841 		return (SATA_FAILURE);
10842 	}
10843 
10844 	return (SATA_SUCCESS);
10845 }
10846 
10847 /*
10848  * Clean up target node at specific address.
10849  *
10850  * NOTE: No Mutex should be hold.
10851  */
10852 static int
10853 sata_offline_device(sata_hba_inst_t *sata_hba_inst,
10854     sata_device_t *sata_device, sata_drive_info_t *sdinfo)
10855 {
10856 	uint8_t cport, pmport, qual;
10857 	dev_info_t *tdip;
10858 
10859 	cport = sata_device->satadev_addr.cport;
10860 	pmport = sata_device->satadev_addr.pmport;
10861 	qual = sata_device->satadev_addr.qual;
10862 
10863 	if (qual == SATA_ADDR_DCPORT) {
10864 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10865 		    "sata_hba_ioctl: disconnect device at port %d", cport));
10866 	} else {
10867 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10868 		    "sata_hba_ioctl: disconnect device at port %d:%d",
10869 		    cport, pmport));
10870 	}
10871 
10872 	/* We are addressing attached device, not a port */
10873 	sata_device->satadev_addr.qual =
10874 	    sdinfo->satadrv_addr.qual;
10875 	tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
10876 	    &sata_device->satadev_addr);
10877 	if (tdip != NULL && ndi_devi_offline(tdip,
10878 	    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10879 		/*
10880 		 * Problem :
10881 		 * The target node remained attached.
10882 		 * This happens when the device file was open
10883 		 * or a node was waiting for resources.
10884 		 * Cannot do anything about it.
10885 		 */
10886 		if (qual == SATA_ADDR_DCPORT) {
10887 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10888 			    "sata_hba_ioctl: disconnect: could "
10889 			    "not unconfigure device before "
10890 			    "disconnecting the SATA port %d",
10891 			    cport));
10892 		} else {
10893 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10894 			    "sata_hba_ioctl: disconnect: could "
10895 			    "not unconfigure device before "
10896 			    "disconnecting the SATA port %d:%d",
10897 			    cport, pmport));
10898 		}
10899 		/*
10900 		 * Set DEVICE REMOVED state in the target
10901 		 * node. It will prevent access to the device
10902 		 * even when a new device is attached, until
10903 		 * the old target node is released, removed and
10904 		 * recreated for a new  device.
10905 		 */
10906 		sata_set_device_removed(tdip);
10907 
10908 		/*
10909 		 * Instruct event daemon to try the target
10910 		 * node cleanup later.
10911 		 */
10912 		sata_set_target_node_cleanup(
10913 		    sata_hba_inst, &sata_device->satadev_addr);
10914 	}
10915 
10916 
10917 	return (SATA_SUCCESS);
10918 }
10919 
10920 
10921 /*
10922  * Create scsi target node for attached device, create node properties and
10923  * attach the node.
10924  * The node could be removed if the device onlining fails.
10925  *
10926  * A dev_info_t pointer is returned if operation is successful, NULL is
10927  * returned otherwise.
10928  */
10929 
10930 static dev_info_t *
10931 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
10932     sata_address_t *sata_addr)
10933 {
10934 	dev_info_t *cdip = NULL;
10935 	int rval;
10936 	char *nname = NULL;
10937 	char **compatible = NULL;
10938 	int ncompatible;
10939 	struct scsi_inquiry inq;
10940 	sata_device_t sata_device;
10941 	sata_drive_info_t *sdinfo;
10942 	int target;
10943 	int i;
10944 
10945 	sata_device.satadev_rev = SATA_DEVICE_REV;
10946 	sata_device.satadev_addr = *sata_addr;
10947 
10948 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
10949 
10950 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
10951 
10952 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
10953 	    sata_addr->pmport, sata_addr->qual);
10954 
10955 	if (sdinfo == NULL) {
10956 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10957 		    sata_addr->cport)));
10958 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10959 		    "sata_create_target_node: no sdinfo for target %x",
10960 		    target));
10961 		return (NULL);
10962 	}
10963 
10964 	/*
10965 	 * create or get scsi inquiry data, expected by
10966 	 * scsi_hba_nodename_compatible_get()
10967 	 * SATA hard disks get Identify Data translated into Inguiry Data.
10968 	 * ATAPI devices respond directly to Inquiry request.
10969 	 */
10970 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10971 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
10972 		    (uint8_t *)&inq);
10973 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10974 		    sata_addr->cport)));
10975 	} else { /* Assume supported ATAPI device */
10976 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10977 		    sata_addr->cport)));
10978 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
10979 		    &inq) == SATA_FAILURE)
10980 			return (NULL);
10981 		/*
10982 		 * Save supported ATAPI transport version
10983 		 */
10984 		sdinfo->satadrv_atapi_trans_ver =
10985 		    SATA_ATAPI_TRANS_VERSION(&inq);
10986 	}
10987 
10988 	/* determine the node name and compatible */
10989 	scsi_hba_nodename_compatible_get(&inq, NULL,
10990 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
10991 
10992 #ifdef SATA_DEBUG
10993 	if (sata_debug_flags & SATA_DBG_NODES) {
10994 		if (nname == NULL) {
10995 			cmn_err(CE_NOTE, "sata_create_target_node: "
10996 			    "cannot determine nodename for target %d\n",
10997 			    target);
10998 		} else {
10999 			cmn_err(CE_WARN, "sata_create_target_node: "
11000 			    "target %d nodename: %s\n", target, nname);
11001 		}
11002 		if (compatible == NULL) {
11003 			cmn_err(CE_WARN,
11004 			    "sata_create_target_node: no compatible name\n");
11005 		} else {
11006 			for (i = 0; i < ncompatible; i++) {
11007 				cmn_err(CE_WARN, "sata_create_target_node: "
11008 				    "compatible name: %s\n", compatible[i]);
11009 			}
11010 		}
11011 	}
11012 #endif
11013 
11014 	/* if nodename can't be determined, log error and exit */
11015 	if (nname == NULL) {
11016 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11017 		    "sata_create_target_node: cannot determine nodename "
11018 		    "for target %d\n", target));
11019 		scsi_hba_nodename_compatible_free(nname, compatible);
11020 		return (NULL);
11021 	}
11022 	/*
11023 	 * Create scsi target node
11024 	 */
11025 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
11026 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
11027 	    "device-type", "scsi");
11028 
11029 	if (rval != DDI_PROP_SUCCESS) {
11030 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
11031 		    "updating device_type prop failed %d", rval));
11032 		goto fail;
11033 	}
11034 
11035 	/*
11036 	 * Create target node properties: target & lun
11037 	 */
11038 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
11039 	if (rval != DDI_PROP_SUCCESS) {
11040 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
11041 		    "updating target prop failed %d", rval));
11042 		goto fail;
11043 	}
11044 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
11045 	if (rval != DDI_PROP_SUCCESS) {
11046 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
11047 		    "updating target prop failed %d", rval));
11048 		goto fail;
11049 	}
11050 
11051 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
11052 		/*
11053 		 * Add "variant" property
11054 		 */
11055 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
11056 		    "variant", "atapi");
11057 		if (rval != DDI_PROP_SUCCESS) {
11058 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11059 			    "sata_create_target_node: variant atapi "
11060 			    "property could not be created: %d", rval));
11061 			goto fail;
11062 		}
11063 	}
11064 	/* decorate the node with compatible */
11065 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
11066 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
11067 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11068 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
11069 		    (void *)cdip));
11070 		goto fail;
11071 	}
11072 
11073 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11074 		/*
11075 		 * Add "sata-phy" property
11076 		 */
11077 		if (ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "sata-phy",
11078 		    (int)sata_addr->cport) != DDI_PROP_SUCCESS) {
11079 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11080 			    "sata_create_target_node: failed to create "
11081 			    "\"sata-phy\" property: port %d",
11082 			    sata_addr->cport));
11083 		}
11084 	}
11085 
11086 
11087 	/*
11088 	 * Now, try to attach the driver. If probing of the device fails,
11089 	 * the target node may be removed
11090 	 */
11091 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
11092 
11093 	scsi_hba_nodename_compatible_free(nname, compatible);
11094 
11095 	if (rval == NDI_SUCCESS)
11096 		return (cdip);
11097 
11098 	/* target node was removed - are we sure? */
11099 	return (NULL);
11100 
11101 fail:
11102 	scsi_hba_nodename_compatible_free(nname, compatible);
11103 	ddi_prop_remove_all(cdip);
11104 	rval = ndi_devi_free(cdip);
11105 	if (rval != NDI_SUCCESS) {
11106 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
11107 		    "node removal failed %d", rval));
11108 	}
11109 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
11110 	    "cannot create target node for SATA device at port %d",
11111 	    sata_addr->cport);
11112 	return (NULL);
11113 }
11114 
11115 /*
11116  * Remove a target node.
11117  */
11118 static void
11119 sata_remove_target_node(sata_hba_inst_t *sata_hba_inst,
11120     sata_address_t *sata_addr)
11121 {
11122 	dev_info_t *tdip;
11123 	uint8_t cport = sata_addr->cport;
11124 	uint8_t pmport = sata_addr->pmport;
11125 	uint8_t qual = sata_addr->qual;
11126 
11127 	/* Note the sata daemon uses the address of the port/pmport */
11128 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
11129 
11130 	/* Remove target node */
11131 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), cport, pmport);
11132 	if (tdip != NULL) {
11133 		/*
11134 		 * Target node exists.  Unconfigure device
11135 		 * then remove the target node (one ndi
11136 		 * operation).
11137 		 */
11138 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11139 			/*
11140 			 * PROBLEM - no device, but target node remained. This
11141 			 * happens when the file was open or node was waiting
11142 			 * for resources.
11143 			 */
11144 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11145 			    "sata_remove_target_node: "
11146 			    "Failed to remove target node for "
11147 			    "detached SATA device."));
11148 			/*
11149 			 * Set target node state to DEVI_DEVICE_REMOVED. But
11150 			 * re-check first that the node still exists.
11151 			 */
11152 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
11153 			    cport, pmport);
11154 			if (tdip != NULL) {
11155 				sata_set_device_removed(tdip);
11156 				/*
11157 				 * Instruct event daemon to retry the cleanup
11158 				 * later.
11159 				 */
11160 				sata_set_target_node_cleanup(sata_hba_inst,
11161 				    sata_addr);
11162 			}
11163 		}
11164 
11165 		if (qual == SATA_ADDR_CPORT)
11166 			sata_log(sata_hba_inst, CE_WARN,
11167 			    "SATA device detached at port %d", cport);
11168 		else
11169 			sata_log(sata_hba_inst, CE_WARN,
11170 			    "SATA device detached at port %d:%d",
11171 			    cport, pmport);
11172 	}
11173 #ifdef SATA_DEBUG
11174 	else {
11175 		if (qual == SATA_ADDR_CPORT)
11176 			sata_log(sata_hba_inst, CE_WARN,
11177 			    "target node not found at port %d", cport);
11178 		else
11179 			sata_log(sata_hba_inst, CE_WARN,
11180 			    "target node not found at port %d:%d",
11181 			    cport, pmport);
11182 	}
11183 #endif
11184 }
11185 
11186 
11187 /*
11188  * Re-probe sata port, check for a device and attach info
11189  * structures when necessary. Identify Device data is fetched, if possible.
11190  * Assumption: sata address is already validated.
11191  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
11192  * the presence of a device and its type.
11193  *
11194  * flag arg specifies that the function should try multiple times to identify
11195  * device type and to initialize it, or it should return immediately on failure.
11196  * SATA_DEV_IDENTIFY_RETRY - retry
11197  * SATA_DEV_IDENTIFY_NORETRY - no retry
11198  *
11199  * SATA_FAILURE is returned if one of the operations failed.
11200  *
11201  * This function cannot be called in interrupt context - it may sleep.
11202  *
11203  * Note: Port multiplier is supported.
11204  */
11205 static int
11206 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
11207     int flag)
11208 {
11209 	sata_cport_info_t *cportinfo;
11210 	sata_pmult_info_t *pmultinfo;
11211 	sata_drive_info_t *sdinfo, *osdinfo;
11212 	boolean_t init_device = B_FALSE;
11213 	int prev_device_type = SATA_DTYPE_NONE;
11214 	int prev_device_settings = 0;
11215 	int prev_device_state = 0;
11216 	clock_t start_time;
11217 	int retry = B_FALSE;
11218 	uint8_t cport = sata_device->satadev_addr.cport;
11219 	int rval_probe, rval_init;
11220 
11221 	/*
11222 	 * If target is pmport, sata_reprobe_pmport() will handle it.
11223 	 */
11224 	if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT ||
11225 	    sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT)
11226 		return (sata_reprobe_pmport(sata_hba_inst, sata_device, flag));
11227 
11228 	/* We only care about host sata cport for now */
11229 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
11230 	    sata_device->satadev_addr.cport);
11231 
11232 	/*
11233 	 * If a port multiplier was previously attached (we have no idea it
11234 	 * still there or not), sata_reprobe_pmult() will handle it.
11235 	 */
11236 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT)
11237 		return (sata_reprobe_pmult(sata_hba_inst, sata_device, flag));
11238 
11239 	/* Store sata_drive_info when a non-pmult device was attached. */
11240 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11241 	if (osdinfo != NULL) {
11242 		/*
11243 		 * We are re-probing port with a previously attached device.
11244 		 * Save previous device type and settings.
11245 		 */
11246 		prev_device_type = cportinfo->cport_dev_type;
11247 		prev_device_settings = osdinfo->satadrv_settings;
11248 		prev_device_state = osdinfo->satadrv_state;
11249 	}
11250 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
11251 		start_time = ddi_get_lbolt();
11252 		retry = B_TRUE;
11253 	}
11254 retry_probe:
11255 
11256 	/* probe port */
11257 	mutex_enter(&cportinfo->cport_mutex);
11258 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11259 	cportinfo->cport_state |= SATA_STATE_PROBING;
11260 	mutex_exit(&cportinfo->cport_mutex);
11261 
11262 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11263 	    (SATA_DIP(sata_hba_inst), sata_device);
11264 
11265 	mutex_enter(&cportinfo->cport_mutex);
11266 	if (rval_probe != SATA_SUCCESS) {
11267 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11268 		mutex_exit(&cportinfo->cport_mutex);
11269 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
11270 		    "SATA port %d probing failed",
11271 		    cportinfo->cport_addr.cport));
11272 		return (SATA_FAILURE);
11273 	}
11274 
11275 	/*
11276 	 * update sata port state and set device type
11277 	 */
11278 	sata_update_port_info(sata_hba_inst, sata_device);
11279 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
11280 
11281 	/*
11282 	 * Sanity check - Port is active? Is the link active?
11283 	 * Is there any device attached?
11284 	 */
11285 	if ((cportinfo->cport_state &
11286 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11287 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11288 	    SATA_PORT_DEVLINK_UP) {
11289 		/*
11290 		 * Port in non-usable state or no link active/no device.
11291 		 * Free info structure if necessary (direct attached drive
11292 		 * only, for now!
11293 		 */
11294 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11295 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11296 		/* Add here differentiation for device attached or not */
11297 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11298 		mutex_exit(&cportinfo->cport_mutex);
11299 		if (sdinfo != NULL)
11300 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11301 		return (SATA_SUCCESS);
11302 	}
11303 
11304 	cportinfo->cport_state |= SATA_STATE_READY;
11305 	cportinfo->cport_state |= SATA_STATE_PROBED;
11306 
11307 	cportinfo->cport_dev_type = sata_device->satadev_type;
11308 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11309 
11310 	/*
11311 	 * If we are re-probing the port, there may be
11312 	 * sata_drive_info structure attached
11313 	 */
11314 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
11315 
11316 		/*
11317 		 * There is no device, so remove device info structure,
11318 		 * if necessary.
11319 		 */
11320 		/* Device change: Drive -> None */
11321 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11322 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11323 		if (sdinfo != NULL) {
11324 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11325 			sata_log(sata_hba_inst, CE_WARN,
11326 			    "SATA device detached "
11327 			    "from port %d", cportinfo->cport_addr.cport);
11328 		}
11329 		mutex_exit(&cportinfo->cport_mutex);
11330 		return (SATA_SUCCESS);
11331 
11332 	}
11333 
11334 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
11335 
11336 		/* Device (may) change: Drive -> Drive */
11337 		if (sdinfo == NULL) {
11338 			/*
11339 			 * There is some device attached, but there is
11340 			 * no sata_drive_info structure - allocate one
11341 			 */
11342 			mutex_exit(&cportinfo->cport_mutex);
11343 			sdinfo = kmem_zalloc(
11344 			    sizeof (sata_drive_info_t), KM_SLEEP);
11345 			mutex_enter(&cportinfo->cport_mutex);
11346 			/*
11347 			 * Recheck, that the port state did not change when we
11348 			 * released mutex.
11349 			 */
11350 			if (cportinfo->cport_state & SATA_STATE_READY) {
11351 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
11352 				sdinfo->satadrv_addr = cportinfo->cport_addr;
11353 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
11354 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11355 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11356 			} else {
11357 				/*
11358 				 * Port is not in ready state, we
11359 				 * cannot attach a device.
11360 				 */
11361 				mutex_exit(&cportinfo->cport_mutex);
11362 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
11363 				return (SATA_SUCCESS);
11364 			}
11365 			/*
11366 			 * Since we are adding device, presumably new one,
11367 			 * indicate that it  should be initalized,
11368 			 * as well as some internal framework states).
11369 			 */
11370 			init_device = B_TRUE;
11371 		}
11372 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11373 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
11374 	} else {
11375 		/* Device change: Drive -> PMult */
11376 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11377 		if (sdinfo != NULL) {
11378 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11379 			sata_log(sata_hba_inst, CE_WARN,
11380 			    "SATA device detached "
11381 			    "from port %d", cportinfo->cport_addr.cport);
11382 		}
11383 
11384 		sata_log(sata_hba_inst, CE_WARN,
11385 		    "SATA port multiplier detected at port %d",
11386 		    cportinfo->cport_addr.cport);
11387 
11388 		mutex_exit(&cportinfo->cport_mutex);
11389 		if (sata_alloc_pmult(sata_hba_inst, sata_device) !=
11390 		    SATA_SUCCESS)
11391 			return (SATA_FAILURE);
11392 		sata_show_pmult_info(sata_hba_inst, sata_device);
11393 		mutex_enter(&cportinfo->cport_mutex);
11394 
11395 		/*
11396 		 * Mark all the port multiplier port behind the port
11397 		 * multiplier behind with link events, so that the sata daemon
11398 		 * will update their status.
11399 		 */
11400 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
11401 		pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
11402 		mutex_exit(&cportinfo->cport_mutex);
11403 		return (SATA_SUCCESS);
11404 	}
11405 	mutex_exit(&cportinfo->cport_mutex);
11406 
11407 	/*
11408 	 * Figure out what kind of device we are really
11409 	 * dealing with. Failure of identifying device does not fail this
11410 	 * function.
11411 	 */
11412 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
11413 	rval_init = SATA_FAILURE;
11414 	mutex_enter(&cportinfo->cport_mutex);
11415 	if (rval_probe == SATA_SUCCESS) {
11416 		/*
11417 		 * If we are dealing with the same type of a device as before,
11418 		 * restore its settings flags.
11419 		 */
11420 		if (osdinfo != NULL &&
11421 		    sata_device->satadev_type == prev_device_type)
11422 			sdinfo->satadrv_settings = prev_device_settings;
11423 
11424 		mutex_exit(&cportinfo->cport_mutex);
11425 		rval_init = SATA_SUCCESS;
11426 		/* Set initial device features, if necessary */
11427 		if (init_device == B_TRUE) {
11428 			rval_init = sata_initialize_device(sata_hba_inst,
11429 			    sdinfo);
11430 		}
11431 		if (rval_init == SATA_SUCCESS)
11432 			return (rval_init);
11433 		/* else we will retry if retry was asked for */
11434 
11435 	} else {
11436 		/*
11437 		 * If there was some device info before we probe the device,
11438 		 * restore previous device setting, so we can retry from scratch
11439 		 * later. Providing, of course, that device has not disapear
11440 		 * during probing process.
11441 		 */
11442 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
11443 			if (osdinfo != NULL) {
11444 				cportinfo->cport_dev_type = prev_device_type;
11445 				sdinfo->satadrv_type = prev_device_type;
11446 				sdinfo->satadrv_state = prev_device_state;
11447 			}
11448 		} else {
11449 			/* device is gone */
11450 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11451 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11452 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11453 			mutex_exit(&cportinfo->cport_mutex);
11454 			return (SATA_SUCCESS);
11455 		}
11456 		mutex_exit(&cportinfo->cport_mutex);
11457 	}
11458 
11459 	if (retry) {
11460 		clock_t cur_time = ddi_get_lbolt();
11461 		/*
11462 		 * A device was not successfully identified or initialized.
11463 		 * Track retry time for device identification.
11464 		 */
11465 		if ((cur_time - start_time) <
11466 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11467 			/* sleep for a while */
11468 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11469 			goto retry_probe;
11470 		}
11471 		/* else no more retries */
11472 		mutex_enter(&cportinfo->cport_mutex);
11473 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
11474 			if (rval_init == SATA_RETRY) {
11475 				/*
11476 				 * Setting drive features have failed, but
11477 				 * because the drive is still accessible,
11478 				 * keep it and emit a warning message.
11479 				 */
11480 				sata_log(sata_hba_inst, CE_WARN,
11481 				    "SATA device at port %d - desired "
11482 				    "drive features could not be set. "
11483 				    "Device may not operate as expected.",
11484 				    cportinfo->cport_addr.cport);
11485 			} else {
11486 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
11487 				    satadrv_state = SATA_DSTATE_FAILED;
11488 			}
11489 		}
11490 		mutex_exit(&cportinfo->cport_mutex);
11491 	}
11492 	return (SATA_SUCCESS);
11493 }
11494 
11495 /*
11496  * Reprobe a controller port that connected to a port multiplier.
11497  *
11498  * NOTE: No Mutex should be hold.
11499  */
11500 static int
11501 sata_reprobe_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
11502     int flag)
11503 {
11504 	_NOTE(ARGUNUSED(flag))
11505 	sata_cport_info_t *cportinfo;
11506 	sata_pmult_info_t *pmultinfo;
11507 	uint8_t cport = sata_device->satadev_addr.cport;
11508 	int rval_probe;
11509 
11510 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11511 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
11512 
11513 	/* probe port */
11514 	mutex_enter(&cportinfo->cport_mutex);
11515 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11516 	cportinfo->cport_state |= SATA_STATE_PROBING;
11517 	mutex_exit(&cportinfo->cport_mutex);
11518 
11519 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11520 	    (SATA_DIP(sata_hba_inst), sata_device);
11521 
11522 	mutex_enter(&cportinfo->cport_mutex);
11523 	if (rval_probe != SATA_SUCCESS) {
11524 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11525 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmult: "
11526 		    "SATA port %d probing failed", cport));
11527 		sata_log(sata_hba_inst, CE_WARN,
11528 		    "SATA port multiplier detached at port %d", cport);
11529 		mutex_exit(&cportinfo->cport_mutex);
11530 		sata_free_pmult(sata_hba_inst, sata_device);
11531 		return (SATA_FAILURE);
11532 	}
11533 
11534 	/*
11535 	 * update sata port state and set device type
11536 	 */
11537 	sata_update_port_info(sata_hba_inst, sata_device);
11538 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
11539 	cportinfo->cport_state |= SATA_STATE_PROBED;
11540 
11541 	/*
11542 	 * Sanity check - Port is active? Is the link active?
11543 	 * Is there any device attached?
11544 	 */
11545 	if ((cportinfo->cport_state &
11546 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11547 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11548 	    SATA_PORT_DEVLINK_UP ||
11549 	    (sata_device->satadev_type == SATA_DTYPE_NONE)) {
11550 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11551 		mutex_exit(&cportinfo->cport_mutex);
11552 		sata_free_pmult(sata_hba_inst, sata_device);
11553 		sata_log(sata_hba_inst, CE_WARN,
11554 		    "SATA port multiplier detached at port %d", cport);
11555 		return (SATA_SUCCESS);
11556 	}
11557 
11558 	/*
11559 	 * Device changed: PMult -> Non-PMult
11560 	 *
11561 	 * This situation is uncommon, most possibly being caused by errors
11562 	 * after which the port multiplier is not correct initialized and
11563 	 * recognized. In that case the new device will be marked as unknown
11564 	 * and will not be automatically probed in this routine. Instead
11565 	 * system administrator could manually restart it via cfgadm(1M).
11566 	 */
11567 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
11568 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11569 		mutex_exit(&cportinfo->cport_mutex);
11570 		sata_free_pmult(sata_hba_inst, sata_device);
11571 		sata_log(sata_hba_inst, CE_WARN,
11572 		    "SATA port multiplier detached at port %d", cport);
11573 		return (SATA_FAILURE);
11574 	}
11575 
11576 	/*
11577 	 * Now we know it is a port multiplier. However, if this is not the
11578 	 * previously attached port multiplier - they may have different
11579 	 * pmport numbers - we need to re-allocate data structures for every
11580 	 * pmport and drive.
11581 	 *
11582 	 * Port multipliers of the same model have identical values in these
11583 	 * registers, so it is still necessary to update the information of
11584 	 * all drives attached to the previous port multiplier afterwards.
11585 	 */
11586 	/* Device changed: PMult -> another PMult */
11587 	mutex_exit(&cportinfo->cport_mutex);
11588 	sata_free_pmult(sata_hba_inst, sata_device);
11589 	if (sata_alloc_pmult(sata_hba_inst, sata_device) != SATA_SUCCESS)
11590 		return (SATA_FAILURE);
11591 	mutex_enter(&cportinfo->cport_mutex);
11592 
11593 	SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11594 	    "SATA port multiplier [changed] at port %d", cport);
11595 	sata_log(sata_hba_inst, CE_WARN,
11596 	    "SATA port multiplier detected at port %d", cport);
11597 
11598 	/*
11599 	 * Mark all the port multiplier port behind the port
11600 	 * multiplier behind with link events, so that the sata daemon
11601 	 * will update their status.
11602 	 */
11603 	pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
11604 	mutex_exit(&cportinfo->cport_mutex);
11605 
11606 	return (SATA_SUCCESS);
11607 }
11608 
11609 /*
11610  * Re-probe a port multiplier port, check for a device and attach info
11611  * structures when necessary. Identify Device data is fetched, if possible.
11612  * Assumption: sata address is already validated as port multiplier port.
11613  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
11614  * the presence of a device and its type.
11615  *
11616  * flag arg specifies that the function should try multiple times to identify
11617  * device type and to initialize it, or it should return immediately on failure.
11618  * SATA_DEV_IDENTIFY_RETRY - retry
11619  * SATA_DEV_IDENTIFY_NORETRY - no retry
11620  *
11621  * SATA_FAILURE is returned if one of the operations failed.
11622  *
11623  * This function cannot be called in interrupt context - it may sleep.
11624  *
11625  * NOTE: Should be only called by sata_probe_port() in case target port is a
11626  *       port multiplier port.
11627  * NOTE: No Mutex should be hold.
11628  */
11629 static int
11630 sata_reprobe_pmport(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
11631     int flag)
11632 {
11633 	sata_cport_info_t *cportinfo = NULL;
11634 	sata_pmport_info_t *pmportinfo = NULL;
11635 	sata_drive_info_t *sdinfo, *osdinfo;
11636 	sata_device_t sdevice;
11637 	boolean_t init_device = B_FALSE;
11638 	int prev_device_type = SATA_DTYPE_NONE;
11639 	int prev_device_settings = 0;
11640 	int prev_device_state = 0;
11641 	clock_t start_time;
11642 	uint8_t cport = sata_device->satadev_addr.cport;
11643 	uint8_t pmport = sata_device->satadev_addr.pmport;
11644 	int rval;
11645 
11646 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11647 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11648 	osdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11649 
11650 	if (osdinfo != NULL) {
11651 		/*
11652 		 * We are re-probing port with a previously attached device.
11653 		 * Save previous device type and settings.
11654 		 */
11655 		prev_device_type = pmportinfo->pmport_dev_type;
11656 		prev_device_settings = osdinfo->satadrv_settings;
11657 		prev_device_state = osdinfo->satadrv_state;
11658 	}
11659 
11660 	start_time = ddi_get_lbolt();
11661 
11662 	/* check parent status */
11663 	mutex_enter(&cportinfo->cport_mutex);
11664 	if ((cportinfo->cport_state &
11665 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11666 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11667 	    SATA_PORT_DEVLINK_UP) {
11668 		mutex_exit(&cportinfo->cport_mutex);
11669 		return (SATA_FAILURE);
11670 	}
11671 	mutex_exit(&cportinfo->cport_mutex);
11672 
11673 retry_probe_pmport:
11674 
11675 	/* probe port */
11676 	mutex_enter(&pmportinfo->pmport_mutex);
11677 	pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11678 	pmportinfo->pmport_state |= SATA_STATE_PROBING;
11679 	mutex_exit(&pmportinfo->pmport_mutex);
11680 
11681 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11682 	    (SATA_DIP(sata_hba_inst), sata_device);
11683 
11684 	/* might need retry because we cannot touch registers. */
11685 	if (rval == SATA_FAILURE) {
11686 		mutex_enter(&pmportinfo->pmport_mutex);
11687 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
11688 		mutex_exit(&pmportinfo->pmport_mutex);
11689 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
11690 		    "SATA port %d:%d probing failed",
11691 		    cport, pmport));
11692 		return (SATA_FAILURE);
11693 	} else if (rval == SATA_RETRY) {
11694 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
11695 		    "SATA port %d:%d probing failed, retrying...",
11696 		    cport, pmport));
11697 		clock_t cur_time = ddi_get_lbolt();
11698 		/*
11699 		 * A device was not successfully identified or initialized.
11700 		 * Track retry time for device identification.
11701 		 */
11702 		if ((cur_time - start_time) <
11703 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11704 			/* sleep for a while */
11705 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11706 			goto retry_probe_pmport;
11707 		} else {
11708 			mutex_enter(&pmportinfo->pmport_mutex);
11709 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11710 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11711 				    satadrv_state = SATA_DSTATE_FAILED;
11712 			mutex_exit(&pmportinfo->pmport_mutex);
11713 			return (SATA_SUCCESS);
11714 		}
11715 	}
11716 
11717 	/*
11718 	 * Sanity check - Controller port is active? Is the link active?
11719 	 * Is it still a port multiplier?
11720 	 */
11721 	if ((cportinfo->cport_state &
11722 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11723 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11724 	    SATA_PORT_DEVLINK_UP ||
11725 	    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
11726 		/*
11727 		 * Port in non-usable state or no link active/no
11728 		 * device. Free info structure.
11729 		 */
11730 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11731 
11732 		sdevice.satadev_addr.cport = cport;
11733 		sdevice.satadev_addr.pmport = pmport;
11734 		sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
11735 		mutex_exit(&cportinfo->cport_mutex);
11736 
11737 		sata_free_pmult(sata_hba_inst, &sdevice);
11738 		return (SATA_FAILURE);
11739 	}
11740 
11741 	/* SATA_SUCCESS NOW */
11742 	/*
11743 	 * update sata port state and set device type
11744 	 */
11745 	mutex_enter(&pmportinfo->pmport_mutex);
11746 	sata_update_pmport_info(sata_hba_inst, sata_device);
11747 	pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
11748 
11749 	/*
11750 	 * Sanity check - Port is active? Is the link active?
11751 	 * Is there any device attached?
11752 	 */
11753 	if ((pmportinfo->pmport_state &
11754 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11755 	    (pmportinfo->pmport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11756 	    SATA_PORT_DEVLINK_UP) {
11757 		/*
11758 		 * Port in non-usable state or no link active/no device.
11759 		 * Free info structure if necessary (direct attached drive
11760 		 * only, for now!
11761 		 */
11762 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11763 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11764 		/* Add here differentiation for device attached or not */
11765 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11766 		mutex_exit(&pmportinfo->pmport_mutex);
11767 		if (sdinfo != NULL)
11768 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11769 		return (SATA_SUCCESS);
11770 	}
11771 
11772 	pmportinfo->pmport_state |= SATA_STATE_READY;
11773 	pmportinfo->pmport_dev_type = sata_device->satadev_type;
11774 	sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11775 
11776 	/*
11777 	 * If we are re-probing the port, there may be
11778 	 * sata_drive_info structure attached
11779 	 * (or sata_pm_info, if PMult is supported).
11780 	 */
11781 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
11782 		/*
11783 		 * There is no device, so remove device info structure,
11784 		 * if necessary.
11785 		 */
11786 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11787 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11788 		if (sdinfo != NULL) {
11789 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11790 			sata_log(sata_hba_inst, CE_WARN,
11791 			    "SATA device detached from port %d:%d",
11792 			    cport, pmport);
11793 		}
11794 		mutex_exit(&pmportinfo->pmport_mutex);
11795 		return (SATA_SUCCESS);
11796 	}
11797 
11798 	/* this should not be a pmult */
11799 	ASSERT(sata_device->satadev_type != SATA_DTYPE_PMULT);
11800 	if (sdinfo == NULL) {
11801 		/*
11802 		 * There is some device attached, but there is
11803 		 * no sata_drive_info structure - allocate one
11804 		 */
11805 		mutex_exit(&pmportinfo->pmport_mutex);
11806 		sdinfo = kmem_zalloc(sizeof (sata_drive_info_t),
11807 		    KM_SLEEP);
11808 		mutex_enter(&pmportinfo->pmport_mutex);
11809 		/*
11810 		 * Recheck, that the port state did not change when we
11811 		 * released mutex.
11812 		 */
11813 		if (pmportinfo->pmport_state & SATA_STATE_READY) {
11814 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = sdinfo;
11815 			sdinfo->satadrv_addr = pmportinfo->pmport_addr;
11816 			sdinfo->satadrv_addr.qual = SATA_ADDR_DPMPORT;
11817 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11818 			sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11819 		} else {
11820 			/*
11821 			 * Port is not in ready state, we
11822 			 * cannot attach a device.
11823 			 */
11824 			mutex_exit(&pmportinfo->pmport_mutex);
11825 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11826 			return (SATA_SUCCESS);
11827 		}
11828 		/*
11829 		 * Since we are adding device, presumably new one,
11830 		 * indicate that it  should be initalized,
11831 		 * as well as some internal framework states).
11832 		 */
11833 		init_device = B_TRUE;
11834 	}
11835 
11836 	pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
11837 	sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
11838 
11839 	mutex_exit(&pmportinfo->pmport_mutex);
11840 	/*
11841 	 * Figure out what kind of device we are really
11842 	 * dealing with.
11843 	 */
11844 	rval = sata_probe_device(sata_hba_inst, sata_device);
11845 
11846 	mutex_enter(&pmportinfo->pmport_mutex);
11847 	if (rval == SATA_SUCCESS) {
11848 		/*
11849 		 * If we are dealing with the same type of a device as before,
11850 		 * restore its settings flags.
11851 		 */
11852 		if (osdinfo != NULL &&
11853 		    sata_device->satadev_type == prev_device_type)
11854 			sdinfo->satadrv_settings = prev_device_settings;
11855 
11856 		mutex_exit(&pmportinfo->pmport_mutex);
11857 		/* Set initial device features, if necessary */
11858 		if (init_device == B_TRUE) {
11859 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
11860 		}
11861 		if (rval == SATA_SUCCESS)
11862 			return (rval);
11863 	} else {
11864 		/*
11865 		 * If there was some device info before we probe the device,
11866 		 * restore previous device setting, so we can retry from scratch
11867 		 * later. Providing, of course, that device has not disappeared
11868 		 * during probing process.
11869 		 */
11870 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
11871 			if (osdinfo != NULL) {
11872 				pmportinfo->pmport_dev_type = prev_device_type;
11873 				sdinfo->satadrv_type = prev_device_type;
11874 				sdinfo->satadrv_state = prev_device_state;
11875 			}
11876 		} else {
11877 			/* device is gone */
11878 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11879 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11880 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11881 			mutex_exit(&pmportinfo->pmport_mutex);
11882 			return (SATA_SUCCESS);
11883 		}
11884 		mutex_exit(&pmportinfo->pmport_mutex);
11885 	}
11886 
11887 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
11888 		clock_t cur_time = ddi_get_lbolt();
11889 		/*
11890 		 * A device was not successfully identified or initialized.
11891 		 * Track retry time for device identification.
11892 		 */
11893 		if ((cur_time - start_time) <
11894 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11895 			/* sleep for a while */
11896 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11897 			goto retry_probe_pmport;
11898 		} else {
11899 			mutex_enter(&pmportinfo->pmport_mutex);
11900 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11901 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11902 				    satadrv_state = SATA_DSTATE_FAILED;
11903 			mutex_exit(&pmportinfo->pmport_mutex);
11904 		}
11905 	}
11906 	return (SATA_SUCCESS);
11907 }
11908 
11909 /*
11910  * Allocated related structure for a port multiplier and its device ports
11911  *
11912  * Port multiplier should be ready and probed, and related information like
11913  * the number of the device ports should be store in sata_device_t.
11914  *
11915  * NOTE: No Mutex should be hold.
11916  */
11917 static int
11918 sata_alloc_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11919 {
11920 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
11921 	sata_cport_info_t *cportinfo = NULL;
11922 	sata_pmult_info_t *pmultinfo = NULL;
11923 	sata_pmport_info_t *pmportinfo = NULL;
11924 	sata_device_t sd;
11925 	dev_t minor_number;
11926 	char name[16];
11927 	uint8_t cport = sata_device->satadev_addr.cport;
11928 	int rval;
11929 	int npmport;
11930 
11931 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11932 
11933 	/* This function might be called while a port-mult is hot-plugged. */
11934 	mutex_enter(&cportinfo->cport_mutex);
11935 
11936 	/* dev_type's not updated when get called from sata_reprobe_port() */
11937 	if (SATA_CPORTINFO_PMULT_INFO(cportinfo) == NULL) {
11938 		/* Create a pmult_info structure */
11939 		SATA_CPORTINFO_PMULT_INFO(cportinfo) =
11940 		    kmem_zalloc(sizeof (sata_pmult_info_t), KM_SLEEP);
11941 	}
11942 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11943 
11944 	pmultinfo->pmult_addr = sata_device->satadev_addr;
11945 	pmultinfo->pmult_addr.qual = SATA_ADDR_PMULT;
11946 	pmultinfo->pmult_state = SATA_STATE_PROBING;
11947 
11948 	/*
11949 	 * Probe the port multiplier with qualifier SATA_ADDR_PMULT_SPEC,
11950 	 * The HBA driver should initialize and register the port multiplier,
11951 	 * sata_register_pmult() will fill following fields,
11952 	 *   + sata_pmult_info.pmult_gscr
11953 	 *   + sata_pmult_info.pmult_num_dev_ports
11954 	 */
11955 	sd.satadev_addr = sata_device->satadev_addr;
11956 	sd.satadev_addr.qual = SATA_ADDR_PMULT_SPEC;
11957 	mutex_exit(&cportinfo->cport_mutex);
11958 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11959 	    (SATA_DIP(sata_hba_inst), &sd);
11960 	mutex_enter(&cportinfo->cport_mutex);
11961 
11962 	if (rval != SATA_SUCCESS ||
11963 	    (sd.satadev_type != SATA_DTYPE_PMULT) ||
11964 	    !(sd.satadev_state & SATA_DSTATE_PMULT_INIT)) {
11965 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
11966 		kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11967 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11968 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11969 		mutex_exit(&cportinfo->cport_mutex);
11970 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11971 		    "sata_alloc_pmult: failed to initialize pmult "
11972 		    "at port %d.", cport)
11973 		return (SATA_FAILURE);
11974 	}
11975 
11976 	/* Initialize pmport_info structure */
11977 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11978 	    npmport++) {
11979 
11980 		/* if everything is allocated, skip */
11981 		if (SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) != NULL)
11982 			continue;
11983 
11984 		pmportinfo = kmem_zalloc(sizeof (sata_pmport_info_t), KM_SLEEP);
11985 		mutex_init(&pmportinfo->pmport_mutex, NULL, MUTEX_DRIVER, NULL);
11986 		mutex_exit(&cportinfo->cport_mutex);
11987 
11988 		mutex_enter(&pmportinfo->pmport_mutex);
11989 		pmportinfo->pmport_addr.cport = cport;
11990 		pmportinfo->pmport_addr.pmport = (uint8_t)npmport;
11991 		pmportinfo->pmport_addr.qual = SATA_ADDR_PMPORT;
11992 		pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11993 		mutex_exit(&pmportinfo->pmport_mutex);
11994 
11995 		mutex_enter(&cportinfo->cport_mutex);
11996 		SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) = pmportinfo;
11997 
11998 		/* Create an attachment point */
11999 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
12000 		    cport, (uint8_t)npmport, SATA_ADDR_PMPORT);
12001 		(void) sprintf(name, "%d.%d", cport, npmport);
12002 
12003 		if (ddi_create_minor_node(dip, name, S_IFCHR, minor_number,
12004 		    DDI_NT_SATA_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
12005 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
12006 			    "cannot create SATA attachment point for "
12007 			    "port %d:%d", cport, npmport);
12008 		}
12009 	}
12010 
12011 	pmultinfo->pmult_state &= ~SATA_STATE_PROBING;
12012 	pmultinfo->pmult_state |= (SATA_STATE_PROBED|SATA_STATE_READY);
12013 	cportinfo->cport_dev_type = SATA_DTYPE_PMULT;
12014 
12015 	mutex_exit(&cportinfo->cport_mutex);
12016 	return (SATA_SUCCESS);
12017 }
12018 
12019 /*
12020  * Free data structures when a port multiplier is removed.
12021  *
12022  * NOTE: No Mutex should be hold.
12023  */
12024 static void
12025 sata_free_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
12026 {
12027 	sata_cport_info_t *cportinfo;
12028 	sata_pmult_info_t *pmultinfo;
12029 	sata_pmport_info_t *pmportinfo;
12030 	sata_device_t pmport_device;
12031 	sata_drive_info_t *sdinfo;
12032 	dev_info_t *tdip;
12033 	char name[16];
12034 	uint8_t cport = sata_device->satadev_addr.cport;
12035 	int npmport;
12036 
12037 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
12038 
12039 	/* This function might be called while port-mult is hot plugged. */
12040 	mutex_enter(&cportinfo->cport_mutex);
12041 
12042 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
12043 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
12044 	ASSERT(pmultinfo != NULL);
12045 
12046 	/* Free pmport_info structure */
12047 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
12048 	    npmport++) {
12049 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
12050 		if (pmportinfo == NULL)
12051 			continue;
12052 		mutex_exit(&cportinfo->cport_mutex);
12053 
12054 		mutex_enter(&pmportinfo->pmport_mutex);
12055 		sdinfo = pmportinfo->pmport_sata_drive;
12056 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
12057 		mutex_exit(&pmportinfo->pmport_mutex);
12058 
12059 		/* Remove attachment point. */
12060 		name[0] = '\0';
12061 		(void) sprintf(name, "%d.%d", cport, npmport);
12062 		ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
12063 		sata_log(sata_hba_inst, CE_NOTE,
12064 		    "Remove attachment point of port %d:%d",
12065 		    cport, npmport);
12066 
12067 		/*
12068 		 * Rumove target node
12069 		 */
12070 		bzero(&pmport_device, sizeof (sata_device_t));
12071 		pmport_device.satadev_rev = SATA_DEVICE_REV;
12072 		pmport_device.satadev_addr.cport = cport;
12073 		pmport_device.satadev_addr.pmport = (uint8_t)npmport;
12074 		pmport_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
12075 
12076 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
12077 		    &(pmport_device.satadev_addr));
12078 		if (tdip != NULL && ndi_devi_offline(tdip,
12079 		    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
12080 			/*
12081 			 * Problem :
12082 			 * The target node remained attached.
12083 			 * This happens when the device file was open
12084 			 * or a node was waiting for resources.
12085 			 * Cannot do anything about it.
12086 			 */
12087 			SATA_LOG_D((sata_hba_inst, CE_WARN,
12088 			    "sata_free_pmult: could not unconfigure device "
12089 			    "before disconnecting the SATA port %d:%d",
12090 			    cport, npmport));
12091 
12092 			/*
12093 			 * Set DEVICE REMOVED state in the target
12094 			 * node. It will prevent access to the device
12095 			 * even when a new device is attached, until
12096 			 * the old target node is released, removed and
12097 			 * recreated for a new  device.
12098 			 */
12099 			sata_set_device_removed(tdip);
12100 
12101 			/*
12102 			 * Instruct event daemon to try the target
12103 			 * node cleanup later.
12104 			 */
12105 			sata_set_target_node_cleanup(
12106 			    sata_hba_inst, &(pmport_device.satadev_addr));
12107 
12108 		}
12109 		mutex_enter(&cportinfo->cport_mutex);
12110 
12111 		/*
12112 		 * Add here differentiation for device attached or not
12113 		 */
12114 		if (sdinfo != NULL)  {
12115 			sata_log(sata_hba_inst, CE_WARN,
12116 			    "SATA device detached from port %d:%d",
12117 			    cport, npmport);
12118 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
12119 		}
12120 
12121 		mutex_destroy(&pmportinfo->pmport_mutex);
12122 		kmem_free(pmportinfo, sizeof (sata_pmport_info_t));
12123 	}
12124 
12125 	kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
12126 
12127 	cportinfo->cport_devp.cport_sata_pmult = NULL;
12128 
12129 	sata_log(sata_hba_inst, CE_WARN,
12130 	    "SATA port multiplier detached at port %d", cport);
12131 
12132 	mutex_exit(&cportinfo->cport_mutex);
12133 }
12134 
12135 /*
12136  * Initialize device
12137  * Specified device is initialized to a default state.
12138  *
12139  * Returns SATA_SUCCESS if all device features are set successfully,
12140  * SATA_RETRY if device is accessible but device features were not set
12141  * successfully, and SATA_FAILURE otherwise.
12142  */
12143 static int
12144 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
12145     sata_drive_info_t *sdinfo)
12146 {
12147 	int rval;
12148 
12149 	sata_save_drive_settings(sdinfo);
12150 
12151 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
12152 
12153 	sata_init_write_cache_mode(sdinfo);
12154 
12155 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
12156 
12157 	/* Determine current data transfer mode */
12158 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
12159 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
12160 	} else if ((sdinfo->satadrv_id.ai_validinfo &
12161 	    SATA_VALIDINFO_88) != 0 &&
12162 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
12163 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
12164 	} else if ((sdinfo->satadrv_id.ai_dworddma &
12165 	    SATA_MDMA_SEL_MASK) != 0) {
12166 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
12167 	} else
12168 		/* DMA supported, not no DMA transfer mode is selected !? */
12169 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
12170 
12171 	if ((sdinfo->satadrv_id.ai_cmdset83 & 0x20) &&
12172 	    (sdinfo->satadrv_id.ai_features86 & 0x20))
12173 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
12174 	else
12175 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
12176 
12177 	return (rval);
12178 }
12179 
12180 
12181 /*
12182  * Initialize write cache mode.
12183  *
12184  * The default write cache setting for SATA HDD is provided by sata_write_cache
12185  * static variable. ATAPI CD/DVDs devices have write cache default is
12186  * determined by sata_atapicdvd_write_cache static variable.
12187  * ATAPI tape devices have write cache default is determined by
12188  * sata_atapitape_write_cache static variable.
12189  * ATAPI disk devices have write cache default is determined by
12190  * sata_atapidisk_write_cache static variable.
12191  * 1 - enable
12192  * 0 - disable
12193  * any other value - current drive setting
12194  *
12195  * Although there is not reason to disable write cache on CD/DVD devices,
12196  * tape devices and ATAPI disk devices, the default setting control is provided
12197  * for the maximun flexibility.
12198  *
12199  * In the future, it may be overridden by the
12200  * disk-write-cache-enable property setting, if it is defined.
12201  * Returns SATA_SUCCESS if all device features are set successfully,
12202  * SATA_FAILURE otherwise.
12203  */
12204 static void
12205 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
12206 {
12207 	switch (sdinfo->satadrv_type) {
12208 	case SATA_DTYPE_ATADISK:
12209 		if (sata_write_cache == 1)
12210 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12211 		else if (sata_write_cache == 0)
12212 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12213 		/*
12214 		 * When sata_write_cache value is not 0 or 1,
12215 		 * a current setting of the drive's write cache is used.
12216 		 */
12217 		break;
12218 	case SATA_DTYPE_ATAPICD:
12219 		if (sata_atapicdvd_write_cache == 1)
12220 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12221 		else if (sata_atapicdvd_write_cache == 0)
12222 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12223 		/*
12224 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
12225 		 * a current setting of the drive's write cache is used.
12226 		 */
12227 		break;
12228 	case SATA_DTYPE_ATAPITAPE:
12229 		if (sata_atapitape_write_cache == 1)
12230 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12231 		else if (sata_atapitape_write_cache == 0)
12232 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12233 		/*
12234 		 * When sata_atapitape_write_cache value is not 0 or 1,
12235 		 * a current setting of the drive's write cache is used.
12236 		 */
12237 		break;
12238 	case SATA_DTYPE_ATAPIDISK:
12239 		if (sata_atapidisk_write_cache == 1)
12240 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12241 		else if (sata_atapidisk_write_cache == 0)
12242 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12243 		/*
12244 		 * When sata_atapidisk_write_cache value is not 0 or 1,
12245 		 * a current setting of the drive's write cache is used.
12246 		 */
12247 		break;
12248 	}
12249 }
12250 
12251 
12252 /*
12253  * Validate sata address.
12254  * Specified cport, pmport and qualifier has to match
12255  * passed sata_scsi configuration info.
12256  * The presence of an attached device is not verified.
12257  *
12258  * Returns 0 when address is valid, -1 otherwise.
12259  */
12260 static int
12261 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
12262     int pmport, int qual)
12263 {
12264 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
12265 		goto invalid_address;
12266 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
12267 		goto invalid_address;
12268 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
12269 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
12270 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
12271 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
12272 		goto invalid_address;
12273 
12274 	return (0);
12275 
12276 invalid_address:
12277 	return (-1);
12278 
12279 }
12280 
12281 /*
12282  * Validate scsi address
12283  * SCSI target address is translated into SATA cport/pmport and compared
12284  * with a controller port/device configuration. LUN has to be 0.
12285  * Returns 0 if a scsi target refers to an attached device,
12286  * returns 1 if address is valid but no valid device is attached,
12287  * returns 2 if address is valid but device type is unknown (not valid device),
12288  * returns -1 if bad address or device is of an unsupported type.
12289  * Upon return sata_device argument is set.
12290  *
12291  * Port multiplier is supported now.
12292  */
12293 static int
12294 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
12295     struct scsi_address *ap, sata_device_t *sata_device)
12296 {
12297 	int cport, pmport, qual, rval;
12298 
12299 	rval = -1;	/* Invalid address */
12300 	if (ap->a_lun != 0)
12301 		goto out;
12302 
12303 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
12304 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
12305 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
12306 
12307 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
12308 		goto out;
12309 
12310 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
12311 	    0) {
12312 
12313 		sata_cport_info_t *cportinfo;
12314 		sata_pmult_info_t *pmultinfo;
12315 		sata_drive_info_t *sdinfo = NULL;
12316 
12317 		sata_device->satadev_addr.qual = qual;
12318 		sata_device->satadev_addr.cport = cport;
12319 		sata_device->satadev_addr.pmport = pmport;
12320 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
12321 
12322 		rval = 1;	/* Valid sata address */
12323 
12324 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
12325 		if (qual == SATA_ADDR_DCPORT) {
12326 			if (cportinfo == NULL ||
12327 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
12328 				goto out;
12329 
12330 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
12331 			if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN &&
12332 			    sdinfo != NULL) {
12333 				rval = 2;
12334 				goto out;
12335 			}
12336 
12337 			if ((cportinfo->cport_dev_type &
12338 			    SATA_VALID_DEV_TYPE) == 0) {
12339 				rval = -1;
12340 				goto out;
12341 			}
12342 
12343 		} else if (qual == SATA_ADDR_DPMPORT) {
12344 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
12345 			if (pmultinfo == NULL) {
12346 				rval = -1;
12347 				goto out;
12348 			}
12349 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
12350 			    NULL ||
12351 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
12352 			    pmport) == SATA_DTYPE_NONE)
12353 				goto out;
12354 
12355 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
12356 			    pmport);
12357 			if (SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
12358 			    pmport) == SATA_DTYPE_UNKNOWN && sdinfo != NULL) {
12359 				rval = 2;
12360 				goto out;
12361 			}
12362 
12363 			if ((SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
12364 			    pmport) & SATA_VALID_DEV_TYPE) == 0) {
12365 				rval = -1;
12366 				goto out;
12367 			}
12368 
12369 		} else {
12370 			rval = -1;
12371 			goto out;
12372 		}
12373 		if ((sdinfo == NULL) ||
12374 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
12375 			goto out;
12376 
12377 		sata_device->satadev_type = sdinfo->satadrv_type;
12378 
12379 		return (0);
12380 	}
12381 out:
12382 	if (rval > 0) {
12383 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
12384 		    "sata_validate_scsi_address: no valid target %x lun %x",
12385 		    ap->a_target, ap->a_lun);
12386 	}
12387 	return (rval);
12388 }
12389 
12390 /*
12391  * Find dip corresponding to passed device number
12392  *
12393  * Returns NULL if invalid device number is passed or device cannot be found,
12394  * Returns dip is device is found.
12395  */
12396 static dev_info_t *
12397 sata_devt_to_devinfo(dev_t dev)
12398 {
12399 	dev_info_t *dip;
12400 #ifndef __lock_lint
12401 	struct devnames *dnp;
12402 	major_t major = getmajor(dev);
12403 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
12404 
12405 	if (major >= devcnt)
12406 		return (NULL);
12407 
12408 	dnp = &devnamesp[major];
12409 	LOCK_DEV_OPS(&(dnp->dn_lock));
12410 	dip = dnp->dn_head;
12411 	while (dip && (ddi_get_instance(dip) != instance)) {
12412 		dip = ddi_get_next(dip);
12413 	}
12414 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
12415 #endif
12416 
12417 	return (dip);
12418 }
12419 
12420 
12421 /*
12422  * Probe device.
12423  * This function issues Identify Device command and initializes local
12424  * sata_drive_info structure if the device can be identified.
12425  * The device type is determined by examining Identify Device
12426  * command response.
12427  * If the sata_hba_inst has linked drive info structure for this
12428  * device address, the Identify Device data is stored into sata_drive_info
12429  * structure linked to the port info structure.
12430  *
12431  * sata_device has to refer to the valid sata port(s) for HBA described
12432  * by sata_hba_inst structure.
12433  *
12434  * Returns:
12435  *	SATA_SUCCESS if device type was successfully probed and port-linked
12436  *		drive info structure was updated;
12437  *	SATA_FAILURE if there is no device, or device was not probed
12438  *		successully;
12439  *	SATA_RETRY if device probe can be retried later.
12440  * If a device cannot be identified, sata_device's dev_state and dev_type
12441  * fields are set to unknown.
12442  * There are no retries in this function. Any retries should be managed by
12443  * the caller.
12444  */
12445 
12446 
12447 static int
12448 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
12449 {
12450 	sata_pmport_info_t *pmportinfo;
12451 	sata_drive_info_t *sdinfo;
12452 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
12453 	int rval;
12454 
12455 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
12456 	    sata_device->satadev_addr.cport) &
12457 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
12458 
12459 	sata_device->satadev_type = SATA_DTYPE_NONE;
12460 
12461 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12462 	    sata_device->satadev_addr.cport)));
12463 
12464 	if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT) {
12465 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
12466 		    sata_device->satadev_addr.cport,
12467 		    sata_device->satadev_addr.pmport);
12468 		ASSERT(pmportinfo != NULL);
12469 	}
12470 
12471 	/* Get pointer to port-linked sata device info structure */
12472 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12473 	if (sdinfo != NULL) {
12474 		sdinfo->satadrv_state &=
12475 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
12476 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
12477 	} else {
12478 		/* No device to probe */
12479 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12480 		    sata_device->satadev_addr.cport)));
12481 		sata_device->satadev_type = SATA_DTYPE_NONE;
12482 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
12483 		return (SATA_FAILURE);
12484 	}
12485 	/*
12486 	 * Need to issue both types of identify device command and
12487 	 * determine device type by examining retreived data/status.
12488 	 * First, ATA Identify Device.
12489 	 */
12490 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
12491 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
12492 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12493 	    sata_device->satadev_addr.cport)));
12494 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
12495 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
12496 	if (rval == SATA_RETRY) {
12497 		/* We may try to check for ATAPI device */
12498 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
12499 			/*
12500 			 * HBA supports ATAPI - try to issue Identify Packet
12501 			 * Device command.
12502 			 */
12503 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
12504 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
12505 		}
12506 	}
12507 	if (rval == SATA_SUCCESS) {
12508 		/*
12509 		 * Got something responding positively to ATA Identify Device
12510 		 * or to Identify Packet Device cmd.
12511 		 * Save last used device type.
12512 		 */
12513 		sata_device->satadev_type = new_sdinfo.satadrv_type;
12514 
12515 		/* save device info, if possible */
12516 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12517 		    sata_device->satadev_addr.cport)));
12518 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12519 		if (sdinfo == NULL) {
12520 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12521 			    sata_device->satadev_addr.cport)));
12522 			return (SATA_FAILURE);
12523 		}
12524 		/*
12525 		 * Copy drive info into the port-linked drive info structure.
12526 		 */
12527 		*sdinfo = new_sdinfo;
12528 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
12529 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
12530 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
12531 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
12532 			    sata_device->satadev_addr.cport) =
12533 			    sdinfo->satadrv_type;
12534 		else { /* SATA_ADDR_DPMPORT */
12535 			mutex_enter(&pmportinfo->pmport_mutex);
12536 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
12537 			    sata_device->satadev_addr.cport,
12538 			    sata_device->satadev_addr.pmport) =
12539 			    sdinfo->satadrv_type;
12540 			mutex_exit(&pmportinfo->pmport_mutex);
12541 		}
12542 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12543 		    sata_device->satadev_addr.cport)));
12544 		return (SATA_SUCCESS);
12545 	}
12546 
12547 	/*
12548 	 * It may be SATA_RETRY or SATA_FAILURE return.
12549 	 * Looks like we cannot determine the device type at this time.
12550 	 */
12551 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12552 	    sata_device->satadev_addr.cport)));
12553 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12554 	if (sdinfo != NULL) {
12555 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
12556 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12557 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
12558 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
12559 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
12560 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
12561 			    sata_device->satadev_addr.cport) =
12562 			    SATA_DTYPE_UNKNOWN;
12563 		else {
12564 			/* SATA_ADDR_DPMPORT */
12565 			mutex_enter(&pmportinfo->pmport_mutex);
12566 			if ((SATA_PMULT_INFO(sata_hba_inst,
12567 			    sata_device->satadev_addr.cport) != NULL) &&
12568 			    (SATA_PMPORT_INFO(sata_hba_inst,
12569 			    sata_device->satadev_addr.cport,
12570 			    sata_device->satadev_addr.pmport) != NULL))
12571 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
12572 				    sata_device->satadev_addr.cport,
12573 				    sata_device->satadev_addr.pmport) =
12574 				    SATA_DTYPE_UNKNOWN;
12575 			mutex_exit(&pmportinfo->pmport_mutex);
12576 		}
12577 	}
12578 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12579 	    sata_device->satadev_addr.cport)));
12580 	return (rval);
12581 }
12582 
12583 
12584 /*
12585  * Get pointer to sata_drive_info structure.
12586  *
12587  * The sata_device has to contain address (cport, pmport and qualifier) for
12588  * specified sata_scsi structure.
12589  *
12590  * Returns NULL if device address is not valid for this HBA configuration.
12591  * Otherwise, returns a pointer to sata_drive_info structure.
12592  *
12593  * This function should be called with a port mutex held.
12594  */
12595 static sata_drive_info_t *
12596 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
12597     sata_device_t *sata_device)
12598 {
12599 	uint8_t cport = sata_device->satadev_addr.cport;
12600 	uint8_t pmport = sata_device->satadev_addr.pmport;
12601 	uint8_t qual = sata_device->satadev_addr.qual;
12602 
12603 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
12604 		return (NULL);
12605 
12606 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
12607 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
12608 		/* Port not probed yet */
12609 		return (NULL);
12610 
12611 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
12612 		return (NULL);
12613 
12614 	if (qual == SATA_ADDR_DCPORT) {
12615 		/* Request for a device on a controller port */
12616 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
12617 		    SATA_DTYPE_PMULT)
12618 			/* Port multiplier attached */
12619 			return (NULL);
12620 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
12621 	}
12622 	if (qual == SATA_ADDR_DPMPORT) {
12623 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
12624 		    SATA_DTYPE_PMULT)
12625 			return (NULL);
12626 
12627 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
12628 			return (NULL);
12629 
12630 		if (!(SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) &
12631 		    (SATA_STATE_PROBED | SATA_STATE_READY)))
12632 			/* Port multiplier port not probed yet */
12633 			return (NULL);
12634 
12635 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
12636 	}
12637 
12638 	/* we should not get here */
12639 	return (NULL);
12640 }
12641 
12642 
12643 /*
12644  * sata_identify_device.
12645  * Send Identify Device command to SATA HBA driver.
12646  * If command executes successfully, update sata_drive_info structure pointed
12647  * to by sdinfo argument, including Identify Device data.
12648  * If command fails, invalidate data in sata_drive_info.
12649  *
12650  * Cannot be called from interrupt level.
12651  *
12652  * Returns:
12653  * SATA_SUCCESS if the device was identified as a supported device,
12654  * SATA_RETRY if the device was not identified but could be retried,
12655  * SATA_FAILURE if the device was not identified and identify attempt
12656  *	should not be retried.
12657  */
12658 static int
12659 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
12660     sata_drive_info_t *sdinfo)
12661 {
12662 	uint16_t cfg_word;
12663 	int rval;
12664 
12665 	/* fetch device identify data */
12666 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
12667 	    sdinfo)) != SATA_SUCCESS)
12668 		goto fail_unknown;
12669 
12670 	cfg_word = sdinfo->satadrv_id.ai_config;
12671 
12672 	/* Set the correct device type */
12673 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
12674 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
12675 	} else if (cfg_word == SATA_CFA_TYPE) {
12676 		/* It's a Compact Flash media via CF-to-SATA HDD adapter */
12677 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
12678 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
12679 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
12680 		case SATA_ATAPI_CDROM_DEV:
12681 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
12682 			break;
12683 		case SATA_ATAPI_SQACC_DEV:
12684 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
12685 			break;
12686 		case SATA_ATAPI_DIRACC_DEV:
12687 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
12688 			break;
12689 		case SATA_ATAPI_PROC_DEV:
12690 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIPROC;
12691 			break;
12692 		default:
12693 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12694 		}
12695 	} else {
12696 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12697 	}
12698 
12699 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12700 		if (sdinfo->satadrv_capacity == 0) {
12701 			/* Non-LBA disk. Too bad... */
12702 			sata_log(sata_hba_inst, CE_WARN,
12703 			    "SATA disk device at port %d does not support LBA",
12704 			    sdinfo->satadrv_addr.cport);
12705 			rval = SATA_FAILURE;
12706 			goto fail_unknown;
12707 		}
12708 	}
12709 #if 0
12710 	/* Left for historical reason */
12711 	/*
12712 	 * Some initial version of SATA spec indicated that at least
12713 	 * UDMA mode 4 has to be supported. It is not metioned in
12714 	 * SerialATA 2.6, so this restriction is removed.
12715 	 */
12716 	/* Check for Ultra DMA modes 6 through 0 being supported */
12717 	for (i = 6; i >= 0; --i) {
12718 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
12719 			break;
12720 	}
12721 
12722 	/*
12723 	 * At least UDMA 4 mode has to be supported. If mode 4 or
12724 	 * higher are not supported by the device, fail this
12725 	 * device.
12726 	 */
12727 	if (i < 4) {
12728 		/* No required Ultra DMA mode supported */
12729 		sata_log(sata_hba_inst, CE_WARN,
12730 		    "SATA disk device at port %d does not support UDMA "
12731 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
12732 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12733 		    "mode 4 or higher required, %d supported", i));
12734 		rval = SATA_FAILURE;
12735 		goto fail_unknown;
12736 	}
12737 #endif
12738 
12739 	/*
12740 	 * For Disk devices, if it doesn't support UDMA mode, we would
12741 	 * like to return failure directly.
12742 	 */
12743 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
12744 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
12745 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
12746 		sata_log(sata_hba_inst, CE_WARN,
12747 		    "SATA disk device at port %d does not support UDMA",
12748 		    sdinfo->satadrv_addr.cport);
12749 		rval = SATA_FAILURE;
12750 		goto fail_unknown;
12751 	}
12752 
12753 	return (SATA_SUCCESS);
12754 
12755 fail_unknown:
12756 	/* Invalidate sata_drive_info ? */
12757 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12758 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
12759 	return (rval);
12760 }
12761 
12762 /*
12763  * Log/display device information
12764  */
12765 static void
12766 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
12767     sata_drive_info_t *sdinfo)
12768 {
12769 	int valid_version;
12770 	char msg_buf[MAXPATHLEN];
12771 	int i;
12772 
12773 	/* Show HBA path */
12774 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
12775 
12776 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
12777 
12778 	switch (sdinfo->satadrv_type) {
12779 	case SATA_DTYPE_ATADISK:
12780 		(void) sprintf(msg_buf, "SATA disk device at");
12781 		break;
12782 
12783 	case SATA_DTYPE_ATAPICD:
12784 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
12785 		break;
12786 
12787 	case SATA_DTYPE_ATAPITAPE:
12788 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
12789 		break;
12790 
12791 	case SATA_DTYPE_ATAPIDISK:
12792 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
12793 		break;
12794 
12795 	case SATA_DTYPE_ATAPIPROC:
12796 		(void) sprintf(msg_buf, "SATA processor (ATAPI) device at");
12797 		break;
12798 
12799 	case SATA_DTYPE_UNKNOWN:
12800 		(void) sprintf(msg_buf,
12801 		    "Unsupported SATA device type (cfg 0x%x) at ",
12802 		    sdinfo->satadrv_id.ai_config);
12803 		break;
12804 	}
12805 
12806 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
12807 		cmn_err(CE_CONT, "?\t%s port %d\n",
12808 		    msg_buf, sdinfo->satadrv_addr.cport);
12809 	else
12810 		cmn_err(CE_CONT, "?\t%s port %d:%d\n",
12811 		    msg_buf, sdinfo->satadrv_addr.cport,
12812 		    sdinfo->satadrv_addr.pmport);
12813 
12814 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
12815 	    sizeof (sdinfo->satadrv_id.ai_model));
12816 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
12817 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
12818 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
12819 
12820 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
12821 	    sizeof (sdinfo->satadrv_id.ai_fw));
12822 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
12823 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
12824 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
12825 
12826 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
12827 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12828 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
12829 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
12830 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12831 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12832 	} else {
12833 		/*
12834 		 * Some drives do not implement serial number and may
12835 		 * violate the spec by providing spaces rather than zeros
12836 		 * in serial number field. Scan the buffer to detect it.
12837 		 */
12838 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
12839 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
12840 				break;
12841 		}
12842 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
12843 			cmn_err(CE_CONT, "?\tserial number - none\n");
12844 		} else {
12845 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12846 		}
12847 	}
12848 
12849 #ifdef SATA_DEBUG
12850 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
12851 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
12852 		int i;
12853 		for (i = 14; i >= 2; i--) {
12854 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
12855 				valid_version = i;
12856 				break;
12857 			}
12858 		}
12859 		cmn_err(CE_CONT,
12860 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
12861 		    valid_version,
12862 		    sdinfo->satadrv_id.ai_majorversion,
12863 		    sdinfo->satadrv_id.ai_minorversion);
12864 	}
12865 #endif
12866 	/* Log some info */
12867 	cmn_err(CE_CONT, "?\tsupported features:\n");
12868 	msg_buf[0] = '\0';
12869 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12870 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
12871 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
12872 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
12873 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
12874 	}
12875 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
12876 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
12877 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
12878 		(void) strlcat(msg_buf, ", Native Command Queueing",
12879 		    MAXPATHLEN);
12880 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
12881 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
12882 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
12883 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
12884 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
12885 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
12886 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
12887 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
12888 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
12889 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA3)
12890 		cmn_err(CE_CONT, "?\tSATA Gen3 signaling speed (6.0Gbps)\n");
12891 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
12892 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
12893 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
12894 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
12895 	if (sdinfo->satadrv_features_support &
12896 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
12897 		msg_buf[0] = '\0';
12898 		(void) snprintf(msg_buf, MAXPATHLEN,
12899 		    "Supported queue depth %d",
12900 		    sdinfo->satadrv_queue_depth);
12901 		if (!(sata_func_enable &
12902 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
12903 			(void) strlcat(msg_buf,
12904 			    " - queueing disabled globally", MAXPATHLEN);
12905 		else if (sdinfo->satadrv_queue_depth >
12906 		    sdinfo->satadrv_max_queue_depth) {
12907 			(void) snprintf(&msg_buf[strlen(msg_buf)],
12908 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
12909 			    (int)sdinfo->satadrv_max_queue_depth);
12910 		}
12911 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
12912 	}
12913 
12914 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12915 #ifdef __i386
12916 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
12917 		    sdinfo->satadrv_capacity);
12918 #else
12919 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
12920 		    sdinfo->satadrv_capacity);
12921 #endif
12922 		cmn_err(CE_CONT, "?%s", msg_buf);
12923 	}
12924 }
12925 
12926 /*
12927  * Log/display port multiplier information
12928  * No Mutex should be hold.
12929  */
12930 static void
12931 sata_show_pmult_info(sata_hba_inst_t *sata_hba_inst,
12932     sata_device_t *sata_device)
12933 {
12934 	_NOTE(ARGUNUSED(sata_hba_inst))
12935 
12936 	int cport = sata_device->satadev_addr.cport;
12937 	sata_pmult_info_t *pmultinfo;
12938 	char msg_buf[MAXPATHLEN];
12939 	uint32_t gscr0, gscr1, gscr2, gscr64;
12940 
12941 	mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12942 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
12943 	if (pmultinfo == NULL) {
12944 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12945 		return;
12946 	}
12947 
12948 	gscr0 = pmultinfo->pmult_gscr.gscr0;
12949 	gscr1 = pmultinfo->pmult_gscr.gscr1;
12950 	gscr2 = pmultinfo->pmult_gscr.gscr2;
12951 	gscr64 = pmultinfo->pmult_gscr.gscr64;
12952 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12953 
12954 	cmn_err(CE_CONT, "?Port Multiplier %d device-ports found at port %d",
12955 	    sata_device->satadev_add_info, sata_device->satadev_addr.cport);
12956 
12957 	(void) sprintf(msg_buf, "\tVendor_ID 0x%04x, Module_ID 0x%04x",
12958 	    gscr0 & 0xffff, (gscr0 >> 16) & 0xffff);
12959 	cmn_err(CE_CONT, "?%s", msg_buf);
12960 
12961 	(void) strcpy(msg_buf, "\tSupport SATA PMP Spec ");
12962 	if (gscr1 & (1 << 3))
12963 		(void) strlcat(msg_buf, "1.2", MAXPATHLEN);
12964 	else if (gscr1 & (1 << 2))
12965 		(void) strlcat(msg_buf, "1.1", MAXPATHLEN);
12966 	else if (gscr1 & (1 << 1))
12967 		(void) strlcat(msg_buf, "1.0", MAXPATHLEN);
12968 	else
12969 		(void) strlcat(msg_buf, "unknown", MAXPATHLEN);
12970 	cmn_err(CE_CONT, "?%s", msg_buf);
12971 
12972 	(void) strcpy(msg_buf, "\tSupport ");
12973 	if (gscr64 & (1 << 3))
12974 		(void) strlcat(msg_buf, "Asy-Notif, ",
12975 		    MAXPATHLEN);
12976 	if (gscr64 & (1 << 2))
12977 		(void) strlcat(msg_buf, "Dyn-SSC, ", MAXPATHLEN);
12978 	if (gscr64 & (1 << 1))
12979 		(void) strlcat(msg_buf, "Iss-PMREQ, ", MAXPATHLEN);
12980 	if (gscr64 & (1 << 0))
12981 		(void) strlcat(msg_buf, "BIST", MAXPATHLEN);
12982 	if ((gscr64 & 0xf) == 0)
12983 		(void) strlcat(msg_buf, "nothing", MAXPATHLEN);
12984 	cmn_err(CE_CONT, "?%s", msg_buf);
12985 
12986 	(void) sprintf(msg_buf, "\tNumber of exposed device fan-out ports: %d",
12987 	    gscr2 & SATA_PMULT_PORTNUM_MASK);
12988 	cmn_err(CE_CONT, "?%s", msg_buf);
12989 }
12990 
12991 /*
12992  * sata_save_drive_settings extracts current setting of the device and stores
12993  * it for future reference, in case the device setup would need to be restored
12994  * after the device reset.
12995  *
12996  * For all devices read ahead and write cache settings are saved, if the
12997  * device supports these features at all.
12998  * For ATAPI devices the Removable Media Status Notification setting is saved.
12999  */
13000 static void
13001 sata_save_drive_settings(sata_drive_info_t *sdinfo)
13002 {
13003 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
13004 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
13005 
13006 		/* Current setting of Read Ahead (and Read Cache) */
13007 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
13008 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
13009 		else
13010 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
13011 
13012 		/* Current setting of Write Cache */
13013 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
13014 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
13015 		else
13016 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
13017 	}
13018 
13019 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
13020 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
13021 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
13022 		else
13023 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
13024 	}
13025 }
13026 
13027 
13028 /*
13029  * sata_check_capacity function determines a disk capacity
13030  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
13031  *
13032  * NOTE: CHS mode is not supported! If a device does not support LBA,
13033  * this function is not called.
13034  *
13035  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
13036  */
13037 static uint64_t
13038 sata_check_capacity(sata_drive_info_t *sdinfo)
13039 {
13040 	uint64_t capacity = 0;
13041 	int i;
13042 
13043 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
13044 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
13045 		/* Capacity valid only for LBA-addressable disk devices */
13046 		return (0);
13047 
13048 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
13049 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
13050 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
13051 		/* LBA48 mode supported and enabled */
13052 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
13053 		    SATA_DEV_F_LBA28;
13054 		for (i = 3;  i >= 0;  --i) {
13055 			capacity <<= 16;
13056 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
13057 		}
13058 	} else {
13059 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
13060 		capacity <<= 16;
13061 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
13062 		if (capacity >= 0x1000000)
13063 			/* LBA28 mode */
13064 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
13065 	}
13066 	return (capacity);
13067 }
13068 
13069 
13070 /*
13071  * Allocate consistent buffer for DMA transfer
13072  *
13073  * Cannot be called from interrupt level or with mutex held - it may sleep.
13074  *
13075  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
13076  */
13077 static struct buf *
13078 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
13079 {
13080 	struct scsi_address ap;
13081 	struct buf *bp;
13082 	ddi_dma_attr_t	cur_dma_attr;
13083 
13084 	ASSERT(spx->txlt_sata_pkt != NULL);
13085 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
13086 	ap.a_target = SATA_TO_SCSI_TARGET(
13087 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
13088 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
13089 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
13090 	ap.a_lun = 0;
13091 
13092 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
13093 	    B_READ, SLEEP_FUNC, NULL);
13094 
13095 	if (bp != NULL) {
13096 		/* Allocate DMA resources for this buffer */
13097 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
13098 		/*
13099 		 * We use a local version of the dma_attr, to account
13100 		 * for a device addressing limitations.
13101 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
13102 		 * will cause dma attributes to be adjusted to a lowest
13103 		 * acceptable level.
13104 		 */
13105 		sata_adjust_dma_attr(NULL,
13106 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
13107 
13108 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
13109 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
13110 			scsi_free_consistent_buf(bp);
13111 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
13112 			bp = NULL;
13113 		}
13114 	}
13115 	return (bp);
13116 }
13117 
13118 /*
13119  * Release local buffer (consistent buffer for DMA transfer) allocated
13120  * via sata_alloc_local_buffer().
13121  */
13122 static void
13123 sata_free_local_buffer(sata_pkt_txlate_t *spx)
13124 {
13125 	ASSERT(spx->txlt_sata_pkt != NULL);
13126 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
13127 
13128 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
13129 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
13130 
13131 	sata_common_free_dma_rsrcs(spx);
13132 
13133 	/* Free buffer */
13134 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
13135 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
13136 }
13137 
13138 /*
13139  * Allocate sata_pkt
13140  * Pkt structure version and embedded strcutures version are initialized.
13141  * sata_pkt and sata_pkt_txlate structures are cross-linked.
13142  *
13143  * Since this may be called in interrupt context by sata_scsi_init_pkt,
13144  * callback argument determines if it can sleep or not.
13145  * Hence, it should not be called from interrupt context.
13146  *
13147  * If successful, non-NULL pointer to a sata pkt is returned.
13148  * Upon failure, NULL pointer is returned.
13149  */
13150 static sata_pkt_t *
13151 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
13152 {
13153 	sata_pkt_t *spkt;
13154 	int kmsflag;
13155 
13156 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
13157 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
13158 	if (spkt == NULL) {
13159 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
13160 		    "sata_pkt_alloc: failed"));
13161 		return (NULL);
13162 	}
13163 	spkt->satapkt_rev = SATA_PKT_REV;
13164 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
13165 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
13166 	spkt->satapkt_framework_private = spx;
13167 	spx->txlt_sata_pkt = spkt;
13168 	return (spkt);
13169 }
13170 
13171 /*
13172  * Free sata pkt allocated via sata_pkt_alloc()
13173  */
13174 static void
13175 sata_pkt_free(sata_pkt_txlate_t *spx)
13176 {
13177 	ASSERT(spx->txlt_sata_pkt != NULL);
13178 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
13179 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
13180 	spx->txlt_sata_pkt = NULL;
13181 }
13182 
13183 
13184 /*
13185  * Adjust DMA attributes.
13186  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
13187  * from 8 bits to 16 bits, depending on a command being used.
13188  * Limiting max block count arbitrarily to 256 for all read/write
13189  * commands may affects performance, so check both the device and
13190  * controller capability before adjusting dma attributes.
13191  */
13192 void
13193 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
13194     ddi_dma_attr_t *adj_dma_attr)
13195 {
13196 	uint32_t count_max;
13197 
13198 	/* Copy original attributes */
13199 	*adj_dma_attr = *dma_attr;
13200 	/*
13201 	 * Things to consider: device addressing capability,
13202 	 * "excessive" controller DMA capabilities.
13203 	 * If a device is being probed/initialized, there are
13204 	 * no device info - use default limits then.
13205 	 */
13206 	if (sdinfo == NULL) {
13207 		count_max = dma_attr->dma_attr_granular * 0x100;
13208 		if (dma_attr->dma_attr_count_max > count_max)
13209 			adj_dma_attr->dma_attr_count_max = count_max;
13210 		if (dma_attr->dma_attr_maxxfer > count_max)
13211 			adj_dma_attr->dma_attr_maxxfer = count_max;
13212 		return;
13213 	}
13214 
13215 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
13216 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
13217 			/*
13218 			 * 16-bit sector count may be used - we rely on
13219 			 * the assumption that only read and write cmds
13220 			 * will request more than 256 sectors worth of data
13221 			 */
13222 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
13223 		} else {
13224 			/*
13225 			 * 8-bit sector count will be used - default limits
13226 			 * for dma attributes
13227 			 */
13228 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
13229 		}
13230 		/*
13231 		 * Adjust controler dma attributes, if necessary
13232 		 */
13233 		if (dma_attr->dma_attr_count_max > count_max)
13234 			adj_dma_attr->dma_attr_count_max = count_max;
13235 		if (dma_attr->dma_attr_maxxfer > count_max)
13236 			adj_dma_attr->dma_attr_maxxfer = count_max;
13237 	}
13238 }
13239 
13240 
13241 /*
13242  * Allocate DMA resources for the buffer
13243  * This function handles initial DMA resource allocation as well as
13244  * DMA window shift and may be called repeatedly for the same DMA window
13245  * until all DMA cookies in the DMA window are processed.
13246  * To guarantee that there is always a coherent set of cookies to process
13247  * by SATA HBA driver (observing alignment, device granularity, etc.),
13248  * the number of slots for DMA cookies is equal to lesser of  a number of
13249  * cookies in a DMA window and a max number of scatter/gather entries.
13250  *
13251  * Returns DDI_SUCCESS upon successful operation.
13252  * Return failure code of a failing command or DDI_FAILURE when
13253  * internal cleanup failed.
13254  */
13255 static int
13256 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
13257     int (*callback)(caddr_t), caddr_t arg,
13258     ddi_dma_attr_t *cur_dma_attr)
13259 {
13260 	int	rval;
13261 	off_t	offset;
13262 	size_t	size;
13263 	int	max_sg_len, req_len, i;
13264 	uint_t	dma_flags;
13265 	struct buf	*bp;
13266 	uint64_t	cur_txfer_len;
13267 
13268 
13269 	ASSERT(spx->txlt_sata_pkt != NULL);
13270 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
13271 	ASSERT(bp != NULL);
13272 
13273 
13274 	if (spx->txlt_buf_dma_handle == NULL) {
13275 		/*
13276 		 * No DMA resources allocated so far - this is a first call
13277 		 * for this sata pkt.
13278 		 */
13279 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
13280 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
13281 
13282 		if (rval != DDI_SUCCESS) {
13283 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
13284 			    "sata_dma_buf_setup: no buf DMA resources %x",
13285 			    rval));
13286 			return (rval);
13287 		}
13288 
13289 		if (bp->b_flags & B_READ)
13290 			dma_flags = DDI_DMA_READ;
13291 		else
13292 			dma_flags = DDI_DMA_WRITE;
13293 
13294 		if (flags & PKT_CONSISTENT)
13295 			dma_flags |= DDI_DMA_CONSISTENT;
13296 
13297 		if (flags & PKT_DMA_PARTIAL)
13298 			dma_flags |= DDI_DMA_PARTIAL;
13299 
13300 		/*
13301 		 * Check buffer alignment and size against dma attributes
13302 		 * Consider dma_attr_align only. There may be requests
13303 		 * with the size lower than device granularity, but they
13304 		 * will not read/write from/to the device, so no adjustment
13305 		 * is necessary. The dma_attr_minxfer theoretically should
13306 		 * be considered, but no HBA driver is checking it.
13307 		 */
13308 		if (IS_P2ALIGNED(bp->b_un.b_addr,
13309 		    cur_dma_attr->dma_attr_align)) {
13310 			rval = ddi_dma_buf_bind_handle(
13311 			    spx->txlt_buf_dma_handle,
13312 			    bp, dma_flags, callback, arg,
13313 			    &spx->txlt_dma_cookie,
13314 			    &spx->txlt_curwin_num_dma_cookies);
13315 		} else { /* Buffer is not aligned */
13316 
13317 			int	(*ddicallback)(caddr_t);
13318 			size_t	bufsz;
13319 
13320 			/* Check id sleeping is allowed */
13321 			ddicallback = (callback == NULL_FUNC) ?
13322 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
13323 
13324 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
13325 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
13326 			    (void *)bp->b_un.b_addr, bp->b_bcount);
13327 
13328 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
13329 				/*
13330 				 * CPU will need to access data in the buffer
13331 				 * (for copying) so map it.
13332 				 */
13333 				bp_mapin(bp);
13334 
13335 			ASSERT(spx->txlt_tmp_buf == NULL);
13336 
13337 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
13338 			rval = ddi_dma_mem_alloc(
13339 			    spx->txlt_buf_dma_handle,
13340 			    bp->b_bcount,
13341 			    &sata_acc_attr,
13342 			    DDI_DMA_STREAMING,
13343 			    ddicallback, NULL,
13344 			    &spx->txlt_tmp_buf,
13345 			    &bufsz,
13346 			    &spx->txlt_tmp_buf_handle);
13347 
13348 			if (rval != DDI_SUCCESS) {
13349 				/* DMA mapping failed */
13350 				(void) ddi_dma_free_handle(
13351 				    &spx->txlt_buf_dma_handle);
13352 				spx->txlt_buf_dma_handle = NULL;
13353 #ifdef SATA_DEBUG
13354 				mbuffail_count++;
13355 #endif
13356 				SATADBG1(SATA_DBG_DMA_SETUP,
13357 				    spx->txlt_sata_hba_inst,
13358 				    "sata_dma_buf_setup: "
13359 				    "buf dma mem alloc failed %x\n", rval);
13360 				return (rval);
13361 			}
13362 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
13363 			    cur_dma_attr->dma_attr_align));
13364 
13365 #ifdef SATA_DEBUG
13366 			mbuf_count++;
13367 
13368 			if (bp->b_bcount != bufsz)
13369 				/*
13370 				 * This will require special handling, because
13371 				 * DMA cookies will be based on the temporary
13372 				 * buffer size, not the original buffer
13373 				 * b_bcount, so the residue may have to
13374 				 * be counted differently.
13375 				 */
13376 				SATADBG2(SATA_DBG_DMA_SETUP,
13377 				    spx->txlt_sata_hba_inst,
13378 				    "sata_dma_buf_setup: bp size %x != "
13379 				    "bufsz %x\n", bp->b_bcount, bufsz);
13380 #endif
13381 			if (dma_flags & DDI_DMA_WRITE) {
13382 				/*
13383 				 * Write operation - copy data into
13384 				 * an aligned temporary buffer. Buffer will be
13385 				 * synced for device by ddi_dma_addr_bind_handle
13386 				 */
13387 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
13388 				    bp->b_bcount);
13389 			}
13390 
13391 			rval = ddi_dma_addr_bind_handle(
13392 			    spx->txlt_buf_dma_handle,
13393 			    NULL,
13394 			    spx->txlt_tmp_buf,
13395 			    bufsz, dma_flags, ddicallback, 0,
13396 			    &spx->txlt_dma_cookie,
13397 			    &spx->txlt_curwin_num_dma_cookies);
13398 		}
13399 
13400 		switch (rval) {
13401 		case DDI_DMA_PARTIAL_MAP:
13402 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
13403 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
13404 			/*
13405 			 * Partial DMA mapping.
13406 			 * Retrieve number of DMA windows for this request.
13407 			 */
13408 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
13409 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
13410 				if (spx->txlt_tmp_buf != NULL) {
13411 					ddi_dma_mem_free(
13412 					    &spx->txlt_tmp_buf_handle);
13413 					spx->txlt_tmp_buf = NULL;
13414 				}
13415 				(void) ddi_dma_unbind_handle(
13416 				    spx->txlt_buf_dma_handle);
13417 				(void) ddi_dma_free_handle(
13418 				    &spx->txlt_buf_dma_handle);
13419 				spx->txlt_buf_dma_handle = NULL;
13420 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
13421 				    "sata_dma_buf_setup: numwin failed\n"));
13422 				return (DDI_FAILURE);
13423 			}
13424 			SATADBG2(SATA_DBG_DMA_SETUP,
13425 			    spx->txlt_sata_hba_inst,
13426 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
13427 			    spx->txlt_num_dma_win,
13428 			    spx->txlt_curwin_num_dma_cookies);
13429 			spx->txlt_cur_dma_win = 0;
13430 			break;
13431 
13432 		case DDI_DMA_MAPPED:
13433 			/* DMA fully mapped */
13434 			spx->txlt_num_dma_win = 1;
13435 			spx->txlt_cur_dma_win = 0;
13436 			SATADBG1(SATA_DBG_DMA_SETUP,
13437 			    spx->txlt_sata_hba_inst,
13438 			    "sata_dma_buf_setup: windows: 1 "
13439 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
13440 			break;
13441 
13442 		default:
13443 			/* DMA mapping failed */
13444 			if (spx->txlt_tmp_buf != NULL) {
13445 				ddi_dma_mem_free(
13446 				    &spx->txlt_tmp_buf_handle);
13447 				spx->txlt_tmp_buf = NULL;
13448 			}
13449 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
13450 			spx->txlt_buf_dma_handle = NULL;
13451 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
13452 			    "sata_dma_buf_setup: buf dma handle binding "
13453 			    "failed %x\n", rval));
13454 			return (rval);
13455 		}
13456 		spx->txlt_curwin_processed_dma_cookies = 0;
13457 		spx->txlt_dma_cookie_list = NULL;
13458 	} else {
13459 		/*
13460 		 * DMA setup is reused. Check if we need to process more
13461 		 * cookies in current window, or to get next window, if any.
13462 		 */
13463 
13464 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
13465 		    spx->txlt_curwin_num_dma_cookies);
13466 
13467 		if (spx->txlt_curwin_processed_dma_cookies ==
13468 		    spx->txlt_curwin_num_dma_cookies) {
13469 			/*
13470 			 * All cookies from current DMA window were processed.
13471 			 * Get next DMA window.
13472 			 */
13473 			spx->txlt_cur_dma_win++;
13474 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
13475 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
13476 				    spx->txlt_cur_dma_win, &offset, &size,
13477 				    &spx->txlt_dma_cookie,
13478 				    &spx->txlt_curwin_num_dma_cookies);
13479 				spx->txlt_curwin_processed_dma_cookies = 0;
13480 			} else {
13481 				/* No more windows! End of request! */
13482 				/* What to do? - panic for now */
13483 				ASSERT(spx->txlt_cur_dma_win >=
13484 				    spx->txlt_num_dma_win);
13485 
13486 				spx->txlt_curwin_num_dma_cookies = 0;
13487 				spx->txlt_curwin_processed_dma_cookies = 0;
13488 				spx->txlt_sata_pkt->
13489 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
13490 				return (DDI_SUCCESS);
13491 			}
13492 		}
13493 	}
13494 	/* There better be at least one DMA cookie outstanding */
13495 	ASSERT((spx->txlt_curwin_num_dma_cookies -
13496 	    spx->txlt_curwin_processed_dma_cookies) > 0);
13497 
13498 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
13499 		/* The default cookie slot was used in previous run */
13500 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
13501 		spx->txlt_dma_cookie_list = NULL;
13502 		spx->txlt_dma_cookie_list_len = 0;
13503 	}
13504 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
13505 		/*
13506 		 * Processing a new DMA window - set-up dma cookies list.
13507 		 * We may reuse previously allocated cookie array if it is
13508 		 * possible.
13509 		 */
13510 		if (spx->txlt_dma_cookie_list != NULL &&
13511 		    spx->txlt_dma_cookie_list_len <
13512 		    spx->txlt_curwin_num_dma_cookies) {
13513 			/*
13514 			 * New DMA window contains more cookies than
13515 			 * the previous one. We need larger cookie list - free
13516 			 * the old one.
13517 			 */
13518 			(void) kmem_free(spx->txlt_dma_cookie_list,
13519 			    spx->txlt_dma_cookie_list_len *
13520 			    sizeof (ddi_dma_cookie_t));
13521 			spx->txlt_dma_cookie_list = NULL;
13522 			spx->txlt_dma_cookie_list_len = 0;
13523 		}
13524 		if (spx->txlt_dma_cookie_list == NULL) {
13525 			/*
13526 			 * Calculate lesser of number of cookies in this
13527 			 * DMA window and number of s/g entries.
13528 			 */
13529 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
13530 			req_len = MIN(max_sg_len,
13531 			    spx->txlt_curwin_num_dma_cookies);
13532 
13533 			/* Allocate new dma cookie array if necessary */
13534 			if (req_len == 1) {
13535 				/* Only one cookie - no need for a list */
13536 				spx->txlt_dma_cookie_list =
13537 				    &spx->txlt_dma_cookie;
13538 				spx->txlt_dma_cookie_list_len = 1;
13539 			} else {
13540 				/*
13541 				 * More than one cookie - try to allocate space.
13542 				 */
13543 				spx->txlt_dma_cookie_list = kmem_zalloc(
13544 				    sizeof (ddi_dma_cookie_t) * req_len,
13545 				    callback == NULL_FUNC ? KM_NOSLEEP :
13546 				    KM_SLEEP);
13547 				if (spx->txlt_dma_cookie_list == NULL) {
13548 					SATADBG1(SATA_DBG_DMA_SETUP,
13549 					    spx->txlt_sata_hba_inst,
13550 					    "sata_dma_buf_setup: cookie list "
13551 					    "allocation failed\n", NULL);
13552 					/*
13553 					 * We could not allocate space for
13554 					 * neccessary number of dma cookies in
13555 					 * this window, so we fail this request.
13556 					 * Next invocation would try again to
13557 					 * allocate space for cookie list.
13558 					 * Note:Packet residue was not modified.
13559 					 */
13560 					return (DDI_DMA_NORESOURCES);
13561 				} else {
13562 					spx->txlt_dma_cookie_list_len = req_len;
13563 				}
13564 			}
13565 		}
13566 		/*
13567 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
13568 		 * First cookie was already fetched.
13569 		 */
13570 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
13571 		cur_txfer_len =
13572 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
13573 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
13574 		spx->txlt_curwin_processed_dma_cookies++;
13575 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
13576 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
13577 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
13578 			    &spx->txlt_dma_cookie_list[i]);
13579 			cur_txfer_len +=
13580 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
13581 			spx->txlt_curwin_processed_dma_cookies++;
13582 			spx->txlt_sata_pkt->
13583 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
13584 		}
13585 	} else {
13586 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
13587 		    "sata_dma_buf_setup: sliding within DMA window, "
13588 		    "cur cookie %d, total cookies %d\n",
13589 		    spx->txlt_curwin_processed_dma_cookies,
13590 		    spx->txlt_curwin_num_dma_cookies);
13591 
13592 		/*
13593 		 * Not all cookies from the current dma window were used because
13594 		 * of s/g limitation.
13595 		 * There is no need to re-size the list - it was set at
13596 		 * optimal size, or only default entry is used (s/g = 1).
13597 		 */
13598 		if (spx->txlt_dma_cookie_list == NULL) {
13599 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
13600 			spx->txlt_dma_cookie_list_len = 1;
13601 		}
13602 		/*
13603 		 * Since we are processing remaining cookies in a DMA window,
13604 		 * there may be less of them than the number of entries in the
13605 		 * current dma cookie list.
13606 		 */
13607 		req_len = MIN(spx->txlt_dma_cookie_list_len,
13608 		    (spx->txlt_curwin_num_dma_cookies -
13609 		    spx->txlt_curwin_processed_dma_cookies));
13610 
13611 		/* Fetch the next batch of cookies */
13612 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
13613 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
13614 			    &spx->txlt_dma_cookie_list[i]);
13615 			cur_txfer_len +=
13616 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
13617 			spx->txlt_sata_pkt->
13618 			    satapkt_cmd.satacmd_num_dma_cookies++;
13619 			spx->txlt_curwin_processed_dma_cookies++;
13620 		}
13621 	}
13622 
13623 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
13624 
13625 	/* Point sata_cmd to the cookie list */
13626 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
13627 	    &spx->txlt_dma_cookie_list[0];
13628 
13629 	/* Remember number of DMA cookies passed in sata packet */
13630 	spx->txlt_num_dma_cookies =
13631 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
13632 
13633 	ASSERT(cur_txfer_len != 0);
13634 	if (cur_txfer_len <= bp->b_bcount)
13635 		spx->txlt_total_residue -= cur_txfer_len;
13636 	else {
13637 		/*
13638 		 * Temporary DMA buffer has been padded by
13639 		 * ddi_dma_mem_alloc()!
13640 		 * This requires special handling, because DMA cookies are
13641 		 * based on the temporary buffer size, not the b_bcount,
13642 		 * and we have extra bytes to transfer - but the packet
13643 		 * residue has to stay correct because we will copy only
13644 		 * the requested number of bytes.
13645 		 */
13646 		spx->txlt_total_residue -= bp->b_bcount;
13647 	}
13648 
13649 	return (DDI_SUCCESS);
13650 }
13651 
13652 /*
13653  * Common routine for releasing DMA resources
13654  */
13655 static void
13656 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
13657 {
13658 	if (spx->txlt_buf_dma_handle != NULL) {
13659 		if (spx->txlt_tmp_buf != NULL)  {
13660 			/*
13661 			 * Intermediate DMA buffer was allocated.
13662 			 * Free allocated buffer and associated access handle.
13663 			 */
13664 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
13665 			spx->txlt_tmp_buf = NULL;
13666 		}
13667 		/*
13668 		 * Free DMA resources - cookies and handles
13669 		 */
13670 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
13671 		if (spx->txlt_dma_cookie_list != NULL) {
13672 			if (spx->txlt_dma_cookie_list !=
13673 			    &spx->txlt_dma_cookie) {
13674 				(void) kmem_free(spx->txlt_dma_cookie_list,
13675 				    spx->txlt_dma_cookie_list_len *
13676 				    sizeof (ddi_dma_cookie_t));
13677 				spx->txlt_dma_cookie_list = NULL;
13678 			}
13679 		}
13680 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
13681 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
13682 		spx->txlt_buf_dma_handle = NULL;
13683 	}
13684 }
13685 
13686 /*
13687  * Free DMA resources
13688  * Used by the HBA driver to release DMA resources that it does not use.
13689  *
13690  * Returns Void
13691  */
13692 void
13693 sata_free_dma_resources(sata_pkt_t *sata_pkt)
13694 {
13695 	sata_pkt_txlate_t *spx;
13696 
13697 	if (sata_pkt == NULL)
13698 		return;
13699 
13700 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
13701 
13702 	sata_common_free_dma_rsrcs(spx);
13703 }
13704 
13705 /*
13706  * Fetch Device Identify data.
13707  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
13708  * command to a device and get the device identify data.
13709  * The device_info structure has to be set to device type (for selecting proper
13710  * device identify command).
13711  *
13712  * Returns:
13713  * SATA_SUCCESS if cmd succeeded
13714  * SATA_RETRY if cmd was rejected and could be retried,
13715  * SATA_FAILURE if cmd failed and should not be retried (port error)
13716  *
13717  * Cannot be called in an interrupt context.
13718  */
13719 
13720 static int
13721 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
13722     sata_drive_info_t *sdinfo)
13723 {
13724 	struct buf *bp;
13725 	sata_pkt_t *spkt;
13726 	sata_cmd_t *scmd;
13727 	sata_pkt_txlate_t *spx;
13728 	int rval;
13729 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
13730 
13731 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13732 	spx->txlt_sata_hba_inst = sata_hba_inst;
13733 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13734 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13735 	if (spkt == NULL) {
13736 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13737 		return (SATA_RETRY); /* may retry later */
13738 	}
13739 	/* address is needed now */
13740 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13741 
13742 	/*
13743 	 * Allocate buffer for Identify Data return data
13744 	 */
13745 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
13746 	if (bp == NULL) {
13747 		sata_pkt_free(spx);
13748 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13749 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13750 		    "sata_fetch_device_identify_data: "
13751 		    "cannot allocate buffer for ID"));
13752 		return (SATA_RETRY); /* may retry later */
13753 	}
13754 
13755 	/* Fill sata_pkt */
13756 	sdinfo->satadrv_state = SATA_STATE_PROBING;
13757 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13758 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13759 	/* Synchronous mode, no callback */
13760 	spkt->satapkt_comp = NULL;
13761 	/* Timeout 30s */
13762 	spkt->satapkt_time = sata_default_pkt_time;
13763 
13764 	scmd = &spkt->satapkt_cmd;
13765 	scmd->satacmd_bp = bp;
13766 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13767 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13768 
13769 	/* Build Identify Device cmd in the sata_pkt */
13770 	scmd->satacmd_addr_type = 0;		/* N/A */
13771 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
13772 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
13773 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
13774 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
13775 	scmd->satacmd_features_reg = 0;		/* N/A */
13776 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13777 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
13778 		/* Identify Packet Device cmd */
13779 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
13780 	} else {
13781 		/* Identify Device cmd - mandatory for all other devices */
13782 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
13783 	}
13784 
13785 	/* Send pkt to SATA HBA driver */
13786 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
13787 
13788 #ifdef SATA_INJECT_FAULTS
13789 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13790 #endif
13791 
13792 	if (rval == SATA_TRAN_ACCEPTED &&
13793 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
13794 		if (spx->txlt_buf_dma_handle != NULL) {
13795 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13796 			    DDI_DMA_SYNC_FORKERNEL);
13797 			ASSERT(rval == DDI_SUCCESS);
13798 			if (sata_check_for_dma_error(dip, spx)) {
13799 				ddi_fm_service_impact(dip,
13800 				    DDI_SERVICE_UNAFFECTED);
13801 				rval = SATA_RETRY;
13802 				goto fail;
13803 			}
13804 
13805 		}
13806 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
13807 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
13808 			SATA_LOG_D((sata_hba_inst, CE_WARN,
13809 			    "SATA disk device at port %d - "
13810 			    "partial Identify Data",
13811 			    sdinfo->satadrv_addr.cport));
13812 			rval = SATA_RETRY; /* may retry later */
13813 			goto fail;
13814 		}
13815 		/* Update sata_drive_info */
13816 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
13817 		    sizeof (sata_id_t));
13818 
13819 		sdinfo->satadrv_features_support = 0;
13820 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
13821 			/*
13822 			 * Retrieve capacity (disks only) and addressing mode
13823 			 */
13824 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
13825 		} else {
13826 			/*
13827 			 * For ATAPI devices one would have to issue
13828 			 * Get Capacity cmd for media capacity. Not here.
13829 			 */
13830 			sdinfo->satadrv_capacity = 0;
13831 			/*
13832 			 * Check what cdb length is supported
13833 			 */
13834 			if ((sdinfo->satadrv_id.ai_config &
13835 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
13836 				sdinfo->satadrv_atapi_cdb_len = 16;
13837 			else
13838 				sdinfo->satadrv_atapi_cdb_len = 12;
13839 		}
13840 		/* Setup supported features flags */
13841 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
13842 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
13843 
13844 		/* Check for SATA GEN and NCQ support */
13845 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
13846 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
13847 			/* SATA compliance */
13848 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
13849 				sdinfo->satadrv_features_support |=
13850 				    SATA_DEV_F_NCQ;
13851 			if (sdinfo->satadrv_id.ai_satacap &
13852 			    (SATA_1_SPEED | SATA_2_SPEED | SATA_3_SPEED)) {
13853 				if (sdinfo->satadrv_id.ai_satacap &
13854 				    SATA_3_SPEED)
13855 					sdinfo->satadrv_features_support |=
13856 					    SATA_DEV_F_SATA3;
13857 				if (sdinfo->satadrv_id.ai_satacap &
13858 				    SATA_2_SPEED)
13859 					sdinfo->satadrv_features_support |=
13860 					    SATA_DEV_F_SATA2;
13861 				if (sdinfo->satadrv_id.ai_satacap &
13862 				    SATA_1_SPEED)
13863 					sdinfo->satadrv_features_support |=
13864 					    SATA_DEV_F_SATA1;
13865 			} else {
13866 				sdinfo->satadrv_features_support |=
13867 				    SATA_DEV_F_SATA1;
13868 			}
13869 		}
13870 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
13871 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
13872 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
13873 
13874 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
13875 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
13876 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
13877 			++sdinfo->satadrv_queue_depth;
13878 			/* Adjust according to controller capabilities */
13879 			sdinfo->satadrv_max_queue_depth = MIN(
13880 			    sdinfo->satadrv_queue_depth,
13881 			    SATA_QDEPTH(sata_hba_inst));
13882 			/* Adjust according to global queue depth limit */
13883 			sdinfo->satadrv_max_queue_depth = MIN(
13884 			    sdinfo->satadrv_max_queue_depth,
13885 			    sata_current_max_qdepth);
13886 			if (sdinfo->satadrv_max_queue_depth == 0)
13887 				sdinfo->satadrv_max_queue_depth = 1;
13888 		} else
13889 			sdinfo->satadrv_max_queue_depth = 1;
13890 
13891 		rval = SATA_SUCCESS;
13892 	} else {
13893 		/*
13894 		 * Woops, no Identify Data.
13895 		 */
13896 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
13897 			rval = SATA_RETRY; /* may retry later */
13898 		} else if (rval == SATA_TRAN_ACCEPTED) {
13899 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
13900 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
13901 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
13902 			    spkt->satapkt_reason == SATA_PKT_RESET)
13903 				rval = SATA_RETRY; /* may retry later */
13904 			else
13905 				rval = SATA_FAILURE;
13906 		} else {
13907 			rval = SATA_FAILURE;
13908 		}
13909 	}
13910 fail:
13911 	/* Free allocated resources */
13912 	sata_free_local_buffer(spx);
13913 	sata_pkt_free(spx);
13914 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13915 
13916 	return (rval);
13917 }
13918 
13919 
13920 /*
13921  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
13922  * UDMA mode is checked first, followed by MWDMA mode.
13923  * set correctly, so this function is setting it to the highest supported level.
13924  * Older SATA spec required that the device supports at least DMA 4 mode and
13925  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
13926  * restriction has been removed.
13927  *
13928  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
13929  * Returns SATA_FAILURE if proper DMA mode could not be selected.
13930  *
13931  * NOTE: This function should be called only if DMA mode is supported.
13932  */
13933 static int
13934 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
13935 {
13936 	sata_pkt_t *spkt;
13937 	sata_cmd_t *scmd;
13938 	sata_pkt_txlate_t *spx;
13939 	int i, mode;
13940 	uint8_t subcmd;
13941 	int rval = SATA_SUCCESS;
13942 
13943 	ASSERT(sdinfo != NULL);
13944 	ASSERT(sata_hba_inst != NULL);
13945 
13946 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
13947 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
13948 		/* Find highest Ultra DMA mode supported */
13949 		for (mode = 6; mode >= 0; --mode) {
13950 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
13951 				break;
13952 		}
13953 #if 0
13954 		/* Left for historical reasons */
13955 		/*
13956 		 * Some initial version of SATA spec indicated that at least
13957 		 * UDMA mode 4 has to be supported. It is not mentioned in
13958 		 * SerialATA 2.6, so this restriction is removed.
13959 		 */
13960 		if (mode < 4)
13961 			return (SATA_FAILURE);
13962 #endif
13963 
13964 		/*
13965 		 * For disk, we're still going to set DMA mode whatever is
13966 		 * selected by default
13967 		 *
13968 		 * We saw an old maxtor sata drive will select Ultra DMA and
13969 		 * Multi-Word DMA simultaneouly by default, which is going
13970 		 * to cause DMA command timed out, so we need to select DMA
13971 		 * mode even when it's already done by default
13972 		 */
13973 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13974 
13975 			/* Find UDMA mode currently selected */
13976 			for (i = 6; i >= 0; --i) {
13977 				if (sdinfo->satadrv_id.ai_ultradma &
13978 				    (1 << (i + 8)))
13979 					break;
13980 			}
13981 			if (i >= mode)
13982 				/* Nothing to do */
13983 				return (SATA_SUCCESS);
13984 		}
13985 
13986 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
13987 
13988 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
13989 		/* Find highest MultiWord DMA mode supported */
13990 		for (mode = 2; mode >= 0; --mode) {
13991 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
13992 				break;
13993 		}
13994 
13995 		/*
13996 		 * For disk, We're still going to set DMA mode whatever is
13997 		 * selected by default
13998 		 *
13999 		 * We saw an old maxtor sata drive will select Ultra DMA and
14000 		 * Multi-Word DMA simultaneouly by default, which is going
14001 		 * to cause DMA command timed out, so we need to select DMA
14002 		 * mode even when it's already done by default
14003 		 */
14004 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
14005 
14006 			/* Find highest MultiWord DMA mode selected */
14007 			for (i = 2; i >= 0; --i) {
14008 				if (sdinfo->satadrv_id.ai_dworddma &
14009 				    (1 << (i + 8)))
14010 					break;
14011 			}
14012 			if (i >= mode)
14013 				/* Nothing to do */
14014 				return (SATA_SUCCESS);
14015 		}
14016 
14017 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
14018 	} else
14019 		return (SATA_SUCCESS);
14020 
14021 	/*
14022 	 * Set DMA mode via SET FEATURES COMMAND.
14023 	 * Prepare packet for SET FEATURES COMMAND.
14024 	 */
14025 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
14026 	spx->txlt_sata_hba_inst = sata_hba_inst;
14027 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
14028 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
14029 	if (spkt == NULL) {
14030 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14031 		    "sata_set_dma_mode: could not set DMA mode %d", mode));
14032 		rval = SATA_FAILURE;
14033 		goto done;
14034 	}
14035 	/* Fill sata_pkt */
14036 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
14037 	/* Timeout 30s */
14038 	spkt->satapkt_time = sata_default_pkt_time;
14039 	/* Synchronous mode, no callback, interrupts */
14040 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
14041 	spkt->satapkt_comp = NULL;
14042 	scmd = &spkt->satapkt_cmd;
14043 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
14044 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
14045 	scmd->satacmd_addr_type = 0;
14046 	scmd->satacmd_device_reg = 0;
14047 	scmd->satacmd_status_reg = 0;
14048 	scmd->satacmd_error_reg = 0;
14049 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
14050 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
14051 	scmd->satacmd_sec_count_lsb = subcmd | mode;
14052 
14053 	/* Transfer command to HBA */
14054 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
14055 	    spkt) != SATA_TRAN_ACCEPTED ||
14056 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
14057 		/* Pkt execution failed */
14058 		rval = SATA_FAILURE;
14059 	}
14060 done:
14061 
14062 	/* Free allocated resources */
14063 	if (spkt != NULL)
14064 		sata_pkt_free(spx);
14065 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
14066 
14067 	return (rval);
14068 }
14069 
14070 
14071 /*
14072  * Set device caching mode.
14073  * One of the following operations should be specified:
14074  * SATAC_SF_ENABLE_READ_AHEAD
14075  * SATAC_SF_DISABLE_READ_AHEAD
14076  * SATAC_SF_ENABLE_WRITE_CACHE
14077  * SATAC_SF_DISABLE_WRITE_CACHE
14078  *
14079  * If operation fails, system log messgage is emitted.
14080  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
14081  * command was sent but did not succeed, and SATA_FAILURE otherwise.
14082  */
14083 
14084 static int
14085 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
14086     int cache_op)
14087 {
14088 	sata_pkt_t *spkt;
14089 	sata_cmd_t *scmd;
14090 	sata_pkt_txlate_t *spx;
14091 	int rval = SATA_SUCCESS;
14092 	int hba_rval;
14093 	char *infop;
14094 
14095 	ASSERT(sdinfo != NULL);
14096 	ASSERT(sata_hba_inst != NULL);
14097 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
14098 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
14099 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
14100 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
14101 
14102 
14103 	/* Prepare packet for SET FEATURES COMMAND */
14104 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
14105 	spx->txlt_sata_hba_inst = sata_hba_inst;
14106 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
14107 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
14108 	if (spkt == NULL) {
14109 		rval = SATA_FAILURE;
14110 		goto failure;
14111 	}
14112 	/* Fill sata_pkt */
14113 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
14114 	/* Timeout 30s */
14115 	spkt->satapkt_time = sata_default_pkt_time;
14116 	/* Synchronous mode, no callback, interrupts */
14117 	spkt->satapkt_op_mode =
14118 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
14119 	spkt->satapkt_comp = NULL;
14120 	scmd = &spkt->satapkt_cmd;
14121 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
14122 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
14123 	scmd->satacmd_addr_type = 0;
14124 	scmd->satacmd_device_reg = 0;
14125 	scmd->satacmd_status_reg = 0;
14126 	scmd->satacmd_error_reg = 0;
14127 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
14128 	scmd->satacmd_features_reg = cache_op;
14129 
14130 	/* Transfer command to HBA */
14131 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
14132 	    SATA_DIP(sata_hba_inst), spkt);
14133 
14134 #ifdef SATA_INJECT_FAULTS
14135 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
14136 #endif
14137 
14138 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
14139 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
14140 		/* Pkt execution failed */
14141 		switch (cache_op) {
14142 		case SATAC_SF_ENABLE_READ_AHEAD:
14143 			infop = "enabling read ahead failed";
14144 			break;
14145 		case SATAC_SF_DISABLE_READ_AHEAD:
14146 			infop = "disabling read ahead failed";
14147 			break;
14148 		case SATAC_SF_ENABLE_WRITE_CACHE:
14149 			infop = "enabling write cache failed";
14150 			break;
14151 		case SATAC_SF_DISABLE_WRITE_CACHE:
14152 			infop = "disabling write cache failed";
14153 			break;
14154 		}
14155 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
14156 		rval = SATA_RETRY;
14157 	}
14158 failure:
14159 	/* Free allocated resources */
14160 	if (spkt != NULL)
14161 		sata_pkt_free(spx);
14162 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
14163 	return (rval);
14164 }
14165 
14166 /*
14167  * Set Removable Media Status Notification (enable/disable)
14168  * state == 0 , disable
14169  * state != 0 , enable
14170  *
14171  * If operation fails, system log messgage is emitted.
14172  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
14173  */
14174 
14175 static int
14176 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
14177     int state)
14178 {
14179 	sata_pkt_t *spkt;
14180 	sata_cmd_t *scmd;
14181 	sata_pkt_txlate_t *spx;
14182 	int rval = SATA_SUCCESS;
14183 	char *infop;
14184 
14185 	ASSERT(sdinfo != NULL);
14186 	ASSERT(sata_hba_inst != NULL);
14187 
14188 	/* Prepare packet for SET FEATURES COMMAND */
14189 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
14190 	spx->txlt_sata_hba_inst = sata_hba_inst;
14191 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
14192 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
14193 	if (spkt == NULL) {
14194 		rval = SATA_FAILURE;
14195 		goto failure;
14196 	}
14197 	/* Fill sata_pkt */
14198 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
14199 	/* Timeout 30s */
14200 	spkt->satapkt_time = sata_default_pkt_time;
14201 	/* Synchronous mode, no callback, interrupts */
14202 	spkt->satapkt_op_mode =
14203 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
14204 	spkt->satapkt_comp = NULL;
14205 	scmd = &spkt->satapkt_cmd;
14206 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
14207 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
14208 	scmd->satacmd_addr_type = 0;
14209 	scmd->satacmd_device_reg = 0;
14210 	scmd->satacmd_status_reg = 0;
14211 	scmd->satacmd_error_reg = 0;
14212 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
14213 	if (state == 0)
14214 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
14215 	else
14216 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
14217 
14218 	/* Transfer command to HBA */
14219 	if (((*SATA_START_FUNC(sata_hba_inst))(
14220 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
14221 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
14222 		/* Pkt execution failed */
14223 		if (state == 0)
14224 			infop = "disabling Removable Media Status "
14225 			    "Notification failed";
14226 		else
14227 			infop = "enabling Removable Media Status "
14228 			    "Notification failed";
14229 
14230 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
14231 		rval = SATA_FAILURE;
14232 	}
14233 failure:
14234 	/* Free allocated resources */
14235 	if (spkt != NULL)
14236 		sata_pkt_free(spx);
14237 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
14238 	return (rval);
14239 }
14240 
14241 
14242 /*
14243  * Update state and copy port ss* values from passed sata_device structure.
14244  * sata_address is validated - if not valid, nothing is changed in sata_scsi
14245  * configuration struct.
14246  *
14247  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
14248  * regardless of the state in device argument.
14249  *
14250  * Port mutex should be held while calling this function.
14251  */
14252 static void
14253 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
14254     sata_device_t *sata_device)
14255 {
14256 	sata_cport_info_t *cportinfo;
14257 
14258 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
14259 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
14260 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
14261 		    sata_device->satadev_addr.cport)
14262 			return;
14263 
14264 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
14265 		    sata_device->satadev_addr.cport);
14266 
14267 		ASSERT(mutex_owned(&cportinfo->cport_mutex));
14268 		cportinfo->cport_scr = sata_device->satadev_scr;
14269 
14270 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
14271 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
14272 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
14273 		cportinfo->cport_state |=
14274 		    sata_device->satadev_state & SATA_PSTATE_VALID;
14275 	}
14276 }
14277 
14278 void
14279 sata_update_pmport_info(sata_hba_inst_t *sata_hba_inst,
14280     sata_device_t *sata_device)
14281 {
14282 	sata_pmport_info_t *pmportinfo;
14283 
14284 	if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT &&
14285 	    sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
14286 	    SATA_NUM_PMPORTS(sata_hba_inst,
14287 	    sata_device->satadev_addr.cport) <
14288 	    sata_device->satadev_addr.pmport) {
14289 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
14290 		    "sata_update_port_info: error address %p.",
14291 		    &sata_device->satadev_addr);
14292 		return;
14293 	}
14294 
14295 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
14296 	    sata_device->satadev_addr.cport,
14297 	    sata_device->satadev_addr.pmport);
14298 
14299 	ASSERT(mutex_owned(&pmportinfo->pmport_mutex));
14300 	pmportinfo->pmport_scr = sata_device->satadev_scr;
14301 
14302 	/* Preserve SATA_PSTATE_SHUTDOWN flag */
14303 	pmportinfo->pmport_state &=
14304 	    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
14305 	pmportinfo->pmport_state |=
14306 	    sata_device->satadev_state & SATA_PSTATE_VALID;
14307 }
14308 
14309 /*
14310  * Extract SATA port specification from an IOCTL argument.
14311  *
14312  * This function return the port the user land send us as is, unless it
14313  * cannot retrieve port spec, then -1 is returned.
14314  *
14315  * Support port multiplier.
14316  */
14317 static int32_t
14318 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
14319 {
14320 	int32_t port;
14321 
14322 	/* Extract port number from nvpair in dca structure  */
14323 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
14324 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
14325 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
14326 		    port));
14327 		port = -1;
14328 	}
14329 
14330 	return (port);
14331 }
14332 
14333 /*
14334  * Get dev_info_t pointer to the device node pointed to by port argument.
14335  * NOTE: target argument is a value used in ioctls to identify
14336  * the AP - it is not a sata_address.
14337  * It is a combination of cport, pmport and address qualifier, encodded same
14338  * way as a scsi target number.
14339  * At this moment it carries only cport number.
14340  *
14341  * PMult hotplug is supported now.
14342  *
14343  * Returns dev_info_t pointer if target device was found, NULL otherwise.
14344  */
14345 
14346 static dev_info_t *
14347 sata_get_target_dip(dev_info_t *dip, uint8_t cport, uint8_t pmport)
14348 {
14349 	dev_info_t	*cdip = NULL;
14350 	int		target, tgt;
14351 	int		circ;
14352 	uint8_t		qual;
14353 
14354 	sata_hba_inst_t	*sata_hba_inst;
14355 	scsi_hba_tran_t *scsi_hba_tran;
14356 
14357 	/* Get target id */
14358 	scsi_hba_tran = ddi_get_driver_private(dip);
14359 	if (scsi_hba_tran == NULL)
14360 		return (NULL);
14361 
14362 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
14363 
14364 	if (sata_hba_inst == NULL)
14365 		return (NULL);
14366 
14367 	/* Identify a port-mult by cport_info.cport_dev_type */
14368 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT)
14369 		qual = SATA_ADDR_DPMPORT;
14370 	else
14371 		qual = SATA_ADDR_DCPORT;
14372 
14373 	target = SATA_TO_SCSI_TARGET(cport, pmport, qual);
14374 
14375 	/* Retrieve target dip */
14376 	ndi_devi_enter(dip, &circ);
14377 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
14378 		dev_info_t *next = ddi_get_next_sibling(cdip);
14379 
14380 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
14381 		    DDI_PROP_DONTPASS, "target", -1);
14382 		if (tgt == -1) {
14383 			/*
14384 			 * This is actually an error condition, but not
14385 			 * a fatal one. Just continue the search.
14386 			 */
14387 			cdip = next;
14388 			continue;
14389 		}
14390 
14391 		if (tgt == target)
14392 			break;
14393 
14394 		cdip = next;
14395 	}
14396 	ndi_devi_exit(dip, circ);
14397 
14398 	return (cdip);
14399 }
14400 
14401 /*
14402  * Get dev_info_t pointer to the device node pointed to by port argument.
14403  * NOTE: target argument is a value used in ioctls to identify
14404  * the AP - it is not a sata_address.
14405  * It is a combination of cport, pmport and address qualifier, encoded same
14406  * way as a scsi target number.
14407  *
14408  * Returns dev_info_t pointer if target device was found, NULL otherwise.
14409  */
14410 
14411 static dev_info_t *
14412 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
14413 {
14414 	dev_info_t	*cdip = NULL;
14415 	int		target, tgt;
14416 	int		circ;
14417 
14418 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
14419 
14420 	ndi_devi_enter(dip, &circ);
14421 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
14422 		dev_info_t *next = ddi_get_next_sibling(cdip);
14423 
14424 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
14425 		    DDI_PROP_DONTPASS, "target", -1);
14426 		if (tgt == -1) {
14427 			/*
14428 			 * This is actually an error condition, but not
14429 			 * a fatal one. Just continue the search.
14430 			 */
14431 			cdip = next;
14432 			continue;
14433 		}
14434 
14435 		if (tgt == target)
14436 			break;
14437 
14438 		cdip = next;
14439 	}
14440 	ndi_devi_exit(dip, circ);
14441 
14442 	return (cdip);
14443 }
14444 
14445 /*
14446  * Process sata port disconnect request.
14447  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
14448  * before this request. Nevertheless, if a device is still configured,
14449  * we need to attempt to offline and unconfigure device.
14450  * Regardless of the unconfigure operation results the port is marked as
14451  * deactivated and no access to the attached device is possible.
14452  * If the target node remains because unconfigure operation failed, its state
14453  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
14454  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
14455  * the device and remove old target node.
14456  *
14457  * This function invokes sata_hba_inst->satahba_tran->
14458  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
14459  * If successful, the device structure (if any) attached to the specified port
14460  * is removed and state of the port marked appropriately.
14461  * Failure of the port_deactivate may keep port in the physically active state,
14462  * or may fail the port.
14463  *
14464  * NOTE: Port multiplier is supported.
14465  */
14466 
14467 static int
14468 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
14469     sata_device_t *sata_device)
14470 {
14471 	sata_drive_info_t *sdinfo = NULL, *subsdinfo = NULL;
14472 	sata_cport_info_t *cportinfo = NULL;
14473 	sata_pmport_info_t *pmportinfo = NULL;
14474 	sata_pmult_info_t *pmultinfo = NULL;
14475 	sata_device_t subsdevice;
14476 	int cport, pmport, qual;
14477 	int rval = SATA_SUCCESS;
14478 	int npmport = 0;
14479 	int rv = 0;
14480 
14481 	cport = sata_device->satadev_addr.cport;
14482 	pmport = sata_device->satadev_addr.pmport;
14483 	qual = sata_device->satadev_addr.qual;
14484 
14485 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14486 	if (qual == SATA_ADDR_DCPORT)
14487 		qual = SATA_ADDR_CPORT;
14488 	else
14489 		qual = SATA_ADDR_PMPORT;
14490 
14491 	/*
14492 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
14493 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
14494 	 * Do the sanity check.
14495 	 */
14496 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
14497 		/* No physical port deactivation supported. */
14498 		return (EINVAL);
14499 	}
14500 
14501 	/* Check the current state of the port */
14502 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14503 	    (SATA_DIP(sata_hba_inst), sata_device);
14504 
14505 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14506 
14507 	/*
14508 	 * Processing port mulitiplier
14509 	 */
14510 	if (qual == SATA_ADDR_CPORT &&
14511 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
14512 		mutex_enter(&cportinfo->cport_mutex);
14513 
14514 		/* Check controller port status */
14515 		sata_update_port_info(sata_hba_inst, sata_device);
14516 		if (rval != SATA_SUCCESS ||
14517 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14518 			/*
14519 			 * Device port status is unknown or it is in failed
14520 			 * state
14521 			 */
14522 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14523 			    SATA_PSTATE_FAILED;
14524 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14525 			    "sata_hba_ioctl: connect: failed to deactivate "
14526 			    "SATA port %d", cport);
14527 			mutex_exit(&cportinfo->cport_mutex);
14528 			return (EIO);
14529 		}
14530 
14531 		/* Disconnect all sub-devices. */
14532 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14533 		if (pmultinfo != NULL) {
14534 
14535 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
14536 			    sata_hba_inst, cport); npmport ++) {
14537 				subsdinfo = SATA_PMPORT_DRV_INFO(
14538 				    sata_hba_inst, cport, npmport);
14539 				if (subsdinfo == NULL)
14540 					continue;
14541 
14542 				subsdevice.satadev_addr = subsdinfo->
14543 				    satadrv_addr;
14544 
14545 				mutex_exit(&cportinfo->cport_mutex);
14546 				if (sata_ioctl_disconnect(sata_hba_inst,
14547 				    &subsdevice) == SATA_SUCCESS) {
14548 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14549 					"[Remove] device at port %d:%d "
14550 					"successfully.", cport, npmport);
14551 				}
14552 				mutex_enter(&cportinfo->cport_mutex);
14553 			}
14554 		}
14555 
14556 		/* Disconnect the port multiplier */
14557 		cportinfo->cport_state &= ~SATA_STATE_READY;
14558 		mutex_exit(&cportinfo->cport_mutex);
14559 
14560 		sata_device->satadev_addr.qual = qual;
14561 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14562 		    (SATA_DIP(sata_hba_inst), sata_device);
14563 
14564 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14565 		    SE_NO_HINT);
14566 
14567 		mutex_enter(&cportinfo->cport_mutex);
14568 		sata_update_port_info(sata_hba_inst, sata_device);
14569 		if (rval != SATA_SUCCESS &&
14570 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14571 			cportinfo->cport_state = SATA_PSTATE_FAILED;
14572 			rv = EIO;
14573 		} else {
14574 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14575 		}
14576 		mutex_exit(&cportinfo->cport_mutex);
14577 
14578 		return (rv);
14579 	}
14580 
14581 	/*
14582 	 * Process non-port-multiplier device - it could be a drive connected
14583 	 * to a port multiplier port or a controller port.
14584 	 */
14585 	if (qual == SATA_ADDR_PMPORT) {
14586 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14587 		mutex_enter(&pmportinfo->pmport_mutex);
14588 		sata_update_pmport_info(sata_hba_inst, sata_device);
14589 		if (rval != SATA_SUCCESS ||
14590 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14591 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
14592 			    SATA_PSTATE_FAILED;
14593 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
14594 			    "sata_hba_ioctl: connect: failed to deactivate "
14595 			    "SATA port %d:%d", cport, pmport);
14596 			mutex_exit(&pmportinfo->pmport_mutex);
14597 			return (EIO);
14598 		}
14599 
14600 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
14601 			sdinfo = pmportinfo->pmport_sata_drive;
14602 			ASSERT(sdinfo != NULL);
14603 		}
14604 
14605 		/*
14606 		 * Set port's dev_state to not ready - this will disable
14607 		 * an access to a potentially attached device.
14608 		 */
14609 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
14610 
14611 		/* Remove and release sata_drive info structure. */
14612 		if (sdinfo != NULL) {
14613 			if ((sdinfo->satadrv_type &
14614 			    SATA_VALID_DEV_TYPE) != 0) {
14615 				/*
14616 				 * If a target node exists, try to offline
14617 				 * a device and remove target node.
14618 				 */
14619 				mutex_exit(&pmportinfo->pmport_mutex);
14620 				(void) sata_offline_device(sata_hba_inst,
14621 				    sata_device, sdinfo);
14622 				mutex_enter(&pmportinfo->pmport_mutex);
14623 			}
14624 
14625 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
14626 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
14627 			(void) kmem_free((void *)sdinfo,
14628 			    sizeof (sata_drive_info_t));
14629 		}
14630 		mutex_exit(&pmportinfo->pmport_mutex);
14631 
14632 	} else if (qual == SATA_ADDR_CPORT) {
14633 		mutex_enter(&cportinfo->cport_mutex);
14634 		sata_update_port_info(sata_hba_inst, sata_device);
14635 		if (rval != SATA_SUCCESS ||
14636 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14637 			/*
14638 			 * Device port status is unknown or it is in failed
14639 			 * state
14640 			 */
14641 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14642 			    SATA_PSTATE_FAILED;
14643 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14644 			    "sata_hba_ioctl: connect: failed to deactivate "
14645 			    "SATA port %d", cport);
14646 			mutex_exit(&cportinfo->cport_mutex);
14647 			return (EIO);
14648 		}
14649 
14650 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
14651 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14652 			ASSERT(pmultinfo != NULL);
14653 		} else if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14654 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14655 			ASSERT(sdinfo != NULL);
14656 		}
14657 		cportinfo->cport_state &= ~SATA_STATE_READY;
14658 
14659 		if (sdinfo != NULL) {
14660 			if ((sdinfo->satadrv_type &
14661 			    SATA_VALID_DEV_TYPE) != 0) {
14662 				/*
14663 				 * If a target node exists, try to offline
14664 				 * a device and remove target node.
14665 				 */
14666 				mutex_exit(&cportinfo->cport_mutex);
14667 				(void) sata_offline_device(sata_hba_inst,
14668 				    sata_device, sdinfo);
14669 				mutex_enter(&cportinfo->cport_mutex);
14670 			}
14671 
14672 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14673 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14674 			(void) kmem_free((void *)sdinfo,
14675 			    sizeof (sata_drive_info_t));
14676 		}
14677 		mutex_exit(&cportinfo->cport_mutex);
14678 	}
14679 
14680 	/* Just ask HBA driver to deactivate port */
14681 	sata_device->satadev_addr.qual = qual;
14682 
14683 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14684 	    (SATA_DIP(sata_hba_inst), sata_device);
14685 
14686 	/*
14687 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14688 	 * without the hint (to force listener to investivate the state).
14689 	 */
14690 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14691 	    SE_NO_HINT);
14692 
14693 	if (qual == SATA_ADDR_PMPORT) {
14694 		mutex_enter(&pmportinfo->pmport_mutex);
14695 		sata_update_pmport_info(sata_hba_inst, sata_device);
14696 
14697 		if (rval != SATA_SUCCESS &&
14698 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14699 			/*
14700 			 * Port deactivation failure - do not change port
14701 			 * state unless the state returned by HBA indicates a
14702 			 * port failure.
14703 			 *
14704 			 * NOTE: device structures were released, so devices
14705 			 * now are invisible! Port reset is needed to
14706 			 * re-enumerate devices.
14707 			 */
14708 			pmportinfo->pmport_state = SATA_PSTATE_FAILED;
14709 			rv = EIO;
14710 		} else {
14711 			/*
14712 			 * Deactivation succeded. From now on the sata framework
14713 			 * will not care what is happening to the device, until
14714 			 * the port is activated again.
14715 			 */
14716 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14717 		}
14718 		mutex_exit(&pmportinfo->pmport_mutex);
14719 	} else if (qual == SATA_ADDR_CPORT) {
14720 		mutex_enter(&cportinfo->cport_mutex);
14721 		sata_update_port_info(sata_hba_inst, sata_device);
14722 
14723 		if (rval != SATA_SUCCESS &&
14724 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14725 			cportinfo->cport_state = SATA_PSTATE_FAILED;
14726 			rv = EIO;
14727 		} else {
14728 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14729 		}
14730 		mutex_exit(&cportinfo->cport_mutex);
14731 	}
14732 
14733 	return (rv);
14734 }
14735 
14736 
14737 
14738 /*
14739  * Process sata port connect request
14740  * The sata cfgadm pluging will invoke this operation only if port was found
14741  * in the disconnect state (failed state is also treated as the disconnected
14742  * state).
14743  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
14744  * sata_tran_hotplug_ops->sata_tran_port_activate().
14745  * If successful and a device is found attached to the port,
14746  * the initialization sequence is executed to attach a device structure to
14747  * a port structure. The state of the port and a device would be set
14748  * appropriately.
14749  * The device is not set in configured state (system-wise) by this operation.
14750  *
14751  * Note, that activating the port may generate link events,
14752  * so it is important that following processing and the
14753  * event processing does not interfere with each other!
14754  *
14755  * This operation may remove port failed state and will
14756  * try to make port active and in good standing.
14757  *
14758  * NOTE: Port multiplier is supported.
14759  */
14760 
14761 static int
14762 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
14763     sata_device_t *sata_device)
14764 {
14765 	sata_pmport_info_t	*pmportinfo = NULL;
14766 	uint8_t cport, pmport, qual;
14767 	int rv = 0;
14768 
14769 	cport = sata_device->satadev_addr.cport;
14770 	pmport = sata_device->satadev_addr.pmport;
14771 	qual = sata_device->satadev_addr.qual;
14772 
14773 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14774 	if (qual == SATA_ADDR_DCPORT)
14775 		qual = SATA_ADDR_CPORT;
14776 	else
14777 		qual = SATA_ADDR_PMPORT;
14778 
14779 	if (qual == SATA_ADDR_PMPORT)
14780 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14781 
14782 	/*
14783 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
14784 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
14785 	 * Perform sanity check now.
14786 	 */
14787 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
14788 		/* No physical port activation supported. */
14789 		return (EINVAL);
14790 	}
14791 
14792 	/* Just ask HBA driver to activate port */
14793 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14794 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14795 		/*
14796 		 * Port activation failure.
14797 		 */
14798 		if (qual == SATA_ADDR_CPORT) {
14799 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14800 			    cport)->cport_mutex);
14801 			sata_update_port_info(sata_hba_inst, sata_device);
14802 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14803 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14804 				    SATA_PSTATE_FAILED;
14805 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14806 				    "sata_hba_ioctl: connect: failed to "
14807 				    "activate SATA port %d", cport);
14808 			}
14809 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14810 			    cport)->cport_mutex);
14811 		} else { /* port multiplier device port */
14812 			mutex_enter(&pmportinfo->pmport_mutex);
14813 			sata_update_pmport_info(sata_hba_inst, sata_device);
14814 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14815 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14816 				    pmport) = SATA_PSTATE_FAILED;
14817 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
14818 				    "sata_hba_ioctl: connect: failed to "
14819 				    "activate SATA port %d:%d", cport, pmport);
14820 			}
14821 			mutex_exit(&pmportinfo->pmport_mutex);
14822 		}
14823 		return (EIO);
14824 	}
14825 
14826 	/* Virgin port state - will be updated by the port re-probe. */
14827 	if (qual == SATA_ADDR_CPORT) {
14828 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14829 		    cport)->cport_mutex);
14830 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
14831 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14832 		    cport)->cport_mutex);
14833 	} else { /* port multiplier device port */
14834 		mutex_enter(&pmportinfo->pmport_mutex);
14835 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
14836 		mutex_exit(&pmportinfo->pmport_mutex);
14837 	}
14838 
14839 	/*
14840 	 * Probe the port to find its state and attached device.
14841 	 */
14842 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14843 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
14844 		rv = EIO;
14845 
14846 	/*
14847 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14848 	 * without the hint
14849 	 */
14850 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14851 	    SE_NO_HINT);
14852 
14853 	/*
14854 	 * If there is a device attached to the port, emit
14855 	 * a message.
14856 	 */
14857 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
14858 
14859 		if (qual == SATA_ADDR_CPORT) {
14860 			if (sata_device->satadev_type == SATA_DTYPE_PMULT) {
14861 				sata_log(sata_hba_inst, CE_WARN,
14862 				    "SATA port multiplier detected "
14863 				    "at port %d", cport);
14864 			} else {
14865 				sata_log(sata_hba_inst, CE_WARN,
14866 				    "SATA device detected at port %d", cport);
14867 				if (sata_device->satadev_type ==
14868 				    SATA_DTYPE_UNKNOWN) {
14869 				/*
14870 				 * A device was not successfully identified
14871 				 */
14872 				sata_log(sata_hba_inst, CE_WARN,
14873 				    "Could not identify SATA "
14874 				    "device at port %d", cport);
14875 				}
14876 			}
14877 		} else { /* port multiplier device port */
14878 			sata_log(sata_hba_inst, CE_WARN,
14879 			    "SATA device detected at port %d:%d",
14880 			    cport, pmport);
14881 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14882 				/*
14883 				 * A device was not successfully identified
14884 				 */
14885 				sata_log(sata_hba_inst, CE_WARN,
14886 				    "Could not identify SATA "
14887 				    "device at port %d:%d", cport, pmport);
14888 			}
14889 		}
14890 	}
14891 
14892 	return (rv);
14893 }
14894 
14895 
14896 /*
14897  * Process sata device unconfigure request.
14898  * The unconfigure operation uses generic nexus operation to
14899  * offline a device. It leaves a target device node attached.
14900  * and obviously sata_drive_info attached as well, because
14901  * from the hardware point of view nothing has changed.
14902  */
14903 static int
14904 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
14905     sata_device_t *sata_device)
14906 {
14907 	int rv = 0;
14908 	dev_info_t *tdip;
14909 
14910 	/* We are addressing attached device, not a port */
14911 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
14912 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14913 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
14914 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14915 
14916 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14917 	    &sata_device->satadev_addr)) != NULL) {
14918 
14919 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
14920 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14921 			    "sata_hba_ioctl: unconfigure: "
14922 			    "failed to unconfigure device at SATA port %d:%d",
14923 			    sata_device->satadev_addr.cport,
14924 			    sata_device->satadev_addr.pmport));
14925 			rv = EIO;
14926 		}
14927 		/*
14928 		 * The target node devi_state should be marked with
14929 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
14930 		 * This would be the indication for cfgadm that
14931 		 * the AP node occupant state is 'unconfigured'.
14932 		 */
14933 
14934 	} else {
14935 		/*
14936 		 * This would indicate a failure on the part of cfgadm
14937 		 * to detect correct state of the node prior to this
14938 		 * call - one cannot unconfigure non-existing device.
14939 		 */
14940 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14941 		    "sata_hba_ioctl: unconfigure: "
14942 		    "attempt to unconfigure non-existing device "
14943 		    "at SATA port %d:%d",
14944 		    sata_device->satadev_addr.cport,
14945 		    sata_device->satadev_addr.pmport));
14946 		rv = ENXIO;
14947 	}
14948 	return (rv);
14949 }
14950 
14951 /*
14952  * Process sata device configure request
14953  * If port is in a failed state, operation is aborted - one has to use
14954  * an explicit connect or port activate request to try to get a port into
14955  * non-failed mode. Port reset wil also work in such situation.
14956  * If the port is in disconnected (shutdown) state, the connect operation is
14957  * attempted prior to any other action.
14958  * When port is in the active state, there is a device attached and the target
14959  * node exists, a device was most likely offlined.
14960  * If target node does not exist, a new target node is created. In both cases
14961  * an attempt is made to online (configure) the device.
14962  *
14963  * NOTE: Port multiplier is supported.
14964  */
14965 static int
14966 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
14967     sata_device_t *sata_device)
14968 {
14969 	int cport, pmport, qual;
14970 	int rval;
14971 	boolean_t target = B_TRUE;
14972 	sata_cport_info_t *cportinfo;
14973 	sata_pmport_info_t *pmportinfo = NULL;
14974 	dev_info_t *tdip;
14975 	sata_drive_info_t *sdinfo;
14976 
14977 	cport = sata_device->satadev_addr.cport;
14978 	pmport = sata_device->satadev_addr.pmport;
14979 	qual = sata_device->satadev_addr.qual;
14980 
14981 	/* Get current port state */
14982 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14983 	    (SATA_DIP(sata_hba_inst), sata_device);
14984 
14985 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14986 	if (qual == SATA_ADDR_DPMPORT) {
14987 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14988 		mutex_enter(&pmportinfo->pmport_mutex);
14989 		sata_update_pmport_info(sata_hba_inst, sata_device);
14990 		if (rval != SATA_SUCCESS ||
14991 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14992 			/*
14993 			 * Obviously, device on a failed port is not visible
14994 			 */
14995 			mutex_exit(&pmportinfo->pmport_mutex);
14996 			return (ENXIO);
14997 		}
14998 		mutex_exit(&pmportinfo->pmport_mutex);
14999 	} else {
15000 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15001 		    cport)->cport_mutex);
15002 		sata_update_port_info(sata_hba_inst, sata_device);
15003 		if (rval != SATA_SUCCESS ||
15004 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
15005 			/*
15006 			 * Obviously, device on a failed port is not visible
15007 			 */
15008 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15009 			    cport)->cport_mutex);
15010 			return (ENXIO);
15011 		}
15012 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15013 		    cport)->cport_mutex);
15014 	}
15015 
15016 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
15017 		/* need to activate port */
15018 		target = B_FALSE;
15019 
15020 		/* Sanity check */
15021 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
15022 			return (ENXIO);
15023 
15024 		/* Just let HBA driver to activate port */
15025 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
15026 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15027 			/*
15028 			 * Port activation failure - do not change port state
15029 			 * unless the state returned by HBA indicates a port
15030 			 * failure.
15031 			 */
15032 			if (qual == SATA_ADDR_DPMPORT) {
15033 				mutex_enter(&pmportinfo->pmport_mutex);
15034 				sata_update_pmport_info(sata_hba_inst,
15035 				    sata_device);
15036 				if (sata_device->satadev_state &
15037 				    SATA_PSTATE_FAILED)
15038 					pmportinfo->pmport_state =
15039 					    SATA_PSTATE_FAILED;
15040 				mutex_exit(&pmportinfo->pmport_mutex);
15041 			} else {
15042 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15043 				    cport)->cport_mutex);
15044 				sata_update_port_info(sata_hba_inst,
15045 				    sata_device);
15046 				if (sata_device->satadev_state &
15047 				    SATA_PSTATE_FAILED)
15048 					cportinfo->cport_state =
15049 					    SATA_PSTATE_FAILED;
15050 				mutex_exit(&SATA_CPORT_INFO(
15051 				    sata_hba_inst, cport)->cport_mutex);
15052 			}
15053 		}
15054 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15055 		    "sata_hba_ioctl: configure: "
15056 		    "failed to activate SATA port %d:%d",
15057 		    cport, pmport));
15058 		return (EIO);
15059 	}
15060 	/*
15061 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
15062 	 * without the hint.
15063 	 */
15064 	sata_gen_sysevent(sata_hba_inst,
15065 	    &sata_device->satadev_addr, SE_NO_HINT);
15066 
15067 	/* Virgin port state */
15068 	if (qual == SATA_ADDR_DPMPORT) {
15069 		mutex_enter(&pmportinfo->pmport_mutex);
15070 		pmportinfo->pmport_state = 0;
15071 		mutex_exit(&pmportinfo->pmport_mutex);
15072 	} else {
15073 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15074 		    cport)-> cport_mutex);
15075 		cportinfo->cport_state = 0;
15076 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15077 		    cport)->cport_mutex);
15078 	}
15079 	/*
15080 	 * Always reprobe port, to get current device info.
15081 	 */
15082 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15083 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15084 		return (EIO);
15085 
15086 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == B_FALSE) {
15087 		if (qual == SATA_ADDR_DPMPORT) {
15088 			/*
15089 			 * That's the transition from "inactive" port
15090 			 * to active one with device attached.
15091 			 */
15092 			sata_log(sata_hba_inst, CE_WARN,
15093 			    "SATA device detected at port %d:%d",
15094 			    cport, pmport);
15095 		} else {
15096 			/*
15097 			 * When PM is attached to the cport and cport is
15098 			 * activated, every PM device port needs to be reprobed.
15099 			 * We need to emit message for all devices detected
15100 			 * at port multiplier's device ports.
15101 			 * Add such code here.
15102 			 * For now, just inform about device attached to
15103 			 * cport.
15104 			 */
15105 			sata_log(sata_hba_inst, CE_WARN,
15106 			    "SATA device detected at port %d", cport);
15107 		}
15108 	}
15109 
15110 	/*
15111 	 * This is where real configuration operation starts.
15112 	 *
15113 	 * When PM is attached to the cport and cport is activated,
15114 	 * devices attached PM device ports may have to be configured
15115 	 * explicitly. This may change when port multiplier is supported.
15116 	 * For now, configure only disks and other valid target devices.
15117 	 */
15118 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
15119 		if (qual == SATA_ADDR_DCPORT) {
15120 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
15121 				/*
15122 				 * A device was not successfully identified
15123 				 */
15124 				sata_log(sata_hba_inst, CE_WARN,
15125 				    "Could not identify SATA "
15126 				    "device at port %d", cport);
15127 			}
15128 		} else { /* port multiplier device port */
15129 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
15130 				/*
15131 				 * A device was not successfully identified
15132 				 */
15133 				sata_log(sata_hba_inst, CE_WARN,
15134 				    "Could not identify SATA "
15135 				    "device at port %d:%d", cport, pmport);
15136 			}
15137 		}
15138 		return (ENXIO);		/* No device to configure */
15139 	}
15140 
15141 	/*
15142 	 * Here we may have a device in reset condition,
15143 	 * but because we are just configuring it, there is
15144 	 * no need to process the reset other than just
15145 	 * to clear device reset condition in the HBA driver.
15146 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
15147 	 * cause a first command sent the HBA driver with the request
15148 	 * to clear device reset condition.
15149 	 */
15150 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15151 	if (qual == SATA_ADDR_DPMPORT)
15152 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
15153 	else
15154 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
15155 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
15156 	if (sdinfo == NULL) {
15157 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15158 		return (ENXIO);
15159 	}
15160 	if (sdinfo->satadrv_event_flags &
15161 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
15162 		sdinfo->satadrv_event_flags = 0;
15163 	}
15164 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
15165 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15166 
15167 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
15168 	    &sata_device->satadev_addr)) != NULL) {
15169 		/*
15170 		 * Target node exists. Verify, that it belongs
15171 		 * to existing, attached device and not to
15172 		 * a removed device.
15173 		 */
15174 		if (sata_check_device_removed(tdip) == B_TRUE) {
15175 			if (qual == SATA_ADDR_DPMPORT)
15176 				sata_log(sata_hba_inst, CE_WARN,
15177 				    "SATA device at port %d cannot be "
15178 				    "configured. "
15179 				    "Application(s) accessing "
15180 				    "previously attached device "
15181 				    "have to release it before newly "
15182 				    "inserted device can be made accessible.",
15183 				    cport);
15184 			else
15185 				sata_log(sata_hba_inst, CE_WARN,
15186 				    "SATA device at port %d:%d cannot be"
15187 				    "configured. "
15188 				    "Application(s) accessing "
15189 				    "previously attached device "
15190 				    "have to release it before newly "
15191 				    "inserted device can be made accessible.",
15192 				    cport, pmport);
15193 			return (EIO);
15194 		}
15195 		/*
15196 		 * Device was not removed and re-inserted.
15197 		 * Try to online it.
15198 		 */
15199 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
15200 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15201 			    "sata_hba_ioctl: configure: "
15202 			    "onlining device at SATA port "
15203 			    "%d:%d failed", cport, pmport));
15204 			return (EIO);
15205 		}
15206 
15207 		if (qual == SATA_ADDR_DPMPORT) {
15208 			mutex_enter(&pmportinfo->pmport_mutex);
15209 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
15210 			mutex_exit(&pmportinfo->pmport_mutex);
15211 		} else {
15212 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15213 			    cport)->cport_mutex);
15214 			cportinfo-> cport_tgtnode_clean = B_TRUE;
15215 			mutex_exit(&SATA_CPORT_INFO(
15216 			    sata_hba_inst, cport)->cport_mutex);
15217 		}
15218 	} else {
15219 		/*
15220 		 * No target node - need to create a new target node.
15221 		 */
15222 		if (qual == SATA_ADDR_DPMPORT) {
15223 			mutex_enter(&pmportinfo->pmport_mutex);
15224 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
15225 			mutex_exit(&pmportinfo->pmport_mutex);
15226 		} else {
15227 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15228 			    cport_mutex);
15229 			cportinfo-> cport_tgtnode_clean = B_TRUE;
15230 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15231 			    cport_mutex);
15232 		}
15233 
15234 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
15235 		    sata_hba_inst, &sata_device->satadev_addr);
15236 		if (tdip == NULL) {
15237 			/* Configure operation failed */
15238 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15239 			    "sata_hba_ioctl: configure: "
15240 			    "configuring SATA device at port %d:%d "
15241 			    "failed", cport, pmport));
15242 			return (EIO);
15243 		}
15244 	}
15245 	return (0);
15246 }
15247 
15248 
15249 /*
15250  * Process ioctl deactivate port request.
15251  * Arbitrarily unconfigure attached device, if any.
15252  * Even if the unconfigure fails, proceed with the
15253  * port deactivation.
15254  *
15255  * NOTE: Port Multiplier is supported now.
15256  */
15257 
15258 static int
15259 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
15260     sata_device_t *sata_device)
15261 {
15262 	int cport, pmport, qual;
15263 	int rval, rv = 0;
15264 	int npmport;
15265 	sata_cport_info_t *cportinfo;
15266 	sata_pmport_info_t *pmportinfo;
15267 	sata_pmult_info_t *pmultinfo;
15268 	dev_info_t *tdip;
15269 	sata_drive_info_t *sdinfo = NULL;
15270 	sata_device_t subsdevice;
15271 
15272 	/* Sanity check */
15273 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
15274 		return (ENOTSUP);
15275 
15276 	cport = sata_device->satadev_addr.cport;
15277 	pmport = sata_device->satadev_addr.pmport;
15278 	qual = sata_device->satadev_addr.qual;
15279 
15280 	/* SCSI_TO_SATA_ADDR_QUAL() translate ap_id into a device qualifier */
15281 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
15282 	if (qual == SATA_ADDR_DCPORT)
15283 		qual = SATA_ADDR_CPORT;
15284 	else
15285 		qual = SATA_ADDR_PMPORT;
15286 
15287 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
15288 	if (qual == SATA_ADDR_PMPORT)
15289 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
15290 
15291 	/*
15292 	 * Processing port multiplier
15293 	 */
15294 	if (qual == SATA_ADDR_CPORT &&
15295 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
15296 		mutex_enter(&cportinfo->cport_mutex);
15297 
15298 		/* Deactivate all sub-deices */
15299 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
15300 		if (pmultinfo != NULL) {
15301 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
15302 			    sata_hba_inst, cport); npmport++) {
15303 
15304 				subsdevice.satadev_addr.cport = cport;
15305 				subsdevice.satadev_addr.pmport =
15306 				    (uint8_t)npmport;
15307 				subsdevice.satadev_addr.qual =
15308 				    SATA_ADDR_DPMPORT;
15309 
15310 				SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
15311 				    "sata_hba_ioctl: deactivate: trying to "
15312 				    "deactivate SATA port %d:%d",
15313 				    cport, npmport);
15314 
15315 				mutex_exit(&cportinfo->cport_mutex);
15316 				if (sata_ioctl_deactivate(sata_hba_inst,
15317 				    &subsdevice) == SATA_SUCCESS) {
15318 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
15319 					    "[Deactivate] device at port %d:%d "
15320 					    "successfully.", cport, npmport);
15321 				}
15322 				mutex_enter(&cportinfo->cport_mutex);
15323 			}
15324 		}
15325 
15326 		/* Deactivate the port multiplier now. */
15327 		cportinfo->cport_state &= ~SATA_STATE_READY;
15328 		mutex_exit(&cportinfo->cport_mutex);
15329 
15330 		sata_device->satadev_addr.qual = qual;
15331 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
15332 		    (SATA_DIP(sata_hba_inst), sata_device);
15333 
15334 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
15335 		    SE_NO_HINT);
15336 
15337 		mutex_enter(&cportinfo->cport_mutex);
15338 		sata_update_port_info(sata_hba_inst, sata_device);
15339 		if (rval != SATA_SUCCESS) {
15340 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
15341 				cportinfo->cport_state = SATA_PSTATE_FAILED;
15342 			}
15343 			rv = EIO;
15344 		} else {
15345 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
15346 		}
15347 		mutex_exit(&cportinfo->cport_mutex);
15348 
15349 		return (rv);
15350 	}
15351 
15352 	/*
15353 	 * Process non-port-multiplier device - it could be a drive connected
15354 	 * to a port multiplier port or a controller port.
15355 	 */
15356 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15357 	if (qual == SATA_ADDR_CPORT) {
15358 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
15359 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
15360 			/* deal only with valid devices */
15361 			if ((cportinfo->cport_dev_type &
15362 			    SATA_VALID_DEV_TYPE) != 0)
15363 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
15364 		}
15365 		cportinfo->cport_state &= ~SATA_STATE_READY;
15366 	} else {
15367 		/* Port multiplier device port */
15368 		mutex_enter(&pmportinfo->pmport_mutex);
15369 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
15370 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
15371 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
15372 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
15373 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
15374 		mutex_exit(&pmportinfo->pmport_mutex);
15375 	}
15376 
15377 	if (sdinfo != NULL) {
15378 		/*
15379 		 * If a target node exists, try to offline a device and
15380 		 * to remove a target node.
15381 		 */
15382 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15383 		    cport_mutex);
15384 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
15385 		    &sata_device->satadev_addr);
15386 		if (tdip != NULL) {
15387 			/* target node exist */
15388 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
15389 			    "sata_hba_ioctl: port deactivate: "
15390 			    "target node exists.", NULL);
15391 
15392 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
15393 			    NDI_SUCCESS) {
15394 				SATA_LOG_D((sata_hba_inst, CE_WARN,
15395 				    "sata_hba_ioctl: port deactivate: "
15396 				    "failed to unconfigure device at port "
15397 				    "%d:%d before deactivating the port",
15398 				    cport, pmport));
15399 				/*
15400 				 * Set DEVICE REMOVED state in the target
15401 				 * node. It will prevent an access to
15402 				 * the device even when a new device is
15403 				 * attached, until the old target node is
15404 				 * released, removed and recreated for a new
15405 				 * device.
15406 				 */
15407 				sata_set_device_removed(tdip);
15408 
15409 				/*
15410 				 * Instruct the event daemon to try the
15411 				 * target node cleanup later.
15412 				 */
15413 				sata_set_target_node_cleanup(sata_hba_inst,
15414 				    &sata_device->satadev_addr);
15415 			}
15416 		}
15417 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15418 		    cport_mutex);
15419 		/*
15420 		 * In any case, remove and release sata_drive_info
15421 		 * structure.
15422 		 */
15423 		if (qual == SATA_ADDR_CPORT) {
15424 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
15425 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
15426 		} else { /* port multiplier device port */
15427 			mutex_enter(&pmportinfo->pmport_mutex);
15428 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
15429 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
15430 			mutex_exit(&pmportinfo->pmport_mutex);
15431 		}
15432 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
15433 	}
15434 
15435 	if (qual == SATA_ADDR_CPORT) {
15436 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
15437 		    SATA_STATE_PROBING);
15438 	} else if (qual == SATA_ADDR_PMPORT) {
15439 		mutex_enter(&pmportinfo->pmport_mutex);
15440 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
15441 		    SATA_STATE_PROBING);
15442 		mutex_exit(&pmportinfo->pmport_mutex);
15443 	}
15444 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15445 
15446 	/* Just let HBA driver to deactivate port */
15447 	sata_device->satadev_addr.qual = qual;
15448 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
15449 	    (SATA_DIP(sata_hba_inst), sata_device);
15450 
15451 	/*
15452 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
15453 	 * without the hint
15454 	 */
15455 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
15456 	    SE_NO_HINT);
15457 
15458 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15459 	sata_update_port_info(sata_hba_inst, sata_device);
15460 	if (qual == SATA_ADDR_CPORT) {
15461 		if (rval != SATA_SUCCESS) {
15462 			/*
15463 			 * Port deactivation failure - do not change port state
15464 			 * unless the state returned by HBA indicates a port
15465 			 * failure.
15466 			 */
15467 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
15468 				SATA_CPORT_STATE(sata_hba_inst, cport) =
15469 				    SATA_PSTATE_FAILED;
15470 			}
15471 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15472 			    "sata_hba_ioctl: port deactivate: "
15473 			    "cannot deactivate SATA port %d", cport));
15474 			rv = EIO;
15475 		} else {
15476 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
15477 		}
15478 	} else {
15479 		mutex_enter(&pmportinfo->pmport_mutex);
15480 		if (rval != SATA_SUCCESS) {
15481 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
15482 				SATA_PMPORT_STATE(sata_hba_inst, cport,
15483 				    pmport) = SATA_PSTATE_FAILED;
15484 			}
15485 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15486 			    "sata_hba_ioctl: port deactivate: "
15487 			    "cannot deactivate SATA port %d:%d",
15488 			    cport, pmport));
15489 			rv = EIO;
15490 		} else {
15491 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
15492 		}
15493 		mutex_exit(&pmportinfo->pmport_mutex);
15494 	}
15495 
15496 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15497 
15498 	return (rv);
15499 }
15500 
15501 /*
15502  * Process ioctl port activate request.
15503  *
15504  * NOTE: Port multiplier is supported now.
15505  */
15506 static int
15507 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
15508     sata_device_t *sata_device)
15509 {
15510 	int cport, pmport, qual;
15511 	sata_cport_info_t *cportinfo;
15512 	sata_pmport_info_t *pmportinfo = NULL;
15513 	boolean_t dev_existed = B_TRUE;
15514 
15515 	/* Sanity check */
15516 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
15517 		return (ENOTSUP);
15518 
15519 	cport = sata_device->satadev_addr.cport;
15520 	pmport = sata_device->satadev_addr.pmport;
15521 	qual = sata_device->satadev_addr.qual;
15522 
15523 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
15524 
15525 	/*
15526 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
15527 	 * is a device. But what we are dealing with is port/pmport.
15528 	 */
15529 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
15530 	if (qual == SATA_ADDR_DCPORT)
15531 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
15532 	else
15533 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
15534 
15535 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15536 	if (qual == SATA_ADDR_PMPORT) {
15537 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
15538 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
15539 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
15540 			dev_existed = B_FALSE;
15541 	} else { /* cport */
15542 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
15543 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
15544 			dev_existed = B_FALSE;
15545 	}
15546 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15547 
15548 	/* Just let HBA driver to activate port, if necessary */
15549 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
15550 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15551 		/*
15552 		 * Port activation failure - do not change port state unless
15553 		 * the state returned by HBA indicates a port failure.
15554 		 */
15555 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15556 		    cport)->cport_mutex);
15557 		sata_update_port_info(sata_hba_inst, sata_device);
15558 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
15559 			if (qual == SATA_ADDR_PMPORT) {
15560 				mutex_enter(&pmportinfo->pmport_mutex);
15561 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
15562 				mutex_exit(&pmportinfo->pmport_mutex);
15563 			} else
15564 				cportinfo->cport_state = SATA_PSTATE_FAILED;
15565 
15566 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15567 			    cport)->cport_mutex);
15568 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15569 			    "sata_hba_ioctl: port activate: cannot activate "
15570 			    "SATA port %d:%d", cport, pmport));
15571 			return (EIO);
15572 		}
15573 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15574 	}
15575 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15576 	if (qual == SATA_ADDR_PMPORT) {
15577 		mutex_enter(&pmportinfo->pmport_mutex);
15578 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
15579 		mutex_exit(&pmportinfo->pmport_mutex);
15580 	} else
15581 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
15582 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15583 
15584 	/*
15585 	 * Re-probe port to find its current state and possibly attached device.
15586 	 * Port re-probing may change the cportinfo device type if device is
15587 	 * found attached.
15588 	 * If port probing failed, the device type would be set to
15589 	 * SATA_DTYPE_NONE.
15590 	 */
15591 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
15592 	    SATA_DEV_IDENTIFY_RETRY);
15593 
15594 	/*
15595 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
15596 	 * without the hint.
15597 	 */
15598 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
15599 	    SE_NO_HINT);
15600 
15601 	if (dev_existed == B_FALSE) {
15602 		if (qual == SATA_ADDR_PMPORT &&
15603 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
15604 			/*
15605 			 * That's the transition from the "inactive" port state
15606 			 * or the active port without a device attached to the
15607 			 * active port state with a device attached.
15608 			 */
15609 			sata_log(sata_hba_inst, CE_WARN,
15610 			    "SATA device detected at port %d:%d",
15611 			    cport, pmport);
15612 		} else if (qual == SATA_ADDR_CPORT &&
15613 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
15614 			/*
15615 			 * That's the transition from the "inactive" port state
15616 			 * or the active port without a device attached to the
15617 			 * active port state with a device attached.
15618 			 */
15619 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
15620 				sata_log(sata_hba_inst, CE_WARN,
15621 				    "SATA device detected at port %d", cport);
15622 			} else {
15623 				sata_log(sata_hba_inst, CE_WARN,
15624 				    "SATA port multiplier detected at port %d",
15625 				    cport);
15626 			}
15627 		}
15628 	}
15629 	return (0);
15630 }
15631 
15632 
15633 
15634 /*
15635  * Process ioctl reset port request.
15636  *
15637  * NOTE: Port-Multiplier is supported.
15638  */
15639 static int
15640 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
15641     sata_device_t *sata_device)
15642 {
15643 	int cport, pmport, qual;
15644 	int rv = 0;
15645 
15646 	cport = sata_device->satadev_addr.cport;
15647 	pmport = sata_device->satadev_addr.pmport;
15648 	qual = sata_device->satadev_addr.qual;
15649 
15650 	/*
15651 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
15652 	 * is a device. But what we are dealing with is port/pmport.
15653 	 */
15654 	if (qual == SATA_ADDR_DCPORT)
15655 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
15656 	else
15657 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
15658 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
15659 
15660 	/* Sanity check */
15661 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15662 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15663 		    "sata_hba_ioctl: sata_hba_tran missing required "
15664 		    "function sata_tran_reset_dport"));
15665 		return (ENOTSUP);
15666 	}
15667 
15668 	/* Ask HBA to reset port */
15669 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
15670 	    sata_device) != SATA_SUCCESS) {
15671 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15672 		    "sata_hba_ioctl: reset port: failed %d:%d",
15673 		    cport, pmport));
15674 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15675 		    cport_mutex);
15676 		sata_update_port_info(sata_hba_inst, sata_device);
15677 		if (qual == SATA_ADDR_CPORT)
15678 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15679 			    SATA_PSTATE_FAILED;
15680 		else {
15681 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
15682 			    pmport));
15683 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15684 			    SATA_PSTATE_FAILED;
15685 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
15686 			    pmport));
15687 		}
15688 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15689 		    cport_mutex);
15690 		rv = EIO;
15691 	}
15692 
15693 	return (rv);
15694 }
15695 
15696 /*
15697  * Process ioctl reset device request.
15698  *
15699  * NOTE: Port multiplier is supported.
15700  */
15701 static int
15702 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
15703     sata_device_t *sata_device)
15704 {
15705 	sata_drive_info_t *sdinfo = NULL;
15706 	sata_pmult_info_t *pmultinfo = NULL;
15707 	int cport, pmport;
15708 	int rv = 0;
15709 
15710 	/* Sanity check */
15711 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15712 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15713 		    "sata_hba_ioctl: sata_hba_tran missing required "
15714 		    "function sata_tran_reset_dport"));
15715 		return (ENOTSUP);
15716 	}
15717 
15718 	cport = sata_device->satadev_addr.cport;
15719 	pmport = sata_device->satadev_addr.pmport;
15720 
15721 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15722 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
15723 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
15724 		    SATA_DTYPE_PMULT)
15725 			pmultinfo = SATA_CPORT_INFO(sata_hba_inst, cport)->
15726 			    cport_devp.cport_sata_pmult;
15727 		else
15728 			sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15729 			    sata_device->satadev_addr.cport);
15730 	} else { /* port multiplier */
15731 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
15732 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15733 		    sata_device->satadev_addr.cport,
15734 		    sata_device->satadev_addr.pmport);
15735 	}
15736 	if (sdinfo == NULL && pmultinfo == NULL) {
15737 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15738 		return (EINVAL);
15739 	}
15740 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15741 
15742 	/* Ask HBA to reset device */
15743 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15744 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15745 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15746 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
15747 		    cport, pmport));
15748 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15749 		    cport_mutex);
15750 		sata_update_port_info(sata_hba_inst, sata_device);
15751 		/*
15752 		 * Device info structure remains attached. Another device reset
15753 		 * or port disconnect/connect and re-probing is
15754 		 * needed to change it's state
15755 		 */
15756 		if (sdinfo != NULL) {
15757 			sdinfo->satadrv_state &= ~SATA_STATE_READY;
15758 			sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
15759 		} else if (pmultinfo != NULL) {
15760 			pmultinfo->pmult_state &= ~SATA_STATE_READY;
15761 			pmultinfo->pmult_state |= SATA_DSTATE_FAILED;
15762 		}
15763 
15764 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15765 		rv = EIO;
15766 	}
15767 	/*
15768 	 * If attached device was a port multiplier, some extra processing
15769 	 * may be needed to bring it back. SATA specification requies a
15770 	 * mandatory software reset on host port to reliably enumerate a port
15771 	 * multiplier, the HBA driver should handle that after reset
15772 	 * operation.
15773 	 */
15774 	return (rv);
15775 }
15776 
15777 
15778 /*
15779  * Process ioctl reset all request.
15780  */
15781 static int
15782 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
15783 {
15784 	sata_device_t sata_device;
15785 	int rv = 0;
15786 	int tcport;
15787 
15788 	sata_device.satadev_rev = SATA_DEVICE_REV;
15789 
15790 	/*
15791 	 * There is no protection here for configured devices.
15792 	 */
15793 	/* Sanity check */
15794 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15795 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15796 		    "sata_hba_ioctl: sata_hba_tran missing required "
15797 		    "function sata_tran_reset_dport"));
15798 		return (ENOTSUP);
15799 	}
15800 
15801 	/*
15802 	 * Need to lock all ports, not just one.
15803 	 * If any port is locked by event processing, fail the whole operation.
15804 	 * One port is already locked, but for simplicity lock it again.
15805 	 */
15806 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15807 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15808 		    cport_mutex);
15809 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
15810 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
15811 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15812 			    cport_mutex);
15813 			rv = EBUSY;
15814 			break;
15815 		} else {
15816 			/*
15817 			 * It is enough to lock cport in command-based
15818 			 * switching mode.
15819 			 */
15820 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
15821 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
15822 		}
15823 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15824 		    cport_mutex);
15825 	}
15826 
15827 	if (rv == 0) {
15828 		/*
15829 		 * All cports were successfully locked.
15830 		 * Reset main SATA controller.
15831 		 * Set the device address to port 0, to have a valid device
15832 		 * address.
15833 		 */
15834 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
15835 		sata_device.satadev_addr.cport = 0;
15836 		sata_device.satadev_addr.pmport = 0;
15837 
15838 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15839 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
15840 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15841 			    "sata_hba_ioctl: reset controller failed"));
15842 			return (EIO);
15843 		}
15844 	}
15845 	/*
15846 	 * Unlock all ports
15847 	 */
15848 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15849 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15850 		    cport_mutex);
15851 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
15852 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
15853 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15854 		    cport_mutex);
15855 	}
15856 
15857 	/*
15858 	 * This operation returns EFAULT if either reset
15859 	 * controller failed or a re-probing of any port failed.
15860 	 */
15861 	return (rv);
15862 }
15863 
15864 
15865 /*
15866  * Process ioctl port self test request.
15867  *
15868  * NOTE: Port multiplier code is not completed nor tested.
15869  */
15870 static int
15871 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
15872     sata_device_t *sata_device)
15873 {
15874 	int cport, pmport, qual;
15875 	int rv = 0;
15876 
15877 	/* Sanity check */
15878 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
15879 		return (ENOTSUP);
15880 
15881 	cport = sata_device->satadev_addr.cport;
15882 	pmport = sata_device->satadev_addr.pmport;
15883 	qual = sata_device->satadev_addr.qual;
15884 
15885 	/*
15886 	 * There is no protection here for a configured
15887 	 * device attached to this port.
15888 	 */
15889 
15890 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
15891 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15892 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15893 		    "sata_hba_ioctl: port selftest: "
15894 		    "failed port %d:%d", cport, pmport));
15895 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15896 		    cport_mutex);
15897 		sata_update_port_info(sata_hba_inst, sata_device);
15898 		if (qual == SATA_ADDR_CPORT)
15899 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15900 			    SATA_PSTATE_FAILED;
15901 		else { /* port multiplier device port */
15902 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
15903 			    cport, pmport));
15904 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15905 			    SATA_PSTATE_FAILED;
15906 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
15907 			    cport, pmport));
15908 		}
15909 
15910 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15911 		    cport_mutex);
15912 		return (EIO);
15913 	}
15914 	/*
15915 	 * Beacuse the port was reset in the course of testing, it should be
15916 	 * re-probed and attached device state should be restored. At this
15917 	 * point the port state is unknown - it's state is HBA-specific.
15918 	 * Force port re-probing to get it into a known state.
15919 	 */
15920 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15921 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15922 		rv = EIO;
15923 	return (rv);
15924 }
15925 
15926 
15927 /*
15928  * sata_cfgadm_state:
15929  * Use the sata port state and state of the target node to figure out
15930  * the cfgadm_state.
15931  *
15932  * The port argument is a value with encoded cport,
15933  * pmport and address qualifier, in the same manner as a scsi target number.
15934  * SCSI_TO_SATA_CPORT macro extracts cport number,
15935  * SCSI_TO_SATA_PMPORT extracts pmport number and
15936  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
15937  *
15938  * Port multiplier is supported.
15939  */
15940 
15941 static void
15942 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
15943     devctl_ap_state_t *ap_state)
15944 {
15945 	uint8_t		cport, pmport, qual;
15946 	uint32_t	port_state, pmult_state;
15947 	uint32_t	dev_type;
15948 	sata_drive_info_t *sdinfo;
15949 
15950 	cport = SCSI_TO_SATA_CPORT(port);
15951 	pmport = SCSI_TO_SATA_PMPORT(port);
15952 	qual = SCSI_TO_SATA_ADDR_QUAL(port);
15953 
15954 	/* Check cport state */
15955 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
15956 	if (port_state & SATA_PSTATE_SHUTDOWN ||
15957 	    port_state & SATA_PSTATE_FAILED) {
15958 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15959 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15960 		if (port_state & SATA_PSTATE_FAILED)
15961 			ap_state->ap_condition = AP_COND_FAILED;
15962 		else
15963 			ap_state->ap_condition = AP_COND_UNKNOWN;
15964 
15965 		return;
15966 	}
15967 
15968 	/* cport state is okay. Now check pmport state */
15969 	if (qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) {
15970 		/* Sanity check */
15971 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
15972 		    SATA_DTYPE_PMULT || SATA_PMPORT_INFO(sata_hba_inst,
15973 		    cport, pmport) == NULL)
15974 			return;
15975 		port_state = SATA_PMPORT_STATE(sata_hba_inst, cport, pmport);
15976 		if (port_state & SATA_PSTATE_SHUTDOWN ||
15977 		    port_state & SATA_PSTATE_FAILED) {
15978 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15979 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15980 			if (port_state & SATA_PSTATE_FAILED)
15981 				ap_state->ap_condition = AP_COND_FAILED;
15982 			else
15983 				ap_state->ap_condition = AP_COND_UNKNOWN;
15984 
15985 			return;
15986 		}
15987 	}
15988 
15989 	/* Port is enabled and ready */
15990 	if (qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_CPORT)
15991 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst, cport);
15992 	else
15993 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport, pmport);
15994 
15995 	switch (dev_type) {
15996 	case SATA_DTYPE_NONE:
15997 	{
15998 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15999 		ap_state->ap_condition = AP_COND_OK;
16000 		/* No device attached */
16001 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
16002 		break;
16003 	}
16004 	case SATA_DTYPE_PMULT:
16005 	{
16006 		/* Need to check port multiplier state */
16007 		ASSERT(qual == SATA_ADDR_DCPORT);
16008 		pmult_state = SATA_PMULT_INFO(sata_hba_inst, cport)->
16009 		    pmult_state;
16010 		if (pmult_state & (SATA_PSTATE_SHUTDOWN|SATA_PSTATE_FAILED)) {
16011 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
16012 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
16013 			if (pmult_state & SATA_PSTATE_FAILED)
16014 				ap_state->ap_condition = AP_COND_FAILED;
16015 			else
16016 				ap_state->ap_condition = AP_COND_UNKNOWN;
16017 
16018 			return;
16019 		}
16020 
16021 		/* Port multiplier is not configurable */
16022 		ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
16023 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
16024 		ap_state->ap_condition = AP_COND_OK;
16025 		break;
16026 	}
16027 
16028 	case SATA_DTYPE_ATADISK:
16029 	case SATA_DTYPE_ATAPICD:
16030 	case SATA_DTYPE_ATAPITAPE:
16031 	case SATA_DTYPE_ATAPIDISK:
16032 	{
16033 		dev_info_t *tdip = NULL;
16034 		dev_info_t *dip = NULL;
16035 		int circ;
16036 
16037 		dip = SATA_DIP(sata_hba_inst);
16038 		tdip = sata_get_target_dip(dip, cport, pmport);
16039 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
16040 		if (tdip != NULL) {
16041 			ndi_devi_enter(dip, &circ);
16042 			mutex_enter(&(DEVI(tdip)->devi_lock));
16043 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
16044 				/*
16045 				 * There could be the case where previously
16046 				 * configured and opened device was removed
16047 				 * and unknown device was plugged.
16048 				 * In such case we want to show a device, and
16049 				 * its configured or unconfigured state but
16050 				 * indicate unusable condition untill the
16051 				 * old target node is released and removed.
16052 				 */
16053 				ap_state->ap_condition = AP_COND_UNUSABLE;
16054 			} else {
16055 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
16056 				    cport));
16057 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
16058 				    cport);
16059 				if (sdinfo != NULL) {
16060 					if ((sdinfo->satadrv_state &
16061 					    SATA_DSTATE_FAILED) != 0)
16062 						ap_state->ap_condition =
16063 						    AP_COND_FAILED;
16064 					else
16065 						ap_state->ap_condition =
16066 						    AP_COND_OK;
16067 				} else {
16068 					ap_state->ap_condition =
16069 					    AP_COND_UNKNOWN;
16070 				}
16071 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
16072 				    cport));
16073 			}
16074 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
16075 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
16076 				ap_state->ap_ostate =
16077 				    AP_OSTATE_UNCONFIGURED;
16078 			} else {
16079 				ap_state->ap_ostate =
16080 				    AP_OSTATE_CONFIGURED;
16081 			}
16082 			mutex_exit(&(DEVI(tdip)->devi_lock));
16083 			ndi_devi_exit(dip, circ);
16084 		} else {
16085 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
16086 			ap_state->ap_condition = AP_COND_UNKNOWN;
16087 		}
16088 		break;
16089 	}
16090 	case SATA_DTYPE_ATAPIPROC:
16091 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
16092 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
16093 		ap_state->ap_condition = AP_COND_OK;
16094 		break;
16095 	default:
16096 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
16097 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
16098 		ap_state->ap_condition = AP_COND_UNKNOWN;
16099 		/*
16100 		 * This is actually internal error condition (non fatal),
16101 		 * because we have already checked all defined device types.
16102 		 */
16103 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16104 		    "sata_cfgadm_state: Internal error: "
16105 		    "unknown device type"));
16106 		break;
16107 	}
16108 }
16109 
16110 
16111 /*
16112  * Process ioctl get device path request.
16113  *
16114  * NOTE: Port multiplier has no target dip. Devices connected to port
16115  * multiplier have target node attached to the HBA node. The only difference
16116  * between them and the directly-attached device node is a target address.
16117  */
16118 static int
16119 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
16120     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
16121 {
16122 	char path[MAXPATHLEN];
16123 	uint32_t size;
16124 	dev_info_t *tdip;
16125 
16126 	(void) strcpy(path, "/devices");
16127 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
16128 	    &sata_device->satadev_addr)) == NULL) {
16129 		/*
16130 		 * No such device. If this is a request for a size, do not
16131 		 * return EINVAL for non-existing target, because cfgadm
16132 		 * will then indicate a meaningless ioctl failure.
16133 		 * If this is a request for a path, indicate invalid
16134 		 * argument.
16135 		 */
16136 		if (ioc->get_size == 0)
16137 			return (EINVAL);
16138 	} else {
16139 		(void) ddi_pathname(tdip, path + strlen(path));
16140 	}
16141 	size = strlen(path) + 1;
16142 
16143 	if (ioc->get_size != 0) {
16144 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
16145 		    mode) != 0)
16146 			return (EFAULT);
16147 	} else {
16148 		if (ioc->bufsiz != size)
16149 			return (EINVAL);
16150 
16151 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
16152 		    mode) != 0)
16153 			return (EFAULT);
16154 	}
16155 	return (0);
16156 }
16157 
16158 /*
16159  * Process ioctl get attachment point type request.
16160  *
16161  * NOTE: Port multiplier is supported.
16162  */
16163 static	int
16164 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
16165     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
16166 {
16167 	uint32_t	type_len;
16168 	const char	*ap_type;
16169 	int		dev_type;
16170 
16171 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
16172 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
16173 		    sata_device->satadev_addr.cport);
16174 	else /* pmport */
16175 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
16176 		    sata_device->satadev_addr.cport,
16177 		    sata_device->satadev_addr.pmport);
16178 
16179 	switch (dev_type) {
16180 	case SATA_DTYPE_NONE:
16181 		ap_type = "port";
16182 		break;
16183 
16184 	case SATA_DTYPE_ATADISK:
16185 	case SATA_DTYPE_ATAPIDISK:
16186 		ap_type = "disk";
16187 		break;
16188 
16189 	case SATA_DTYPE_ATAPICD:
16190 		ap_type = "cd/dvd";
16191 		break;
16192 
16193 	case SATA_DTYPE_ATAPITAPE:
16194 		ap_type = "tape";
16195 		break;
16196 
16197 	case SATA_DTYPE_ATAPIPROC:
16198 		ap_type = "processor";
16199 		break;
16200 
16201 	case SATA_DTYPE_PMULT:
16202 		ap_type = "sata-pmult";
16203 		break;
16204 
16205 	case SATA_DTYPE_UNKNOWN:
16206 		ap_type = "unknown";
16207 		break;
16208 
16209 	default:
16210 		ap_type = "unsupported";
16211 		break;
16212 
16213 	} /* end of dev_type switch */
16214 
16215 	type_len = strlen(ap_type) + 1;
16216 
16217 	if (ioc->get_size) {
16218 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
16219 		    mode) != 0)
16220 			return (EFAULT);
16221 	} else {
16222 		if (ioc->bufsiz != type_len)
16223 			return (EINVAL);
16224 
16225 		if (ddi_copyout((void *)ap_type, ioc->buf,
16226 		    ioc->bufsiz, mode) != 0)
16227 			return (EFAULT);
16228 	}
16229 	return (0);
16230 
16231 }
16232 
16233 /*
16234  * Process ioctl get device model info request.
16235  * This operation should return to cfgadm the device model
16236  * information string
16237  *
16238  * NOTE: Port multiplier is supported.
16239  */
16240 static	int
16241 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
16242     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
16243 {
16244 	sata_drive_info_t *sdinfo;
16245 	uint32_t info_len;
16246 	char ap_info[SATA_ID_MODEL_LEN + 1];
16247 
16248 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
16249 	    sata_device->satadev_addr.cport)->cport_mutex);
16250 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
16251 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
16252 		    sata_device->satadev_addr.cport);
16253 	else /* port multiplier */
16254 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
16255 		    sata_device->satadev_addr.cport,
16256 		    sata_device->satadev_addr.pmport);
16257 	if (sdinfo == NULL) {
16258 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
16259 		    sata_device->satadev_addr.cport)->cport_mutex);
16260 		return (EINVAL);
16261 	}
16262 
16263 #ifdef	_LITTLE_ENDIAN
16264 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
16265 #else	/* _LITTLE_ENDIAN */
16266 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
16267 #endif	/* _LITTLE_ENDIAN */
16268 
16269 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
16270 	    sata_device->satadev_addr.cport)->cport_mutex);
16271 
16272 	ap_info[SATA_ID_MODEL_LEN] = '\0';
16273 
16274 	info_len = strlen(ap_info) + 1;
16275 
16276 	if (ioc->get_size) {
16277 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
16278 		    mode) != 0)
16279 			return (EFAULT);
16280 	} else {
16281 		if (ioc->bufsiz < info_len)
16282 			return (EINVAL);
16283 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
16284 		    mode) != 0)
16285 			return (EFAULT);
16286 	}
16287 	return (0);
16288 }
16289 
16290 
16291 /*
16292  * Process ioctl get device firmware revision info request.
16293  * This operation should return to cfgadm the device firmware revision
16294  * information string
16295  *
16296  * Port multiplier is supported.
16297  */
16298 static	int
16299 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
16300     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
16301 {
16302 	sata_drive_info_t *sdinfo;
16303 	uint32_t info_len;
16304 	char ap_info[SATA_ID_FW_LEN + 1];
16305 
16306 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
16307 	    sata_device->satadev_addr.cport)->cport_mutex);
16308 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
16309 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
16310 		    sata_device->satadev_addr.cport);
16311 	else /* port multiplier */
16312 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
16313 		    sata_device->satadev_addr.cport,
16314 		    sata_device->satadev_addr.pmport);
16315 	if (sdinfo == NULL) {
16316 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
16317 		    sata_device->satadev_addr.cport)->cport_mutex);
16318 		return (EINVAL);
16319 	}
16320 
16321 #ifdef	_LITTLE_ENDIAN
16322 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
16323 #else	/* _LITTLE_ENDIAN */
16324 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
16325 #endif	/* _LITTLE_ENDIAN */
16326 
16327 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
16328 	    sata_device->satadev_addr.cport)->cport_mutex);
16329 
16330 	ap_info[SATA_ID_FW_LEN] = '\0';
16331 
16332 	info_len = strlen(ap_info) + 1;
16333 
16334 	if (ioc->get_size) {
16335 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
16336 		    mode) != 0)
16337 			return (EFAULT);
16338 	} else {
16339 		if (ioc->bufsiz < info_len)
16340 			return (EINVAL);
16341 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
16342 		    mode) != 0)
16343 			return (EFAULT);
16344 	}
16345 	return (0);
16346 }
16347 
16348 
16349 /*
16350  * Process ioctl get device serial number info request.
16351  * This operation should return to cfgadm the device serial number string.
16352  *
16353  * NOTE: Port multiplier is supported.
16354  */
16355 static	int
16356 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
16357     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
16358 {
16359 	sata_drive_info_t *sdinfo;
16360 	uint32_t info_len;
16361 	char ap_info[SATA_ID_SERIAL_LEN + 1];
16362 
16363 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
16364 	    sata_device->satadev_addr.cport)->cport_mutex);
16365 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
16366 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
16367 		    sata_device->satadev_addr.cport);
16368 	else /* port multiplier */
16369 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
16370 		    sata_device->satadev_addr.cport,
16371 		    sata_device->satadev_addr.pmport);
16372 	if (sdinfo == NULL) {
16373 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
16374 		    sata_device->satadev_addr.cport)->cport_mutex);
16375 		return (EINVAL);
16376 	}
16377 
16378 #ifdef	_LITTLE_ENDIAN
16379 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
16380 #else	/* _LITTLE_ENDIAN */
16381 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
16382 #endif	/* _LITTLE_ENDIAN */
16383 
16384 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
16385 	    sata_device->satadev_addr.cport)->cport_mutex);
16386 
16387 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
16388 
16389 	info_len = strlen(ap_info) + 1;
16390 
16391 	if (ioc->get_size) {
16392 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
16393 		    mode) != 0)
16394 			return (EFAULT);
16395 	} else {
16396 		if (ioc->bufsiz < info_len)
16397 			return (EINVAL);
16398 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
16399 		    mode) != 0)
16400 			return (EFAULT);
16401 	}
16402 	return (0);
16403 }
16404 
16405 
16406 /*
16407  * Preset scsi extended sense data (to NO SENSE)
16408  * First 18 bytes of the sense data are preset to current valid sense
16409  * with a key NO SENSE data.
16410  *
16411  * Returns void
16412  */
16413 static void
16414 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
16415 {
16416 	sense->es_valid = 1;		/* Valid sense */
16417 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
16418 	sense->es_key = KEY_NO_SENSE;
16419 	sense->es_info_1 = 0;
16420 	sense->es_info_2 = 0;
16421 	sense->es_info_3 = 0;
16422 	sense->es_info_4 = 0;
16423 	sense->es_add_len = 10;	/* Additional length - replace with a def */
16424 	sense->es_cmd_info[0] = 0;
16425 	sense->es_cmd_info[1] = 0;
16426 	sense->es_cmd_info[2] = 0;
16427 	sense->es_cmd_info[3] = 0;
16428 	sense->es_add_code = 0;
16429 	sense->es_qual_code = 0;
16430 }
16431 
16432 /*
16433  * Register a legacy cmdk-style devid for the target (disk) device.
16434  *
16435  * Note: This function is called only when the HBA devinfo node has the
16436  * property "use-cmdk-devid-format" set. This property indicates that
16437  * devid compatible with old cmdk (target) driver is to be generated
16438  * for any target device attached to this controller. This will take
16439  * precedence over the devid generated by sd (target) driver.
16440  * This function is derived from cmdk_devid_setup() function in cmdk.c.
16441  */
16442 static void
16443 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
16444 {
16445 	char	*hwid;
16446 	int	modlen;
16447 	int	serlen;
16448 	int	rval;
16449 	ddi_devid_t	devid;
16450 
16451 	/*
16452 	 * device ID is a concatanation of model number, "=", serial number.
16453 	 */
16454 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
16455 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
16456 	    sizeof (sdinfo->satadrv_id.ai_model));
16457 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
16458 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
16459 	if (modlen == 0)
16460 		goto err;
16461 	hwid[modlen++] = '=';
16462 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
16463 	    sizeof (sdinfo->satadrv_id.ai_drvser));
16464 	swab(&hwid[modlen], &hwid[modlen],
16465 	    sizeof (sdinfo->satadrv_id.ai_drvser));
16466 	serlen = sata_check_modser(&hwid[modlen],
16467 	    sizeof (sdinfo->satadrv_id.ai_drvser));
16468 	if (serlen == 0)
16469 		goto err;
16470 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
16471 
16472 	/* initialize/register devid */
16473 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
16474 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
16475 		rval = ddi_devid_register(dip, devid);
16476 		/*
16477 		 * Free up the allocated devid buffer.
16478 		 * NOTE: This doesn't mean unregistering devid.
16479 		 */
16480 		ddi_devid_free(devid);
16481 	}
16482 
16483 	if (rval != DDI_SUCCESS)
16484 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
16485 		    " on port %d", sdinfo->satadrv_addr.cport);
16486 err:
16487 	kmem_free(hwid, LEGACY_HWID_LEN);
16488 }
16489 
16490 /*
16491  * valid model/serial string must contain a non-zero non-space characters.
16492  * trim trailing spaces/NULLs.
16493  */
16494 static int
16495 sata_check_modser(char *buf, int buf_len)
16496 {
16497 	boolean_t ret;
16498 	char *s;
16499 	int i;
16500 	int tb;
16501 	char ch;
16502 
16503 	ret = B_FALSE;
16504 	s = buf;
16505 	for (i = 0; i < buf_len; i++) {
16506 		ch = *s++;
16507 		if (ch != ' ' && ch != '\0')
16508 			tb = i + 1;
16509 		if (ch != ' ' && ch != '\0' && ch != '0')
16510 			ret = B_TRUE;
16511 	}
16512 
16513 	if (ret == B_FALSE)
16514 		return (0); /* invalid string */
16515 
16516 	return (tb); /* return length */
16517 }
16518 
16519 /*
16520  * sata_set_drive_features function compares current device features setting
16521  * with the saved device features settings and, if there is a difference,
16522  * it restores device features setting to the previously saved state.
16523  * It also arbitrarily tries to select the highest supported DMA mode.
16524  * Device Identify or Identify Packet Device data has to be current.
16525  * At the moment read ahead and write cache are considered for all devices.
16526  * For atapi devices, Removable Media Status Notification is set in addition
16527  * to common features.
16528  *
16529  * This function cannot be called in the interrupt context (it may sleep).
16530  *
16531  * The input argument sdinfo should point to the drive info structure
16532  * to be updated after features are set. Note, that only
16533  * device (packet) identify data is updated, not the flags indicating the
16534  * supported features.
16535  *
16536  * Returns SATA_SUCCESS if successful or there was nothing to do.
16537  * Device Identify data in the drive info structure pointed to by the sdinfo
16538  * arguments is updated even when no features were set or changed.
16539  *
16540  * Returns SATA_FAILURE if device features could not be set or DMA mode
16541  * for a disk cannot be set and device identify data cannot be fetched.
16542  *
16543  * Returns SATA_RETRY if device features could not be set (other than disk
16544  * DMA mode) but the device identify data was fetched successfully.
16545  *
16546  * Note: This function may fail the port, making it inaccessible.
16547  * In such case the explicit port disconnect/connect or physical device
16548  * detach/attach is required to re-evaluate port state again.
16549  */
16550 
16551 static int
16552 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
16553     sata_drive_info_t *sdinfo, int restore)
16554 {
16555 	int rval = SATA_SUCCESS;
16556 	int rval_set;
16557 	sata_drive_info_t new_sdinfo;
16558 	char *finfo = "sata_set_drive_features: cannot";
16559 	char *finfox;
16560 	int cache_op;
16561 
16562 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
16563 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
16564 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
16565 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
16566 		/*
16567 		 * Cannot get device identification - caller may retry later
16568 		 */
16569 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16570 		    "%s fetch device identify data\n", finfo);
16571 		return (SATA_FAILURE);
16572 	}
16573 	finfox = (restore != 0) ? " restore device features" :
16574 	    " initialize device features\n";
16575 
16576 	switch (sdinfo->satadrv_type) {
16577 	case SATA_DTYPE_ATADISK:
16578 		/* Arbitrarily set UDMA mode */
16579 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
16580 		    SATA_SUCCESS) {
16581 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16582 			    "%s set UDMA mode\n", finfo));
16583 			return (SATA_FAILURE);
16584 		}
16585 		break;
16586 	case SATA_DTYPE_ATAPICD:
16587 	case SATA_DTYPE_ATAPITAPE:
16588 	case SATA_DTYPE_ATAPIDISK:
16589 		/*  Set Removable Media Status Notification, if necessary */
16590 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
16591 		    restore != 0) {
16592 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
16593 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
16594 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
16595 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
16596 				/* Current setting does not match saved one */
16597 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
16598 				    sdinfo->satadrv_settings &
16599 				    SATA_DEV_RMSN) != SATA_SUCCESS)
16600 					rval = SATA_FAILURE;
16601 			}
16602 		}
16603 		/*
16604 		 * We have to set Multiword DMA or UDMA, if it is supported, as
16605 		 * we want to use DMA transfer mode whenever possible.
16606 		 * Some devices require explicit setting of the DMA mode.
16607 		 */
16608 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
16609 			/* Set highest supported DMA mode */
16610 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
16611 			    SATA_SUCCESS) {
16612 				SATA_LOG_D((sata_hba_inst, CE_WARN,
16613 				    "%s set UDMA mode\n", finfo));
16614 				rval = SATA_FAILURE;
16615 			}
16616 		}
16617 		break;
16618 	}
16619 
16620 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
16621 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
16622 		/*
16623 		 * neither READ AHEAD nor WRITE CACHE is supported
16624 		 * - do nothing
16625 		 */
16626 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16627 		    "settable features not supported\n", NULL);
16628 		goto update_sdinfo;
16629 	}
16630 
16631 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
16632 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
16633 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
16634 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
16635 		/*
16636 		 * both READ AHEAD and WRITE CACHE are enabled
16637 		 * - Nothing to do
16638 		 */
16639 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16640 		    "no device features to set\n", NULL);
16641 		goto update_sdinfo;
16642 	}
16643 
16644 	cache_op = 0;
16645 
16646 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
16647 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
16648 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
16649 			/* Enable read ahead / read cache */
16650 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
16651 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16652 			    "enabling read cache\n", NULL);
16653 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
16654 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
16655 			/* Disable read ahead  / read cache */
16656 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
16657 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16658 			    "disabling read cache\n", NULL);
16659 		}
16660 
16661 		if (cache_op != 0) {
16662 			/* Try to set read cache mode */
16663 			rval_set = sata_set_cache_mode(sata_hba_inst,
16664 			    &new_sdinfo, cache_op);
16665 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
16666 				rval = rval_set;
16667 		}
16668 	}
16669 
16670 	cache_op = 0;
16671 
16672 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
16673 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
16674 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
16675 			/* Enable write cache */
16676 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
16677 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16678 			    "enabling write cache\n", NULL);
16679 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
16680 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
16681 			/* Disable write cache */
16682 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
16683 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16684 			    "disabling write cache\n", NULL);
16685 		}
16686 
16687 		if (cache_op != 0) {
16688 			/* Try to set write cache mode */
16689 			rval_set = sata_set_cache_mode(sata_hba_inst,
16690 			    &new_sdinfo, cache_op);
16691 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
16692 				rval = rval_set;
16693 		}
16694 	}
16695 	if (rval != SATA_SUCCESS)
16696 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16697 		    "%s %s", finfo, finfox));
16698 
16699 update_sdinfo:
16700 	/*
16701 	 * We need to fetch Device Identify data again
16702 	 */
16703 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
16704 		/*
16705 		 * Cannot get device identification - retry later
16706 		 */
16707 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16708 		    "%s re-fetch device identify data\n", finfo));
16709 		rval = SATA_FAILURE;
16710 	}
16711 	/* Copy device sata info. */
16712 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
16713 
16714 	return (rval);
16715 }
16716 
16717 
16718 /*
16719  *
16720  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
16721  * unable to determine.
16722  *
16723  * Cannot be called in an interrupt context.
16724  *
16725  * Called by sata_build_lsense_page_2f()
16726  */
16727 
16728 static int
16729 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
16730     sata_drive_info_t *sdinfo)
16731 {
16732 	sata_pkt_t *spkt;
16733 	sata_cmd_t *scmd;
16734 	sata_pkt_txlate_t *spx;
16735 	int rval;
16736 
16737 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16738 	spx->txlt_sata_hba_inst = sata_hba_inst;
16739 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16740 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16741 	if (spkt == NULL) {
16742 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16743 		return (-1);
16744 	}
16745 	/* address is needed now */
16746 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16747 
16748 
16749 	/* Fill sata_pkt */
16750 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16751 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16752 	/* Synchronous mode, no callback */
16753 	spkt->satapkt_comp = NULL;
16754 	/* Timeout 30s */
16755 	spkt->satapkt_time = sata_default_pkt_time;
16756 
16757 	scmd = &spkt->satapkt_cmd;
16758 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
16759 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
16760 
16761 	/* Set up which registers need to be returned */
16762 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
16763 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
16764 
16765 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
16766 	scmd->satacmd_addr_type = 0;		/* N/A */
16767 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16768 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
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_RETURN_STATUS;
16772 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16773 	scmd->satacmd_cmd_reg = SATAC_SMART;
16774 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16775 	    sdinfo->satadrv_addr.cport)));
16776 
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 		 * Whoops, no SMART RETURN STATUS
16786 		 */
16787 		rval = -1;
16788 	} else {
16789 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16790 		    sdinfo->satadrv_addr.cport)));
16791 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
16792 			rval = -1;
16793 			goto fail;
16794 		}
16795 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
16796 			rval = -1;
16797 			goto fail;
16798 		}
16799 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
16800 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
16801 			rval = 0;
16802 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
16803 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
16804 			rval = 1;
16805 		else {
16806 			rval = -1;
16807 			goto fail;
16808 		}
16809 	}
16810 fail:
16811 	/* Free allocated resources */
16812 	sata_pkt_free(spx);
16813 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16814 
16815 	return (rval);
16816 }
16817 
16818 /*
16819  *
16820  * Returns 0 if succeeded, -1 otherwise
16821  *
16822  * Cannot be called in an interrupt context.
16823  *
16824  */
16825 static int
16826 sata_fetch_smart_data(
16827 	sata_hba_inst_t *sata_hba_inst,
16828 	sata_drive_info_t *sdinfo,
16829 	struct smart_data *smart_data)
16830 {
16831 	sata_pkt_t *spkt;
16832 	sata_cmd_t *scmd;
16833 	sata_pkt_txlate_t *spx;
16834 	int rval;
16835 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
16836 
16837 #if ! defined(lint)
16838 	ASSERT(sizeof (struct smart_data) == 512);
16839 #endif
16840 
16841 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16842 	spx->txlt_sata_hba_inst = sata_hba_inst;
16843 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16844 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16845 	if (spkt == NULL) {
16846 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16847 		return (-1);
16848 	}
16849 	/* address is needed now */
16850 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16851 
16852 
16853 	/* Fill sata_pkt */
16854 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16855 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16856 	/* Synchronous mode, no callback */
16857 	spkt->satapkt_comp = NULL;
16858 	/* Timeout 30s */
16859 	spkt->satapkt_time = sata_default_pkt_time;
16860 
16861 	scmd = &spkt->satapkt_cmd;
16862 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16863 
16864 	/*
16865 	 * Allocate buffer for SMART data
16866 	 */
16867 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16868 	    sizeof (struct smart_data));
16869 	if (scmd->satacmd_bp == NULL) {
16870 		sata_pkt_free(spx);
16871 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16872 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16873 		    "sata_fetch_smart_data: "
16874 		    "cannot allocate buffer"));
16875 		return (-1);
16876 	}
16877 
16878 
16879 	/* Build SMART_READ_DATA cmd in the sata_pkt */
16880 	scmd->satacmd_addr_type = 0;		/* N/A */
16881 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16882 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16883 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16884 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16885 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
16886 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16887 	scmd->satacmd_cmd_reg = SATAC_SMART;
16888 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16889 	    sdinfo->satadrv_addr.cport)));
16890 
16891 	/* Send pkt to SATA HBA driver */
16892 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16893 	    SATA_TRAN_ACCEPTED ||
16894 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16895 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16896 		    sdinfo->satadrv_addr.cport)));
16897 		/*
16898 		 * Whoops, no SMART DATA available
16899 		 */
16900 		rval = -1;
16901 		goto fail;
16902 	} else {
16903 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16904 		    sdinfo->satadrv_addr.cport)));
16905 		if (spx->txlt_buf_dma_handle != NULL) {
16906 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16907 			    DDI_DMA_SYNC_FORKERNEL);
16908 			ASSERT(rval == DDI_SUCCESS);
16909 			if (sata_check_for_dma_error(dip, spx)) {
16910 				ddi_fm_service_impact(dip,
16911 				    DDI_SERVICE_UNAFFECTED);
16912 				rval = -1;
16913 				goto fail;
16914 			}
16915 		}
16916 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
16917 		    sizeof (struct smart_data));
16918 	}
16919 
16920 fail:
16921 	/* Free allocated resources */
16922 	sata_free_local_buffer(spx);
16923 	sata_pkt_free(spx);
16924 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16925 
16926 	return (rval);
16927 }
16928 
16929 /*
16930  * Used by LOG SENSE page 0x10
16931  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
16932  * Note: cannot be called in the interrupt context.
16933  *
16934  * return 0 for success, -1 otherwise
16935  *
16936  */
16937 static int
16938 sata_ext_smart_selftest_read_log(
16939 	sata_hba_inst_t *sata_hba_inst,
16940 	sata_drive_info_t *sdinfo,
16941 	struct smart_ext_selftest_log *ext_selftest_log,
16942 	uint16_t block_num)
16943 {
16944 	sata_pkt_txlate_t *spx;
16945 	sata_pkt_t *spkt;
16946 	sata_cmd_t *scmd;
16947 	int rval;
16948 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
16949 
16950 #if ! defined(lint)
16951 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
16952 #endif
16953 
16954 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16955 	spx->txlt_sata_hba_inst = sata_hba_inst;
16956 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16957 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16958 	if (spkt == NULL) {
16959 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16960 		return (-1);
16961 	}
16962 	/* address is needed now */
16963 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16964 
16965 
16966 	/* Fill sata_pkt */
16967 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16968 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16969 	/* Synchronous mode, no callback */
16970 	spkt->satapkt_comp = NULL;
16971 	/* Timeout 30s */
16972 	spkt->satapkt_time = sata_default_pkt_time;
16973 
16974 	scmd = &spkt->satapkt_cmd;
16975 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16976 
16977 	/*
16978 	 * Allocate buffer for SMART extended self-test log
16979 	 */
16980 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16981 	    sizeof (struct smart_ext_selftest_log));
16982 	if (scmd->satacmd_bp == NULL) {
16983 		sata_pkt_free(spx);
16984 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16985 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16986 		    "sata_ext_smart_selftest_log: "
16987 		    "cannot allocate buffer"));
16988 		return (-1);
16989 	}
16990 
16991 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
16992 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16993 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
16994 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
16995 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
16996 	scmd->satacmd_lba_low_msb = 0;
16997 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
16998 	scmd->satacmd_lba_mid_msb = block_num >> 8;
16999 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
17000 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
17001 
17002 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
17003 	    sdinfo->satadrv_addr.cport)));
17004 
17005 	/* Send pkt to SATA HBA driver */
17006 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
17007 	    SATA_TRAN_ACCEPTED ||
17008 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
17009 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17010 		    sdinfo->satadrv_addr.cport)));
17011 
17012 		/*
17013 		 * Whoops, no SMART selftest log info available
17014 		 */
17015 		rval = -1;
17016 		goto fail;
17017 	} else {
17018 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17019 		    sdinfo->satadrv_addr.cport)));
17020 
17021 		if (spx->txlt_buf_dma_handle != NULL) {
17022 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
17023 			    DDI_DMA_SYNC_FORKERNEL);
17024 			ASSERT(rval == DDI_SUCCESS);
17025 			if (sata_check_for_dma_error(dip, spx)) {
17026 				ddi_fm_service_impact(dip,
17027 				    DDI_SERVICE_UNAFFECTED);
17028 				rval = -1;
17029 				goto fail;
17030 			}
17031 		}
17032 		bcopy(scmd->satacmd_bp->b_un.b_addr,
17033 		    (uint8_t *)ext_selftest_log,
17034 		    sizeof (struct smart_ext_selftest_log));
17035 		rval = 0;
17036 	}
17037 
17038 fail:
17039 	/* Free allocated resources */
17040 	sata_free_local_buffer(spx);
17041 	sata_pkt_free(spx);
17042 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
17043 
17044 	return (rval);
17045 }
17046 
17047 /*
17048  * Returns 0 for success, -1 otherwise
17049  *
17050  * SMART self-test log data is returned in buffer pointed to by selftest_log
17051  */
17052 static int
17053 sata_smart_selftest_log(
17054 	sata_hba_inst_t *sata_hba_inst,
17055 	sata_drive_info_t *sdinfo,
17056 	struct smart_selftest_log *selftest_log)
17057 {
17058 	sata_pkt_t *spkt;
17059 	sata_cmd_t *scmd;
17060 	sata_pkt_txlate_t *spx;
17061 	int rval;
17062 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
17063 
17064 #if ! defined(lint)
17065 	ASSERT(sizeof (struct smart_selftest_log) == 512);
17066 #endif
17067 
17068 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
17069 	spx->txlt_sata_hba_inst = sata_hba_inst;
17070 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
17071 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
17072 	if (spkt == NULL) {
17073 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
17074 		return (-1);
17075 	}
17076 	/* address is needed now */
17077 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
17078 
17079 
17080 	/* Fill sata_pkt */
17081 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
17082 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
17083 	/* Synchronous mode, no callback */
17084 	spkt->satapkt_comp = NULL;
17085 	/* Timeout 30s */
17086 	spkt->satapkt_time = sata_default_pkt_time;
17087 
17088 	scmd = &spkt->satapkt_cmd;
17089 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
17090 
17091 	/*
17092 	 * Allocate buffer for SMART SELFTEST LOG
17093 	 */
17094 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
17095 	    sizeof (struct smart_selftest_log));
17096 	if (scmd->satacmd_bp == NULL) {
17097 		sata_pkt_free(spx);
17098 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
17099 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17100 		    "sata_smart_selftest_log: "
17101 		    "cannot allocate buffer"));
17102 		return (-1);
17103 	}
17104 
17105 	/* Build SMART_READ_LOG cmd in the sata_pkt */
17106 	scmd->satacmd_addr_type = 0;		/* N/A */
17107 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
17108 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
17109 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
17110 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
17111 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
17112 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
17113 	scmd->satacmd_cmd_reg = SATAC_SMART;
17114 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
17115 	    sdinfo->satadrv_addr.cport)));
17116 
17117 	/* Send pkt to SATA HBA driver */
17118 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
17119 	    SATA_TRAN_ACCEPTED ||
17120 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
17121 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17122 		    sdinfo->satadrv_addr.cport)));
17123 		/*
17124 		 * Whoops, no SMART DATA available
17125 		 */
17126 		rval = -1;
17127 		goto fail;
17128 	} else {
17129 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17130 		    sdinfo->satadrv_addr.cport)));
17131 		if (spx->txlt_buf_dma_handle != NULL) {
17132 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
17133 			    DDI_DMA_SYNC_FORKERNEL);
17134 			ASSERT(rval == DDI_SUCCESS);
17135 			if (sata_check_for_dma_error(dip, spx)) {
17136 				ddi_fm_service_impact(dip,
17137 				    DDI_SERVICE_UNAFFECTED);
17138 				rval = -1;
17139 				goto fail;
17140 			}
17141 		}
17142 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
17143 		    sizeof (struct smart_selftest_log));
17144 		rval = 0;
17145 	}
17146 
17147 fail:
17148 	/* Free allocated resources */
17149 	sata_free_local_buffer(spx);
17150 	sata_pkt_free(spx);
17151 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
17152 
17153 	return (rval);
17154 }
17155 
17156 
17157 /*
17158  * Returns 0 for success, -1 otherwise
17159  *
17160  * SMART READ LOG data is returned in buffer pointed to by smart_log
17161  */
17162 static int
17163 sata_smart_read_log(
17164 	sata_hba_inst_t *sata_hba_inst,
17165 	sata_drive_info_t *sdinfo,
17166 	uint8_t *smart_log,		/* where the data should be returned */
17167 	uint8_t which_log,		/* which log should be returned */
17168 	uint8_t log_size)		/* # of 512 bytes in log */
17169 {
17170 	sata_pkt_t *spkt;
17171 	sata_cmd_t *scmd;
17172 	sata_pkt_txlate_t *spx;
17173 	int rval;
17174 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
17175 
17176 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
17177 	spx->txlt_sata_hba_inst = sata_hba_inst;
17178 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
17179 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
17180 	if (spkt == NULL) {
17181 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
17182 		return (-1);
17183 	}
17184 	/* address is needed now */
17185 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
17186 
17187 
17188 	/* Fill sata_pkt */
17189 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
17190 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
17191 	/* Synchronous mode, no callback */
17192 	spkt->satapkt_comp = NULL;
17193 	/* Timeout 30s */
17194 	spkt->satapkt_time = sata_default_pkt_time;
17195 
17196 	scmd = &spkt->satapkt_cmd;
17197 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
17198 
17199 	/*
17200 	 * Allocate buffer for SMART READ LOG
17201 	 */
17202 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
17203 	if (scmd->satacmd_bp == NULL) {
17204 		sata_pkt_free(spx);
17205 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
17206 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17207 		    "sata_smart_read_log: " "cannot allocate buffer"));
17208 		return (-1);
17209 	}
17210 
17211 	/* Build SMART_READ_LOG cmd in the sata_pkt */
17212 	scmd->satacmd_addr_type = 0;		/* N/A */
17213 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
17214 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
17215 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
17216 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
17217 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
17218 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
17219 	scmd->satacmd_cmd_reg = SATAC_SMART;
17220 
17221 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
17222 	    sdinfo->satadrv_addr.cport)));
17223 
17224 	/* Send pkt to SATA HBA driver */
17225 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
17226 	    SATA_TRAN_ACCEPTED ||
17227 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
17228 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17229 		    sdinfo->satadrv_addr.cport)));
17230 
17231 		/*
17232 		 * Whoops, no SMART DATA available
17233 		 */
17234 		rval = -1;
17235 		goto fail;
17236 	} else {
17237 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17238 		    sdinfo->satadrv_addr.cport)));
17239 
17240 		if (spx->txlt_buf_dma_handle != NULL) {
17241 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
17242 			    DDI_DMA_SYNC_FORKERNEL);
17243 			ASSERT(rval == DDI_SUCCESS);
17244 			if (sata_check_for_dma_error(dip, spx)) {
17245 				ddi_fm_service_impact(dip,
17246 				    DDI_SERVICE_UNAFFECTED);
17247 				rval = -1;
17248 				goto fail;
17249 			}
17250 		}
17251 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
17252 		rval = 0;
17253 	}
17254 
17255 fail:
17256 	/* Free allocated resources */
17257 	sata_free_local_buffer(spx);
17258 	sata_pkt_free(spx);
17259 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
17260 
17261 	return (rval);
17262 }
17263 
17264 /*
17265  * Used by LOG SENSE page 0x10
17266  *
17267  * return 0 for success, -1 otherwise
17268  *
17269  */
17270 static int
17271 sata_read_log_ext_directory(
17272 	sata_hba_inst_t *sata_hba_inst,
17273 	sata_drive_info_t *sdinfo,
17274 	struct read_log_ext_directory *logdir)
17275 {
17276 	sata_pkt_txlate_t *spx;
17277 	sata_pkt_t *spkt;
17278 	sata_cmd_t *scmd;
17279 	int rval;
17280 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
17281 
17282 #if ! defined(lint)
17283 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
17284 #endif
17285 
17286 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
17287 	spx->txlt_sata_hba_inst = sata_hba_inst;
17288 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
17289 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
17290 	if (spkt == NULL) {
17291 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
17292 		return (-1);
17293 	}
17294 
17295 	/* Fill sata_pkt */
17296 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
17297 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
17298 	/* Synchronous mode, no callback */
17299 	spkt->satapkt_comp = NULL;
17300 	/* Timeout 30s */
17301 	spkt->satapkt_time = sata_default_pkt_time;
17302 
17303 	scmd = &spkt->satapkt_cmd;
17304 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
17305 
17306 	/*
17307 	 * Allocate buffer for SMART READ LOG EXTENDED command
17308 	 */
17309 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
17310 	    sizeof (struct read_log_ext_directory));
17311 	if (scmd->satacmd_bp == NULL) {
17312 		sata_pkt_free(spx);
17313 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
17314 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17315 		    "sata_read_log_ext_directory: "
17316 		    "cannot allocate buffer"));
17317 		return (-1);
17318 	}
17319 
17320 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
17321 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
17322 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
17323 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
17324 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
17325 	scmd->satacmd_lba_low_msb = 0;
17326 	scmd->satacmd_lba_mid_lsb = 0;
17327 	scmd->satacmd_lba_mid_msb = 0;
17328 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
17329 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
17330 
17331 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
17332 	    sdinfo->satadrv_addr.cport)));
17333 
17334 	/* Send pkt to SATA HBA driver */
17335 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
17336 	    SATA_TRAN_ACCEPTED ||
17337 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
17338 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17339 		    sdinfo->satadrv_addr.cport)));
17340 		/*
17341 		 * Whoops, no SMART selftest log info available
17342 		 */
17343 		rval = -1;
17344 		goto fail;
17345 	} else {
17346 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17347 		    sdinfo->satadrv_addr.cport)));
17348 		if (spx->txlt_buf_dma_handle != NULL) {
17349 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
17350 			    DDI_DMA_SYNC_FORKERNEL);
17351 			ASSERT(rval == DDI_SUCCESS);
17352 			if (sata_check_for_dma_error(dip, spx)) {
17353 				ddi_fm_service_impact(dip,
17354 				    DDI_SERVICE_UNAFFECTED);
17355 				rval = -1;
17356 				goto fail;
17357 			}
17358 		}
17359 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
17360 		    sizeof (struct read_log_ext_directory));
17361 		rval = 0;
17362 	}
17363 
17364 fail:
17365 	/* Free allocated resources */
17366 	sata_free_local_buffer(spx);
17367 	sata_pkt_free(spx);
17368 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
17369 
17370 	return (rval);
17371 }
17372 
17373 /*
17374  * Set up error retrieval sata command for NCQ command error data
17375  * recovery.
17376  *
17377  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
17378  * returns SATA_FAILURE otherwise.
17379  */
17380 static int
17381 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
17382 {
17383 #ifndef __lock_lint
17384 	_NOTE(ARGUNUSED(sdinfo))
17385 #endif
17386 
17387 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
17388 	sata_cmd_t *scmd;
17389 	struct buf *bp;
17390 
17391 	/* Operation modes are up to the caller */
17392 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
17393 
17394 	/* Synchronous mode, no callback - may be changed by the caller */
17395 	spkt->satapkt_comp = NULL;
17396 	spkt->satapkt_time = sata_default_pkt_time;
17397 
17398 	scmd = &spkt->satapkt_cmd;
17399 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
17400 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
17401 
17402 	/*
17403 	 * Allocate dma_able buffer error data.
17404 	 * Buffer allocation will take care of buffer alignment and other DMA
17405 	 * attributes.
17406 	 */
17407 	bp = sata_alloc_local_buffer(spx,
17408 	    sizeof (struct sata_ncq_error_recovery_page));
17409 	if (bp == NULL)
17410 		return (SATA_FAILURE);
17411 
17412 	bp_mapin(bp); /* make data buffer accessible */
17413 	scmd->satacmd_bp = bp;
17414 
17415 	/*
17416 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
17417 	 * before accessing it. Handle is in usual place in translate struct.
17418 	 */
17419 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
17420 
17421 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
17422 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
17423 
17424 	return (SATA_SUCCESS);
17425 }
17426 
17427 /*
17428  * sata_xlate_errors() is used to translate (S)ATA error
17429  * information to SCSI information returned in the SCSI
17430  * packet.
17431  */
17432 static void
17433 sata_xlate_errors(sata_pkt_txlate_t *spx)
17434 {
17435 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
17436 	struct scsi_extended_sense *sense;
17437 
17438 	scsipkt->pkt_reason = CMD_INCOMPLETE;
17439 	*scsipkt->pkt_scbp = STATUS_CHECK;
17440 	sense = sata_arq_sense(spx);
17441 
17442 	switch (spx->txlt_sata_pkt->satapkt_reason) {
17443 	case SATA_PKT_PORT_ERROR:
17444 		/*
17445 		 * We have no device data. Assume no data transfered.
17446 		 */
17447 		sense->es_key = KEY_HARDWARE_ERROR;
17448 		break;
17449 
17450 	case SATA_PKT_DEV_ERROR:
17451 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
17452 		    SATA_STATUS_ERR) {
17453 			/*
17454 			 * determine dev error reason from error
17455 			 * reg content
17456 			 */
17457 			sata_decode_device_error(spx, sense);
17458 			break;
17459 		}
17460 		/* No extended sense key - no info available */
17461 		break;
17462 
17463 	case SATA_PKT_TIMEOUT:
17464 		scsipkt->pkt_reason = CMD_TIMEOUT;
17465 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
17466 		/* No extended sense key */
17467 		break;
17468 
17469 	case SATA_PKT_ABORTED:
17470 		scsipkt->pkt_reason = CMD_ABORTED;
17471 		scsipkt->pkt_statistics |= STAT_ABORTED;
17472 		/* No extended sense key */
17473 		break;
17474 
17475 	case SATA_PKT_RESET:
17476 		/*
17477 		 * pkt aborted either by an explicit reset request from
17478 		 * a host, or due to error recovery
17479 		 */
17480 		scsipkt->pkt_reason = CMD_RESET;
17481 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
17482 		break;
17483 
17484 	default:
17485 		scsipkt->pkt_reason = CMD_TRAN_ERR;
17486 		break;
17487 	}
17488 }
17489 
17490 
17491 
17492 
17493 /*
17494  * Log sata message
17495  * dev pathname msg line preceeds the logged message.
17496  */
17497 
17498 static	void
17499 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
17500 {
17501 	char pathname[128];
17502 	dev_info_t *dip = NULL;
17503 	va_list ap;
17504 
17505 	mutex_enter(&sata_log_mutex);
17506 
17507 	va_start(ap, fmt);
17508 	(void) vsprintf(sata_log_buf, fmt, ap);
17509 	va_end(ap);
17510 
17511 	if (sata_hba_inst != NULL) {
17512 		dip = SATA_DIP(sata_hba_inst);
17513 		(void) ddi_pathname(dip, pathname);
17514 	} else {
17515 		pathname[0] = 0;
17516 	}
17517 	if (level == CE_CONT) {
17518 		if (sata_debug_flags == 0)
17519 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
17520 		else
17521 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
17522 	} else {
17523 		if (level != CE_NOTE) {
17524 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
17525 		} else if (sata_msg) {
17526 			cmn_err(level, "%s:\n %s", pathname,
17527 			    sata_log_buf);
17528 		}
17529 	}
17530 
17531 	/* sata trace debug */
17532 	sata_trace_debug(dip, sata_log_buf);
17533 
17534 	mutex_exit(&sata_log_mutex);
17535 }
17536 
17537 
17538 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
17539 
17540 /*
17541  * Start or terminate the thread, depending on flag arg and current state
17542  */
17543 static void
17544 sata_event_thread_control(int startstop)
17545 {
17546 	static int sata_event_thread_terminating = 0;
17547 	static int sata_event_thread_starting = 0;
17548 	int i;
17549 
17550 	mutex_enter(&sata_event_mutex);
17551 
17552 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
17553 	    sata_event_thread_terminating == 1)) {
17554 		mutex_exit(&sata_event_mutex);
17555 		return;
17556 	}
17557 	if (startstop == 1 && sata_event_thread_starting == 1) {
17558 		mutex_exit(&sata_event_mutex);
17559 		return;
17560 	}
17561 	if (startstop == 1 && sata_event_thread_terminating == 1) {
17562 		sata_event_thread_starting = 1;
17563 		/* wait til terminate operation completes */
17564 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
17565 		while (sata_event_thread_terminating == 1) {
17566 			if (i-- <= 0) {
17567 				sata_event_thread_starting = 0;
17568 				mutex_exit(&sata_event_mutex);
17569 #ifdef SATA_DEBUG
17570 				cmn_err(CE_WARN, "sata_event_thread_control: "
17571 				    "timeout waiting for thread to terminate");
17572 #endif
17573 				return;
17574 			}
17575 			mutex_exit(&sata_event_mutex);
17576 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
17577 			mutex_enter(&sata_event_mutex);
17578 		}
17579 	}
17580 	if (startstop == 1) {
17581 		if (sata_event_thread == NULL) {
17582 			sata_event_thread = thread_create(NULL, 0,
17583 			    (void (*)())sata_event_daemon,
17584 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
17585 		}
17586 		sata_event_thread_starting = 0;
17587 		mutex_exit(&sata_event_mutex);
17588 		return;
17589 	}
17590 
17591 	/*
17592 	 * If we got here, thread may need to be terminated
17593 	 */
17594 	if (sata_event_thread != NULL) {
17595 		int i;
17596 		/* Signal event thread to go away */
17597 		sata_event_thread_terminating = 1;
17598 		sata_event_thread_terminate = 1;
17599 		cv_signal(&sata_event_cv);
17600 		/*
17601 		 * Wait til daemon terminates.
17602 		 */
17603 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
17604 		while (sata_event_thread_terminate == 1) {
17605 			mutex_exit(&sata_event_mutex);
17606 			if (i-- <= 0) {
17607 				/* Daemon did not go away !!! */
17608 #ifdef SATA_DEBUG
17609 				cmn_err(CE_WARN, "sata_event_thread_control: "
17610 				    "cannot terminate event daemon thread");
17611 #endif
17612 				mutex_enter(&sata_event_mutex);
17613 				break;
17614 			}
17615 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
17616 			mutex_enter(&sata_event_mutex);
17617 		}
17618 		sata_event_thread_terminating = 0;
17619 	}
17620 	ASSERT(sata_event_thread_terminating == 0);
17621 	ASSERT(sata_event_thread_starting == 0);
17622 	mutex_exit(&sata_event_mutex);
17623 }
17624 
17625 
17626 /*
17627  * SATA HBA event notification function.
17628  * Events reported by SATA HBA drivers per HBA instance relate to a change in
17629  * a port and/or device state or a controller itself.
17630  * Events for different addresses/addr types cannot be combined.
17631  * A warning message is generated for each event type.
17632  * Events are not processed by this function, so only the
17633  * event flag(s)is set for an affected entity and the event thread is
17634  * waken up. Event daemon thread processes all events.
17635  *
17636  * NOTE: Since more than one event may be reported at the same time, one
17637  * cannot determine a sequence of events when opposite event are reported, eg.
17638  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
17639  * is taking precedence over reported events, i.e. may cause ignoring some
17640  * events.
17641  */
17642 #define	SATA_EVENT_MAX_MSG_LENGTH	79
17643 
17644 void
17645 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
17646 {
17647 	sata_hba_inst_t *sata_hba_inst = NULL;
17648 	sata_address_t *saddr;
17649 	sata_pmult_info_t *pmultinfo;
17650 	sata_drive_info_t *sdinfo;
17651 	sata_port_stats_t *pstats;
17652 	sata_cport_info_t *cportinfo;
17653 	sata_pmport_info_t *pmportinfo;
17654 	int cport, pmport;
17655 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
17656 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
17657 	char *lcp;
17658 	static char *err_msg_evnt_1 =
17659 	    "sata_hba_event_notify: invalid port event 0x%x ";
17660 	static char *err_msg_evnt_2 =
17661 	    "sata_hba_event_notify: invalid device event 0x%x ";
17662 	int linkevent;
17663 
17664 	/*
17665 	 * There is a possibility that an event will be generated on HBA
17666 	 * that has not completed attachment or is detaching. We still want
17667 	 * to process events until HBA is detached.
17668 	 */
17669 	mutex_enter(&sata_mutex);
17670 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17671 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17672 		if (SATA_DIP(sata_hba_inst) == dip)
17673 			if (sata_hba_inst->satahba_attached == 1)
17674 				break;
17675 	}
17676 	mutex_exit(&sata_mutex);
17677 	if (sata_hba_inst == NULL)
17678 		/* HBA not attached */
17679 		return;
17680 
17681 	ASSERT(sata_device != NULL);
17682 
17683 	/*
17684 	 * Validate address before - do not proceed with invalid address.
17685 	 */
17686 	saddr = &sata_device->satadev_addr;
17687 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
17688 		return;
17689 
17690 	cport = saddr->cport;
17691 	pmport = saddr->pmport;
17692 
17693 	buf1[0] = buf2[0] = '\0';
17694 
17695 	/*
17696 	 * If event relates to port or device, check port state.
17697 	 * Port has to be initialized, or we cannot accept an event.
17698 	 */
17699 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
17700 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT | SATA_ADDR_PMULT)) != 0) {
17701 		mutex_enter(&sata_hba_inst->satahba_mutex);
17702 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17703 		mutex_exit(&sata_hba_inst->satahba_mutex);
17704 		if (cportinfo == NULL || cportinfo->cport_state == 0)
17705 			return;
17706 	}
17707 
17708 	if ((saddr->qual & (SATA_ADDR_PMULT | SATA_ADDR_PMPORT |
17709 	    SATA_ADDR_DPMPORT)) != 0) {
17710 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
17711 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17712 			    "sata_hba_event_notify: Non-pmult device (0x%x)"
17713 			    "is attached to port %d, ignore pmult/pmport "
17714 			    "event 0x%x", cportinfo->cport_dev_type,
17715 			    cport, event));
17716 			return;
17717 		}
17718 
17719 		mutex_enter(&cportinfo->cport_mutex);
17720 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17721 		mutex_exit(&cportinfo->cport_mutex);
17722 
17723 		/*
17724 		 * The daemon might be processing attachment of port
17725 		 * multiplier, in that case we should ignore events on its
17726 		 * sub-devices.
17727 		 *
17728 		 * NOTE: Only pmult_state is checked in sata_hba_event_notify.
17729 		 * The pmport_state is checked by sata daemon.
17730 		 */
17731 		if (pmultinfo == NULL ||
17732 		    pmultinfo->pmult_state == SATA_STATE_UNKNOWN) {
17733 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17734 			    "sata_hba_event_notify: pmult is not"
17735 			    "available at port %d:%d, ignore event 0x%x",
17736 			    cport, pmport, event));
17737 			return;
17738 		}
17739 	}
17740 
17741 	if ((saddr->qual &
17742 	    (SATA_ADDR_PMPORT | SATA_ADDR_DPMPORT)) != 0) {
17743 
17744 		mutex_enter(&cportinfo->cport_mutex);
17745 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport)) {
17746 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17747 			    "sata_hba_event_notify: invalid/"
17748 			    "un-implemented port %d:%d (%d ports), "
17749 			    "ignore event 0x%x", cport, pmport,
17750 			    SATA_NUM_PMPORTS(sata_hba_inst, cport), event));
17751 			mutex_exit(&cportinfo->cport_mutex);
17752 			return;
17753 		}
17754 		mutex_exit(&cportinfo->cport_mutex);
17755 
17756 		mutex_enter(&sata_hba_inst->satahba_mutex);
17757 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17758 		    cport, pmport);
17759 		mutex_exit(&sata_hba_inst->satahba_mutex);
17760 
17761 		/* pmport is implemented/valid? */
17762 		if (pmportinfo == NULL) {
17763 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17764 			    "sata_hba_event_notify: invalid/"
17765 			    "un-implemented port %d:%d, ignore "
17766 			    "event 0x%x", cport, pmport, event));
17767 			return;
17768 		}
17769 	}
17770 
17771 	/*
17772 	 * Events refer to devices, ports and controllers - each has
17773 	 * unique address. Events for different addresses cannot be combined.
17774 	 */
17775 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
17776 
17777 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17778 
17779 		/* qualify this event(s) */
17780 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
17781 			/* Invalid event for the device port */
17782 			(void) sprintf(buf2, err_msg_evnt_1,
17783 			    event & SATA_EVNT_PORT_EVENTS);
17784 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17785 			goto event_info;
17786 		}
17787 		if (saddr->qual == SATA_ADDR_CPORT) {
17788 			/* Controller's device port event */
17789 
17790 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
17791 			    cport_event_flags |=
17792 			    event & SATA_EVNT_PORT_EVENTS;
17793 			pstats =
17794 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
17795 			    cport_stats;
17796 		} else {
17797 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17798 			mutex_enter(&pmportinfo->pmport_mutex);
17799 			/* Port multiplier's device port event */
17800 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17801 			    pmport_event_flags |=
17802 			    event & SATA_EVNT_PORT_EVENTS;
17803 			pstats =
17804 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17805 			    pmport_stats;
17806 			mutex_exit(&pmportinfo->pmport_mutex);
17807 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17808 		}
17809 
17810 		/*
17811 		 * Add to statistics and log the message. We have to do it
17812 		 * here rather than in the event daemon, because there may be
17813 		 * multiple events occuring before they are processed.
17814 		 */
17815 		linkevent = event &
17816 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
17817 		if (linkevent) {
17818 			if (linkevent == (SATA_EVNT_LINK_LOST |
17819 			    SATA_EVNT_LINK_ESTABLISHED)) {
17820 				/* This is likely event combination */
17821 				(void) strlcat(buf1, "link lost/established, ",
17822 				    SATA_EVENT_MAX_MSG_LENGTH);
17823 
17824 				if (pstats->link_lost < 0xffffffffffffffffULL)
17825 					pstats->link_lost++;
17826 				if (pstats->link_established <
17827 				    0xffffffffffffffffULL)
17828 					pstats->link_established++;
17829 				linkevent = 0;
17830 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
17831 				(void) strlcat(buf1, "link lost, ",
17832 				    SATA_EVENT_MAX_MSG_LENGTH);
17833 
17834 				if (pstats->link_lost < 0xffffffffffffffffULL)
17835 					pstats->link_lost++;
17836 			} else {
17837 				(void) strlcat(buf1, "link established, ",
17838 				    SATA_EVENT_MAX_MSG_LENGTH);
17839 				if (pstats->link_established <
17840 				    0xffffffffffffffffULL)
17841 					pstats->link_established++;
17842 			}
17843 		}
17844 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
17845 			(void) strlcat(buf1, "device attached, ",
17846 			    SATA_EVENT_MAX_MSG_LENGTH);
17847 			if (pstats->device_attached < 0xffffffffffffffffULL)
17848 				pstats->device_attached++;
17849 		}
17850 		if (event & SATA_EVNT_DEVICE_DETACHED) {
17851 			(void) strlcat(buf1, "device detached, ",
17852 			    SATA_EVENT_MAX_MSG_LENGTH);
17853 			if (pstats->device_detached < 0xffffffffffffffffULL)
17854 				pstats->device_detached++;
17855 		}
17856 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
17857 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17858 			    "port %d power level changed", cport);
17859 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
17860 				pstats->port_pwr_changed++;
17861 		}
17862 
17863 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
17864 			/* There should be no other events for this address */
17865 			(void) sprintf(buf2, err_msg_evnt_1,
17866 			    event & ~SATA_EVNT_PORT_EVENTS);
17867 		}
17868 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17869 
17870 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
17871 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17872 
17873 		/* qualify this event */
17874 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
17875 			/* Invalid event for a device */
17876 			(void) sprintf(buf2, err_msg_evnt_2,
17877 			    event & SATA_EVNT_DEVICE_RESET);
17878 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17879 			goto event_info;
17880 		}
17881 		/* drive event */
17882 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
17883 		if (sdinfo != NULL) {
17884 			if (event & SATA_EVNT_DEVICE_RESET) {
17885 				(void) strlcat(buf1, "device reset, ",
17886 				    SATA_EVENT_MAX_MSG_LENGTH);
17887 				if (sdinfo->satadrv_stats.drive_reset <
17888 				    0xffffffffffffffffULL)
17889 					sdinfo->satadrv_stats.drive_reset++;
17890 				sdinfo->satadrv_event_flags |=
17891 				    SATA_EVNT_DEVICE_RESET;
17892 			}
17893 		}
17894 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
17895 			/* Invalid event for a device */
17896 			(void) sprintf(buf2, err_msg_evnt_2,
17897 			    event & ~SATA_EVNT_DRIVE_EVENTS);
17898 		}
17899 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17900 	} else if (saddr->qual == SATA_ADDR_PMULT) {
17901 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17902 
17903 		/* qualify this event */
17904 		if ((event & (SATA_EVNT_DEVICE_RESET |
17905 		    SATA_EVNT_PMULT_LINK_CHANGED)) == 0) {
17906 			/* Invalid event for a port multiplier */
17907 			(void) sprintf(buf2, err_msg_evnt_2,
17908 			    event & SATA_EVNT_DEVICE_RESET);
17909 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17910 			goto event_info;
17911 		}
17912 
17913 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17914 
17915 		if (event & SATA_EVNT_DEVICE_RESET) {
17916 
17917 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17918 			    "[Reset] port-mult on cport %d", cport);
17919 			pmultinfo->pmult_event_flags |=
17920 			    SATA_EVNT_DEVICE_RESET;
17921 			(void) strlcat(buf1, "pmult reset, ",
17922 			    SATA_EVENT_MAX_MSG_LENGTH);
17923 		}
17924 
17925 		if (event & SATA_EVNT_PMULT_LINK_CHANGED) {
17926 
17927 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17928 			    "pmult link changed on cport %d", cport);
17929 			pmultinfo->pmult_event_flags |=
17930 			    SATA_EVNT_PMULT_LINK_CHANGED;
17931 			(void) strlcat(buf1, "pmult link changed, ",
17932 			    SATA_EVENT_MAX_MSG_LENGTH);
17933 		}
17934 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17935 
17936 	} else {
17937 		if (saddr->qual != SATA_ADDR_NULL) {
17938 			/* Wrong address qualifier */
17939 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17940 			    "sata_hba_event_notify: invalid address 0x%x",
17941 			    *(uint32_t *)saddr));
17942 			return;
17943 		}
17944 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
17945 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
17946 			/* Invalid event for the controller */
17947 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17948 			    "sata_hba_event_notify: invalid event 0x%x for "
17949 			    "controller",
17950 			    event & SATA_EVNT_CONTROLLER_EVENTS));
17951 			return;
17952 		}
17953 		buf1[0] = '\0';
17954 		/* This may be a frequent and not interesting event */
17955 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17956 		    "controller power level changed\n", NULL);
17957 
17958 		mutex_enter(&sata_hba_inst->satahba_mutex);
17959 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
17960 		    0xffffffffffffffffULL)
17961 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
17962 
17963 		sata_hba_inst->satahba_event_flags |=
17964 		    SATA_EVNT_PWR_LEVEL_CHANGED;
17965 		mutex_exit(&sata_hba_inst->satahba_mutex);
17966 	}
17967 	/*
17968 	 * If we got here, there is something to do with this HBA
17969 	 * instance.
17970 	 */
17971 	mutex_enter(&sata_hba_inst->satahba_mutex);
17972 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17973 	mutex_exit(&sata_hba_inst->satahba_mutex);
17974 	mutex_enter(&sata_mutex);
17975 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
17976 	mutex_exit(&sata_mutex);
17977 
17978 	/* Tickle event thread */
17979 	mutex_enter(&sata_event_mutex);
17980 	if (sata_event_thread_active == 0)
17981 		cv_signal(&sata_event_cv);
17982 	mutex_exit(&sata_event_mutex);
17983 
17984 event_info:
17985 	if (buf1[0] != '\0') {
17986 		lcp = strrchr(buf1, ',');
17987 		if (lcp != NULL)
17988 			*lcp = '\0';
17989 	}
17990 	if (saddr->qual == SATA_ADDR_CPORT ||
17991 	    saddr->qual == SATA_ADDR_DCPORT) {
17992 		if (buf1[0] != '\0') {
17993 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17994 			    cport, buf1);
17995 		}
17996 		if (buf2[0] != '\0') {
17997 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17998 			    cport, buf2);
17999 		}
18000 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
18001 	    saddr->qual == SATA_ADDR_DPMPORT) {
18002 		if (buf1[0] != '\0') {
18003 			sata_log(sata_hba_inst, CE_NOTE,
18004 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
18005 		}
18006 		if (buf2[0] != '\0') {
18007 			sata_log(sata_hba_inst, CE_NOTE,
18008 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
18009 		}
18010 	}
18011 }
18012 
18013 
18014 /*
18015  * Event processing thread.
18016  * Arg is a pointer to the sata_hba_list pointer.
18017  * It is not really needed, because sata_hba_list is global and static
18018  */
18019 static void
18020 sata_event_daemon(void *arg)
18021 {
18022 #ifndef __lock_lint
18023 	_NOTE(ARGUNUSED(arg))
18024 #endif
18025 	sata_hba_inst_t *sata_hba_inst;
18026 	clock_t delta;
18027 
18028 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
18029 	    "SATA event daemon started\n", NULL);
18030 loop:
18031 	/*
18032 	 * Process events here. Walk through all registered HBAs
18033 	 */
18034 	mutex_enter(&sata_mutex);
18035 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
18036 	    sata_hba_inst = sata_hba_inst->satahba_next) {
18037 		ASSERT(sata_hba_inst != NULL);
18038 		mutex_enter(&sata_hba_inst->satahba_mutex);
18039 		if (sata_hba_inst->satahba_attached == 0 ||
18040 		    (sata_hba_inst->satahba_event_flags &
18041 		    SATA_EVNT_SKIP) != 0) {
18042 			mutex_exit(&sata_hba_inst->satahba_mutex);
18043 			continue;
18044 		}
18045 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
18046 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
18047 			mutex_exit(&sata_hba_inst->satahba_mutex);
18048 			mutex_exit(&sata_mutex);
18049 			/* Got the controller with pending event */
18050 			sata_process_controller_events(sata_hba_inst);
18051 			/*
18052 			 * Since global mutex was released, there is a
18053 			 * possibility that HBA list has changed, so start
18054 			 * over from the top. Just processed controller
18055 			 * will be passed-over because of the SKIP flag.
18056 			 */
18057 			goto loop;
18058 		}
18059 		mutex_exit(&sata_hba_inst->satahba_mutex);
18060 	}
18061 	/* Clear SKIP flag in all controllers */
18062 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
18063 	    sata_hba_inst = sata_hba_inst->satahba_next) {
18064 		mutex_enter(&sata_hba_inst->satahba_mutex);
18065 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
18066 		mutex_exit(&sata_hba_inst->satahba_mutex);
18067 	}
18068 	mutex_exit(&sata_mutex);
18069 
18070 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
18071 	    "SATA EVENT DAEMON suspending itself", NULL);
18072 
18073 #ifdef SATA_DEBUG
18074 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
18075 		sata_log(sata_hba_inst, CE_WARN,
18076 		    "SATA EVENTS PROCESSING DISABLED\n");
18077 		thread_exit(); /* Daemon will not run again */
18078 	}
18079 #endif
18080 	mutex_enter(&sata_event_mutex);
18081 	sata_event_thread_active = 0;
18082 	mutex_exit(&sata_event_mutex);
18083 	/*
18084 	 * Go to sleep/suspend itself and wake up either because new event or
18085 	 * wait timeout. Exit if there is a termination request (driver
18086 	 * unload).
18087 	 */
18088 	delta = drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
18089 	do {
18090 		mutex_enter(&sata_event_mutex);
18091 		(void) cv_reltimedwait(&sata_event_cv, &sata_event_mutex,
18092 		    delta, TR_CLOCK_TICK);
18093 
18094 		if (sata_event_thread_active != 0) {
18095 			mutex_exit(&sata_event_mutex);
18096 			continue;
18097 		}
18098 
18099 		/* Check if it is time to go away */
18100 		if (sata_event_thread_terminate == 1) {
18101 			/*
18102 			 * It is up to the thread setting above flag to make
18103 			 * sure that this thread is not killed prematurely.
18104 			 */
18105 			sata_event_thread_terminate = 0;
18106 			sata_event_thread = NULL;
18107 			mutex_exit(&sata_event_mutex);
18108 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
18109 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
18110 			thread_exit();  { _NOTE(NOT_REACHED) }
18111 		}
18112 		mutex_exit(&sata_event_mutex);
18113 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
18114 
18115 	mutex_enter(&sata_event_mutex);
18116 	sata_event_thread_active = 1;
18117 	mutex_exit(&sata_event_mutex);
18118 
18119 	mutex_enter(&sata_mutex);
18120 	sata_event_pending &= ~SATA_EVNT_MAIN;
18121 	mutex_exit(&sata_mutex);
18122 
18123 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
18124 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
18125 
18126 	goto loop;
18127 }
18128 
18129 /*
18130  * Specific HBA instance event processing.
18131  *
18132  * NOTE: At the moment, device event processing is limited to hard disks
18133  * only.
18134  * Port multiplier is supported now.
18135  */
18136 static void
18137 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
18138 {
18139 	int ncport;
18140 	uint32_t event_flags;
18141 	sata_address_t *saddr;
18142 	sata_cport_info_t *cportinfo;
18143 	sata_pmult_info_t *pmultinfo;
18144 
18145 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
18146 	    "Processing controller %d event(s)",
18147 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
18148 
18149 	mutex_enter(&sata_hba_inst->satahba_mutex);
18150 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
18151 	event_flags = sata_hba_inst->satahba_event_flags;
18152 	mutex_exit(&sata_hba_inst->satahba_mutex);
18153 	/*
18154 	 * Process controller power change first
18155 	 * HERE
18156 	 */
18157 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
18158 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
18159 
18160 	/*
18161 	 * Search through ports/devices to identify affected port/device.
18162 	 * We may have to process events for more than one port/device.
18163 	 */
18164 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
18165 		/*
18166 		 * Not all ports may be processed in attach by the time we
18167 		 * get an event. Check if port info is initialized.
18168 		 */
18169 		mutex_enter(&sata_hba_inst->satahba_mutex);
18170 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
18171 		mutex_exit(&sata_hba_inst->satahba_mutex);
18172 		if (cportinfo == NULL || cportinfo->cport_state == 0)
18173 			continue;
18174 
18175 		/* We have initialized controller port info */
18176 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
18177 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
18178 		    cport_event_flags;
18179 		/* Check if port was locked by IOCTL processing */
18180 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
18181 			/*
18182 			 * We ignore port events because port is busy
18183 			 * with AP control processing. Set again
18184 			 * controller and main event flag, so that
18185 			 * events may be processed by the next daemon
18186 			 * run.
18187 			 */
18188 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
18189 			mutex_enter(&sata_hba_inst->satahba_mutex);
18190 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18191 			mutex_exit(&sata_hba_inst->satahba_mutex);
18192 			mutex_enter(&sata_mutex);
18193 			sata_event_pending |= SATA_EVNT_MAIN;
18194 			mutex_exit(&sata_mutex);
18195 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
18196 			    "Event processing postponed until "
18197 			    "AP control processing completes",
18198 			    NULL);
18199 			/* Check other ports */
18200 			continue;
18201 		} else {
18202 			/*
18203 			 * Set BSY flag so that AP control would not
18204 			 * interfere with events processing for
18205 			 * this port.
18206 			 */
18207 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
18208 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
18209 		}
18210 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
18211 
18212 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
18213 
18214 		if ((event_flags &
18215 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
18216 			/*
18217 			 * Got port event.
18218 			 * We need some hierarchy of event processing as they
18219 			 * are affecting each other:
18220 			 * 1. port failed
18221 			 * 2. device detached/attached
18222 			 * 3. link events - link events may trigger device
18223 			 *    detached or device attached events in some
18224 			 *    circumstances.
18225 			 * 4. port power level changed
18226 			 */
18227 			if (event_flags & SATA_EVNT_PORT_FAILED) {
18228 				sata_process_port_failed_event(sata_hba_inst,
18229 				    saddr);
18230 			}
18231 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
18232 				sata_process_device_detached(sata_hba_inst,
18233 				    saddr);
18234 			}
18235 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
18236 				sata_process_device_attached(sata_hba_inst,
18237 				    saddr);
18238 			}
18239 			if (event_flags &
18240 			    (SATA_EVNT_LINK_ESTABLISHED |
18241 			    SATA_EVNT_LINK_LOST)) {
18242 				sata_process_port_link_events(sata_hba_inst,
18243 				    saddr);
18244 			}
18245 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
18246 				sata_process_port_pwr_change(sata_hba_inst,
18247 				    saddr);
18248 			}
18249 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
18250 				sata_process_target_node_cleanup(
18251 				    sata_hba_inst, saddr);
18252 			}
18253 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
18254 				sata_process_device_autoonline(
18255 				    sata_hba_inst, saddr);
18256 			}
18257 		}
18258 
18259 
18260 		/*
18261 		 * Scan port multiplier and all its sub-ports event flags.
18262 		 * The events are marked by
18263 		 * (1) sata_pmult_info.pmult_event_flags
18264 		 * (2) sata_pmport_info.pmport_event_flags
18265 		 */
18266 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
18267 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
18268 			/*
18269 			 * There should be another extra check: this
18270 			 * port multiplier still exists?
18271 			 */
18272 			pmultinfo = SATA_PMULT_INFO(sata_hba_inst,
18273 			    ncport);
18274 
18275 			if (pmultinfo != NULL) {
18276 				mutex_exit(&(SATA_CPORT_MUTEX(
18277 				    sata_hba_inst, ncport)));
18278 				sata_process_pmult_events(
18279 				    sata_hba_inst, ncport);
18280 				mutex_enter(&(SATA_CPORT_MUTEX(
18281 				    sata_hba_inst, ncport)));
18282 			} else {
18283 				SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
18284 				    "Port-multiplier is gone. "
18285 				    "Ignore all sub-device events "
18286 				    "at port %d.", ncport);
18287 			}
18288 		}
18289 
18290 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
18291 		    SATA_DTYPE_NONE) &&
18292 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
18293 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
18294 			    satadrv_event_flags &
18295 			    (SATA_EVNT_DEVICE_RESET |
18296 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
18297 				/* Have device event */
18298 				sata_process_device_reset(sata_hba_inst,
18299 				    saddr);
18300 			}
18301 		}
18302 		/* Release PORT_BUSY flag */
18303 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
18304 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
18305 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
18306 
18307 	} /* End of loop through the controller SATA ports */
18308 }
18309 
18310 /*
18311  * Specific port multiplier instance event processing. At the moment, device
18312  * event processing is limited to link/attach event only.
18313  *
18314  * NOTE: power management event is not supported yet.
18315  */
18316 static void
18317 sata_process_pmult_events(sata_hba_inst_t *sata_hba_inst, uint8_t cport)
18318 {
18319 	sata_cport_info_t *cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
18320 	sata_pmult_info_t *pmultinfo;
18321 	sata_pmport_info_t *pmportinfo;
18322 	sata_address_t *saddr;
18323 	sata_device_t sata_device;
18324 	uint32_t event_flags;
18325 	int npmport;
18326 	int rval;
18327 
18328 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
18329 	    "Processing pmult event(s) on cport %d of controller %d",
18330 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
18331 
18332 	/* First process events on port multiplier */
18333 	mutex_enter(&cportinfo->cport_mutex);
18334 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
18335 	event_flags = pmultinfo->pmult_event_flags;
18336 
18337 	/*
18338 	 * Reset event (of port multiplier) has higher priority because the
18339 	 * port multiplier itself might be failed or removed after reset.
18340 	 */
18341 	if (event_flags & SATA_EVNT_DEVICE_RESET) {
18342 		/*
18343 		 * The status of the sub-links are uncertain,
18344 		 * so mark all sub-ports as RESET
18345 		 */
18346 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(
18347 		    sata_hba_inst, cport); npmport ++) {
18348 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
18349 			    cport, npmport);
18350 			if (pmportinfo == NULL) {
18351 				/* That's weird. */
18352 				SATA_LOG_D((sata_hba_inst, CE_WARN,
18353 				    "sata_hba_event_notify: "
18354 				    "invalid/un-implemented "
18355 				    "port %d:%d (%d ports), ",
18356 				    cport, npmport, SATA_NUM_PMPORTS(
18357 				    sata_hba_inst, cport)));
18358 				continue;
18359 			}
18360 
18361 			mutex_enter(&pmportinfo->pmport_mutex);
18362 
18363 			/* Mark all pmport to unknow state. */
18364 			pmportinfo->pmport_state = SATA_STATE_UNKNOWN;
18365 			/* Mark all pmports with link events. */
18366 			pmportinfo->pmport_event_flags =
18367 			    (SATA_EVNT_LINK_ESTABLISHED|SATA_EVNT_LINK_LOST);
18368 			mutex_exit(&pmportinfo->pmport_mutex);
18369 		}
18370 
18371 	} else if (event_flags & SATA_EVNT_PMULT_LINK_CHANGED) {
18372 		/*
18373 		 * We need probe the port multiplier to know what has
18374 		 * happened.
18375 		 */
18376 		bzero(&sata_device, sizeof (sata_device_t));
18377 		sata_device.satadev_rev = SATA_DEVICE_REV;
18378 		sata_device.satadev_addr.cport = cport;
18379 		sata_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
18380 		sata_device.satadev_addr.qual = SATA_ADDR_PMULT;
18381 
18382 		mutex_exit(&cportinfo->cport_mutex);
18383 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18384 		    (SATA_DIP(sata_hba_inst), &sata_device);
18385 		mutex_enter(&cportinfo->cport_mutex);
18386 		if (rval != SATA_SUCCESS) {
18387 			/* Something went wrong? Fail the port */
18388 			cportinfo->cport_state = SATA_PSTATE_FAILED;
18389 			mutex_exit(&cportinfo->cport_mutex);
18390 			SATA_LOG_D((sata_hba_inst, CE_WARN,
18391 			    "SATA port %d probing failed", cport));
18392 
18393 			/* PMult structure must be released.  */
18394 			sata_free_pmult(sata_hba_inst, &sata_device);
18395 			return;
18396 		}
18397 
18398 		sata_update_port_info(sata_hba_inst, &sata_device);
18399 
18400 		/*
18401 		 * Sanity check - Port is active? Is the link active?
18402 		 * The device is still a port multiplier?
18403 		 */
18404 		if ((cportinfo->cport_state &
18405 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
18406 		    ((cportinfo->cport_scr.sstatus &
18407 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) ||
18408 		    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
18409 			mutex_exit(&cportinfo->cport_mutex);
18410 
18411 			/* PMult structure must be released.  */
18412 			sata_free_pmult(sata_hba_inst, &sata_device);
18413 			return;
18414 		}
18415 
18416 		/* Probed succeed, set port ready. */
18417 		cportinfo->cport_state |=
18418 		    SATA_STATE_PROBED | SATA_STATE_READY;
18419 	}
18420 
18421 	/* Release port multiplier event flags. */
18422 	pmultinfo->pmult_event_flags &=
18423 	    ~(SATA_EVNT_DEVICE_RESET|SATA_EVNT_PMULT_LINK_CHANGED);
18424 	mutex_exit(&cportinfo->cport_mutex);
18425 
18426 	/*
18427 	 * Check all sub-links.
18428 	 */
18429 	for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst, cport);
18430 	    npmport ++) {
18431 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
18432 		mutex_enter(&pmportinfo->pmport_mutex);
18433 		event_flags = pmportinfo->pmport_event_flags;
18434 		mutex_exit(&pmportinfo->pmport_mutex);
18435 		saddr = &pmportinfo->pmport_addr;
18436 
18437 		if ((event_flags &
18438 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
18439 			/*
18440 			 * Got port multiplier port event.
18441 			 * We need some hierarchy of event processing as they
18442 			 * are affecting each other:
18443 			 * 1. device detached/attached
18444 			 * 2. link events - link events may trigger device
18445 			 *    detached or device attached events in some
18446 			 *    circumstances.
18447 			 */
18448 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
18449 				sata_process_pmdevice_detached(sata_hba_inst,
18450 				    saddr);
18451 			}
18452 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
18453 				sata_process_pmdevice_attached(sata_hba_inst,
18454 				    saddr);
18455 			}
18456 			if (event_flags & SATA_EVNT_LINK_ESTABLISHED ||
18457 			    event_flags & SATA_EVNT_LINK_LOST) {
18458 				sata_process_pmport_link_events(sata_hba_inst,
18459 				    saddr);
18460 			}
18461 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
18462 				sata_process_target_node_cleanup(
18463 				    sata_hba_inst, saddr);
18464 			}
18465 		}
18466 
18467 		/* Checking drive event(s). */
18468 		mutex_enter(&pmportinfo->pmport_mutex);
18469 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
18470 		    pmportinfo->pmport_sata_drive != NULL) {
18471 			event_flags = pmportinfo->pmport_sata_drive->
18472 			    satadrv_event_flags;
18473 			if (event_flags & (SATA_EVNT_DEVICE_RESET |
18474 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
18475 
18476 				/* Have device event */
18477 				sata_process_pmdevice_reset(sata_hba_inst,
18478 				    saddr);
18479 			}
18480 		}
18481 		mutex_exit(&pmportinfo->pmport_mutex);
18482 
18483 		/* Release PORT_BUSY flag */
18484 		mutex_enter(&cportinfo->cport_mutex);
18485 		cportinfo->cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
18486 		mutex_exit(&cportinfo->cport_mutex);
18487 	}
18488 
18489 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
18490 	    "[DONE] pmult event(s) on cport %d of controller %d",
18491 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
18492 }
18493 
18494 /*
18495  * Process HBA power level change reported by HBA driver.
18496  * Not implemented at this time - event is ignored.
18497  */
18498 static void
18499 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
18500 {
18501 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18502 	    "Processing controller power level change", NULL);
18503 
18504 	/* Ignoring it for now */
18505 	mutex_enter(&sata_hba_inst->satahba_mutex);
18506 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
18507 	mutex_exit(&sata_hba_inst->satahba_mutex);
18508 }
18509 
18510 /*
18511  * Process port power level change reported by HBA driver.
18512  * Not implemented at this time - event is ignored.
18513  */
18514 static void
18515 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
18516     sata_address_t *saddr)
18517 {
18518 	sata_cport_info_t *cportinfo;
18519 
18520 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18521 	    "Processing port power level change", NULL);
18522 
18523 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18524 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18525 	/* Reset event flag */
18526 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
18527 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18528 }
18529 
18530 /*
18531  * Process port failure reported by HBA driver.
18532  * cports support only - no pmports.
18533  */
18534 static void
18535 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
18536     sata_address_t *saddr)
18537 {
18538 	sata_cport_info_t *cportinfo;
18539 
18540 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18541 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18542 	/* Reset event flag first */
18543 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
18544 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
18545 	if ((cportinfo->cport_state &
18546 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
18547 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18548 		    cport_mutex);
18549 		return;
18550 	}
18551 	/* Fail the port */
18552 	cportinfo->cport_state = SATA_PSTATE_FAILED;
18553 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18554 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
18555 }
18556 
18557 /*
18558  * Device Reset Event processing.
18559  * The sequence is managed by 3 stage flags:
18560  * - reset event reported,
18561  * - reset event being processed,
18562  * - request to clear device reset state.
18563  *
18564  * NOTE: This function has to be entered with cport mutex held. It exits with
18565  * mutex held as well, but can release mutex during the processing.
18566  */
18567 static void
18568 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
18569     sata_address_t *saddr)
18570 {
18571 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
18572 	sata_drive_info_t *sdinfo;
18573 	sata_cport_info_t *cportinfo;
18574 	sata_device_t sata_device;
18575 	int rval_probe, rval_set;
18576 
18577 	/* We only care about host sata cport for now */
18578 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18579 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18580 	/*
18581 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
18582 	 * state, ignore reset event.
18583 	 */
18584 	if (((cportinfo->cport_state &
18585 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
18586 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
18587 		sdinfo->satadrv_event_flags &=
18588 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
18589 		return;
18590 	}
18591 
18592 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) ==
18593 	    SATA_DTYPE_PMULT)) {
18594 		/*
18595 		 * Should not happened: this is already handled in
18596 		 * sata_hba_event_notify()
18597 		 */
18598 		mutex_exit(&cportinfo->cport_mutex);
18599 		goto done;
18600 	}
18601 
18602 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
18603 	    SATA_VALID_DEV_TYPE) == 0) {
18604 		/*
18605 		 * This should not happen - coding error.
18606 		 * But we can recover, so do not panic, just clean up
18607 		 * and if in debug mode, log the message.
18608 		 */
18609 #ifdef SATA_DEBUG
18610 		sata_log(sata_hba_inst, CE_WARN,
18611 		    "sata_process_device_reset: "
18612 		    "Invalid device type with sdinfo!", NULL);
18613 #endif
18614 		sdinfo->satadrv_event_flags = 0;
18615 		return;
18616 	}
18617 
18618 #ifdef SATA_DEBUG
18619 	if ((sdinfo->satadrv_event_flags &
18620 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
18621 		/* Nothing to do */
18622 		/* Something is weird - why we are processing dev reset? */
18623 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18624 		    "No device reset event!!!!", NULL);
18625 
18626 		return;
18627 	}
18628 	if ((sdinfo->satadrv_event_flags &
18629 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
18630 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
18631 		/* Something is weird - new device reset event */
18632 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18633 		    "Overlapping device reset events!", NULL);
18634 	}
18635 #endif
18636 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18637 	    "Processing port %d device reset", saddr->cport);
18638 
18639 	/* Clear event flag */
18640 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
18641 
18642 	/* It seems that we always need to check the port state first */
18643 	sata_device.satadev_rev = SATA_DEVICE_REV;
18644 	sata_device.satadev_addr = *saddr;
18645 	/*
18646 	 * We have to exit mutex, because the HBA probe port function may
18647 	 * block on its own mutex.
18648 	 */
18649 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18650 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18651 	    (SATA_DIP(sata_hba_inst), &sata_device);
18652 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18653 	sata_update_port_info(sata_hba_inst, &sata_device);
18654 	if (rval_probe != SATA_SUCCESS) {
18655 		/* Something went wrong? Fail the port */
18656 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18657 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18658 		if (sdinfo != NULL)
18659 			sdinfo->satadrv_event_flags = 0;
18660 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18661 		    cport_mutex);
18662 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18663 		    "SATA port %d probing failed",
18664 		    saddr->cport));
18665 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
18666 		    saddr->cport)->cport_mutex);
18667 		return;
18668 	}
18669 	if ((sata_device.satadev_scr.sstatus  &
18670 	    SATA_PORT_DEVLINK_UP_MASK) !=
18671 	    SATA_PORT_DEVLINK_UP ||
18672 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18673 		/*
18674 		 * No device to process, anymore. Some other event processing
18675 		 * would or have already performed port info cleanup.
18676 		 * To be safe (HBA may need it), request clearing device
18677 		 * reset condition.
18678 		 */
18679 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18680 		if (sdinfo != NULL) {
18681 			sdinfo->satadrv_event_flags &=
18682 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18683 			sdinfo->satadrv_event_flags |=
18684 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18685 		}
18686 		return;
18687 	}
18688 
18689 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18690 	if (sdinfo == NULL) {
18691 		return;
18692 	}
18693 	if ((sdinfo->satadrv_event_flags &
18694 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18695 		/*
18696 		 * Start tracking time for device feature restoration and
18697 		 * identification. Save current time (lbolt value).
18698 		 */
18699 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18700 	}
18701 	/* Mark device reset processing as active */
18702 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18703 
18704 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18705 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18706 
18707 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
18708 
18709 	if (rval_set  != SATA_SUCCESS) {
18710 		/*
18711 		 * Restoring drive setting failed.
18712 		 * Probe the port first, to check if the port state has changed
18713 		 */
18714 		sata_device.satadev_rev = SATA_DEVICE_REV;
18715 		sata_device.satadev_addr = *saddr;
18716 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
18717 		/* probe port */
18718 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18719 		    (SATA_DIP(sata_hba_inst), &sata_device);
18720 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18721 		    cport_mutex);
18722 		if (rval_probe == SATA_SUCCESS &&
18723 		    (sata_device.satadev_state &
18724 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18725 		    (sata_device.satadev_scr.sstatus  &
18726 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18727 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18728 			/*
18729 			 * We may retry this a bit later - in-process reset
18730 			 * condition should be already set.
18731 			 * Track retry time for device identification.
18732 			 */
18733 			if ((cportinfo->cport_dev_type &
18734 			    SATA_VALID_DEV_TYPE) != 0 &&
18735 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
18736 			    sdinfo->satadrv_reset_time != 0) {
18737 				clock_t cur_time = ddi_get_lbolt();
18738 				/*
18739 				 * If the retry time limit was not
18740 				 * exceeded, retry.
18741 				 */
18742 				if ((cur_time - sdinfo->satadrv_reset_time) <
18743 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18744 					mutex_enter(
18745 					    &sata_hba_inst->satahba_mutex);
18746 					sata_hba_inst->satahba_event_flags |=
18747 					    SATA_EVNT_MAIN;
18748 					mutex_exit(
18749 					    &sata_hba_inst->satahba_mutex);
18750 					mutex_enter(&sata_mutex);
18751 					sata_event_pending |= SATA_EVNT_MAIN;
18752 					mutex_exit(&sata_mutex);
18753 					return;
18754 				}
18755 				if (rval_set == SATA_RETRY) {
18756 					/*
18757 					 * Setting drive features failed, but
18758 					 * the drive is still accessible,
18759 					 * so emit a warning message before
18760 					 * return.
18761 					 */
18762 					mutex_exit(&SATA_CPORT_INFO(
18763 					    sata_hba_inst,
18764 					    saddr->cport)->cport_mutex);
18765 					goto done;
18766 				}
18767 			}
18768 			/* Fail the drive */
18769 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18770 
18771 			sata_log(sata_hba_inst, CE_WARN,
18772 			    "SATA device at port %d - device failed",
18773 			    saddr->cport);
18774 
18775 			DTRACE_PROBE(port_failed_f);
18776 		}
18777 		/*
18778 		 * No point of retrying - device failed or some other event
18779 		 * processing or already did or will do port info cleanup.
18780 		 * To be safe (HBA may need it),
18781 		 * request clearing device reset condition.
18782 		 */
18783 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
18784 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18785 		sdinfo->satadrv_reset_time = 0;
18786 		return;
18787 	}
18788 done:
18789 	/*
18790 	 * If setting of drive features failed, but the drive is still
18791 	 * accessible, emit a warning message.
18792 	 */
18793 	if (rval_set == SATA_RETRY) {
18794 		sata_log(sata_hba_inst, CE_WARN,
18795 		    "SATA device at port %d - desired setting could not be "
18796 		    "restored after reset. Device may not operate as expected.",
18797 		    saddr->cport);
18798 	}
18799 	/*
18800 	 * Raise the flag indicating that the next sata command could
18801 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18802 	 * reset is reported.
18803 	 */
18804 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18805 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18806 		sdinfo->satadrv_reset_time = 0;
18807 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
18808 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18809 			sdinfo->satadrv_event_flags &=
18810 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18811 			sdinfo->satadrv_event_flags |=
18812 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18813 		}
18814 	}
18815 }
18816 
18817 
18818 /*
18819  * Port Multiplier Port Device Reset Event processing.
18820  *
18821  * NOTE: This function has to be entered with pmport mutex held. It exits with
18822  * mutex held as well, but can release mutex during the processing.
18823  */
18824 static void
18825 sata_process_pmdevice_reset(sata_hba_inst_t *sata_hba_inst,
18826     sata_address_t *saddr)
18827 {
18828 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
18829 	sata_drive_info_t *sdinfo = NULL;
18830 	sata_cport_info_t *cportinfo = NULL;
18831 	sata_pmport_info_t *pmportinfo = NULL;
18832 	sata_pmult_info_t *pminfo = NULL;
18833 	sata_device_t sata_device;
18834 	uint8_t cport = saddr->cport;
18835 	uint8_t pmport = saddr->pmport;
18836 	int rval;
18837 
18838 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18839 	    "Processing drive reset at port %d:%d", cport, pmport);
18840 
18841 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
18842 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18843 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport);
18844 
18845 	/*
18846 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
18847 	 * state, ignore reset event.
18848 	 */
18849 	if (((cportinfo->cport_state &
18850 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
18851 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
18852 		sdinfo->satadrv_event_flags &=
18853 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
18854 		return;
18855 	}
18856 
18857 	if ((pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
18858 		/*
18859 		 * This should not happen - coding error.
18860 		 * But we can recover, so do not panic, just clean up
18861 		 * and if in debug mode, log the message.
18862 		 */
18863 #ifdef SATA_DEBUG
18864 		sata_log(sata_hba_inst, CE_WARN,
18865 		    "sata_process_pmdevice_reset: "
18866 		    "Invalid device type with sdinfo!", NULL);
18867 #endif
18868 		sdinfo->satadrv_event_flags = 0;
18869 		return;
18870 	}
18871 
18872 #ifdef SATA_DEBUG
18873 	if ((sdinfo->satadrv_event_flags &
18874 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
18875 		/* Nothing to do */
18876 		/* Something is weird - why we are processing dev reset? */
18877 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18878 		    "No device reset event!!!!", NULL);
18879 
18880 		return;
18881 	}
18882 	if ((sdinfo->satadrv_event_flags &
18883 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
18884 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
18885 		/* Something is weird - new device reset event */
18886 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18887 		    "Overlapping device reset events!", NULL);
18888 	}
18889 #endif
18890 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18891 	    "Processing port %d:%d device reset", cport, pmport);
18892 
18893 	/* Clear event flag */
18894 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
18895 
18896 	/* It seems that we always need to check the port state first */
18897 	sata_device.satadev_rev = SATA_DEVICE_REV;
18898 	sata_device.satadev_addr = *saddr;
18899 	/*
18900 	 * We have to exit mutex, because the HBA probe port function may
18901 	 * block on its own mutex.
18902 	 */
18903 	mutex_exit(&pmportinfo->pmport_mutex);
18904 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18905 	    (SATA_DIP(sata_hba_inst), &sata_device);
18906 	mutex_enter(&pmportinfo->pmport_mutex);
18907 
18908 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18909 	if (rval != SATA_SUCCESS) {
18910 		/* Something went wrong? Fail the port */
18911 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18912 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18913 		    saddr->pmport);
18914 		if (sdinfo != NULL)
18915 			sdinfo->satadrv_event_flags = 0;
18916 		mutex_exit(&pmportinfo->pmport_mutex);
18917 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18918 		    "SATA port %d:%d probing failed",
18919 		    saddr->cport, saddr->pmport));
18920 		mutex_enter(&pmportinfo->pmport_mutex);
18921 		return;
18922 	}
18923 	if ((sata_device.satadev_scr.sstatus  &
18924 	    SATA_PORT_DEVLINK_UP_MASK) !=
18925 	    SATA_PORT_DEVLINK_UP ||
18926 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18927 		/*
18928 		 * No device to process, anymore. Some other event processing
18929 		 * would or have already performed port info cleanup.
18930 		 * To be safe (HBA may need it), request clearing device
18931 		 * reset condition.
18932 		 */
18933 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18934 		    saddr->pmport);
18935 		if (sdinfo != NULL) {
18936 			sdinfo->satadrv_event_flags &=
18937 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18938 			/* must clear flags on cport */
18939 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18940 			    saddr->cport);
18941 			pminfo->pmult_event_flags |=
18942 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18943 		}
18944 		return;
18945 	}
18946 
18947 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18948 	    saddr->pmport);
18949 	if (sdinfo == NULL) {
18950 		return;
18951 	}
18952 	if ((sdinfo->satadrv_event_flags &
18953 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18954 		/*
18955 		 * Start tracking time for device feature restoration and
18956 		 * identification. Save current time (lbolt value).
18957 		 */
18958 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18959 	}
18960 	/* Mark device reset processing as active */
18961 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18962 
18963 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18964 	mutex_exit(&pmportinfo->pmport_mutex);
18965 
18966 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
18967 	    SATA_FAILURE) {
18968 		/*
18969 		 * Restoring drive setting failed.
18970 		 * Probe the port first, to check if the port state has changed
18971 		 */
18972 		sata_device.satadev_rev = SATA_DEVICE_REV;
18973 		sata_device.satadev_addr = *saddr;
18974 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
18975 
18976 		/* probe port */
18977 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18978 		    (SATA_DIP(sata_hba_inst), &sata_device);
18979 		mutex_enter(&pmportinfo->pmport_mutex);
18980 		if (rval == SATA_SUCCESS &&
18981 		    (sata_device.satadev_state &
18982 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18983 		    (sata_device.satadev_scr.sstatus  &
18984 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18985 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18986 			/*
18987 			 * We may retry this a bit later - in-process reset
18988 			 * condition should be already set.
18989 			 * Track retry time for device identification.
18990 			 */
18991 			if ((pmportinfo->pmport_dev_type &
18992 			    SATA_VALID_DEV_TYPE) != 0 &&
18993 			    SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL &&
18994 			    sdinfo->satadrv_reset_time != 0) {
18995 				clock_t cur_time = ddi_get_lbolt();
18996 				/*
18997 				 * If the retry time limit was not
18998 				 * exceeded, retry.
18999 				 */
19000 				if ((cur_time - sdinfo->satadrv_reset_time) <
19001 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
19002 					mutex_enter(
19003 					    &sata_hba_inst->satahba_mutex);
19004 					sata_hba_inst->satahba_event_flags |=
19005 					    SATA_EVNT_MAIN;
19006 					mutex_exit(
19007 					    &sata_hba_inst->satahba_mutex);
19008 					mutex_enter(&sata_mutex);
19009 					sata_event_pending |= SATA_EVNT_MAIN;
19010 					mutex_exit(&sata_mutex);
19011 					return;
19012 				}
19013 			}
19014 			/* Fail the drive */
19015 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
19016 
19017 			sata_log(sata_hba_inst, CE_WARN,
19018 			    "SATA device at port %d:%d - device failed",
19019 			    saddr->cport, saddr->pmport);
19020 		} else {
19021 			/*
19022 			 * No point of retrying - some other event processing
19023 			 * would or already did port info cleanup.
19024 			 * To be safe (HBA may need it),
19025 			 * request clearing device reset condition.
19026 			 */
19027 			sdinfo->satadrv_event_flags |=
19028 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19029 		}
19030 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
19031 		sdinfo->satadrv_reset_time = 0;
19032 		return;
19033 	}
19034 	/*
19035 	 * Raise the flag indicating that the next sata command could
19036 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
19037 	 * reset is reported.
19038 	 */
19039 	mutex_enter(&pmportinfo->pmport_mutex);
19040 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19041 		sdinfo->satadrv_reset_time = 0;
19042 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
19043 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19044 			sdinfo->satadrv_event_flags &=
19045 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
19046 			/* must clear flags on cport */
19047 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
19048 			    saddr->cport);
19049 			pminfo->pmult_event_flags |=
19050 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19051 		}
19052 	}
19053 }
19054 
19055 /*
19056  * Port Link Events processing.
19057  * Every link established event may involve device reset (due to
19058  * COMRESET signal, equivalent of the hard reset) so arbitrarily
19059  * set device reset event for an attached device (if any).
19060  * If the port is in SHUTDOWN or FAILED state, ignore link events.
19061  *
19062  * The link established event processing varies, depending on the state
19063  * of the target node, HBA hotplugging capabilities, state of the port.
19064  * If the link is not active, the link established event is ignored.
19065  * If HBA cannot detect device attachment and there is no target node,
19066  * the link established event triggers device attach event processing.
19067  * Else, link established event triggers device reset event processing.
19068  *
19069  * The link lost event processing varies, depending on a HBA hotplugging
19070  * capability and the state of the port (link active or not active).
19071  * If the link is active, the lost link event is ignored.
19072  * If HBA cannot detect device removal, the lost link event triggers
19073  * device detached event processing after link lost timeout.
19074  * Else, the event is ignored.
19075  *
19076  * NOTE: Port multiplier ports events are handled by
19077  * sata_process_pmport_link_events();
19078  */
19079 static void
19080 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
19081     sata_address_t *saddr)
19082 {
19083 	sata_device_t sata_device;
19084 	sata_cport_info_t *cportinfo;
19085 	sata_drive_info_t *sdinfo;
19086 	uint32_t event_flags;
19087 	int rval;
19088 
19089 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19090 	    "Processing port %d link event(s)", saddr->cport);
19091 
19092 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19093 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19094 	event_flags = cportinfo->cport_event_flags;
19095 
19096 	/* Reset event flags first */
19097 	cportinfo->cport_event_flags &=
19098 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
19099 
19100 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
19101 	if ((cportinfo->cport_state &
19102 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19103 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19104 		    cport_mutex);
19105 		return;
19106 	}
19107 
19108 	/*
19109 	 * For the sanity sake get current port state.
19110 	 * Set device address only. Other sata_device fields should be
19111 	 * set by HBA driver.
19112 	 */
19113 	sata_device.satadev_rev = SATA_DEVICE_REV;
19114 	sata_device.satadev_addr = *saddr;
19115 	/*
19116 	 * We have to exit mutex, because the HBA probe port function may
19117 	 * block on its own mutex.
19118 	 */
19119 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19120 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19121 	    (SATA_DIP(sata_hba_inst), &sata_device);
19122 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19123 	sata_update_port_info(sata_hba_inst, &sata_device);
19124 	if (rval != SATA_SUCCESS) {
19125 		/* Something went wrong? Fail the port */
19126 		cportinfo->cport_state = SATA_PSTATE_FAILED;
19127 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19128 		    cport_mutex);
19129 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19130 		    "SATA port %d probing failed",
19131 		    saddr->cport));
19132 		/*
19133 		 * We may want to release device info structure, but
19134 		 * it is not necessary.
19135 		 */
19136 		return;
19137 	} else {
19138 		/* port probed successfully */
19139 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
19140 	}
19141 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
19142 
19143 		if ((sata_device.satadev_scr.sstatus &
19144 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
19145 			/* Ignore event */
19146 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19147 			    "Ignoring port %d link established event - "
19148 			    "link down",
19149 			    saddr->cport);
19150 			goto linklost;
19151 		}
19152 
19153 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19154 		    "Processing port %d link established event",
19155 		    saddr->cport);
19156 
19157 		/*
19158 		 * For the sanity sake check if a device is attached - check
19159 		 * return state of a port probing.
19160 		 */
19161 		if (sata_device.satadev_type != SATA_DTYPE_NONE) {
19162 			/*
19163 			 * HBA port probe indicated that there is a device
19164 			 * attached. Check if the framework had device info
19165 			 * structure attached for this device.
19166 			 */
19167 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
19168 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
19169 				    NULL);
19170 
19171 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
19172 				if ((sdinfo->satadrv_type &
19173 				    SATA_VALID_DEV_TYPE) != 0) {
19174 					/*
19175 					 * Dev info structure is present.
19176 					 * If dev_type is set to known type in
19177 					 * the framework's drive info struct
19178 					 * then the device existed before and
19179 					 * the link was probably lost
19180 					 * momentarily - in such case
19181 					 * we may want to check device
19182 					 * identity.
19183 					 * Identity check is not supported now.
19184 					 *
19185 					 * Link established event
19186 					 * triggers device reset event.
19187 					 */
19188 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
19189 					    satadrv_event_flags |=
19190 					    SATA_EVNT_DEVICE_RESET;
19191 				}
19192 			} else if (cportinfo->cport_dev_type ==
19193 			    SATA_DTYPE_NONE) {
19194 				/*
19195 				 * We got new device attached! If HBA does not
19196 				 * generate device attached events, trigger it
19197 				 * here.
19198 				 */
19199 				if (!(SATA_FEATURES(sata_hba_inst) &
19200 				    SATA_CTLF_HOTPLUG)) {
19201 					cportinfo->cport_event_flags |=
19202 					    SATA_EVNT_DEVICE_ATTACHED;
19203 				}
19204 			}
19205 			/* Reset link lost timeout */
19206 			cportinfo->cport_link_lost_time = 0;
19207 		}
19208 	}
19209 linklost:
19210 	if (event_flags & SATA_EVNT_LINK_LOST) {
19211 		if ((sata_device.satadev_scr.sstatus &
19212 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
19213 			/* Ignore event */
19214 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19215 			    "Ignoring port %d link lost event - link is up",
19216 			    saddr->cport);
19217 			goto done;
19218 		}
19219 #ifdef SATA_DEBUG
19220 		if (cportinfo->cport_link_lost_time == 0) {
19221 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19222 			    "Processing port %d link lost event",
19223 			    saddr->cport);
19224 		}
19225 #endif
19226 		/*
19227 		 * When HBA cannot generate device attached/detached events,
19228 		 * we need to track link lost time and eventually generate
19229 		 * device detach event.
19230 		 */
19231 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
19232 			/* We are tracking link lost time */
19233 			if (cportinfo->cport_link_lost_time == 0) {
19234 				/* save current time (lbolt value) */
19235 				cportinfo->cport_link_lost_time =
19236 				    ddi_get_lbolt();
19237 				/* just keep link lost event */
19238 				cportinfo->cport_event_flags |=
19239 				    SATA_EVNT_LINK_LOST;
19240 			} else {
19241 				clock_t cur_time = ddi_get_lbolt();
19242 				if ((cur_time -
19243 				    cportinfo->cport_link_lost_time) >=
19244 				    drv_usectohz(
19245 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
19246 					/* trigger device detach event */
19247 					cportinfo->cport_event_flags |=
19248 					    SATA_EVNT_DEVICE_DETACHED;
19249 					cportinfo->cport_link_lost_time = 0;
19250 					SATADBG1(SATA_DBG_EVENTS,
19251 					    sata_hba_inst,
19252 					    "Triggering port %d "
19253 					    "device detached event",
19254 					    saddr->cport);
19255 				} else {
19256 					/* keep link lost event */
19257 					cportinfo->cport_event_flags |=
19258 					    SATA_EVNT_LINK_LOST;
19259 				}
19260 			}
19261 		}
19262 		/*
19263 		 * We could change port state to disable/delay access to
19264 		 * the attached device until the link is recovered.
19265 		 */
19266 	}
19267 done:
19268 	event_flags = cportinfo->cport_event_flags;
19269 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19270 	if (event_flags != 0) {
19271 		mutex_enter(&sata_hba_inst->satahba_mutex);
19272 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19273 		mutex_exit(&sata_hba_inst->satahba_mutex);
19274 		mutex_enter(&sata_mutex);
19275 		sata_event_pending |= SATA_EVNT_MAIN;
19276 		mutex_exit(&sata_mutex);
19277 	}
19278 }
19279 
19280 /*
19281  * Port Multiplier Port Link Events processing.
19282  */
19283 static void
19284 sata_process_pmport_link_events(sata_hba_inst_t *sata_hba_inst,
19285     sata_address_t *saddr)
19286 {
19287 	sata_device_t sata_device;
19288 	sata_pmport_info_t *pmportinfo = NULL;
19289 	sata_drive_info_t *sdinfo = NULL;
19290 	uint32_t event_flags;
19291 	uint8_t cport = saddr->cport;
19292 	uint8_t pmport = saddr->pmport;
19293 	int rval;
19294 
19295 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19296 	    "Processing port %d:%d link event(s)",
19297 	    cport, pmport);
19298 
19299 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19300 	mutex_enter(&pmportinfo->pmport_mutex);
19301 	event_flags = pmportinfo->pmport_event_flags;
19302 
19303 	/* Reset event flags first */
19304 	pmportinfo->pmport_event_flags &=
19305 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
19306 
19307 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
19308 	if ((pmportinfo->pmport_state &
19309 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19310 		mutex_exit(&pmportinfo->pmport_mutex);
19311 		return;
19312 	}
19313 
19314 	/*
19315 	 * For the sanity sake get current port state.
19316 	 * Set device address only. Other sata_device fields should be
19317 	 * set by HBA driver.
19318 	 */
19319 	sata_device.satadev_rev = SATA_DEVICE_REV;
19320 	sata_device.satadev_addr = *saddr;
19321 	/*
19322 	 * We have to exit mutex, because the HBA probe port function may
19323 	 * block on its own mutex.
19324 	 */
19325 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
19326 	    saddr->pmport));
19327 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19328 	    (SATA_DIP(sata_hba_inst), &sata_device);
19329 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
19330 	    saddr->pmport));
19331 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19332 	if (rval != SATA_SUCCESS) {
19333 		/* Something went wrong? Fail the port */
19334 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19335 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
19336 		    saddr->pmport));
19337 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19338 		    "SATA port %d:%d probing failed",
19339 		    saddr->cport, saddr->pmport));
19340 		/*
19341 		 * We may want to release device info structure, but
19342 		 * it is not necessary.
19343 		 */
19344 		return;
19345 	} else {
19346 		/* port probed successfully */
19347 		pmportinfo->pmport_state |=
19348 		    SATA_STATE_PROBED | SATA_STATE_READY;
19349 	}
19350 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
19351 	    saddr->cport, saddr->pmport));
19352 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
19353 	    saddr->cport, saddr->pmport));
19354 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
19355 
19356 		if ((sata_device.satadev_scr.sstatus &
19357 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
19358 			/* Ignore event */
19359 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19360 			    "Ignoring port %d:%d link established event - "
19361 			    "link down",
19362 			    saddr->cport, saddr->pmport);
19363 			goto linklost;
19364 		}
19365 
19366 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19367 		    "Processing port %d:%d link established event",
19368 		    cport, pmport);
19369 
19370 		/*
19371 		 * For the sanity sake check if a device is attached - check
19372 		 * return state of a port probing.
19373 		 */
19374 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
19375 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
19376 			/*
19377 			 * HBA port probe indicated that there is a device
19378 			 * attached. Check if the framework had device info
19379 			 * structure attached for this device.
19380 			 */
19381 			if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
19382 				ASSERT(SATA_PMPORTINFO_DRV_INFO(pmportinfo) !=
19383 				    NULL);
19384 
19385 				sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19386 				if ((sdinfo->satadrv_type &
19387 				    SATA_VALID_DEV_TYPE) != 0) {
19388 					/*
19389 					 * Dev info structure is present.
19390 					 * If dev_type is set to known type in
19391 					 * the framework's drive info struct
19392 					 * then the device existed before and
19393 					 * the link was probably lost
19394 					 * momentarily - in such case
19395 					 * we may want to check device
19396 					 * identity.
19397 					 * Identity check is not supported now.
19398 					 *
19399 					 * Link established event
19400 					 * triggers device reset event.
19401 					 */
19402 					(SATA_PMPORTINFO_DRV_INFO(pmportinfo))->
19403 					    satadrv_event_flags |=
19404 					    SATA_EVNT_DEVICE_RESET;
19405 				}
19406 			} else if (pmportinfo->pmport_dev_type ==
19407 			    SATA_DTYPE_NONE) {
19408 				/*
19409 				 * We got new device attached! If HBA does not
19410 				 * generate device attached events, trigger it
19411 				 * here.
19412 				 */
19413 				if (!(SATA_FEATURES(sata_hba_inst) &
19414 				    SATA_CTLF_HOTPLUG)) {
19415 					pmportinfo->pmport_event_flags |=
19416 					    SATA_EVNT_DEVICE_ATTACHED;
19417 				}
19418 			}
19419 			/* Reset link lost timeout */
19420 			pmportinfo->pmport_link_lost_time = 0;
19421 		}
19422 	}
19423 linklost:
19424 	if (event_flags & SATA_EVNT_LINK_LOST) {
19425 #ifdef SATA_DEBUG
19426 		if (pmportinfo->pmport_link_lost_time == 0) {
19427 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19428 			    "Processing port %d:%d link lost event",
19429 			    saddr->cport, saddr->pmport);
19430 		}
19431 #endif
19432 		if ((sata_device.satadev_scr.sstatus &
19433 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
19434 			/* Ignore event */
19435 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19436 			    "Ignoring port %d:%d link lost event - link is up",
19437 			    saddr->cport, saddr->pmport);
19438 			goto done;
19439 		}
19440 		/*
19441 		 * When HBA cannot generate device attached/detached events,
19442 		 * we need to track link lost time and eventually generate
19443 		 * device detach event.
19444 		 */
19445 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
19446 			/* We are tracking link lost time */
19447 			if (pmportinfo->pmport_link_lost_time == 0) {
19448 				/* save current time (lbolt value) */
19449 				pmportinfo->pmport_link_lost_time =
19450 				    ddi_get_lbolt();
19451 				/* just keep link lost event */
19452 				pmportinfo->pmport_event_flags |=
19453 				    SATA_EVNT_LINK_LOST;
19454 			} else {
19455 				clock_t cur_time = ddi_get_lbolt();
19456 				if ((cur_time -
19457 				    pmportinfo->pmport_link_lost_time) >=
19458 				    drv_usectohz(
19459 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
19460 					/* trigger device detach event */
19461 					pmportinfo->pmport_event_flags |=
19462 					    SATA_EVNT_DEVICE_DETACHED;
19463 					pmportinfo->pmport_link_lost_time = 0;
19464 					SATADBG2(SATA_DBG_EVENTS,
19465 					    sata_hba_inst,
19466 					    "Triggering port %d:%d "
19467 					    "device detached event",
19468 					    saddr->cport, saddr->pmport);
19469 				} else {
19470 					/* keep link lost event */
19471 					pmportinfo->pmport_event_flags |=
19472 					    SATA_EVNT_LINK_LOST;
19473 				}
19474 			}
19475 		}
19476 		/*
19477 		 * We could change port state to disable/delay access to
19478 		 * the attached device until the link is recovered.
19479 		 */
19480 	}
19481 done:
19482 	event_flags = pmportinfo->pmport_event_flags;
19483 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
19484 	    saddr->pmport));
19485 	if (event_flags != 0) {
19486 		mutex_enter(&sata_hba_inst->satahba_mutex);
19487 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19488 		mutex_exit(&sata_hba_inst->satahba_mutex);
19489 		mutex_enter(&sata_mutex);
19490 		sata_event_pending |= SATA_EVNT_MAIN;
19491 		mutex_exit(&sata_mutex);
19492 	}
19493 }
19494 
19495 /*
19496  * Device Detached Event processing.
19497  * Port is probed to find if a device is really gone. If so,
19498  * the device info structure is detached from the SATA port info structure
19499  * and released.
19500  * Port status is updated.
19501  *
19502  * NOTE: Port multiplier ports events are handled by
19503  * sata_process_pmdevice_detached()
19504  */
19505 static void
19506 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
19507     sata_address_t *saddr)
19508 {
19509 	sata_cport_info_t *cportinfo;
19510 	sata_pmport_info_t *pmportinfo;
19511 	sata_drive_info_t *sdevinfo;
19512 	sata_device_t sata_device;
19513 	sata_address_t pmport_addr;
19514 	char name[16];
19515 	uint8_t cport = saddr->cport;
19516 	int npmport;
19517 	int rval;
19518 
19519 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19520 	    "Processing port %d device detached", saddr->cport);
19521 
19522 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19523 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19524 	/* Clear event flag */
19525 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
19526 
19527 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
19528 	if ((cportinfo->cport_state &
19529 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19530 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19531 		    cport_mutex);
19532 		return;
19533 	}
19534 	/* For sanity, re-probe the port */
19535 	sata_device.satadev_rev = SATA_DEVICE_REV;
19536 	sata_device.satadev_addr = *saddr;
19537 
19538 	/*
19539 	 * We have to exit mutex, because the HBA probe port function may
19540 	 * block on its own mutex.
19541 	 */
19542 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19543 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19544 	    (SATA_DIP(sata_hba_inst), &sata_device);
19545 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19546 	sata_update_port_info(sata_hba_inst, &sata_device);
19547 	if (rval != SATA_SUCCESS) {
19548 		/* Something went wrong? Fail the port */
19549 		cportinfo->cport_state = SATA_PSTATE_FAILED;
19550 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19551 		    cport_mutex);
19552 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19553 		    "SATA port %d probing failed",
19554 		    saddr->cport));
19555 		/*
19556 		 * We may want to release device info structure, but
19557 		 * it is not necessary.
19558 		 */
19559 		return;
19560 	} else {
19561 		/* port probed successfully */
19562 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
19563 	}
19564 	/*
19565 	 * Check if a device is still attached. For sanity, check also
19566 	 * link status - if no link, there is no device.
19567 	 */
19568 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
19569 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
19570 	    SATA_DTYPE_NONE) {
19571 		/*
19572 		 * Device is still attached - ignore detach event.
19573 		 */
19574 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19575 		    cport_mutex);
19576 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19577 		    "Ignoring detach - device still attached to port %d",
19578 		    sata_device.satadev_addr.cport);
19579 		return;
19580 	}
19581 	/*
19582 	 * We need to detach and release device info structure here
19583 	 */
19584 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19585 		/*
19586 		 * A port-multiplier is removed.
19587 		 *
19588 		 * Calling sata_process_pmdevice_detached() does not work
19589 		 * here. The port multiplier is gone, so we cannot probe
19590 		 * sub-port any more and all pmult-related data structure must
19591 		 * be de-allocated immediately. Following structure of every
19592 		 * implemented sub-port behind the pmult are required to
19593 		 * released.
19594 		 *
19595 		 *   - attachment point
19596 		 *   - target node
19597 		 *   - sata_drive_info
19598 		 *   - sata_pmport_info
19599 		 */
19600 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst,
19601 		    cport); npmport ++) {
19602 			SATADBG2(SATA_DBG_PMULT|SATA_DBG_EVENTS_PROC,
19603 			    sata_hba_inst,
19604 			    "Detaching target node at port %d:%d",
19605 			    cport, npmport);
19606 
19607 			mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
19608 
19609 			/* Remove attachment point. */
19610 			name[0] = '\0';
19611 			(void) sprintf(name, "%d.%d", cport, npmport);
19612 			ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
19613 			sata_log(sata_hba_inst, CE_NOTE,
19614 			    "Remove attachment point of port %d:%d",
19615 			    cport, npmport);
19616 
19617 			/* Remove target node */
19618 			pmport_addr.cport = cport;
19619 			pmport_addr.pmport = (uint8_t)npmport;
19620 			pmport_addr.qual = SATA_ADDR_PMPORT;
19621 			sata_remove_target_node(sata_hba_inst, &pmport_addr);
19622 
19623 			mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
19624 
19625 			/* Release sata_pmport_info & sata_drive_info. */
19626 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19627 			    cport, npmport);
19628 			ASSERT(pmportinfo != NULL);
19629 
19630 			sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19631 			if (sdevinfo != NULL) {
19632 				(void) kmem_free((void *) sdevinfo,
19633 				    sizeof (sata_drive_info_t));
19634 			}
19635 
19636 			/* Release sata_pmport_info at last */
19637 			(void) kmem_free((void *) pmportinfo,
19638 			    sizeof (sata_pmport_info_t));
19639 		}
19640 
19641 		/* Finally, release sata_pmult_info */
19642 		(void) kmem_free((void *)
19643 		    SATA_CPORTINFO_PMULT_INFO(cportinfo),
19644 		    sizeof (sata_pmult_info_t));
19645 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
19646 
19647 		sata_log(sata_hba_inst, CE_WARN,
19648 		    "SATA port-multiplier detached at port %d", cport);
19649 
19650 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19651 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19652 		    saddr->cport)->cport_mutex);
19653 	} else {
19654 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19655 			sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
19656 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
19657 			(void) kmem_free((void *)sdevinfo,
19658 			    sizeof (sata_drive_info_t));
19659 		}
19660 		sata_log(sata_hba_inst, CE_WARN,
19661 		    "SATA device detached at port %d", cport);
19662 
19663 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19664 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19665 		    saddr->cport)->cport_mutex);
19666 
19667 		/*
19668 		 * Try to offline a device and remove target node
19669 		 * if it still exists
19670 		 */
19671 		sata_remove_target_node(sata_hba_inst, saddr);
19672 	}
19673 
19674 
19675 	/*
19676 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19677 	 * with the hint: SE_HINT_REMOVE
19678 	 */
19679 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
19680 }
19681 
19682 /*
19683  * Port Multiplier Port Device Deattached Event processing.
19684  *
19685  * NOTE: No Mutex should be hold.
19686  */
19687 static void
19688 sata_process_pmdevice_detached(sata_hba_inst_t *sata_hba_inst,
19689     sata_address_t *saddr)
19690 {
19691 	sata_pmport_info_t *pmportinfo;
19692 	sata_drive_info_t *sdevinfo;
19693 	sata_device_t sata_device;
19694 	int rval;
19695 	uint8_t cport, pmport;
19696 
19697 	cport = saddr->cport;
19698 	pmport = saddr->pmport;
19699 
19700 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19701 	    "Processing port %d:%d device detached",
19702 	    cport, pmport);
19703 
19704 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19705 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19706 
19707 	/* Clear event flag */
19708 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
19709 
19710 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
19711 	if ((pmportinfo->pmport_state &
19712 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19713 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19714 		return;
19715 	}
19716 	/* For sanity, re-probe the port */
19717 	sata_device.satadev_rev = SATA_DEVICE_REV;
19718 	sata_device.satadev_addr = *saddr;
19719 
19720 	/*
19721 	 * We have to exit mutex, because the HBA probe port function may
19722 	 * block on its own mutex.
19723 	 */
19724 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19725 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19726 	    (SATA_DIP(sata_hba_inst), &sata_device);
19727 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19728 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19729 	if (rval != SATA_SUCCESS) {
19730 		/* Something went wrong? Fail the port */
19731 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19732 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19733 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19734 		    "SATA port %d:%d probing failed",
19735 		    saddr->pmport));
19736 		/*
19737 		 * We may want to release device info structure, but
19738 		 * it is not necessary.
19739 		 */
19740 		return;
19741 	} else {
19742 		/* port probed successfully */
19743 		pmportinfo->pmport_state |=
19744 		    SATA_STATE_PROBED | SATA_STATE_READY;
19745 	}
19746 	/*
19747 	 * Check if a device is still attached. For sanity, check also
19748 	 * link status - if no link, there is no device.
19749 	 */
19750 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
19751 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
19752 	    SATA_DTYPE_NONE) {
19753 		/*
19754 		 * Device is still attached - ignore detach event.
19755 		 */
19756 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19757 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19758 		    "Ignoring detach - device still attached to port %d",
19759 		    sata_device.satadev_addr.pmport);
19760 		return;
19761 	}
19762 	/*
19763 	 * We need to detach and release device info structure here
19764 	 */
19765 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19766 		sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19767 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19768 		(void) kmem_free((void *)sdevinfo,
19769 		    sizeof (sata_drive_info_t));
19770 	}
19771 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19772 	/*
19773 	 * Device cannot be reached anymore, even if the target node may be
19774 	 * still present.
19775 	 */
19776 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19777 
19778 	/*
19779 	 * Try to offline a device and remove target node if it still exists
19780 	 */
19781 	sata_remove_target_node(sata_hba_inst, saddr);
19782 
19783 	/*
19784 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19785 	 * with the hint: SE_HINT_REMOVE
19786 	 */
19787 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
19788 }
19789 
19790 
19791 /*
19792  * Device Attached Event processing.
19793  * Port state is checked to verify that a device is really attached. If so,
19794  * the device info structure is created and attached to the SATA port info
19795  * structure.
19796  *
19797  * If attached device cannot be identified or set-up, the retry for the
19798  * attach processing is set-up. Subsequent daemon run would try again to
19799  * identify the device, until the time limit is reached
19800  * (SATA_DEV_IDENTIFY_TIMEOUT).
19801  *
19802  * This function cannot be called in interrupt context (it may sleep).
19803  *
19804  * NOTE: Port multiplier ports events are handled by
19805  * sata_process_pmdevice_attached()
19806  */
19807 static void
19808 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
19809     sata_address_t *saddr)
19810 {
19811 	sata_cport_info_t *cportinfo = NULL;
19812 	sata_drive_info_t *sdevinfo = NULL;
19813 	sata_pmult_info_t *pmultinfo = NULL;
19814 	sata_pmport_info_t *pmportinfo = NULL;
19815 	sata_device_t sata_device;
19816 	dev_info_t *tdip;
19817 	uint32_t event_flags = 0, pmult_event_flags = 0;
19818 	int rval;
19819 	int npmport;
19820 
19821 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19822 	    "Processing port %d device attached", saddr->cport);
19823 
19824 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19825 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19826 
19827 	/* Clear attach event flag first */
19828 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19829 
19830 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19831 	if ((cportinfo->cport_state &
19832 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19833 		cportinfo->cport_dev_attach_time = 0;
19834 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19835 		    cport_mutex);
19836 		return;
19837 	}
19838 
19839 	/*
19840 	 * If the sata_drive_info structure is found attached to the port info,
19841 	 * despite the fact the device was removed and now it is re-attached,
19842 	 * the old drive info structure was not removed.
19843 	 * Arbitrarily release device info structure.
19844 	 */
19845 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19846 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
19847 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
19848 		(void) kmem_free((void *)sdevinfo,
19849 		    sizeof (sata_drive_info_t));
19850 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19851 		    "Arbitrarily detaching old device info.", NULL);
19852 	}
19853 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19854 
19855 	/* For sanity, re-probe the port */
19856 	sata_device.satadev_rev = SATA_DEVICE_REV;
19857 	sata_device.satadev_addr = *saddr;
19858 
19859 	/*
19860 	 * We have to exit mutex, because the HBA probe port function may
19861 	 * block on its own mutex.
19862 	 */
19863 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19864 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19865 	    (SATA_DIP(sata_hba_inst), &sata_device);
19866 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19867 	sata_update_port_info(sata_hba_inst, &sata_device);
19868 	if (rval != SATA_SUCCESS) {
19869 		/* Something went wrong? Fail the port */
19870 		cportinfo->cport_state = SATA_PSTATE_FAILED;
19871 		cportinfo->cport_dev_attach_time = 0;
19872 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19873 		    cport_mutex);
19874 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19875 		    "SATA port %d probing failed",
19876 		    saddr->cport));
19877 		return;
19878 	} else {
19879 		/* port probed successfully */
19880 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
19881 	}
19882 	/*
19883 	 * Check if a device is still attached. For sanity, check also
19884 	 * link status - if no link, there is no device.
19885 	 */
19886 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19887 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19888 	    SATA_DTYPE_NONE) {
19889 		/*
19890 		 * No device - ignore attach event.
19891 		 */
19892 		cportinfo->cport_dev_attach_time = 0;
19893 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19894 		    cport_mutex);
19895 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19896 		    "Ignoring attach - no device connected to port %d",
19897 		    sata_device.satadev_addr.cport);
19898 		return;
19899 	}
19900 
19901 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19902 	/*
19903 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19904 	 * with the hint: SE_HINT_INSERT
19905 	 */
19906 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19907 
19908 	/*
19909 	 * Port reprobing will take care of the creation of the device
19910 	 * info structure and determination of the device type.
19911 	 */
19912 	sata_device.satadev_addr = *saddr;
19913 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19914 	    SATA_DEV_IDENTIFY_NORETRY);
19915 
19916 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19917 	    cport_mutex);
19918 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
19919 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
19920 		/* Some device is attached to the port */
19921 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
19922 			/*
19923 			 * A device was not successfully attached.
19924 			 * Track retry time for device identification.
19925 			 */
19926 			if (cportinfo->cport_dev_attach_time != 0) {
19927 				clock_t cur_time = ddi_get_lbolt();
19928 				/*
19929 				 * If the retry time limit was not exceeded,
19930 				 * reinstate attach event.
19931 				 */
19932 				if ((cur_time -
19933 				    cportinfo->cport_dev_attach_time) <
19934 				    drv_usectohz(
19935 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19936 					/* OK, restore attach event */
19937 					cportinfo->cport_event_flags |=
19938 					    SATA_EVNT_DEVICE_ATTACHED;
19939 				} else {
19940 					/* Timeout - cannot identify device */
19941 					cportinfo->cport_dev_attach_time = 0;
19942 					sata_log(sata_hba_inst,
19943 					    CE_WARN,
19944 					    "Could not identify SATA device "
19945 					    "at port %d",
19946 					    saddr->cport);
19947 				}
19948 			} else {
19949 				/*
19950 				 * Start tracking time for device
19951 				 * identification.
19952 				 * Save current time (lbolt value).
19953 				 */
19954 				cportinfo->cport_dev_attach_time =
19955 				    ddi_get_lbolt();
19956 				/* Restore attach event */
19957 				cportinfo->cport_event_flags |=
19958 				    SATA_EVNT_DEVICE_ATTACHED;
19959 			}
19960 		} else if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19961 			cportinfo->cport_dev_attach_time = 0;
19962 			sata_log(sata_hba_inst, CE_NOTE,
19963 			    "SATA port-multiplier detected at port %d",
19964 			    saddr->cport);
19965 
19966 			if (SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL) {
19967 				/* Log the info of new port multiplier */
19968 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19969 				    saddr->cport)->cport_mutex);
19970 				sata_show_pmult_info(sata_hba_inst,
19971 				    &sata_device);
19972 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19973 				    saddr->cport)->cport_mutex);
19974 			}
19975 
19976 			ASSERT(SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL);
19977 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
19978 			for (npmport = 0; npmport <
19979 			    pmultinfo->pmult_num_dev_ports; npmport++) {
19980 				pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19981 				    saddr->cport, npmport);
19982 				ASSERT(pmportinfo != NULL);
19983 
19984 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19985 				    saddr->cport)->cport_mutex);
19986 				mutex_enter(&pmportinfo->pmport_mutex);
19987 				/* Marked all pmports with link events. */
19988 				pmportinfo->pmport_event_flags =
19989 				    SATA_EVNT_LINK_ESTABLISHED;
19990 				pmult_event_flags |=
19991 				    pmportinfo->pmport_event_flags;
19992 				mutex_exit(&pmportinfo->pmport_mutex);
19993 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19994 				    saddr->cport)->cport_mutex);
19995 			}
19996 			/* Auto-online is not available for PMult now. */
19997 
19998 		} else {
19999 			/*
20000 			 * If device was successfully attached, the subsequent
20001 			 * action depends on a state of the
20002 			 * sata_auto_online variable. If it is set to zero.
20003 			 * an explicit 'configure' command will be needed to
20004 			 * configure it. If its value is non-zero, we will
20005 			 * attempt to online (configure) the device.
20006 			 * First, log the message indicating that a device
20007 			 * was attached.
20008 			 */
20009 			cportinfo->cport_dev_attach_time = 0;
20010 			sata_log(sata_hba_inst, CE_WARN,
20011 			    "SATA device detected at port %d", saddr->cport);
20012 
20013 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
20014 				sata_drive_info_t new_sdinfo;
20015 
20016 				/* Log device info data */
20017 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
20018 				    cportinfo));
20019 				sata_show_drive_info(sata_hba_inst,
20020 				    &new_sdinfo);
20021 			}
20022 
20023 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20024 			    saddr->cport)->cport_mutex);
20025 
20026 			/*
20027 			 * Make sure that there is no target node for that
20028 			 * device. If so, release it. It should not happen,
20029 			 * unless we had problem removing the node when
20030 			 * device was detached.
20031 			 */
20032 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
20033 			    saddr->cport, saddr->pmport);
20034 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20035 			    saddr->cport)->cport_mutex);
20036 			if (tdip != NULL) {
20037 
20038 #ifdef SATA_DEBUG
20039 				if ((cportinfo->cport_event_flags &
20040 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
20041 					sata_log(sata_hba_inst, CE_WARN,
20042 					    "sata_process_device_attached: "
20043 					    "old device target node exists!");
20044 #endif
20045 				/*
20046 				 * target node exists - try to unconfigure
20047 				 * device and remove the node.
20048 				 */
20049 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20050 				    saddr->cport)->cport_mutex);
20051 				rval = ndi_devi_offline(tdip,
20052 				    NDI_DEVI_REMOVE);
20053 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20054 				    saddr->cport)->cport_mutex);
20055 
20056 				if (rval == NDI_SUCCESS) {
20057 					cportinfo->cport_event_flags &=
20058 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
20059 					cportinfo->cport_tgtnode_clean = B_TRUE;
20060 				} else {
20061 					/*
20062 					 * PROBLEM - the target node remained
20063 					 * and it belongs to a previously
20064 					 * attached device.
20065 					 * This happens when the file was open
20066 					 * or the node was waiting for
20067 					 * resources at the time the
20068 					 * associated device was removed.
20069 					 * Instruct event daemon to retry the
20070 					 * cleanup later.
20071 					 */
20072 					sata_log(sata_hba_inst,
20073 					    CE_WARN,
20074 					    "Application(s) accessing "
20075 					    "previously attached SATA "
20076 					    "device have to release "
20077 					    "it before newly inserted "
20078 					    "device can be made accessible.",
20079 					    saddr->cport);
20080 					cportinfo->cport_event_flags |=
20081 					    SATA_EVNT_TARGET_NODE_CLEANUP;
20082 					cportinfo->cport_tgtnode_clean =
20083 					    B_FALSE;
20084 				}
20085 			}
20086 			if (sata_auto_online != 0) {
20087 				cportinfo->cport_event_flags |=
20088 				    SATA_EVNT_AUTOONLINE_DEVICE;
20089 			}
20090 
20091 		}
20092 	} else {
20093 		cportinfo->cport_dev_attach_time = 0;
20094 	}
20095 
20096 	event_flags = cportinfo->cport_event_flags;
20097 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
20098 	if (event_flags != 0 || pmult_event_flags != 0) {
20099 		mutex_enter(&sata_hba_inst->satahba_mutex);
20100 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20101 		mutex_exit(&sata_hba_inst->satahba_mutex);
20102 		mutex_enter(&sata_mutex);
20103 		sata_event_pending |= SATA_EVNT_MAIN;
20104 		mutex_exit(&sata_mutex);
20105 	}
20106 }
20107 
20108 /*
20109  * Port Multiplier Port Device Attached Event processing.
20110  *
20111  * NOTE: No Mutex should be hold.
20112  */
20113 static void
20114 sata_process_pmdevice_attached(sata_hba_inst_t *sata_hba_inst,
20115     sata_address_t *saddr)
20116 {
20117 	sata_pmport_info_t *pmportinfo;
20118 	sata_drive_info_t *sdinfo;
20119 	sata_device_t sata_device;
20120 	dev_info_t *tdip;
20121 	uint32_t event_flags;
20122 	uint8_t cport = saddr->cport;
20123 	uint8_t pmport = saddr->pmport;
20124 	int rval;
20125 
20126 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20127 	    "Processing port %d:%d device attached", cport, pmport);
20128 
20129 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
20130 
20131 	mutex_enter(&pmportinfo->pmport_mutex);
20132 
20133 	/* Clear attach event flag first */
20134 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
20135 
20136 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
20137 	if ((pmportinfo->pmport_state &
20138 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
20139 		pmportinfo->pmport_dev_attach_time = 0;
20140 		mutex_exit(&pmportinfo->pmport_mutex);
20141 		return;
20142 	}
20143 
20144 	/*
20145 	 * If the sata_drive_info structure is found attached to the port info,
20146 	 * despite the fact the device was removed and now it is re-attached,
20147 	 * the old drive info structure was not removed.
20148 	 * Arbitrarily release device info structure.
20149 	 */
20150 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
20151 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
20152 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
20153 		(void) kmem_free((void *)sdinfo,
20154 		    sizeof (sata_drive_info_t));
20155 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20156 		    "Arbitrarily detaching old device info.", NULL);
20157 	}
20158 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
20159 
20160 	/* For sanity, re-probe the port */
20161 	sata_device.satadev_rev = SATA_DEVICE_REV;
20162 	sata_device.satadev_addr = *saddr;
20163 
20164 	/*
20165 	 * We have to exit mutex, because the HBA probe port function may
20166 	 * block on its own mutex.
20167 	 */
20168 	mutex_exit(&pmportinfo->pmport_mutex);
20169 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
20170 	    (SATA_DIP(sata_hba_inst), &sata_device);
20171 	mutex_enter(&pmportinfo->pmport_mutex);
20172 
20173 	sata_update_pmport_info(sata_hba_inst, &sata_device);
20174 	if (rval != SATA_SUCCESS) {
20175 		/* Something went wrong? Fail the port */
20176 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
20177 		pmportinfo->pmport_dev_attach_time = 0;
20178 		mutex_exit(&pmportinfo->pmport_mutex);
20179 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20180 		    "SATA port %d:%d probing failed", cport, pmport));
20181 		return;
20182 	} else {
20183 		/* pmport probed successfully */
20184 		pmportinfo->pmport_state |=
20185 		    SATA_STATE_PROBED | SATA_STATE_READY;
20186 	}
20187 	/*
20188 	 * Check if a device is still attached. For sanity, check also
20189 	 * link status - if no link, there is no device.
20190 	 */
20191 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
20192 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
20193 	    SATA_DTYPE_NONE) {
20194 		/*
20195 		 * No device - ignore attach event.
20196 		 */
20197 		pmportinfo->pmport_dev_attach_time = 0;
20198 		mutex_exit(&pmportinfo->pmport_mutex);
20199 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20200 		    "Ignoring attach - no device connected to port %d:%d",
20201 		    cport, pmport);
20202 		return;
20203 	}
20204 
20205 	mutex_exit(&pmportinfo->pmport_mutex);
20206 	/*
20207 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
20208 	 * with the hint: SE_HINT_INSERT
20209 	 */
20210 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
20211 
20212 	/*
20213 	 * Port reprobing will take care of the creation of the device
20214 	 * info structure and determination of the device type.
20215 	 */
20216 	sata_device.satadev_addr = *saddr;
20217 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
20218 	    SATA_DEV_IDENTIFY_NORETRY);
20219 
20220 	mutex_enter(&pmportinfo->pmport_mutex);
20221 	if ((pmportinfo->pmport_state & SATA_STATE_READY) &&
20222 	    (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE)) {
20223 		/* Some device is attached to the port */
20224 		if (pmportinfo->pmport_dev_type == SATA_DTYPE_UNKNOWN) {
20225 			/*
20226 			 * A device was not successfully attached.
20227 			 * Track retry time for device identification.
20228 			 */
20229 			if (pmportinfo->pmport_dev_attach_time != 0) {
20230 				clock_t cur_time = ddi_get_lbolt();
20231 				/*
20232 				 * If the retry time limit was not exceeded,
20233 				 * reinstate attach event.
20234 				 */
20235 				if ((cur_time -
20236 				    pmportinfo->pmport_dev_attach_time) <
20237 				    drv_usectohz(
20238 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
20239 					/* OK, restore attach event */
20240 					pmportinfo->pmport_event_flags |=
20241 					    SATA_EVNT_DEVICE_ATTACHED;
20242 				} else {
20243 					/* Timeout - cannot identify device */
20244 					pmportinfo->pmport_dev_attach_time = 0;
20245 					sata_log(sata_hba_inst, CE_WARN,
20246 					    "Could not identify SATA device "
20247 					    "at port %d:%d",
20248 					    cport, pmport);
20249 				}
20250 			} else {
20251 				/*
20252 				 * Start tracking time for device
20253 				 * identification.
20254 				 * Save current time (lbolt value).
20255 				 */
20256 				pmportinfo->pmport_dev_attach_time =
20257 				    ddi_get_lbolt();
20258 				/* Restore attach event */
20259 				pmportinfo->pmport_event_flags |=
20260 				    SATA_EVNT_DEVICE_ATTACHED;
20261 			}
20262 		} else {
20263 			/*
20264 			 * If device was successfully attached, the subsequent
20265 			 * action depends on a state of the
20266 			 * sata_auto_online variable. If it is set to zero.
20267 			 * an explicit 'configure' command will be needed to
20268 			 * configure it. If its value is non-zero, we will
20269 			 * attempt to online (configure) the device.
20270 			 * First, log the message indicating that a device
20271 			 * was attached.
20272 			 */
20273 			pmportinfo->pmport_dev_attach_time = 0;
20274 			sata_log(sata_hba_inst, CE_WARN,
20275 			    "SATA device detected at port %d:%d",
20276 			    cport, pmport);
20277 
20278 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
20279 				sata_drive_info_t new_sdinfo;
20280 
20281 				/* Log device info data */
20282 				new_sdinfo = *(SATA_PMPORTINFO_DRV_INFO(
20283 				    pmportinfo));
20284 				sata_show_drive_info(sata_hba_inst,
20285 				    &new_sdinfo);
20286 			}
20287 
20288 			mutex_exit(&pmportinfo->pmport_mutex);
20289 
20290 			/*
20291 			 * Make sure that there is no target node for that
20292 			 * device. If so, release it. It should not happen,
20293 			 * unless we had problem removing the node when
20294 			 * device was detached.
20295 			 */
20296 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
20297 			    saddr->cport, saddr->pmport);
20298 			mutex_enter(&pmportinfo->pmport_mutex);
20299 			if (tdip != NULL) {
20300 
20301 #ifdef SATA_DEBUG
20302 				if ((pmportinfo->pmport_event_flags &
20303 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
20304 					sata_log(sata_hba_inst, CE_WARN,
20305 					    "sata_process_device_attached: "
20306 					    "old device target node exists!");
20307 #endif
20308 				/*
20309 				 * target node exists - try to unconfigure
20310 				 * device and remove the node.
20311 				 */
20312 				mutex_exit(&pmportinfo->pmport_mutex);
20313 				rval = ndi_devi_offline(tdip,
20314 				    NDI_DEVI_REMOVE);
20315 				mutex_enter(&pmportinfo->pmport_mutex);
20316 
20317 				if (rval == NDI_SUCCESS) {
20318 					pmportinfo->pmport_event_flags &=
20319 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
20320 					pmportinfo->pmport_tgtnode_clean =
20321 					    B_TRUE;
20322 				} else {
20323 					/*
20324 					 * PROBLEM - the target node remained
20325 					 * and it belongs to a previously
20326 					 * attached device.
20327 					 * This happens when the file was open
20328 					 * or the node was waiting for
20329 					 * resources at the time the
20330 					 * associated device was removed.
20331 					 * Instruct event daemon to retry the
20332 					 * cleanup later.
20333 					 */
20334 					sata_log(sata_hba_inst,
20335 					    CE_WARN,
20336 					    "Application(s) accessing "
20337 					    "previously attached SATA "
20338 					    "device have to release "
20339 					    "it before newly inserted "
20340 					    "device can be made accessible."
20341 					    "at port %d:%d",
20342 					    cport, pmport);
20343 					pmportinfo->pmport_event_flags |=
20344 					    SATA_EVNT_TARGET_NODE_CLEANUP;
20345 					pmportinfo->pmport_tgtnode_clean =
20346 					    B_FALSE;
20347 				}
20348 			}
20349 			if (sata_auto_online != 0) {
20350 				pmportinfo->pmport_event_flags |=
20351 				    SATA_EVNT_AUTOONLINE_DEVICE;
20352 			}
20353 
20354 		}
20355 	} else {
20356 		pmportinfo->pmport_dev_attach_time = 0;
20357 	}
20358 
20359 	event_flags = pmportinfo->pmport_event_flags;
20360 	mutex_exit(&pmportinfo->pmport_mutex);
20361 	if (event_flags != 0) {
20362 		mutex_enter(&sata_hba_inst->satahba_mutex);
20363 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20364 		mutex_exit(&sata_hba_inst->satahba_mutex);
20365 		mutex_enter(&sata_mutex);
20366 		sata_event_pending |= SATA_EVNT_MAIN;
20367 		mutex_exit(&sata_mutex);
20368 	}
20369 
20370 	/* clear the reset_in_progress events */
20371 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
20372 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
20373 			/* must clear flags on cport */
20374 			sata_pmult_info_t *pminfo =
20375 			    SATA_PMULT_INFO(sata_hba_inst,
20376 			    saddr->cport);
20377 			pminfo->pmult_event_flags |=
20378 			    SATA_EVNT_CLEAR_DEVICE_RESET;
20379 		}
20380 	}
20381 }
20382 
20383 /*
20384  * Device Target Node Cleanup Event processing.
20385  * If the target node associated with a sata port device is in
20386  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
20387  * If the target node cannot be removed, the event flag is left intact,
20388  * so that event daemon may re-run this function later.
20389  *
20390  * This function cannot be called in interrupt context (it may sleep).
20391  *
20392  * NOTE: Processes cport events only, not port multiplier ports.
20393  */
20394 static void
20395 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
20396     sata_address_t *saddr)
20397 {
20398 	sata_cport_info_t *cportinfo;
20399 	dev_info_t *tdip;
20400 
20401 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20402 	    "Processing port %d device target node cleanup", saddr->cport);
20403 
20404 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
20405 
20406 	/*
20407 	 * Check if there is target node for that device and it is in the
20408 	 * DEVI_DEVICE_REMOVED state. If so, release it.
20409 	 */
20410 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
20411 	    saddr->pmport);
20412 	if (tdip != NULL) {
20413 		/*
20414 		 * target node exists - check if it is target node of
20415 		 * a removed device.
20416 		 */
20417 		if (sata_check_device_removed(tdip) == B_TRUE) {
20418 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20419 			    "sata_process_target_node_cleanup: "
20420 			    "old device target node exists!", NULL);
20421 			/*
20422 			 * Unconfigure and remove the target node
20423 			 */
20424 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
20425 			    NDI_SUCCESS) {
20426 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20427 				    saddr->cport)->cport_mutex);
20428 				cportinfo->cport_event_flags &=
20429 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
20430 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20431 				    saddr->cport)->cport_mutex);
20432 				return;
20433 			}
20434 			/*
20435 			 * Event daemon will retry the cleanup later.
20436 			 */
20437 			mutex_enter(&sata_hba_inst->satahba_mutex);
20438 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20439 			mutex_exit(&sata_hba_inst->satahba_mutex);
20440 			mutex_enter(&sata_mutex);
20441 			sata_event_pending |= SATA_EVNT_MAIN;
20442 			mutex_exit(&sata_mutex);
20443 		}
20444 	} else {
20445 		if (saddr->qual == SATA_ADDR_CPORT ||
20446 		    saddr->qual == SATA_ADDR_DCPORT) {
20447 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20448 			    saddr->cport)->cport_mutex);
20449 			cportinfo->cport_event_flags &=
20450 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
20451 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20452 			    saddr->cport)->cport_mutex);
20453 		} else {
20454 			/* sanity check */
20455 			if (SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) !=
20456 			    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
20457 			    saddr->cport) == NULL)
20458 				return;
20459 			if (SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
20460 			    saddr->pmport) == NULL)
20461 				return;
20462 
20463 			mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
20464 			    saddr->cport, saddr->pmport)->pmport_mutex);
20465 			SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
20466 			    saddr->pmport)->pmport_event_flags &=
20467 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
20468 			mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
20469 			    saddr->cport, saddr->pmport)->pmport_mutex);
20470 		}
20471 	}
20472 }
20473 
20474 /*
20475  * Device AutoOnline Event processing.
20476  * If attached device is to be onlined, an attempt is made to online this
20477  * device, but only if there is no lingering (old) target node present.
20478  * If the device cannot be onlined, the event flag is left intact,
20479  * so that event daemon may re-run this function later.
20480  *
20481  * This function cannot be called in interrupt context (it may sleep).
20482  *
20483  * NOTE: Processes cport events only, not port multiplier ports.
20484  */
20485 static void
20486 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
20487     sata_address_t *saddr)
20488 {
20489 	sata_cport_info_t *cportinfo;
20490 	sata_drive_info_t *sdinfo;
20491 	sata_device_t sata_device;
20492 	dev_info_t *tdip;
20493 
20494 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20495 	    "Processing port %d attached device auto-onlining", saddr->cport);
20496 
20497 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
20498 
20499 	/*
20500 	 * Check if device is present and recognized. If not, reset event.
20501 	 */
20502 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
20503 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
20504 		/* Nothing to online */
20505 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
20506 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20507 		    saddr->cport)->cport_mutex);
20508 		return;
20509 	}
20510 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
20511 
20512 	/*
20513 	 * Check if there is target node for this device and if it is in the
20514 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
20515 	 * the event for later processing.
20516 	 */
20517 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
20518 	    saddr->pmport);
20519 	if (tdip != NULL) {
20520 		/*
20521 		 * target node exists - check if it is target node of
20522 		 * a removed device.
20523 		 */
20524 		if (sata_check_device_removed(tdip) == B_TRUE) {
20525 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20526 			    "sata_process_device_autoonline: "
20527 			    "old device target node exists!", NULL);
20528 			/*
20529 			 * Event daemon will retry device onlining later.
20530 			 */
20531 			mutex_enter(&sata_hba_inst->satahba_mutex);
20532 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20533 			mutex_exit(&sata_hba_inst->satahba_mutex);
20534 			mutex_enter(&sata_mutex);
20535 			sata_event_pending |= SATA_EVNT_MAIN;
20536 			mutex_exit(&sata_mutex);
20537 			return;
20538 		}
20539 		/*
20540 		 * If the target node is not in the 'removed" state, assume
20541 		 * that it belongs to this device. There is nothing more to do,
20542 		 * but reset the event.
20543 		 */
20544 	} else {
20545 
20546 		/*
20547 		 * Try to online the device
20548 		 * If there is any reset-related event, remove it. We are
20549 		 * configuring the device and no state restoring is needed.
20550 		 */
20551 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20552 		    saddr->cport)->cport_mutex);
20553 		sata_device.satadev_addr = *saddr;
20554 		if (saddr->qual == SATA_ADDR_CPORT)
20555 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
20556 		else
20557 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
20558 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
20559 		if (sdinfo != NULL) {
20560 			if (sdinfo->satadrv_event_flags &
20561 			    (SATA_EVNT_DEVICE_RESET |
20562 			    SATA_EVNT_INPROC_DEVICE_RESET))
20563 				sdinfo->satadrv_event_flags = 0;
20564 			sdinfo->satadrv_event_flags |=
20565 			    SATA_EVNT_CLEAR_DEVICE_RESET;
20566 
20567 			/* Need to create a new target node. */
20568 			cportinfo->cport_tgtnode_clean = B_TRUE;
20569 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20570 			    saddr->cport)->cport_mutex);
20571 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
20572 			    sata_hba_inst, &sata_device.satadev_addr);
20573 			if (tdip == NULL) {
20574 				/*
20575 				 * Configure (onlining) failed.
20576 				 * We will NOT retry
20577 				 */
20578 				SATA_LOG_D((sata_hba_inst, CE_WARN,
20579 				    "sata_process_device_autoonline: "
20580 				    "configuring SATA device at port %d failed",
20581 				    saddr->cport));
20582 			}
20583 		} else {
20584 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20585 			    saddr->cport)->cport_mutex);
20586 		}
20587 
20588 	}
20589 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
20590 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
20591 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20592 	    saddr->cport)->cport_mutex);
20593 }
20594 
20595 
20596 static void
20597 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
20598     int hint)
20599 {
20600 	char ap[MAXPATHLEN];
20601 	nvlist_t *ev_attr_list = NULL;
20602 	int err;
20603 
20604 	/* Allocate and build sysevent attribute list */
20605 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
20606 	if (err != 0) {
20607 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20608 		    "sata_gen_sysevent: "
20609 		    "cannot allocate memory for sysevent attributes\n"));
20610 		return;
20611 	}
20612 	/* Add hint attribute */
20613 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
20614 	if (err != 0) {
20615 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20616 		    "sata_gen_sysevent: "
20617 		    "failed to add DR_HINT attr for sysevent"));
20618 		nvlist_free(ev_attr_list);
20619 		return;
20620 	}
20621 	/*
20622 	 * Add AP attribute.
20623 	 * Get controller pathname and convert it into AP pathname by adding
20624 	 * a target number.
20625 	 */
20626 	(void) snprintf(ap, MAXPATHLEN, "/devices");
20627 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
20628 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
20629 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
20630 
20631 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
20632 	if (err != 0) {
20633 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20634 		    "sata_gen_sysevent: "
20635 		    "failed to add DR_AP_ID attr for sysevent"));
20636 		nvlist_free(ev_attr_list);
20637 		return;
20638 	}
20639 
20640 	/* Generate/log sysevent */
20641 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
20642 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
20643 	if (err != DDI_SUCCESS) {
20644 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20645 		    "sata_gen_sysevent: "
20646 		    "cannot log sysevent, err code %x\n", err));
20647 	}
20648 
20649 	nvlist_free(ev_attr_list);
20650 }
20651 
20652 
20653 
20654 
20655 /*
20656  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
20657  */
20658 static void
20659 sata_set_device_removed(dev_info_t *tdip)
20660 {
20661 	int circ;
20662 
20663 	ASSERT(tdip != NULL);
20664 
20665 	ndi_devi_enter(tdip, &circ);
20666 	mutex_enter(&DEVI(tdip)->devi_lock);
20667 	DEVI_SET_DEVICE_REMOVED(tdip);
20668 	mutex_exit(&DEVI(tdip)->devi_lock);
20669 	ndi_devi_exit(tdip, circ);
20670 }
20671 
20672 
20673 /*
20674  * Set internal event instructing event daemon to try
20675  * to perform the target node cleanup.
20676  */
20677 static void
20678 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
20679     sata_address_t *saddr)
20680 {
20681 	if (saddr->qual == SATA_ADDR_CPORT ||
20682 	    saddr->qual == SATA_ADDR_DCPORT) {
20683 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20684 		    saddr->cport)->cport_mutex);
20685 		SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
20686 		    SATA_EVNT_TARGET_NODE_CLEANUP;
20687 		SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
20688 		    cport_tgtnode_clean = B_FALSE;
20689 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20690 		    saddr->cport)->cport_mutex);
20691 	} else {
20692 		mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
20693 		    saddr->cport, saddr->pmport)->pmport_mutex);
20694 		SATA_PMPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport,
20695 		    saddr->pmport) |= SATA_EVNT_TARGET_NODE_CLEANUP;
20696 		SATA_PMPORT_INFO(sata_hba_inst, saddr->cport, saddr->pmport)->
20697 		    pmport_tgtnode_clean = B_FALSE;
20698 		mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
20699 		    saddr->cport, saddr->pmport)->pmport_mutex);
20700 	}
20701 	mutex_enter(&sata_hba_inst->satahba_mutex);
20702 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20703 	mutex_exit(&sata_hba_inst->satahba_mutex);
20704 	mutex_enter(&sata_mutex);
20705 	sata_event_pending |= SATA_EVNT_MAIN;
20706 	mutex_exit(&sata_mutex);
20707 }
20708 
20709 
20710 /*
20711  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
20712  * i.e. check if the target node state indicates that it belongs to a removed
20713  * device.
20714  *
20715  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
20716  * B_FALSE otherwise.
20717  */
20718 static boolean_t
20719 sata_check_device_removed(dev_info_t *tdip)
20720 {
20721 	ASSERT(tdip != NULL);
20722 
20723 	if (DEVI_IS_DEVICE_REMOVED(tdip))
20724 		return (B_TRUE);
20725 	else
20726 		return (B_FALSE);
20727 }
20728 
20729 
20730 /*
20731  * Check for DMA error. Return B_TRUE if error, B_FALSE otherwise.
20732  */
20733 static boolean_t
20734 sata_check_for_dma_error(dev_info_t *dip, sata_pkt_txlate_t *spx)
20735 {
20736 	int fm_capability = ddi_fm_capable(dip);
20737 	ddi_fm_error_t de;
20738 
20739 	if (fm_capability & DDI_FM_DMACHK_CAPABLE) {
20740 		if (spx->txlt_buf_dma_handle != NULL) {
20741 			ddi_fm_dma_err_get(spx->txlt_buf_dma_handle, &de,
20742 			    DDI_FME_VERSION);
20743 			if (de.fme_status != DDI_SUCCESS)
20744 				return (B_TRUE);
20745 		}
20746 	}
20747 	return (B_FALSE);
20748 }
20749 
20750 
20751 /* ************************ FAULT INJECTTION **************************** */
20752 
20753 #ifdef SATA_INJECT_FAULTS
20754 
20755 static	uint32_t sata_fault_count = 0;
20756 static	uint32_t sata_fault_suspend_count = 0;
20757 
20758 /*
20759  * Inject sata pkt fault
20760  * It modifies returned values of the sata packet.
20761  * It returns immediately if:
20762  * pkt fault injection is not enabled (via sata_inject_fault,
20763  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
20764  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
20765  * pkt is not directed to specified fault controller/device
20766  * (sata_fault_ctrl_dev and sata_fault_device).
20767  * If fault controller is not specified, fault injection applies to all
20768  * controllers and devices.
20769  *
20770  * First argument is the pointer to the executed sata packet.
20771  * Second argument is a pointer to a value returned by the HBA tran_start
20772  * function.
20773  * Third argument specifies injected error. Injected sata packet faults
20774  * are the satapkt_reason values.
20775  * SATA_PKT_BUSY		-1	Not completed, busy
20776  * SATA_PKT_DEV_ERROR		1	Device reported error
20777  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
20778  * SATA_PKT_PORT_ERROR		3	Not completed, port error
20779  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
20780  * SATA_PKT_ABORTED		5	Aborted by request
20781  * SATA_PKT_TIMEOUT		6	Operation timeut
20782  * SATA_PKT_RESET		7	Aborted by reset request
20783  *
20784  * Additional global variables affecting the execution:
20785  *
20786  * sata_inject_fault_count variable specifies number of times in row the
20787  * error is injected. Value of -1 specifies permanent fault, ie. every time
20788  * the fault injection point is reached, the fault is injected and a pause
20789  * between fault injection specified by sata_inject_fault_pause_count is
20790  * ignored). Fault injection routine decrements sata_inject_fault_count
20791  * (if greater than zero) until it reaches 0. No fault is injected when
20792  * sata_inject_fault_count is 0 (zero).
20793  *
20794  * sata_inject_fault_pause_count variable specifies number of times a fault
20795  * injection is bypassed (pause between fault injections).
20796  * If set to 0, a fault is injected only a number of times specified by
20797  * sata_inject_fault_count.
20798  *
20799  * The fault counts are static, so for periodic errors they have to be manually
20800  * reset to start repetition sequence from scratch.
20801  * If the original value returned by the HBA tran_start function is not
20802  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
20803  * is injected (to avoid masking real problems);
20804  *
20805  * NOTE: In its current incarnation, this function should be invoked only for
20806  * commands executed in SYNCHRONOUS mode.
20807  */
20808 
20809 
20810 static void
20811 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
20812 {
20813 
20814 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
20815 		return;
20816 
20817 	if (sata_inject_fault_count == 0)
20818 		return;
20819 
20820 	if (fault == 0)
20821 		return;
20822 
20823 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
20824 		return;
20825 
20826 	if (sata_fault_ctrl != NULL) {
20827 		sata_pkt_txlate_t *spx =
20828 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
20829 
20830 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
20831 		    spx->txlt_sata_hba_inst->satahba_dip)
20832 			return;
20833 
20834 		if (sata_fault_device.satadev_addr.cport !=
20835 		    spkt->satapkt_device.satadev_addr.cport ||
20836 		    sata_fault_device.satadev_addr.pmport !=
20837 		    spkt->satapkt_device.satadev_addr.pmport ||
20838 		    sata_fault_device.satadev_addr.qual !=
20839 		    spkt->satapkt_device.satadev_addr.qual)
20840 			return;
20841 	}
20842 
20843 	/* Modify pkt return parameters */
20844 	if (*rval != SATA_TRAN_ACCEPTED ||
20845 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
20846 		sata_fault_count = 0;
20847 		sata_fault_suspend_count = 0;
20848 		return;
20849 	}
20850 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
20851 		/* Pause in the injection */
20852 		sata_fault_suspend_count -= 1;
20853 		return;
20854 	}
20855 
20856 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
20857 		/*
20858 		 * Init inject fault cycle. If fault count is set to -1,
20859 		 * it is a permanent fault.
20860 		 */
20861 		if (sata_inject_fault_count != -1) {
20862 			sata_fault_count = sata_inject_fault_count;
20863 			sata_fault_suspend_count =
20864 			    sata_inject_fault_pause_count;
20865 			if (sata_fault_suspend_count == 0)
20866 				sata_inject_fault_count = 0;
20867 		}
20868 	}
20869 
20870 	if (sata_fault_count != 0)
20871 		sata_fault_count -= 1;
20872 
20873 	switch (fault) {
20874 	case SATA_PKT_BUSY:
20875 		*rval = SATA_TRAN_BUSY;
20876 		spkt->satapkt_reason = SATA_PKT_BUSY;
20877 		break;
20878 
20879 	case SATA_PKT_QUEUE_FULL:
20880 		*rval = SATA_TRAN_QUEUE_FULL;
20881 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
20882 		break;
20883 
20884 	case SATA_PKT_CMD_UNSUPPORTED:
20885 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
20886 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
20887 		break;
20888 
20889 	case SATA_PKT_PORT_ERROR:
20890 		/* This is "rejected" command */
20891 		*rval = SATA_TRAN_PORT_ERROR;
20892 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
20893 		/* Additional error setup could be done here - port state */
20894 		break;
20895 
20896 	case SATA_PKT_DEV_ERROR:
20897 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
20898 		/*
20899 		 * Additional error setup could be done here
20900 		 */
20901 		break;
20902 
20903 	case SATA_PKT_ABORTED:
20904 		spkt->satapkt_reason = SATA_PKT_ABORTED;
20905 		break;
20906 
20907 	case SATA_PKT_TIMEOUT:
20908 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
20909 		/* Additional error setup could be done here */
20910 		break;
20911 
20912 	case SATA_PKT_RESET:
20913 		spkt->satapkt_reason = SATA_PKT_RESET;
20914 		/*
20915 		 * Additional error setup could be done here - device reset
20916 		 */
20917 		break;
20918 
20919 	default:
20920 		break;
20921 	}
20922 }
20923 
20924 #endif
20925 
20926 /*
20927  * SATA Trace Ring Buffer
20928  * ----------------------
20929  *
20930  * Overview
20931  *
20932  * The SATA trace ring buffer is a ring buffer created and managed by
20933  * the SATA framework module that can be used by any module or driver
20934  * within the SATA framework to store debug messages.
20935  *
20936  * Ring Buffer Interfaces:
20937  *
20938  *	sata_vtrace_debug()	<-- Adds debug message to ring buffer
20939  *	sata_trace_debug()	<-- Wraps varargs into sata_vtrace_debug()
20940  *
20941  *	Note that the sata_trace_debug() interface was created to give
20942  *	consumers the flexibilty of sending debug messages to ring buffer
20943  *	as variable arguments.  Consumers can send type va_list debug
20944  *	messages directly to sata_vtrace_debug(). The sata_trace_debug()
20945  *	and sata_vtrace_debug() relationship is similar to that of
20946  *	cmn_err(9F) and vcmn_err(9F).
20947  *
20948  * Below is a diagram of the SATA trace ring buffer interfaces and
20949  * sample consumers:
20950  *
20951  * +---------------------------------+
20952  * |    o  o  SATA Framework Module  |
20953  * | o  SATA  o     +------------------+      +------------------+
20954  * |o   Trace  o <--|sata_vtrace_debug/|<-----|SATA HBA Driver #1|
20955  * |o   R-Buf  o    |sata_trace_debug  |<--+  +------------------+
20956  * | o        o     +------------------+   |  +------------------+
20957  * |    o  o                ^        |     +--|SATA HBA Driver #2|
20958  * |                        |        |        +------------------+
20959  * |           +------------------+  |
20960  * |           |SATA Debug Message|  |
20961  * |           +------------------+  |
20962  * +---------------------------------+
20963  *
20964  * Supporting Routines:
20965  *
20966  *	sata_trace_rbuf_alloc()	<-- Initializes ring buffer
20967  *	sata_trace_rbuf_free()	<-- Destroys ring buffer
20968  *	sata_trace_dmsg_alloc() <-- Creates or reuses buffer in ring buffer
20969  *	sata_trace_dmsg_free()	<-- Destroys content of ring buffer
20970  *
20971  * The default SATA trace ring buffer size is defined by DMSG_RING_SIZE.
20972  * The ring buffer size can be adjusted by setting dmsg_ring_size in
20973  * /etc/system to desired size in unit of bytes.
20974  *
20975  * The individual debug message size in the ring buffer is restricted
20976  * to DMSG_BUF_SIZE.
20977  */
20978 void
20979 sata_vtrace_debug(dev_info_t *dip, const char *fmt, va_list ap)
20980 {
20981 	sata_trace_dmsg_t *dmsg;
20982 
20983 	if (sata_debug_rbuf == NULL) {
20984 		return;
20985 	}
20986 
20987 	/*
20988 	 * If max size of ring buffer is smaller than size
20989 	 * required for one debug message then just return
20990 	 * since we have no room for the debug message.
20991 	 */
20992 	if (sata_debug_rbuf->maxsize < (sizeof (sata_trace_dmsg_t))) {
20993 		return;
20994 	}
20995 
20996 	mutex_enter(&sata_debug_rbuf->lock);
20997 
20998 	/* alloc or reuse on ring buffer */
20999 	dmsg = sata_trace_dmsg_alloc();
21000 
21001 	if (dmsg == NULL) {
21002 		/* resource allocation failed */
21003 		mutex_exit(&sata_debug_rbuf->lock);
21004 		return;
21005 	}
21006 
21007 	dmsg->dip = dip;
21008 	gethrestime(&dmsg->timestamp);
21009 
21010 	(void) vsnprintf(dmsg->buf, sizeof (dmsg->buf), fmt, ap);
21011 
21012 	mutex_exit(&sata_debug_rbuf->lock);
21013 }
21014 
21015 void
21016 sata_trace_debug(dev_info_t *dip, const char *fmt, ...)
21017 {
21018 	va_list ap;
21019 
21020 	va_start(ap, fmt);
21021 	sata_vtrace_debug(dip, fmt, ap);
21022 	va_end(ap);
21023 }
21024 
21025 /*
21026  * This routine is used to manage debug messages
21027  * on ring buffer.
21028  */
21029 static sata_trace_dmsg_t *
21030 sata_trace_dmsg_alloc(void)
21031 {
21032 	sata_trace_dmsg_t *dmsg_alloc, *dmsg = sata_debug_rbuf->dmsgp;
21033 
21034 	if (sata_debug_rbuf->looped == TRUE) {
21035 		sata_debug_rbuf->dmsgp = dmsg->next;
21036 		return (sata_debug_rbuf->dmsgp);
21037 	}
21038 
21039 	/*
21040 	 * If we're looping for the first time,
21041 	 * connect the ring.
21042 	 */
21043 	if (((sata_debug_rbuf->size + (sizeof (sata_trace_dmsg_t))) >
21044 	    sata_debug_rbuf->maxsize) && (sata_debug_rbuf->dmsgh != NULL)) {
21045 		dmsg->next = sata_debug_rbuf->dmsgh;
21046 		sata_debug_rbuf->dmsgp = sata_debug_rbuf->dmsgh;
21047 		sata_debug_rbuf->looped = TRUE;
21048 		return (sata_debug_rbuf->dmsgp);
21049 	}
21050 
21051 	/* If we've gotten this far then memory allocation is needed */
21052 	dmsg_alloc = kmem_zalloc(sizeof (sata_trace_dmsg_t), KM_NOSLEEP);
21053 	if (dmsg_alloc == NULL) {
21054 		sata_debug_rbuf->allocfailed++;
21055 		return (dmsg_alloc);
21056 	} else {
21057 		sata_debug_rbuf->size += sizeof (sata_trace_dmsg_t);
21058 	}
21059 
21060 	if (sata_debug_rbuf->dmsgp != NULL) {
21061 		dmsg->next = dmsg_alloc;
21062 		sata_debug_rbuf->dmsgp = dmsg->next;
21063 		return (sata_debug_rbuf->dmsgp);
21064 	} else {
21065 		/*
21066 		 * We should only be here if we're initializing
21067 		 * the ring buffer.
21068 		 */
21069 		if (sata_debug_rbuf->dmsgh == NULL) {
21070 			sata_debug_rbuf->dmsgh = dmsg_alloc;
21071 		} else {
21072 			/* Something is wrong */
21073 			kmem_free(dmsg_alloc, sizeof (sata_trace_dmsg_t));
21074 			return (NULL);
21075 		}
21076 
21077 		sata_debug_rbuf->dmsgp = dmsg_alloc;
21078 		return (sata_debug_rbuf->dmsgp);
21079 	}
21080 }
21081 
21082 
21083 /*
21084  * Free all messages on debug ring buffer.
21085  */
21086 static void
21087 sata_trace_dmsg_free(void)
21088 {
21089 	sata_trace_dmsg_t *dmsg_next, *dmsg = sata_debug_rbuf->dmsgh;
21090 
21091 	while (dmsg != NULL) {
21092 		dmsg_next = dmsg->next;
21093 		kmem_free(dmsg, sizeof (sata_trace_dmsg_t));
21094 
21095 		/*
21096 		 * If we've looped around the ring than we're done.
21097 		 */
21098 		if (dmsg_next == sata_debug_rbuf->dmsgh) {
21099 			break;
21100 		} else {
21101 			dmsg = dmsg_next;
21102 		}
21103 	}
21104 }
21105 
21106 
21107 /*
21108  * This function can block
21109  */
21110 static void
21111 sata_trace_rbuf_alloc(void)
21112 {
21113 	sata_debug_rbuf = kmem_zalloc(sizeof (sata_trace_rbuf_t), KM_SLEEP);
21114 
21115 	mutex_init(&sata_debug_rbuf->lock, NULL, MUTEX_DRIVER, NULL);
21116 
21117 	if (dmsg_ring_size > 0) {
21118 		sata_debug_rbuf->maxsize = (size_t)dmsg_ring_size;
21119 	}
21120 }
21121 
21122 
21123 static void
21124 sata_trace_rbuf_free(void)
21125 {
21126 	sata_trace_dmsg_free();
21127 	mutex_destroy(&sata_debug_rbuf->lock);
21128 	kmem_free(sata_debug_rbuf, sizeof (sata_trace_rbuf_t));
21129 }
21130 
21131 /*
21132  * If SATA_DEBUG is not defined then this routine is called instead
21133  * of sata_log() via the SATA_LOG_D macro.
21134  */
21135 static void
21136 sata_trace_log(sata_hba_inst_t *sata_hba_inst, uint_t level,
21137     const char *fmt, ...)
21138 {
21139 #ifndef __lock_lint
21140 	_NOTE(ARGUNUSED(level))
21141 #endif
21142 
21143 	dev_info_t *dip = NULL;
21144 	va_list ap;
21145 
21146 	if (sata_hba_inst != NULL) {
21147 		dip = SATA_DIP(sata_hba_inst);
21148 	}
21149 
21150 	va_start(ap, fmt);
21151 	sata_vtrace_debug(dip, fmt, ap);
21152 	va_end(ap);
21153 }
21154