xref: /illumos-gate/usr/src/uts/common/io/sata/impl/sata.c (revision 5bb0bdfe588c5df0f63ff8ac292cd608a5f4492a)
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 				    NULL) {
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 			    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
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 				    NULL) {
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 			    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
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) == NULL) {
3489 				return (TRAN_BUSY);
3490 			}
3491 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3492 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3493 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3494 			/* Scheduling the callback failed */
3495 			return (TRAN_BUSY);
3496 		}
3497 	}
3498 	return (TRAN_ACCEPT);
3499 }
3500 
3501 /*
3502  * Scsi response set up for check condition with special sense key
3503  * and additional sense code.
3504  *
3505  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3506  */
3507 static int
3508 sata_txlt_check_condition(sata_pkt_txlate_t *spx, uchar_t key, uchar_t code)
3509 {
3510 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3511 	int cport = SATA_TXLT_CPORT(spx);
3512 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3513 	struct scsi_extended_sense *sense;
3514 
3515 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3516 	scsipkt->pkt_reason = CMD_CMPLT;
3517 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3518 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3519 
3520 	*scsipkt->pkt_scbp = STATUS_CHECK;
3521 
3522 	sense = sata_arq_sense(spx);
3523 	sense->es_key = key;
3524 	sense->es_add_code = code;
3525 
3526 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3527 
3528 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3529 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3530 
3531 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3532 	    scsipkt->pkt_comp != NULL) {
3533 		/* scsi callback required */
3534 		if (servicing_interrupt()) {
3535 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3536 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3537 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3538 				return (TRAN_BUSY);
3539 			}
3540 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3541 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3542 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3543 			/* Scheduling the callback failed */
3544 			return (TRAN_BUSY);
3545 		}
3546 	}
3547 	return (TRAN_ACCEPT);
3548 }
3549 
3550 /*
3551  * Scsi response setup for
3552  * emulated non-data command that requires no action/return data
3553  *
3554  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3555  */
3556 static	int
3557 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3558 {
3559 	int rval;
3560 	int reason;
3561 	kmutex_t *cport_mutex =  &(SATA_TXLT_CPORT_MUTEX(spx));
3562 
3563 	mutex_enter(cport_mutex);
3564 
3565 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3566 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3567 		mutex_exit(cport_mutex);
3568 		return (rval);
3569 	}
3570 	mutex_exit(cport_mutex);
3571 
3572 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3573 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3574 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3575 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3576 
3577 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3578 	    "Scsi_pkt completion reason %x\n",
3579 	    spx->txlt_scsi_pkt->pkt_reason);
3580 
3581 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3582 	    spx->txlt_scsi_pkt->pkt_comp != NULL) {
3583 		/* scsi callback required */
3584 		if (servicing_interrupt()) {
3585 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3586 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3587 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3588 				return (TRAN_BUSY);
3589 			}
3590 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3591 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3592 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3593 			/* Scheduling the callback failed */
3594 			return (TRAN_BUSY);
3595 		}
3596 	}
3597 	return (TRAN_ACCEPT);
3598 }
3599 
3600 
3601 /*
3602  * SATA translate command: Inquiry / Identify Device
3603  * Use cached Identify Device data for now, rather than issuing actual
3604  * Device Identify cmd request. If device is detached and re-attached,
3605  * asynchronous event processing should fetch and refresh Identify Device
3606  * data.
3607  * VPD pages supported now:
3608  * Vital Product Data page
3609  * Unit Serial Number page
3610  * Block Device Characteristics Page
3611  * ATA Information Page
3612  *
3613  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3614  */
3615 
3616 #define	EVPD			1	/* Extended Vital Product Data flag */
3617 #define	CMDDT			2	/* Command Support Data - Obsolete */
3618 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VPD Pages Page Code */
3619 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3620 #define	INQUIRY_BDC_PAGE	0xB1	/* Block Device Characteristics Page */
3621 					/* Code */
3622 #define	INQUIRY_ATA_INFO_PAGE	0x89	/* ATA Information Page Code */
3623 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3624 
3625 static int
3626 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3627 {
3628 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3629 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3630 	sata_drive_info_t *sdinfo;
3631 	struct scsi_extended_sense *sense;
3632 	int count;
3633 	uint8_t *p;
3634 	int i, j;
3635 	uint8_t page_buf[1024]; /* Max length */
3636 	int rval, reason;
3637 	ushort_t rate;
3638 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
3639 
3640 	mutex_enter(cport_mutex);
3641 
3642 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3643 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3644 		mutex_exit(cport_mutex);
3645 		return (rval);
3646 	}
3647 
3648 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3649 	    &spx->txlt_sata_pkt->satapkt_device);
3650 
3651 	ASSERT(sdinfo != NULL);
3652 
3653 	scsipkt->pkt_reason = CMD_CMPLT;
3654 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3655 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3656 
3657 	/* Reject not supported request */
3658 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3659 		*scsipkt->pkt_scbp = STATUS_CHECK;
3660 		sense = sata_arq_sense(spx);
3661 		sense->es_key = KEY_ILLEGAL_REQUEST;
3662 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3663 		goto done;
3664 	}
3665 
3666 	/* Valid Inquiry request */
3667 	*scsipkt->pkt_scbp = STATUS_GOOD;
3668 
3669 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3670 
3671 		/*
3672 		 * Because it is fully emulated command storing data
3673 		 * programatically in the specified buffer, release
3674 		 * preallocated DMA resources before storing data in the buffer,
3675 		 * so no unwanted DMA sync would take place.
3676 		 */
3677 		sata_scsi_dmafree(NULL, scsipkt);
3678 
3679 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3680 			/* Standard Inquiry Data request */
3681 			struct scsi_inquiry inq;
3682 			unsigned int bufsize;
3683 
3684 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3685 			    sdinfo, (uint8_t *)&inq);
3686 			/* Copy no more than requested */
3687 			count = MIN(bp->b_bcount,
3688 			    sizeof (struct scsi_inquiry));
3689 			bufsize = scsipkt->pkt_cdbp[4];
3690 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3691 			count = MIN(count, bufsize);
3692 			bcopy(&inq, bp->b_un.b_addr, count);
3693 
3694 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3695 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3696 			    bufsize - count : 0;
3697 		} else {
3698 			/*
3699 			 * peripheral_qualifier = 0;
3700 			 *
3701 			 * We are dealing only with HD and will be
3702 			 * dealing with CD/DVD devices soon
3703 			 */
3704 			uint8_t peripheral_device_type =
3705 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3706 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3707 
3708 			bzero(page_buf, sizeof (page_buf));
3709 
3710 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3711 			case INQUIRY_SUP_VPD_PAGE:
3712 				/*
3713 				 * Request for supported Vital Product Data
3714 				 * pages.
3715 				 */
3716 				page_buf[0] = peripheral_device_type;
3717 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3718 				page_buf[2] = 0;
3719 				page_buf[3] = 4; /* page length */
3720 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3721 				page_buf[5] = INQUIRY_USN_PAGE;
3722 				page_buf[6] = INQUIRY_BDC_PAGE;
3723 				page_buf[7] = INQUIRY_ATA_INFO_PAGE;
3724 				/* Copy no more than requested */
3725 				count = MIN(bp->b_bcount, 8);
3726 				bcopy(page_buf, bp->b_un.b_addr, count);
3727 				break;
3728 
3729 			case INQUIRY_USN_PAGE:
3730 				/*
3731 				 * Request for Unit Serial Number page.
3732 				 * Set-up the page.
3733 				 */
3734 				page_buf[0] = peripheral_device_type;
3735 				page_buf[1] = INQUIRY_USN_PAGE;
3736 				page_buf[2] = 0;
3737 				/* remaining page length */
3738 				page_buf[3] = SATA_ID_SERIAL_LEN;
3739 
3740 				/*
3741 				 * Copy serial number from Identify Device data
3742 				 * words into the inquiry page and swap bytes
3743 				 * when necessary.
3744 				 */
3745 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3746 #ifdef	_LITTLE_ENDIAN
3747 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3748 #else
3749 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3750 #endif
3751 				/*
3752 				 * Least significant character of the serial
3753 				 * number shall appear as the last byte,
3754 				 * according to SBC-3 spec.
3755 				 * Count trailing spaces to determine the
3756 				 * necessary shift length.
3757 				 */
3758 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3759 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3760 					if (*(p - j) != '\0' &&
3761 					    *(p - j) != '\040')
3762 						break;
3763 				}
3764 
3765 				/*
3766 				 * Shift SN string right, so that the last
3767 				 * non-blank character would appear in last
3768 				 * byte of SN field in the page.
3769 				 * 'j' is the shift length.
3770 				 */
3771 				for (i = 0;
3772 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3773 				    i++, p--)
3774 					*p = *(p - j);
3775 
3776 				/*
3777 				 * Add leading spaces - same number as the
3778 				 * shift size
3779 				 */
3780 				for (; j > 0; j--)
3781 					page_buf[4 + j - 1] = '\040';
3782 
3783 				count = MIN(bp->b_bcount,
3784 				    SATA_ID_SERIAL_LEN + 4);
3785 				bcopy(page_buf, bp->b_un.b_addr, count);
3786 				break;
3787 
3788 			case INQUIRY_BDC_PAGE:
3789 				/*
3790 				 * Request for Block Device Characteristics
3791 				 * page.  Set-up the page.
3792 				 */
3793 				page_buf[0] = peripheral_device_type;
3794 				page_buf[1] = INQUIRY_BDC_PAGE;
3795 				page_buf[2] = 0;
3796 				/* remaining page length */
3797 				page_buf[3] = SATA_ID_BDC_LEN;
3798 
3799 				rate = sdinfo->satadrv_id.ai_medrotrate;
3800 				page_buf[4] = (rate >> 8) & 0xff;
3801 				page_buf[5] = rate & 0xff;
3802 				page_buf[6] = 0;
3803 				page_buf[7] = sdinfo->satadrv_id.
3804 				    ai_nomformfactor & 0xf;
3805 
3806 				count = MIN(bp->b_bcount,
3807 				    SATA_ID_BDC_LEN + 4);
3808 				bcopy(page_buf, bp->b_un.b_addr, count);
3809 				break;
3810 
3811 			case INQUIRY_ATA_INFO_PAGE:
3812 				/*
3813 				 * Request for ATA Information page.
3814 				 */
3815 				page_buf[0] = peripheral_device_type;
3816 				page_buf[1] = INQUIRY_ATA_INFO_PAGE;
3817 				page_buf[2] = (SATA_ID_ATA_INFO_LEN >> 8) &
3818 				    0xff;
3819 				page_buf[3] = SATA_ID_ATA_INFO_LEN & 0xff;
3820 				/* page_buf[4-7] reserved */
3821 #ifdef  _LITTLE_ENDIAN
3822 				bcopy("ATA     ", &page_buf[8], 8);
3823 				swab(sdinfo->satadrv_id.ai_model,
3824 				    &page_buf[16], 16);
3825 				if (strncmp(&sdinfo->satadrv_id.ai_fw[4],
3826 				    "    ", 4) == 0) {
3827 					swab(sdinfo->satadrv_id.ai_fw,
3828 					    &page_buf[32], 4);
3829 				} else {
3830 					swab(&sdinfo->satadrv_id.ai_fw[4],
3831 					    &page_buf[32], 4);
3832 				}
3833 #else   /* _LITTLE_ENDIAN */
3834 				bcopy("ATA     ", &page_buf[8], 8);
3835 				bcopy(sdinfo->satadrv_id.ai_model,
3836 				    &page_buf[16], 16);
3837 				if (strncmp(&sdinfo->satadrv_id.ai_fw[4],
3838 				    "    ", 4) == 0) {
3839 					bcopy(sdinfo->satadrv_id.ai_fw,
3840 					    &page_buf[32], 4);
3841 				} else {
3842 					bcopy(&sdinfo->satadrv_id.ai_fw[4],
3843 					    &page_buf[32], 4);
3844 				}
3845 #endif  /* _LITTLE_ENDIAN */
3846 				/*
3847 				 * page_buf[36-55] which defines the device
3848 				 * signature is not defined at this
3849 				 * time.
3850 				 */
3851 
3852 				/* Set the command code */
3853 				if (sdinfo->satadrv_type ==
3854 				    SATA_DTYPE_ATADISK) {
3855 					page_buf[56] = SATAC_ID_DEVICE;
3856 				} else if (sdinfo->satadrv_type ==
3857 				    SATA_DTYPE_ATAPI) {
3858 					page_buf[56] = SATAC_ID_PACKET_DEVICE;
3859 				}
3860 				/*
3861 				 * If the command code, page_buf[56], is not
3862 				 * zero and if one of the identify commands
3863 				 * succeeds, return the identify data.
3864 				 */
3865 				if ((page_buf[56] != 0) &&
3866 				    (sata_fetch_device_identify_data(
3867 				    spx->txlt_sata_hba_inst, sdinfo) ==
3868 				    SATA_SUCCESS)) {
3869 					bcopy(&sdinfo->satadrv_id,
3870 					    &page_buf[60], sizeof (sata_id_t));
3871 				}
3872 
3873 				/* Need to copy out the page_buf to bp */
3874 				count = MIN(bp->b_bcount,
3875 				    SATA_ID_ATA_INFO_LEN + 4);
3876 				bcopy(page_buf, bp->b_un.b_addr, count);
3877 				break;
3878 
3879 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3880 				/*
3881 				 * We may want to implement this page, when
3882 				 * identifiers are common for SATA devices
3883 				 * But not now.
3884 				 */
3885 				/*FALLTHROUGH*/
3886 
3887 			default:
3888 				/* Request for unsupported VPD page */
3889 				*scsipkt->pkt_scbp = STATUS_CHECK;
3890 				sense = sata_arq_sense(spx);
3891 				sense->es_key = KEY_ILLEGAL_REQUEST;
3892 				sense->es_add_code =
3893 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3894 				goto done;
3895 			}
3896 		}
3897 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3898 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3899 		    scsipkt->pkt_cdbp[4] - count : 0;
3900 	}
3901 done:
3902 	mutex_exit(cport_mutex);
3903 
3904 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3905 	    "Scsi_pkt completion reason %x\n",
3906 	    scsipkt->pkt_reason);
3907 
3908 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3909 	    scsipkt->pkt_comp != NULL) {
3910 		/* scsi callback required */
3911 		if (servicing_interrupt()) {
3912 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3913 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3914 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3915 				return (TRAN_BUSY);
3916 			}
3917 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3918 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3919 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3920 			/* Scheduling the callback failed */
3921 			return (TRAN_BUSY);
3922 		}
3923 	}
3924 	return (TRAN_ACCEPT);
3925 }
3926 
3927 /*
3928  * SATA translate command: Request Sense.
3929  *
3930  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3931  * At the moment this is an emulated command (ATA version for SATA hard disks).
3932  * May be translated into Check Power Mode command in the future.
3933  *
3934  * Note: There is a mismatch between already implemented Informational
3935  * Exception Mode Select page 0x1C and this function.
3936  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3937  * NO SENSE and set additional sense code to the exception code - this is not
3938  * implemented here.
3939  */
3940 static int
3941 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3942 {
3943 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3944 	struct scsi_extended_sense sense;
3945 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3946 	sata_drive_info_t *sdinfo;
3947 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3948 	int rval, reason, power_state = 0;
3949 	kmutex_t *cport_mutex;
3950 
3951 	cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
3952 	mutex_enter(cport_mutex);
3953 
3954 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3955 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3956 		mutex_exit(cport_mutex);
3957 		return (rval);
3958 	}
3959 
3960 	scsipkt->pkt_reason = CMD_CMPLT;
3961 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3962 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3963 	*scsipkt->pkt_scbp = STATUS_GOOD;
3964 
3965 	/*
3966 	 * when CONTROL field's NACA bit == 1
3967 	 * return ILLEGAL_REQUEST
3968 	 */
3969 	if (scsipkt->pkt_cdbp[5] & CTL_BYTE_NACA_MASK) {
3970 		mutex_exit(cport_mutex);
3971 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3972 		    SD_SCSI_ASC_CMD_SEQUENCE_ERR));
3973 	}
3974 
3975 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3976 	    &spx->txlt_sata_pkt->satapkt_device);
3977 	ASSERT(sdinfo != NULL);
3978 
3979 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3980 
3981 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3982 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3983 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3984 	if (sata_hba_start(spx, &rval) != 0) {
3985 		mutex_exit(cport_mutex);
3986 		return (rval);
3987 	}
3988 	if (scmd->satacmd_error_reg != 0) {
3989 		mutex_exit(cport_mutex);
3990 		return (sata_txlt_check_condition(spx, KEY_NO_SENSE,
3991 		    SD_SCSI_ASC_NO_ADD_SENSE));
3992 	}
3993 
3994 	switch (scmd->satacmd_sec_count_lsb) {
3995 	case SATA_PWRMODE_STANDBY: /* device in standby mode */
3996 		if (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)
3997 			power_state = SATA_POWER_STOPPED;
3998 		else {
3999 			power_state = SATA_POWER_STANDBY;
4000 			sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4001 		}
4002 		break;
4003 	case SATA_PWRMODE_IDLE: /* device in idle mode */
4004 		power_state = SATA_POWER_IDLE;
4005 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4006 		break;
4007 	case SATA_PWRMODE_ACTIVE: /* device in active or idle mode */
4008 	default:		  /* 0x40, 0x41 active mode */
4009 		if (sdinfo->satadrv_power_level == SATA_POWER_IDLE)
4010 			power_state = SATA_POWER_IDLE;
4011 		else {
4012 			power_state = SATA_POWER_ACTIVE;
4013 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4014 		}
4015 		break;
4016 	}
4017 
4018 	mutex_exit(cport_mutex);
4019 
4020 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4021 		/*
4022 		 * Because it is fully emulated command storing data
4023 		 * programatically in the specified buffer, release
4024 		 * preallocated DMA resources before storing data in the buffer,
4025 		 * so no unwanted DMA sync would take place.
4026 		 */
4027 		int count = MIN(bp->b_bcount,
4028 		    sizeof (struct scsi_extended_sense));
4029 		sata_scsi_dmafree(NULL, scsipkt);
4030 		bzero(&sense, sizeof (struct scsi_extended_sense));
4031 		sense.es_valid = 0;	/* Valid LBA */
4032 		sense.es_class = 7;	/* Response code 0x70 - current err */
4033 		sense.es_key = KEY_NO_SENSE;
4034 		sense.es_add_len = 6;	/* Additional length */
4035 		/* Copy no more than requested */
4036 		bcopy(&sense, bp->b_un.b_addr, count);
4037 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4038 		scsipkt->pkt_resid = 0;
4039 		switch (power_state) {
4040 		case SATA_POWER_IDLE:
4041 		case SATA_POWER_STANDBY:
4042 			sense.es_add_code =
4043 			    SD_SCSI_ASC_LOW_POWER_CONDITION_ON;
4044 			break;
4045 		case SATA_POWER_STOPPED:
4046 			sense.es_add_code = SD_SCSI_ASC_NO_ADD_SENSE;
4047 			break;
4048 		case SATA_POWER_ACTIVE:
4049 		default:
4050 			break;
4051 		}
4052 	}
4053 
4054 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4055 	    "Scsi_pkt completion reason %x\n",
4056 	    scsipkt->pkt_reason);
4057 
4058 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4059 	    scsipkt->pkt_comp != NULL) {
4060 		/* scsi callback required */
4061 		if (servicing_interrupt()) {
4062 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4063 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4064 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4065 				return (TRAN_BUSY);
4066 			}
4067 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4068 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4069 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4070 			/* Scheduling the callback failed */
4071 			return (TRAN_BUSY);
4072 		}
4073 	}
4074 	return (TRAN_ACCEPT);
4075 }
4076 
4077 /*
4078  * SATA translate command: Test Unit Ready
4079  * (ATA version for SATA hard disks).
4080  * It is translated into the Check Power Mode command.
4081  *
4082  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4083  */
4084 static int
4085 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
4086 {
4087 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4088 	struct scsi_extended_sense *sense;
4089 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4090 	sata_drive_info_t *sdinfo;
4091 	int power_state;
4092 	int rval, reason;
4093 	kmutex_t *cport_mutex =  &(SATA_TXLT_CPORT_MUTEX(spx));
4094 
4095 	mutex_enter(cport_mutex);
4096 
4097 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4098 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4099 		mutex_exit(cport_mutex);
4100 		return (rval);
4101 	}
4102 
4103 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4104 	    &spx->txlt_sata_pkt->satapkt_device);
4105 	ASSERT(sdinfo != NULL);
4106 
4107 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
4108 
4109 	/* send CHECK POWER MODE command */
4110 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4111 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4112 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4113 	if (sata_hba_start(spx, &rval) != 0) {
4114 		mutex_exit(cport_mutex);
4115 		return (rval);
4116 	}
4117 
4118 	if (scmd->satacmd_error_reg != 0) {
4119 		mutex_exit(cport_mutex);
4120 		return (sata_txlt_check_condition(spx, KEY_NOT_READY,
4121 		    SD_SCSI_ASC_LU_NOT_RESPONSE));
4122 	}
4123 
4124 	power_state = scmd->satacmd_sec_count_lsb;
4125 
4126 	/*
4127 	 * return NOT READY when device in STOPPED mode
4128 	 */
4129 	if (power_state == SATA_PWRMODE_STANDBY &&
4130 	    sdinfo->satadrv_power_level == SATA_POWER_STOPPED) {
4131 		*scsipkt->pkt_scbp = STATUS_CHECK;
4132 		sense = sata_arq_sense(spx);
4133 		sense->es_key = KEY_NOT_READY;
4134 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
4135 	} else {
4136 		/*
4137 		 * For other power mode, return GOOD status
4138 		 */
4139 		*scsipkt->pkt_scbp = STATUS_GOOD;
4140 	}
4141 
4142 	scsipkt->pkt_reason = CMD_CMPLT;
4143 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4144 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4145 
4146 	mutex_exit(cport_mutex);
4147 
4148 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4149 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4150 
4151 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4152 	    scsipkt->pkt_comp != NULL) {
4153 		/* scsi callback required */
4154 		if (servicing_interrupt()) {
4155 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4156 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4157 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4158 				return (TRAN_BUSY);
4159 			}
4160 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4161 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4162 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4163 			/* Scheduling the callback failed */
4164 			return (TRAN_BUSY);
4165 		}
4166 	}
4167 
4168 	return (TRAN_ACCEPT);
4169 }
4170 
4171 /*
4172  * SATA translate command: Start Stop Unit
4173  * Translation depends on a command:
4174  *
4175  * Power condition bits will be supported
4176  * and the power level should be maintained by SATL,
4177  * When SATL received a command, it will check the
4178  * power level firstly, and return the status according
4179  * to SAT2 v2.6 and SAT-2 Standby Modifications
4180  *
4181  * SPC-4/SBC-3      SATL    ATA power condition  SATL      SPC/SBC
4182  * -----------------------------------------------------------------------
4183  * SSU_PC1 Active   <==>     ATA  Active         <==>     SSU:start_bit =1
4184  * SSU_PC2 Idle     <==>     ATA  Idle           <==>     N/A
4185  * SSU_PC3 Standby  <==>     ATA  Standby        <==>     N/A
4186  * SSU_PC4 Stopped  <==>     ATA  Standby        <==>     SSU:start_bit = 0
4187  *
4188  *	Unload Media / NOT SUPPORTED YET
4189  *	Load Media / NOT SUPPROTED YET
4190  *	Immediate bit / NOT SUPPORTED YET (deferred error)
4191  *
4192  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4193  * appropriate values in scsi_pkt fields.
4194  */
4195 static int
4196 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
4197 {
4198 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4199 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4200 	int rval, reason;
4201 	sata_drive_info_t *sdinfo;
4202 	sata_id_t *sata_id;
4203 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
4204 
4205 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4206 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
4207 
4208 	mutex_enter(cport_mutex);
4209 
4210 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4211 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4212 		mutex_exit(cport_mutex);
4213 		return (rval);
4214 	}
4215 
4216 	if (scsipkt->pkt_cdbp[1] & START_STOP_IMMED_MASK) {
4217 		/* IMMED bit - not supported */
4218 		mutex_exit(cport_mutex);
4219 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4220 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4221 	}
4222 
4223 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
4224 	spx->txlt_sata_pkt->satapkt_comp = NULL;
4225 
4226 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4227 	    &spx->txlt_sata_pkt->satapkt_device);
4228 	ASSERT(sdinfo != NULL);
4229 	sata_id = &sdinfo->satadrv_id;
4230 
4231 	switch ((scsipkt->pkt_cdbp[4] & START_STOP_POWER_COND_MASK) >> 4) {
4232 	case 0:
4233 		if (scsipkt->pkt_cdbp[4] & START_STOP_LOEJ_MASK) {
4234 			/* Load/Unload Media - invalid request */
4235 			goto err_out;
4236 		}
4237 		if (scsipkt->pkt_cdbp[4] & START_STOP_START_MASK) {
4238 			/* Start Unit */
4239 			sata_build_read_verify_cmd(scmd, 1, 5);
4240 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4241 			/* Transfer command to HBA */
4242 			if (sata_hba_start(spx, &rval) != 0) {
4243 				/* Pkt not accepted for execution */
4244 				mutex_exit(cport_mutex);
4245 				return (rval);
4246 			}
4247 			if (scmd->satacmd_error_reg != 0) {
4248 				goto err_out;
4249 			}
4250 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4251 		} else {
4252 			/* Stop Unit */
4253 			sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4254 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4255 			if (sata_hba_start(spx, &rval) != 0) {
4256 				mutex_exit(cport_mutex);
4257 				return (rval);
4258 			} else {
4259 				if (scmd->satacmd_error_reg != 0) {
4260 					goto err_out;
4261 				}
4262 			}
4263 			/* ata standby immediate command */
4264 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4265 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4266 			if (sata_hba_start(spx, &rval) != 0) {
4267 				mutex_exit(cport_mutex);
4268 				return (rval);
4269 			}
4270 			if (scmd->satacmd_error_reg != 0) {
4271 				goto err_out;
4272 			}
4273 			sdinfo->satadrv_power_level = SATA_POWER_STOPPED;
4274 		}
4275 		break;
4276 	case 0x1:
4277 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4278 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4279 		if (sata_hba_start(spx, &rval) != 0) {
4280 			mutex_exit(cport_mutex);
4281 			return (rval);
4282 		}
4283 		if (scmd->satacmd_error_reg != 0) {
4284 			goto err_out;
4285 		}
4286 		sata_build_read_verify_cmd(scmd, 1, 5);
4287 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4288 		/* Transfer command to HBA */
4289 		if (sata_hba_start(spx, &rval) != 0) {
4290 			/* Pkt not accepted for execution */
4291 			mutex_exit(cport_mutex);
4292 			return (rval);
4293 		} else {
4294 			if (scmd->satacmd_error_reg != 0) {
4295 				goto err_out;
4296 			}
4297 		}
4298 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4299 		break;
4300 	case 0x2:
4301 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4302 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4303 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4304 			if (sata_hba_start(spx, &rval) != 0) {
4305 				mutex_exit(cport_mutex);
4306 				return (rval);
4307 			}
4308 			if (scmd->satacmd_error_reg != 0) {
4309 				goto err_out;
4310 			}
4311 		}
4312 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4313 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4314 		if (sata_hba_start(spx, &rval) != 0) {
4315 			mutex_exit(cport_mutex);
4316 			return (rval);
4317 		}
4318 		if (scmd->satacmd_error_reg != 0) {
4319 			goto err_out;
4320 		}
4321 		if ((scsipkt->pkt_cdbp[3] & START_STOP_MODIFIER_MASK)) {
4322 			/*
4323 			 *  POWER CONDITION MODIFIER bit set
4324 			 *  to 0x1 or larger it will be handled
4325 			 *  on the same way as bit = 0x1
4326 			 */
4327 			if (!(sata_id->ai_cmdset84 &
4328 			    SATA_IDLE_UNLOAD_SUPPORTED)) {
4329 				sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4330 				break;
4331 			}
4332 			sata_build_generic_cmd(scmd, SATAC_IDLE_IM);
4333 			scmd->satacmd_features_reg = 0x44;
4334 			scmd->satacmd_lba_low_lsb = 0x4c;
4335 			scmd->satacmd_lba_mid_lsb = 0x4e;
4336 			scmd->satacmd_lba_high_lsb = 0x55;
4337 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4338 			if (sata_hba_start(spx, &rval) != 0) {
4339 				mutex_exit(cport_mutex);
4340 				return (rval);
4341 			}
4342 			if (scmd->satacmd_error_reg != 0) {
4343 				goto err_out;
4344 			}
4345 		}
4346 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4347 		break;
4348 	case 0x3:
4349 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4350 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4351 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4352 			if (sata_hba_start(spx, &rval) != 0) {
4353 				mutex_exit(cport_mutex);
4354 				return (rval);
4355 			}
4356 			if (scmd->satacmd_error_reg != 0) {
4357 				goto err_out;
4358 			}
4359 		}
4360 		sata_build_generic_cmd(scmd, SATAC_STANDBY);
4361 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4362 		if (sata_hba_start(spx, &rval) != 0) {
4363 			mutex_exit(cport_mutex);
4364 			return (rval);
4365 		}
4366 		if (scmd->satacmd_error_reg != 0) {
4367 			goto err_out;
4368 		}
4369 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4370 		break;
4371 	case 0x7:
4372 		sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4373 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4374 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4375 		if (sata_hba_start(spx, &rval) != 0) {
4376 			mutex_exit(cport_mutex);
4377 			return (rval);
4378 		}
4379 		if (scmd->satacmd_error_reg != 0) {
4380 			goto err_out;
4381 		}
4382 		switch (scmd->satacmd_sec_count_lsb) {
4383 		case SATA_PWRMODE_STANDBY:
4384 			sata_build_generic_cmd(scmd, SATAC_STANDBY);
4385 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4386 			    sdinfo->satadrv_standby_timer);
4387 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4388 			if (sata_hba_start(spx, &rval) != 0) {
4389 				mutex_exit(cport_mutex);
4390 				return (rval);
4391 			} else {
4392 				if (scmd->satacmd_error_reg != 0) {
4393 					goto err_out;
4394 				}
4395 			}
4396 			break;
4397 		case SATA_PWRMODE_IDLE:
4398 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4399 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4400 			    sdinfo->satadrv_standby_timer);
4401 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4402 			if (sata_hba_start(spx, &rval) != 0) {
4403 				mutex_exit(cport_mutex);
4404 				return (rval);
4405 			} else {
4406 				if (scmd->satacmd_error_reg != 0) {
4407 					goto err_out;
4408 				}
4409 			}
4410 			break;
4411 		case SATA_PWRMODE_ACTIVE_SPINDOWN:
4412 		case SATA_PWRMODE_ACTIVE_SPINUP:
4413 		case SATA_PWRMODE_ACTIVE:
4414 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4415 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4416 			    sdinfo->satadrv_standby_timer);
4417 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4418 			if (sata_hba_start(spx, &rval) != 0) {
4419 				mutex_exit(cport_mutex);
4420 				return (rval);
4421 			}
4422 			if (scmd->satacmd_error_reg != 0) {
4423 				goto err_out;
4424 			}
4425 			sata_build_read_verify_cmd(scmd, 1, 5);
4426 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4427 			if (sata_hba_start(spx, &rval) != 0) {
4428 				mutex_exit(cport_mutex);
4429 				return (rval);
4430 			}
4431 			if (scmd->satacmd_error_reg != 0) {
4432 				goto err_out;
4433 			}
4434 			break;
4435 		default:
4436 			goto err_out;
4437 		}
4438 		break;
4439 	case 0xb:
4440 		if ((sata_get_standby_timer(sdinfo->satadrv_standby_timer) ==
4441 		    0) || (!(sata_id->ai_cap & SATA_STANDBYTIMER))) {
4442 			mutex_exit(cport_mutex);
4443 			return (sata_txlt_check_condition(spx,
4444 			    KEY_ILLEGAL_REQUEST,
4445 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4446 		}
4447 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4448 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4449 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4450 			if (sata_hba_start(spx, &rval) != 0) {
4451 				mutex_exit(cport_mutex);
4452 				return (rval);
4453 			}
4454 			if (scmd->satacmd_error_reg != 0) {
4455 				goto err_out;
4456 			}
4457 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4458 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4459 			if (sata_hba_start(spx, &rval) != 0) {
4460 				mutex_exit(cport_mutex);
4461 				return (rval);
4462 			}
4463 			if (scmd->satacmd_error_reg != 0) {
4464 				goto err_out;
4465 			}
4466 		}
4467 		bzero(sdinfo->satadrv_standby_timer, sizeof (uchar_t) * 4);
4468 		break;
4469 	default:
4470 err_out:
4471 		mutex_exit(cport_mutex);
4472 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4473 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4474 	}
4475 
4476 	/*
4477 	 * Since it was a synchronous command,
4478 	 * a callback function will be called directly.
4479 	 */
4480 	mutex_exit(cport_mutex);
4481 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4482 	    "synchronous execution status %x\n",
4483 	    spx->txlt_sata_pkt->satapkt_reason);
4484 
4485 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4486 	    scsipkt->pkt_comp != NULL) {
4487 		sata_set_arq_data(spx->txlt_sata_pkt);
4488 		if (servicing_interrupt()) {
4489 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4490 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4491 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4492 				return (TRAN_BUSY);
4493 			}
4494 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4495 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4496 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4497 			/* Scheduling the callback failed */
4498 			return (TRAN_BUSY);
4499 		}
4500 	}
4501 	else
4502 
4503 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
4504 
4505 	return (TRAN_ACCEPT);
4506 
4507 }
4508 
4509 /*
4510  * SATA translate command:  Read Capacity.
4511  * Emulated command for SATA disks.
4512  * Capacity is retrieved from cached Idenifty Device data.
4513  * Identify Device data shows effective disk capacity, not the native
4514  * capacity, which may be limitted by Set Max Address command.
4515  * This is ATA version for SATA hard disks.
4516  *
4517  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4518  */
4519 static int
4520 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
4521 {
4522 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4523 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4524 	sata_drive_info_t *sdinfo;
4525 	uint64_t val;
4526 	uint32_t lbsize = DEV_BSIZE;
4527 	uchar_t *rbuf;
4528 	int rval, reason;
4529 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
4530 
4531 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4532 	    "sata_txlt_read_capacity: ", NULL);
4533 
4534 	mutex_enter(cport_mutex);
4535 
4536 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4537 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4538 		mutex_exit(cport_mutex);
4539 		return (rval);
4540 	}
4541 
4542 	scsipkt->pkt_reason = CMD_CMPLT;
4543 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4544 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4545 	*scsipkt->pkt_scbp = STATUS_GOOD;
4546 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4547 		/*
4548 		 * Because it is fully emulated command storing data
4549 		 * programatically in the specified buffer, release
4550 		 * preallocated DMA resources before storing data in the buffer,
4551 		 * so no unwanted DMA sync would take place.
4552 		 */
4553 		sata_scsi_dmafree(NULL, scsipkt);
4554 
4555 		sdinfo = sata_get_device_info(
4556 		    spx->txlt_sata_hba_inst,
4557 		    &spx->txlt_sata_pkt->satapkt_device);
4558 
4559 		/*
4560 		 * As per SBC-3, the "returned LBA" is either the highest
4561 		 * addressable LBA or 0xffffffff, whichever is smaller.
4562 		 */
4563 		val = MIN(sdinfo->satadrv_capacity - 1, UINT32_MAX);
4564 
4565 		if (sdinfo->satadrv_id.ai_phys_sect_sz & SATA_L2PS_CHECK_BIT) {
4566 			/* physical/logical sector size word is valid */
4567 
4568 			if (sdinfo->satadrv_id.ai_phys_sect_sz &
4569 			    SATA_L2PS_BIG_SECTORS) {
4570 				/* if this set 117-118 words are valid */
4571 				lbsize = sdinfo->satadrv_id.ai_words_lsec[0] |
4572 				    (sdinfo->satadrv_id.ai_words_lsec[1] << 16);
4573 				lbsize <<= 1; /* convert from words to bytes */
4574 			}
4575 		}
4576 		rbuf = (uchar_t *)bp->b_un.b_addr;
4577 		/* Need to swap endians to match scsi format */
4578 		rbuf[0] = (val >> 24) & 0xff;
4579 		rbuf[1] = (val >> 16) & 0xff;
4580 		rbuf[2] = (val >> 8) & 0xff;
4581 		rbuf[3] = val & 0xff;
4582 		rbuf[4] = (lbsize >> 24) & 0xff;
4583 		rbuf[5] = (lbsize >> 16) & 0xff;
4584 		rbuf[6] = (lbsize >> 8) & 0xff;
4585 		rbuf[7] = lbsize & 0xff;
4586 
4587 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4588 		scsipkt->pkt_resid = 0;
4589 
4590 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
4591 		    sdinfo->satadrv_capacity -1);
4592 	}
4593 	mutex_exit(cport_mutex);
4594 	/*
4595 	 * If a callback was requested, do it now.
4596 	 */
4597 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4598 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4599 
4600 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4601 	    scsipkt->pkt_comp != NULL) {
4602 		/* scsi callback required */
4603 		if (servicing_interrupt()) {
4604 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4605 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4606 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4607 				return (TRAN_BUSY);
4608 			}
4609 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4610 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4611 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4612 			/* Scheduling the callback failed */
4613 			return (TRAN_BUSY);
4614 		}
4615 	}
4616 
4617 	return (TRAN_ACCEPT);
4618 }
4619 
4620 /*
4621  * SATA translate command:  Read Capacity (16).
4622  * Emulated command for SATA disks.
4623  * Info is retrieved from cached Identify Device data.
4624  * Implemented to SBC-3 (draft 21) and SAT-2 (final) specifications.
4625  *
4626  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4627  */
4628 static int
4629 sata_txlt_read_capacity16(sata_pkt_txlate_t *spx)
4630 {
4631 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4632 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4633 	sata_drive_info_t *sdinfo;
4634 	uint64_t val;
4635 	uint16_t l2p_exp;
4636 	uint32_t lbsize = DEV_BSIZE;
4637 	uchar_t *rbuf;
4638 	int rval, reason;
4639 #define	TPE	0x80
4640 #define	TPRZ	0x40
4641 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
4642 
4643 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4644 	    "sata_txlt_read_capacity: ", NULL);
4645 
4646 	mutex_enter(cport_mutex);
4647 
4648 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4649 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4650 		mutex_exit(cport_mutex);
4651 		return (rval);
4652 	}
4653 
4654 	scsipkt->pkt_reason = CMD_CMPLT;
4655 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4656 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4657 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4658 		/*
4659 		 * Because it is fully emulated command storing data
4660 		 * programatically in the specified buffer, release
4661 		 * preallocated DMA resources before storing data in the buffer,
4662 		 * so no unwanted DMA sync would take place.
4663 		 */
4664 		sata_scsi_dmafree(NULL, scsipkt);
4665 
4666 		/* Check SERVICE ACTION field */
4667 		if ((scsipkt->pkt_cdbp[1] & 0x1f) !=
4668 		    SSVC_ACTION_READ_CAPACITY_G4) {
4669 			mutex_exit(cport_mutex);
4670 			return (sata_txlt_check_condition(spx,
4671 			    KEY_ILLEGAL_REQUEST,
4672 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4673 		}
4674 
4675 		/* Check LBA field */
4676 		if ((scsipkt->pkt_cdbp[2] != 0) ||
4677 		    (scsipkt->pkt_cdbp[3] != 0) ||
4678 		    (scsipkt->pkt_cdbp[4] != 0) ||
4679 		    (scsipkt->pkt_cdbp[5] != 0) ||
4680 		    (scsipkt->pkt_cdbp[6] != 0) ||
4681 		    (scsipkt->pkt_cdbp[7] != 0) ||
4682 		    (scsipkt->pkt_cdbp[8] != 0) ||
4683 		    (scsipkt->pkt_cdbp[9] != 0)) {
4684 			mutex_exit(cport_mutex);
4685 			return (sata_txlt_check_condition(spx,
4686 			    KEY_ILLEGAL_REQUEST,
4687 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4688 		}
4689 
4690 		/* Check PMI bit */
4691 		if (scsipkt->pkt_cdbp[14] & 0x1) {
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 		*scsipkt->pkt_scbp = STATUS_GOOD;
4699 
4700 		sdinfo = sata_get_device_info(
4701 		    spx->txlt_sata_hba_inst,
4702 		    &spx->txlt_sata_pkt->satapkt_device);
4703 
4704 		/* last logical block address */
4705 		val = MIN(sdinfo->satadrv_capacity - 1,
4706 		    SCSI_READ_CAPACITY16_MAX_LBA);
4707 
4708 		/* logical to physical block size exponent */
4709 		l2p_exp = 0;
4710 		if (sdinfo->satadrv_id.ai_phys_sect_sz & SATA_L2PS_CHECK_BIT) {
4711 			/* physical/logical sector size word is valid */
4712 
4713 			if (sdinfo->satadrv_id.ai_phys_sect_sz &
4714 			    SATA_L2PS_HAS_MULT) {
4715 				/* multiple logical sectors per phys sectors */
4716 				l2p_exp =
4717 				    sdinfo->satadrv_id.ai_phys_sect_sz &
4718 				    SATA_L2PS_EXP_MASK;
4719 			}
4720 
4721 			if (sdinfo->satadrv_id.ai_phys_sect_sz &
4722 			    SATA_L2PS_BIG_SECTORS) {
4723 				/* if this set 117-118 words are valid */
4724 				lbsize = sdinfo->satadrv_id.ai_words_lsec[0] |
4725 				    (sdinfo->satadrv_id.ai_words_lsec[1] << 16);
4726 				lbsize <<= 1; /* convert from words to bytes */
4727 			}
4728 		}
4729 
4730 		rbuf = (uchar_t *)bp->b_un.b_addr;
4731 		bzero(rbuf, bp->b_bcount);
4732 
4733 		/* returned logical block address */
4734 		rbuf[0] = (val >> 56) & 0xff;
4735 		rbuf[1] = (val >> 48) & 0xff;
4736 		rbuf[2] = (val >> 40) & 0xff;
4737 		rbuf[3] = (val >> 32) & 0xff;
4738 		rbuf[4] = (val >> 24) & 0xff;
4739 		rbuf[5] = (val >> 16) & 0xff;
4740 		rbuf[6] = (val >> 8) & 0xff;
4741 		rbuf[7] = val & 0xff;
4742 		rbuf[8] = (lbsize >> 24) & 0xff;
4743 		rbuf[9] = (lbsize >> 16) & 0xff;
4744 		rbuf[10] = (lbsize >> 8) & 0xff;
4745 		rbuf[11] = lbsize & 0xff;
4746 
4747 		/* p_type, prot_en, unspecified by SAT-2 */
4748 		/* rbuf[12] = 0; */
4749 
4750 		/* p_i_exponent, undefined by SAT-2 */
4751 		/* logical blocks per physical block exponent */
4752 		rbuf[13] = l2p_exp;
4753 
4754 		/* lowest aligned logical block address = 0 (for now) */
4755 		/* tpe and tprz as defined in T10/10-079 r0 */
4756 		if (sdinfo->satadrv_id.ai_addsupported &
4757 		    SATA_DETERMINISTIC_READ) {
4758 			if (sdinfo->satadrv_id.ai_addsupported &
4759 			    SATA_READ_ZERO) {
4760 				rbuf[14] |= TPRZ;
4761 			} else {
4762 				rbuf[14] |= TPE;
4763 			}
4764 		}
4765 		/* rbuf[15] = 0; */
4766 
4767 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4768 		scsipkt->pkt_resid = 0;
4769 
4770 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%llu\n",
4771 		    sdinfo->satadrv_capacity -1);
4772 	}
4773 
4774 	mutex_exit(cport_mutex);
4775 
4776 	/*
4777 	 * If a callback was requested, do it now.
4778 	 */
4779 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4780 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4781 
4782 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4783 	    scsipkt->pkt_comp != NULL) {
4784 		/* scsi callback required */
4785 		if (servicing_interrupt()) {
4786 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4787 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4788 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4789 				return (TRAN_BUSY);
4790 			}
4791 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4792 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4793 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4794 			/* Scheduling the callback failed */
4795 			return (TRAN_BUSY);
4796 		}
4797 	}
4798 
4799 	return (TRAN_ACCEPT);
4800 }
4801 
4802 /*
4803  * Translate command: UNMAP
4804  *
4805  * The function cannot be called in interrupt context since it may sleep.
4806  */
4807 static int
4808 sata_txlt_unmap(sata_pkt_txlate_t *spx)
4809 {
4810 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4811 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4812 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4813 	uint16_t count = 0;
4814 	int synch;
4815 	int rval, reason;
4816 	int i, x;
4817 	int bdlen = 0;
4818 	int ranges = 0;
4819 	int paramlen = 8;
4820 	uint8_t *data, *tmpbd;
4821 	sata_drive_info_t *sdinfo;
4822 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
4823 #define	TRIM	0x1
4824 
4825 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4826 	    "sata_txlt_unmap: ", NULL);
4827 
4828 	mutex_enter(cport_mutex);
4829 
4830 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4831 	    &spx->txlt_sata_pkt->satapkt_device);
4832 	if (sdinfo != NULL) {
4833 		SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4834 		    "DSM support 0x%x, max number of 512 byte blocks of LBA "
4835 		    "range entries 0x%x\n", sdinfo->satadrv_id.ai_dsm,
4836 		    sdinfo->satadrv_id.ai_maxcount);
4837 	}
4838 
4839 	rval = sata_txlt_generic_pkt_info(spx, &reason, 1);
4840 	if ((rval != TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4841 		mutex_exit(cport_mutex);
4842 		return (rval);
4843 	}
4844 
4845 	/*
4846 	 * Need to modify bp to have TRIM data instead of UNMAP data.
4847 	 * Start by getting the block descriptor data length by subtracting
4848 	 * the 8 byte parameter list header from the parameter list length.
4849 	 * The block descriptor size has to be a multiple of 16 bytes.
4850 	 */
4851 	bdlen = scsipkt->pkt_cdbp[7];
4852 	bdlen = (bdlen << 8) + scsipkt->pkt_cdbp[8] - paramlen;
4853 	if ((bdlen < 0) || ((bdlen % 16) != 0) ||
4854 	    ((bp != NULL) && (bdlen > (bp->b_bcount - paramlen)))) {
4855 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4856 		    "sata_txlt_unmap: invalid block descriptor length", NULL);
4857 		mutex_exit(cport_mutex);
4858 		return ((sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4859 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB)));
4860 	}
4861 	/*
4862 	 * If there are no parameter data or block descriptors, it is not
4863 	 * considered an error so just complete the command without sending
4864 	 * TRIM.
4865 	 */
4866 	if ((bdlen == 0) || (bp == NULL) || (bp->b_un.b_addr == NULL) ||
4867 	    (bp->b_bcount == 0)) {
4868 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4869 		    "sata_txlt_unmap: no parameter data or block descriptors",
4870 		    NULL);
4871 		mutex_exit(cport_mutex);
4872 		return (sata_txlt_unmap_nodata_cmd(spx));
4873 	}
4874 	tmpbd = (uint8_t *)bp->b_un.b_addr + paramlen;
4875 	data = kmem_zalloc(bdlen, KM_SLEEP);
4876 
4877 	/*
4878 	 * Loop through all the UNMAP block descriptors and convert the data
4879 	 * into TRIM format.
4880 	 */
4881 	for (i = 0, x = 0; i < bdlen; i += 16, x += 8) {
4882 		/* get range length */
4883 		data[x] = tmpbd[i+7];
4884 		data[x+1] = tmpbd[i+6];
4885 		/* get LBA */
4886 		data[x+2] = tmpbd[i+5];
4887 		data[x+3] = tmpbd[i+4];
4888 		data[x+4] = tmpbd[i+3];
4889 		data[x+5] = tmpbd[i+2];
4890 		data[x+6] = tmpbd[i+11];
4891 		data[x+7] = tmpbd[i+10];
4892 
4893 		ranges++;
4894 	}
4895 
4896 	/*
4897 	 * The TRIM command expects the data buffer to be a multiple of
4898 	 * 512-byte blocks of range entries.  This means that the UNMAP buffer
4899 	 * may be too small.  Free the original DMA resources and create a
4900 	 * local buffer.
4901 	 */
4902 	sata_common_free_dma_rsrcs(spx);
4903 
4904 	/*
4905 	 * Get count of 512-byte blocks of range entries.  The length
4906 	 * of a range entry is 8 bytes which means one count has 64 range
4907 	 * entries.
4908 	 */
4909 	count = (ranges + 63)/64;
4910 
4911 	/* Allocate a buffer that is a multiple of 512 bytes. */
4912 	mutex_exit(cport_mutex);
4913 	bp = sata_alloc_local_buffer(spx, count * 512);
4914 	if (bp == NULL) {
4915 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
4916 		    "sata_txlt_unmap: "
4917 		    "cannot allocate buffer for TRIM command", NULL);
4918 		kmem_free(data, bdlen);
4919 		return (TRAN_BUSY);
4920 	}
4921 	bp_mapin(bp); /* make data buffer accessible */
4922 	mutex_enter(cport_mutex);
4923 
4924 	bzero(bp->b_un.b_addr, bp->b_bcount);
4925 	bcopy(data, bp->b_un.b_addr, x);
4926 	kmem_free(data, bdlen);
4927 	rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
4928 	    DDI_DMA_SYNC_FORDEV);
4929 	ASSERT(rval == DDI_SUCCESS);
4930 
4931 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
4932 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
4933 	scmd->satacmd_cmd_reg = SATAC_DSM;
4934 	scmd->satacmd_sec_count_msb = (count >> 8) & 0xff;
4935 	scmd->satacmd_sec_count_lsb = count & 0xff;
4936 	scmd->satacmd_features_reg = TRIM;
4937 	scmd->satacmd_device_reg = SATA_ADH_LBA;
4938 	scmd->satacmd_status_reg = 0;
4939 	scmd->satacmd_error_reg = 0;
4940 
4941 	/* Start processing command */
4942 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
4943 		spx->txlt_sata_pkt->satapkt_comp =
4944 		    sata_txlt_unmap_completion;
4945 		synch = FALSE;
4946 	} else {
4947 		synch = TRUE;
4948 	}
4949 
4950 	if (sata_hba_start(spx, &rval) != 0) {
4951 		mutex_exit(cport_mutex);
4952 		return (rval);
4953 	}
4954 
4955 	mutex_exit(cport_mutex);
4956 
4957 	if (synch) {
4958 		sata_txlt_unmap_completion(spx->txlt_sata_pkt);
4959 	}
4960 
4961 	return (TRAN_ACCEPT);
4962 }
4963 
4964 /*
4965  * SATA translate command: Mode Sense.
4966  * Translated into appropriate SATA command or emulated.
4967  * Saved Values Page Control (03) are not supported.
4968  *
4969  * NOTE: only caching mode sense page is currently implemented.
4970  *
4971  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4972  */
4973 
4974 #define	LLBAA	0x10	/* Long LBA Accepted */
4975 
4976 static int
4977 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4978 {
4979 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4980 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4981 	sata_drive_info_t *sdinfo;
4982 	sata_id_t *sata_id;
4983 	struct scsi_extended_sense *sense;
4984 	int 		len, bdlen, count, alc_len;
4985 	int		pc;	/* Page Control code */
4986 	uint8_t		*buf;	/* mode sense buffer */
4987 	int		rval, reason;
4988 	kmutex_t	*cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
4989 
4990 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4991 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
4992 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4993 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4994 
4995 	if (servicing_interrupt()) {
4996 		buf = kmem_zalloc(1024, KM_NOSLEEP);
4997 		if (buf == NULL) {
4998 			return (TRAN_BUSY);
4999 		}
5000 	} else {
5001 		buf = kmem_zalloc(1024, KM_SLEEP);
5002 	}
5003 
5004 	mutex_enter(cport_mutex);
5005 
5006 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
5007 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5008 		mutex_exit(cport_mutex);
5009 		kmem_free(buf, 1024);
5010 		return (rval);
5011 	}
5012 
5013 	scsipkt->pkt_reason = CMD_CMPLT;
5014 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5015 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5016 
5017 	pc = scsipkt->pkt_cdbp[2] >> 6;
5018 
5019 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
5020 		/*
5021 		 * Because it is fully emulated command storing data
5022 		 * programatically in the specified buffer, release
5023 		 * preallocated DMA resources before storing data in the buffer,
5024 		 * so no unwanted DMA sync would take place.
5025 		 */
5026 		sata_scsi_dmafree(NULL, scsipkt);
5027 
5028 		len = 0;
5029 		bdlen = 0;
5030 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
5031 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
5032 			    (scsipkt->pkt_cdbp[1] & LLBAA))
5033 				bdlen = 16;
5034 			else
5035 				bdlen = 8;
5036 		}
5037 		/* Build mode parameter header */
5038 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
5039 			/* 4-byte mode parameter header */
5040 			buf[len++] = 0;		/* mode data length */
5041 			buf[len++] = 0;		/* medium type */
5042 			buf[len++] = 0;		/* dev-specific param */
5043 			buf[len++] = bdlen;	/* Block Descriptor length */
5044 		} else {
5045 			/* 8-byte mode parameter header */
5046 			buf[len++] = 0;		/* mode data length */
5047 			buf[len++] = 0;
5048 			buf[len++] = 0;		/* medium type */
5049 			buf[len++] = 0;		/* dev-specific param */
5050 			if (bdlen == 16)
5051 				buf[len++] = 1;	/* long lba descriptor */
5052 			else
5053 				buf[len++] = 0;
5054 			buf[len++] = 0;
5055 			buf[len++] = 0;		/* Block Descriptor length */
5056 			buf[len++] = bdlen;
5057 		}
5058 
5059 		sdinfo = sata_get_device_info(
5060 		    spx->txlt_sata_hba_inst,
5061 		    &spx->txlt_sata_pkt->satapkt_device);
5062 
5063 		/* Build block descriptor only if not disabled (DBD) */
5064 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
5065 			/* Block descriptor - direct-access device format */
5066 			if (bdlen == 8) {
5067 				/* build regular block descriptor */
5068 				buf[len++] =
5069 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
5070 				buf[len++] =
5071 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
5072 				buf[len++] =
5073 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
5074 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
5075 				buf[len++] = 0; /* density code */
5076 				buf[len++] = 0;
5077 				if (sdinfo->satadrv_type ==
5078 				    SATA_DTYPE_ATADISK)
5079 					buf[len++] = 2;
5080 				else
5081 					/* ATAPI */
5082 					buf[len++] = 8;
5083 				buf[len++] = 0;
5084 			} else if (bdlen == 16) {
5085 				/* Long LBA Accepted */
5086 				/* build long lba block descriptor */
5087 #ifndef __lock_lint
5088 				buf[len++] =
5089 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
5090 				buf[len++] =
5091 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
5092 				buf[len++] =
5093 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
5094 				buf[len++] =
5095 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
5096 #endif
5097 				buf[len++] =
5098 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
5099 				buf[len++] =
5100 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
5101 				buf[len++] =
5102 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
5103 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
5104 				buf[len++] = 0;
5105 				buf[len++] = 0; /* density code */
5106 				buf[len++] = 0;
5107 				buf[len++] = 0;
5108 				if (sdinfo->satadrv_type ==
5109 				    SATA_DTYPE_ATADISK)
5110 					buf[len++] = 2;
5111 				else
5112 					/* ATAPI */
5113 					buf[len++] = 8;
5114 				buf[len++] = 0;
5115 			}
5116 		}
5117 
5118 		sata_id = &sdinfo->satadrv_id;
5119 
5120 		/*
5121 		 * Add requested pages.
5122 		 * Page 3 and 4 are obsolete and we are not supporting them.
5123 		 * We deal now with:
5124 		 * caching (read/write cache control).
5125 		 * We should eventually deal with following mode pages:
5126 		 * error recovery  (0x01),
5127 		 * power condition (0x1a),
5128 		 * exception control page (enables SMART) (0x1c),
5129 		 * enclosure management (ses),
5130 		 * protocol-specific port mode (port control).
5131 		 */
5132 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
5133 		case MODEPAGE_RW_ERRRECOV:
5134 			/* DAD_MODE_ERR_RECOV */
5135 			/* R/W recovery */
5136 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
5137 			break;
5138 		case MODEPAGE_CACHING:
5139 			/* DAD_MODE_CACHE */
5140 			/* Reject not supported request for saved parameters */
5141 			if (pc == 3) {
5142 				*scsipkt->pkt_scbp = STATUS_CHECK;
5143 				sense = sata_arq_sense(spx);
5144 				sense->es_key = KEY_ILLEGAL_REQUEST;
5145 				sense->es_add_code =
5146 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
5147 				goto done;
5148 			}
5149 
5150 			/* caching */
5151 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
5152 			break;
5153 		case MODEPAGE_INFO_EXCPT:
5154 			/* exception cntrl */
5155 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
5156 				len += sata_build_msense_page_1c(sdinfo, pc,
5157 				    buf+len);
5158 			}
5159 			else
5160 				goto err;
5161 			break;
5162 		case MODEPAGE_POWER_COND:
5163 			/* DAD_MODE_POWER_COND */
5164 			/* power condition */
5165 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
5166 			break;
5167 
5168 		case MODEPAGE_ACOUSTIC_MANAG:
5169 			/* acoustic management */
5170 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
5171 			break;
5172 		case MODEPAGE_ALLPAGES:
5173 			/* all pages */
5174 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
5175 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
5176 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
5177 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
5178 				len += sata_build_msense_page_1c(sdinfo, pc,
5179 				    buf+len);
5180 			}
5181 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
5182 			break;
5183 		default:
5184 		err:
5185 			/* Invalid request */
5186 			*scsipkt->pkt_scbp = STATUS_CHECK;
5187 			sense = sata_arq_sense(spx);
5188 			sense->es_key = KEY_ILLEGAL_REQUEST;
5189 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5190 			goto done;
5191 		}
5192 
5193 		/* fix total mode data length */
5194 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
5195 			/* 4-byte mode parameter header */
5196 			buf[0] = len - 1;	/* mode data length */
5197 		} else {
5198 			buf[0] = (len -2) >> 8;
5199 			buf[1] = (len -2) & 0xff;
5200 		}
5201 
5202 
5203 		/* Check allocation length */
5204 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
5205 			alc_len = scsipkt->pkt_cdbp[4];
5206 		} else {
5207 			alc_len = scsipkt->pkt_cdbp[7];
5208 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
5209 		}
5210 		/*
5211 		 * We do not check for possible parameters truncation
5212 		 * (alc_len < len) assuming that the target driver works
5213 		 * correctly. Just avoiding overrun.
5214 		 * Copy no more than requested and possible, buffer-wise.
5215 		 */
5216 		count = MIN(alc_len, len);
5217 		count = MIN(bp->b_bcount, count);
5218 		bcopy(buf, bp->b_un.b_addr, count);
5219 
5220 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5221 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
5222 	}
5223 	*scsipkt->pkt_scbp = STATUS_GOOD;
5224 done:
5225 	mutex_exit(cport_mutex);
5226 	(void) kmem_free(buf, 1024);
5227 
5228 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5229 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5230 
5231 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5232 	    scsipkt->pkt_comp != NULL) {
5233 		/* scsi callback required */
5234 		if (servicing_interrupt()) {
5235 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5236 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5237 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
5238 				return (TRAN_BUSY);
5239 			}
5240 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5241 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5242 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
5243 			/* Scheduling the callback failed */
5244 			return (TRAN_BUSY);
5245 		}
5246 	}
5247 
5248 	return (TRAN_ACCEPT);
5249 }
5250 
5251 
5252 /*
5253  * SATA translate command: Mode Select.
5254  * Translated into appropriate SATA command or emulated.
5255  * Saving parameters is not supported.
5256  * Changing device capacity is not supported (although theoretically
5257  * possible by executing SET FEATURES/SET MAX ADDRESS)
5258  *
5259  * Assumption is that the target driver is working correctly.
5260  *
5261  * More than one SATA command may be executed to perform operations specified
5262  * by mode select pages. The first error terminates further execution.
5263  * Operations performed successully are not backed-up in such case.
5264  *
5265  * NOTE: Implemented pages:
5266  * - caching page
5267  * - informational exception page
5268  * - acoustic management page
5269  * - power condition page
5270  * Caching setup is remembered so it could be re-stored in case of
5271  * an unexpected device reset.
5272  *
5273  * Returns TRAN_XXXX.
5274  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
5275  */
5276 
5277 static int
5278 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
5279 {
5280 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5281 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5282 	struct scsi_extended_sense *sense;
5283 	int len, pagelen, count, pllen;
5284 	uint8_t *buf;	/* mode select buffer */
5285 	int rval, stat, reason;
5286 	uint_t nointr_flag;
5287 	int dmod = 0;
5288 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
5289 
5290 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5291 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
5292 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5293 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5294 
5295 	mutex_enter(cport_mutex);
5296 
5297 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5298 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5299 		mutex_exit(cport_mutex);
5300 		return (rval);
5301 	}
5302 
5303 	rval = TRAN_ACCEPT;
5304 
5305 	scsipkt->pkt_reason = CMD_CMPLT;
5306 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5307 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5308 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
5309 
5310 	/* Reject not supported request */
5311 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
5312 		*scsipkt->pkt_scbp = STATUS_CHECK;
5313 		sense = sata_arq_sense(spx);
5314 		sense->es_key = KEY_ILLEGAL_REQUEST;
5315 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5316 		goto done;
5317 	}
5318 
5319 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
5320 		pllen = scsipkt->pkt_cdbp[4];
5321 	} else {
5322 		pllen = scsipkt->pkt_cdbp[7];
5323 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
5324 	}
5325 
5326 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
5327 
5328 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
5329 		buf = (uint8_t *)bp->b_un.b_addr;
5330 		count = MIN(bp->b_bcount, pllen);
5331 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5332 		scsipkt->pkt_resid = 0;
5333 		pllen = count;
5334 
5335 		/*
5336 		 * Check the header to skip the block descriptor(s) - we
5337 		 * do not support setting device capacity.
5338 		 * Existing macros do not recognize long LBA dscriptor,
5339 		 * hence manual calculation.
5340 		 */
5341 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
5342 			/* 6-bytes CMD, 4 bytes header */
5343 			if (count <= 4)
5344 				goto done;		/* header only */
5345 			len = buf[3] + 4;
5346 		} else {
5347 			/* 10-bytes CMD, 8 bytes header */
5348 			if (count <= 8)
5349 				goto done;		/* header only */
5350 			len = buf[6];
5351 			len = (len << 8) + buf[7] + 8;
5352 		}
5353 		if (len >= count)
5354 			goto done;	/* header + descriptor(s) only */
5355 
5356 		pllen -= len;		/* remaining data length */
5357 
5358 		/*
5359 		 * We may be executing SATA command and want to execute it
5360 		 * in SYNCH mode, regardless of scsi_pkt setting.
5361 		 * Save scsi_pkt setting and indicate SYNCH mode
5362 		 */
5363 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5364 		    scsipkt->pkt_comp != NULL) {
5365 			scsipkt->pkt_flags |= FLAG_NOINTR;
5366 		}
5367 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
5368 
5369 		/*
5370 		 * len is now the offset to a first mode select page
5371 		 * Process all pages
5372 		 */
5373 		while (pllen > 0) {
5374 			switch ((int)buf[len]) {
5375 			case MODEPAGE_CACHING:
5376 				/* No support for SP (saving) */
5377 				if (scsipkt->pkt_cdbp[1] & 0x01) {
5378 					*scsipkt->pkt_scbp = STATUS_CHECK;
5379 					sense = sata_arq_sense(spx);
5380 					sense->es_key = KEY_ILLEGAL_REQUEST;
5381 					sense->es_add_code =
5382 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5383 					goto done;
5384 				}
5385 				stat = sata_mode_select_page_8(spx,
5386 				    (struct mode_cache_scsi3 *)&buf[len],
5387 				    pllen, &pagelen, &rval, &dmod);
5388 				/*
5389 				 * The pagelen value indicates the number of
5390 				 * parameter bytes already processed.
5391 				 * The rval is the return value from
5392 				 * sata_tran_start().
5393 				 * The stat indicates the overall status of
5394 				 * the operation(s).
5395 				 */
5396 				if (stat != SATA_SUCCESS)
5397 					/*
5398 					 * Page processing did not succeed -
5399 					 * all error info is already set-up,
5400 					 * just return
5401 					 */
5402 					pllen = 0; /* this breaks the loop */
5403 				else {
5404 					len += pagelen;
5405 					pllen -= pagelen;
5406 				}
5407 				break;
5408 
5409 			case MODEPAGE_INFO_EXCPT:
5410 				stat = sata_mode_select_page_1c(spx,
5411 				    (struct mode_info_excpt_page *)&buf[len],
5412 				    pllen, &pagelen, &rval, &dmod);
5413 				/*
5414 				 * The pagelen value indicates the number of
5415 				 * parameter bytes already processed.
5416 				 * The rval is the return value from
5417 				 * sata_tran_start().
5418 				 * The stat indicates the overall status of
5419 				 * the operation(s).
5420 				 */
5421 				if (stat != SATA_SUCCESS)
5422 					/*
5423 					 * Page processing did not succeed -
5424 					 * all error info is already set-up,
5425 					 * just return
5426 					 */
5427 					pllen = 0; /* this breaks the loop */
5428 				else {
5429 					len += pagelen;
5430 					pllen -= pagelen;
5431 				}
5432 				break;
5433 
5434 			case MODEPAGE_ACOUSTIC_MANAG:
5435 				stat = sata_mode_select_page_30(spx,
5436 				    (struct mode_acoustic_management *)
5437 				    &buf[len], pllen, &pagelen, &rval, &dmod);
5438 				/*
5439 				 * The pagelen value indicates the number of
5440 				 * parameter bytes already processed.
5441 				 * The rval is the return value from
5442 				 * sata_tran_start().
5443 				 * The stat indicates the overall status of
5444 				 * the operation(s).
5445 				 */
5446 				if (stat != SATA_SUCCESS)
5447 					/*
5448 					 * Page processing did not succeed -
5449 					 * all error info is already set-up,
5450 					 * just return
5451 					 */
5452 					pllen = 0; /* this breaks the loop */
5453 				else {
5454 					len += pagelen;
5455 					pllen -= pagelen;
5456 				}
5457 
5458 				break;
5459 			case MODEPAGE_POWER_COND:
5460 				stat = sata_mode_select_page_1a(spx,
5461 				    (struct mode_info_power_cond *)&buf[len],
5462 				    pllen, &pagelen, &rval, &dmod);
5463 				/*
5464 				 * The pagelen value indicates the number of
5465 				 * parameter bytes already processed.
5466 				 * The rval is the return value from
5467 				 * sata_tran_start().
5468 				 * The stat indicates the overall status of
5469 				 * the operation(s).
5470 				 */
5471 				if (stat != SATA_SUCCESS)
5472 					/*
5473 					 * Page processing did not succeed -
5474 					 * all error info is already set-up,
5475 					 * just return
5476 					 */
5477 					pllen = 0; /* this breaks the loop */
5478 				else {
5479 					len += pagelen;
5480 					pllen -= pagelen;
5481 				}
5482 				break;
5483 			default:
5484 				*scsipkt->pkt_scbp = STATUS_CHECK;
5485 				sense = sata_arq_sense(spx);
5486 				sense->es_key = KEY_ILLEGAL_REQUEST;
5487 				sense->es_add_code =
5488 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
5489 				goto done;
5490 			}
5491 		}
5492 	}
5493 done:
5494 	mutex_exit(cport_mutex);
5495 	/*
5496 	 * If device parameters were modified, fetch and store the new
5497 	 * Identify Device data. Since port mutex could have been released
5498 	 * for accessing HBA driver, we need to re-check device existence.
5499 	 */
5500 	if (dmod != 0) {
5501 		sata_drive_info_t new_sdinfo, *sdinfo;
5502 		int rv = 0;
5503 
5504 		/*
5505 		 * Following statement has to be changed if this function is
5506 		 * used for devices other than SATA hard disks.
5507 		 */
5508 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
5509 
5510 		new_sdinfo.satadrv_addr =
5511 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
5512 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
5513 		    &new_sdinfo);
5514 
5515 		mutex_enter(cport_mutex);
5516 		/*
5517 		 * Since port mutex could have been released when
5518 		 * accessing HBA driver, we need to re-check that the
5519 		 * framework still holds the device info structure.
5520 		 */
5521 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5522 		    &spx->txlt_sata_pkt->satapkt_device);
5523 		if (sdinfo != NULL) {
5524 			/*
5525 			 * Device still has info structure in the
5526 			 * sata framework. Copy newly fetched info
5527 			 */
5528 			if (rv == 0) {
5529 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
5530 				sata_save_drive_settings(sdinfo);
5531 			} else {
5532 				/*
5533 				 * Could not fetch new data - invalidate
5534 				 * sata_drive_info. That makes device
5535 				 * unusable.
5536 				 */
5537 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
5538 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
5539 			}
5540 		}
5541 		if (rv != 0 || sdinfo == NULL) {
5542 			/*
5543 			 * This changes the overall mode select completion
5544 			 * reason to a failed one !!!!!
5545 			 */
5546 			*scsipkt->pkt_scbp = STATUS_CHECK;
5547 			sense = sata_arq_sense(spx);
5548 			scsipkt->pkt_reason = CMD_INCOMPLETE;
5549 			rval = TRAN_ACCEPT;
5550 		}
5551 		mutex_exit(cport_mutex);
5552 	}
5553 	/* Restore the scsi pkt flags */
5554 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
5555 	scsipkt->pkt_flags |= nointr_flag;
5556 
5557 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5558 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5559 
5560 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5561 	    scsipkt->pkt_comp != NULL) {
5562 		/* scsi callback required */
5563 		if (servicing_interrupt()) {
5564 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5565 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5566 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
5567 				return (TRAN_BUSY);
5568 			}
5569 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5570 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5571 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
5572 			/* Scheduling the callback failed */
5573 			return (TRAN_BUSY);
5574 		}
5575 	}
5576 
5577 	return (rval);
5578 }
5579 
5580 /*
5581  * Translate command: ATA Pass Through
5582  * Incomplete implementation.  Only supports No-Data, PIO Data-In, and
5583  * PIO Data-Out protocols.  Also supports CK_COND bit.
5584  *
5585  * Mapping of the incoming CDB bytes to the outgoing satacmd bytes is
5586  * described in Table 111 of SAT-2 (Draft 9).
5587  */
5588 static  int
5589 sata_txlt_ata_pass_thru(sata_pkt_txlate_t *spx)
5590 {
5591 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5592 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5593 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5594 	int extend;
5595 	uint64_t lba;
5596 	uint16_t feature, sec_count;
5597 	int t_len, synch;
5598 	int rval, reason;
5599 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
5600 
5601 	mutex_enter(cport_mutex);
5602 
5603 	rval = sata_txlt_generic_pkt_info(spx, &reason, 1);
5604 	if ((rval != TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5605 		mutex_exit(cport_mutex);
5606 		return (rval);
5607 	}
5608 
5609 	/* T_DIR bit */
5610 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_T_DIR)
5611 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5612 	else
5613 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5614 
5615 	/* MULTIPLE_COUNT field.  If non-zero, invalid command (for now). */
5616 	if (((scsipkt->pkt_cdbp[1] >> 5) & 0x7) != 0) {
5617 		mutex_exit(cport_mutex);
5618 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5619 	}
5620 
5621 	/* OFFLINE field. If non-zero, invalid command (for now). */
5622 	if (((scsipkt->pkt_cdbp[2] >> 6) & 0x3) != 0) {
5623 		mutex_exit(cport_mutex);
5624 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5625 	}
5626 
5627 	/* PROTOCOL field */
5628 	switch ((scsipkt->pkt_cdbp[1] >> 1) & 0xf) {
5629 	case SATL_APT_P_HW_RESET:
5630 	case SATL_APT_P_SRST:
5631 	case SATL_APT_P_DMA:
5632 	case SATL_APT_P_DMA_QUEUED:
5633 	case SATL_APT_P_DEV_DIAG:
5634 	case SATL_APT_P_DEV_RESET:
5635 	case SATL_APT_P_UDMA_IN:
5636 	case SATL_APT_P_UDMA_OUT:
5637 	case SATL_APT_P_FPDMA:
5638 	case SATL_APT_P_RET_RESP:
5639 		/* Not yet implemented */
5640 	default:
5641 		mutex_exit(cport_mutex);
5642 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5643 
5644 	case SATL_APT_P_NON_DATA:
5645 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
5646 		break;
5647 
5648 	case SATL_APT_P_PIO_DATA_IN:
5649 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5650 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_WRITE) {
5651 			mutex_exit(cport_mutex);
5652 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5653 		}
5654 
5655 		/* if there is a buffer, release its DMA resources */
5656 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5657 			sata_scsi_dmafree(NULL, scsipkt);
5658 		} else {
5659 			/* if there is no buffer, how do you PIO in? */
5660 			mutex_exit(cport_mutex);
5661 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5662 		}
5663 
5664 		break;
5665 
5666 	case SATL_APT_P_PIO_DATA_OUT:
5667 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5668 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_READ) {
5669 			mutex_exit(cport_mutex);
5670 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5671 		}
5672 
5673 		/* if there is a buffer, release its DMA resources */
5674 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5675 			sata_scsi_dmafree(NULL, scsipkt);
5676 		} else {
5677 			/* if there is no buffer, how do you PIO out? */
5678 			mutex_exit(cport_mutex);
5679 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5680 		}
5681 
5682 		break;
5683 	}
5684 
5685 	/* Parse the ATA cmd fields, transfer some straight to the satacmd */
5686 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5687 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
5688 		feature = scsipkt->pkt_cdbp[3];
5689 
5690 		sec_count = scsipkt->pkt_cdbp[4];
5691 
5692 		lba = scsipkt->pkt_cdbp[8] & 0xf;
5693 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5694 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5695 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5696 
5697 		scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] & 0xf0;
5698 		scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[9];
5699 
5700 		break;
5701 
5702 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
5703 		if (scsipkt->pkt_cdbp[1] & SATL_APT_BM_EXTEND) {
5704 			extend = 1;
5705 
5706 			feature = scsipkt->pkt_cdbp[3];
5707 			feature = (feature << 8) | scsipkt->pkt_cdbp[4];
5708 
5709 			sec_count = scsipkt->pkt_cdbp[5];
5710 			sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[6];
5711 
5712 			lba = scsipkt->pkt_cdbp[11];
5713 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5714 			lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5715 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5716 			lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5717 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5718 
5719 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13];
5720 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5721 		} else {
5722 			feature = scsipkt->pkt_cdbp[3];
5723 
5724 			sec_count = scsipkt->pkt_cdbp[5];
5725 
5726 			lba = scsipkt->pkt_cdbp[13] & 0xf;
5727 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5728 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5729 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5730 
5731 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] &
5732 			    0xf0;
5733 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5734 		}
5735 
5736 		break;
5737 	}
5738 
5739 	/* CK_COND bit */
5740 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
5741 		if (extend) {
5742 			scmd->satacmd_flags.sata_copy_out_sec_count_msb = 1;
5743 			scmd->satacmd_flags.sata_copy_out_lba_low_msb = 1;
5744 			scmd->satacmd_flags.sata_copy_out_lba_mid_msb = 1;
5745 			scmd->satacmd_flags.sata_copy_out_lba_high_msb = 1;
5746 		}
5747 
5748 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
5749 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
5750 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
5751 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
5752 		scmd->satacmd_flags.sata_copy_out_device_reg = 1;
5753 		scmd->satacmd_flags.sata_copy_out_error_reg = 1;
5754 	}
5755 
5756 	/* Transfer remaining parsed ATA cmd values to the satacmd */
5757 	if (extend) {
5758 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5759 
5760 		scmd->satacmd_features_reg_ext = (feature >> 8) & 0xff;
5761 		scmd->satacmd_sec_count_msb = (sec_count >> 8) & 0xff;
5762 		scmd->satacmd_lba_low_msb = (lba >> 8) & 0xff;
5763 		scmd->satacmd_lba_mid_msb = (lba >> 8) & 0xff;
5764 		scmd->satacmd_lba_high_msb = lba >> 40;
5765 	} else {
5766 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5767 
5768 		scmd->satacmd_features_reg_ext = 0;
5769 		scmd->satacmd_sec_count_msb = 0;
5770 		scmd->satacmd_lba_low_msb = 0;
5771 		scmd->satacmd_lba_mid_msb = 0;
5772 		scmd->satacmd_lba_high_msb = 0;
5773 	}
5774 
5775 	scmd->satacmd_features_reg = feature & 0xff;
5776 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5777 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5778 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5779 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5780 
5781 	/* Determine transfer length */
5782 	switch (scsipkt->pkt_cdbp[2] & 0x3) {		/* T_LENGTH field */
5783 	case 1:
5784 		t_len = feature;
5785 		break;
5786 	case 2:
5787 		t_len = sec_count;
5788 		break;
5789 	default:
5790 		t_len = 0;
5791 		break;
5792 	}
5793 
5794 	/* Adjust transfer length for the Byte Block bit */
5795 	if ((scsipkt->pkt_cdbp[2] >> 2) & 1)
5796 		t_len *= SATA_DISK_SECTOR_SIZE;
5797 
5798 	/* Start processing command */
5799 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5800 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_apt_completion;
5801 		synch = FALSE;
5802 	} else {
5803 		synch = TRUE;
5804 	}
5805 
5806 	if (sata_hba_start(spx, &rval) != 0) {
5807 		mutex_exit(cport_mutex);
5808 		return (rval);
5809 	}
5810 
5811 	mutex_exit(cport_mutex);
5812 
5813 	if (synch) {
5814 		sata_txlt_apt_completion(spx->txlt_sata_pkt);
5815 	}
5816 
5817 	return (TRAN_ACCEPT);
5818 }
5819 
5820 /*
5821  * Translate command: Log Sense
5822  */
5823 static 	int
5824 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
5825 {
5826 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
5827 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5828 	sata_drive_info_t *sdinfo;
5829 	struct scsi_extended_sense *sense;
5830 	int 		len, count, alc_len;
5831 	int		pc;	/* Page Control code */
5832 	int		page_code;	/* Page code */
5833 	uint8_t		*buf;	/* log sense buffer */
5834 	int		rval, reason;
5835 #define	MAX_LOG_SENSE_PAGE_SIZE	512
5836 	kmutex_t	*cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
5837 
5838 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5839 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
5840 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5841 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5842 
5843 	if (servicing_interrupt()) {
5844 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_NOSLEEP);
5845 		if (buf == NULL) {
5846 			return (TRAN_BUSY);
5847 		}
5848 	} else {
5849 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
5850 	}
5851 
5852 	mutex_enter(cport_mutex);
5853 
5854 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5855 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5856 		mutex_exit(cport_mutex);
5857 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5858 		return (rval);
5859 	}
5860 
5861 	scsipkt->pkt_reason = CMD_CMPLT;
5862 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5863 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5864 
5865 	pc = scsipkt->pkt_cdbp[2] >> 6;
5866 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
5867 
5868 	/* Reject not supported request for all but cumulative values */
5869 	switch (pc) {
5870 	case PC_CUMULATIVE_VALUES:
5871 		break;
5872 	default:
5873 		*scsipkt->pkt_scbp = STATUS_CHECK;
5874 		sense = sata_arq_sense(spx);
5875 		sense->es_key = KEY_ILLEGAL_REQUEST;
5876 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5877 		goto done;
5878 	}
5879 
5880 	switch (page_code) {
5881 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5882 	case PAGE_CODE_SELF_TEST_RESULTS:
5883 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
5884 	case PAGE_CODE_SMART_READ_DATA:
5885 	case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5886 		break;
5887 	default:
5888 		*scsipkt->pkt_scbp = STATUS_CHECK;
5889 		sense = sata_arq_sense(spx);
5890 		sense->es_key = KEY_ILLEGAL_REQUEST;
5891 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5892 		goto done;
5893 	}
5894 
5895 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
5896 		/*
5897 		 * Because log sense uses local buffers for data retrieval from
5898 		 * the devices and sets the data programatically in the
5899 		 * original specified buffer, release preallocated DMA
5900 		 * resources before storing data in the original buffer,
5901 		 * so no unwanted DMA sync would take place.
5902 		 */
5903 		sata_id_t *sata_id;
5904 
5905 		sata_scsi_dmafree(NULL, scsipkt);
5906 
5907 		len = 0;
5908 
5909 		/* Build log parameter header */
5910 		buf[len++] = page_code;	/* page code as in the CDB */
5911 		buf[len++] = 0;		/* reserved */
5912 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
5913 		buf[len++] = 0;		/* (LSB) */
5914 
5915 		sdinfo = sata_get_device_info(
5916 		    spx->txlt_sata_hba_inst,
5917 		    &spx->txlt_sata_pkt->satapkt_device);
5918 
5919 		/*
5920 		 * Add requested pages.
5921 		 */
5922 		switch (page_code) {
5923 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5924 			len = sata_build_lsense_page_0(sdinfo, buf + len);
5925 			break;
5926 		case PAGE_CODE_SELF_TEST_RESULTS:
5927 			sata_id = &sdinfo->satadrv_id;
5928 			if ((! (sata_id->ai_cmdset84 &
5929 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
5930 			    (! (sata_id->ai_features87 &
5931 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
5932 				*scsipkt->pkt_scbp = STATUS_CHECK;
5933 				sense = sata_arq_sense(spx);
5934 				sense->es_key = KEY_ILLEGAL_REQUEST;
5935 				sense->es_add_code =
5936 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5937 
5938 				goto done;
5939 			}
5940 			len = sata_build_lsense_page_10(sdinfo, buf + len,
5941 			    spx->txlt_sata_hba_inst);
5942 			break;
5943 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
5944 			sata_id = &sdinfo->satadrv_id;
5945 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5946 				*scsipkt->pkt_scbp = STATUS_CHECK;
5947 				sense = sata_arq_sense(spx);
5948 				sense->es_key = KEY_ILLEGAL_REQUEST;
5949 				sense->es_add_code =
5950 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5951 
5952 				goto done;
5953 			}
5954 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5955 				*scsipkt->pkt_scbp = STATUS_CHECK;
5956 				sense = sata_arq_sense(spx);
5957 				sense->es_key = KEY_ABORTED_COMMAND;
5958 				sense->es_add_code =
5959 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5960 				sense->es_qual_code =
5961 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5962 
5963 				goto done;
5964 			}
5965 
5966 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
5967 			    spx->txlt_sata_hba_inst);
5968 			break;
5969 		case PAGE_CODE_SMART_READ_DATA:
5970 			sata_id = &sdinfo->satadrv_id;
5971 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5972 				*scsipkt->pkt_scbp = STATUS_CHECK;
5973 				sense = sata_arq_sense(spx);
5974 				sense->es_key = KEY_ILLEGAL_REQUEST;
5975 				sense->es_add_code =
5976 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5977 
5978 				goto done;
5979 			}
5980 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5981 				*scsipkt->pkt_scbp = STATUS_CHECK;
5982 				sense = sata_arq_sense(spx);
5983 				sense->es_key = KEY_ABORTED_COMMAND;
5984 				sense->es_add_code =
5985 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5986 				sense->es_qual_code =
5987 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5988 
5989 				goto done;
5990 			}
5991 
5992 			/* This page doesn't include a page header */
5993 			len = sata_build_lsense_page_30(sdinfo, buf,
5994 			    spx->txlt_sata_hba_inst);
5995 			goto no_header;
5996 		case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5997 			sata_id = &sdinfo->satadrv_id;
5998 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5999 				*scsipkt->pkt_scbp = STATUS_CHECK;
6000 				sense = sata_arq_sense(spx);
6001 				sense->es_key = KEY_ILLEGAL_REQUEST;
6002 				sense->es_add_code =
6003 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6004 
6005 				goto done;
6006 			}
6007 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
6008 				*scsipkt->pkt_scbp = STATUS_CHECK;
6009 				sense = sata_arq_sense(spx);
6010 				sense->es_key = KEY_ABORTED_COMMAND;
6011 				sense->es_add_code =
6012 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
6013 				sense->es_qual_code =
6014 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
6015 
6016 				goto done;
6017 			}
6018 			len = sata_build_lsense_page_0e(sdinfo, buf, spx);
6019 			goto no_header;
6020 		default:
6021 			/* Invalid request */
6022 			*scsipkt->pkt_scbp = STATUS_CHECK;
6023 			sense = sata_arq_sense(spx);
6024 			sense->es_key = KEY_ILLEGAL_REQUEST;
6025 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6026 			goto done;
6027 		}
6028 
6029 		/* set parameter log sense data length */
6030 		buf[2] = len >> 8;	/* log sense length (MSB) */
6031 		buf[3] = len & 0xff;	/* log sense length (LSB) */
6032 
6033 		len += SCSI_LOG_PAGE_HDR_LEN;
6034 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
6035 
6036 no_header:
6037 		/* Check allocation length */
6038 		alc_len = scsipkt->pkt_cdbp[7];
6039 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
6040 
6041 		/*
6042 		 * We do not check for possible parameters truncation
6043 		 * (alc_len < len) assuming that the target driver works
6044 		 * correctly. Just avoiding overrun.
6045 		 * Copy no more than requested and possible, buffer-wise.
6046 		 */
6047 		count = MIN(alc_len, len);
6048 		count = MIN(bp->b_bcount, count);
6049 		bcopy(buf, bp->b_un.b_addr, count);
6050 
6051 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
6052 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
6053 	}
6054 	*scsipkt->pkt_scbp = STATUS_GOOD;
6055 done:
6056 	mutex_exit(cport_mutex);
6057 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
6058 
6059 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6060 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6061 
6062 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6063 	    scsipkt->pkt_comp != NULL) {
6064 		/* scsi callback required */
6065 		if (servicing_interrupt()) {
6066 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6067 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6068 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6069 				return (TRAN_BUSY);
6070 			}
6071 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6072 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6073 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6074 			/* Scheduling the callback failed */
6075 			return (TRAN_BUSY);
6076 		}
6077 	}
6078 
6079 	return (TRAN_ACCEPT);
6080 }
6081 
6082 /*
6083  * Translate command: Log Select
6084  * Not implemented at this time - returns invalid command response.
6085  */
6086 static	int
6087 sata_txlt_log_select(sata_pkt_txlate_t *spx)
6088 {
6089 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6090 	    "sata_txlt_log_select\n", NULL);
6091 
6092 	return (sata_txlt_invalid_command(spx));
6093 }
6094 
6095 
6096 /*
6097  * Translate command: Read (various types).
6098  * Translated into appropriate type of ATA READ command
6099  * for SATA hard disks.
6100  * Both the device capabilities and requested operation mode are
6101  * considered.
6102  *
6103  * Following scsi cdb fields are ignored:
6104  * rdprotect, dpo, fua, fua_nv, group_number.
6105  *
6106  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
6107  * enable variable sata_func_enable), the capability of the controller and
6108  * capability of a device are checked and if both support queueing, read
6109  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
6110  * command rather than plain READ_XXX command.
6111  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
6112  * both the controller and device suport such functionality, the read
6113  * request will be translated to READ_FPDMA_QUEUED command.
6114  * In both cases the maximum queue depth is derived as minimum of:
6115  * HBA capability,device capability and sata_max_queue_depth variable setting.
6116  * The value passed to HBA driver is decremented by 1, because only 5 bits are
6117  * used to pass max queue depth value, and the maximum possible queue depth
6118  * is 32.
6119  *
6120  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6121  * appropriate values in scsi_pkt fields.
6122  */
6123 static int
6124 sata_txlt_read(sata_pkt_txlate_t *spx)
6125 {
6126 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6127 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6128 	sata_drive_info_t *sdinfo;
6129 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6130 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
6131 	uint16_t sec_count;
6132 	uint64_t lba;
6133 	int rval, reason;
6134 	int synch;
6135 
6136 	mutex_enter(cport_mutex);
6137 
6138 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
6139 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6140 		mutex_exit(cport_mutex);
6141 		return (rval);
6142 	}
6143 
6144 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6145 	    &spx->txlt_sata_pkt->satapkt_device);
6146 
6147 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
6148 	/*
6149 	 * Extract LBA and sector count from scsi CDB.
6150 	 */
6151 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
6152 	case SCMD_READ:
6153 		/* 6-byte scsi read cmd : 0x08 */
6154 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
6155 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
6156 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6157 		sec_count = scsipkt->pkt_cdbp[4];
6158 		/* sec_count 0 will be interpreted as 256 by a device */
6159 		break;
6160 	case SCMD_READ_G1:
6161 		/* 10-bytes scsi read command : 0x28 */
6162 		lba = scsipkt->pkt_cdbp[2];
6163 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6164 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6165 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6166 		sec_count = scsipkt->pkt_cdbp[7];
6167 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
6168 		break;
6169 	case SCMD_READ_G5:
6170 		/* 12-bytes scsi read command : 0xA8 */
6171 		lba = scsipkt->pkt_cdbp[2];
6172 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6173 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6174 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6175 		sec_count = scsipkt->pkt_cdbp[6];
6176 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
6177 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
6178 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
6179 		break;
6180 	case SCMD_READ_G4:
6181 		/* 16-bytes scsi read command : 0x88 */
6182 		lba = scsipkt->pkt_cdbp[2];
6183 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6184 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6185 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6186 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
6187 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
6188 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
6189 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
6190 		sec_count = scsipkt->pkt_cdbp[10];
6191 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
6192 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
6193 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
6194 		break;
6195 	default:
6196 		/* Unsupported command */
6197 		mutex_exit(cport_mutex);
6198 		return (sata_txlt_invalid_command(spx));
6199 	}
6200 
6201 	/*
6202 	 * Check if specified address exceeds device capacity
6203 	 */
6204 	if ((lba >= sdinfo->satadrv_capacity) ||
6205 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
6206 		/* LBA out of range */
6207 		mutex_exit(cport_mutex);
6208 		return (sata_txlt_lba_out_of_range(spx));
6209 	}
6210 
6211 	/*
6212 	 * For zero-length transfer, emulate good completion of the command
6213 	 * (reasons for rejecting the command were already checked).
6214 	 * No DMA resources were allocated.
6215 	 */
6216 	if (spx->txlt_dma_cookie_list == NULL) {
6217 		mutex_exit(cport_mutex);
6218 		return (sata_emul_rw_completion(spx));
6219 	}
6220 
6221 	/*
6222 	 * Build cmd block depending on the device capability and
6223 	 * requested operation mode.
6224 	 * Do not bother with non-dma mode - we are working only with
6225 	 * devices supporting DMA.
6226 	 */
6227 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
6228 	scmd->satacmd_device_reg = SATA_ADH_LBA;
6229 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
6230 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
6231 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
6232 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
6233 		scmd->satacmd_sec_count_msb = sec_count >> 8;
6234 #ifndef __lock_lint
6235 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
6236 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
6237 		scmd->satacmd_lba_high_msb = lba >> 40;
6238 #endif
6239 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
6240 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
6241 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
6242 	}
6243 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
6244 	scmd->satacmd_lba_low_lsb = lba & 0xff;
6245 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
6246 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
6247 	scmd->satacmd_features_reg = 0;
6248 	scmd->satacmd_status_reg = 0;
6249 	scmd->satacmd_error_reg = 0;
6250 
6251 	/*
6252 	 * Check if queueing commands should be used and switch
6253 	 * to appropriate command if possible
6254 	 */
6255 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
6256 		boolean_t using_queuing;
6257 
6258 		/* Queuing supported by controller and device? */
6259 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
6260 		    (sdinfo->satadrv_features_support &
6261 		    SATA_DEV_F_NCQ) &&
6262 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6263 		    SATA_CTLF_NCQ)) {
6264 			using_queuing = B_TRUE;
6265 
6266 			/* NCQ supported - use FPDMA READ */
6267 			scmd->satacmd_cmd_reg =
6268 			    SATAC_READ_FPDMA_QUEUED;
6269 			scmd->satacmd_features_reg_ext =
6270 			    scmd->satacmd_sec_count_msb;
6271 			scmd->satacmd_sec_count_msb = 0;
6272 		} else if ((sdinfo->satadrv_features_support &
6273 		    SATA_DEV_F_TCQ) &&
6274 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6275 		    SATA_CTLF_QCMD)) {
6276 			using_queuing = B_TRUE;
6277 
6278 			/* Legacy queueing */
6279 			if (sdinfo->satadrv_features_support &
6280 			    SATA_DEV_F_LBA48) {
6281 				scmd->satacmd_cmd_reg =
6282 				    SATAC_READ_DMA_QUEUED_EXT;
6283 				scmd->satacmd_features_reg_ext =
6284 				    scmd->satacmd_sec_count_msb;
6285 				scmd->satacmd_sec_count_msb = 0;
6286 			} else {
6287 				scmd->satacmd_cmd_reg =
6288 				    SATAC_READ_DMA_QUEUED;
6289 			}
6290 		} else	/* NCQ nor legacy queuing not supported */
6291 			using_queuing = B_FALSE;
6292 
6293 		/*
6294 		 * If queuing, the sector count goes in the features register
6295 		 * and the secount count will contain the tag.
6296 		 */
6297 		if (using_queuing) {
6298 			scmd->satacmd_features_reg =
6299 			    scmd->satacmd_sec_count_lsb;
6300 			scmd->satacmd_sec_count_lsb = 0;
6301 			scmd->satacmd_flags.sata_queued = B_TRUE;
6302 
6303 			/* Set-up maximum queue depth */
6304 			scmd->satacmd_flags.sata_max_queue_depth =
6305 			    sdinfo->satadrv_max_queue_depth - 1;
6306 		} else if (sdinfo->satadrv_features_enabled &
6307 		    SATA_DEV_F_E_UNTAGGED_QING) {
6308 			/*
6309 			 * Although NCQ/TCQ is not enabled, untagged queuing
6310 			 * may be still used.
6311 			 * Set-up the maximum untagged queue depth.
6312 			 * Use controller's queue depth from sata_hba_tran.
6313 			 * SATA HBA drivers may ignore this value and rely on
6314 			 * the internal limits.For drivers that do not
6315 			 * ignore untaged queue depth, limit the value to
6316 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
6317 			 * largest value that can be passed via
6318 			 * satacmd_flags.sata_max_queue_depth.
6319 			 */
6320 			scmd->satacmd_flags.sata_max_queue_depth =
6321 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
6322 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
6323 
6324 		} else {
6325 			scmd->satacmd_flags.sata_max_queue_depth = 0;
6326 		}
6327 	} else
6328 		scmd->satacmd_flags.sata_max_queue_depth = 0;
6329 
6330 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
6331 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
6332 	    scmd->satacmd_cmd_reg, lba, sec_count);
6333 
6334 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6335 		/* Need callback function */
6336 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
6337 		synch = FALSE;
6338 	} else
6339 		synch = TRUE;
6340 
6341 	/* Transfer command to HBA */
6342 	if (sata_hba_start(spx, &rval) != 0) {
6343 		/* Pkt not accepted for execution */
6344 		mutex_exit(cport_mutex);
6345 		return (rval);
6346 	}
6347 	mutex_exit(cport_mutex);
6348 	/*
6349 	 * If execution is non-synchronous,
6350 	 * a callback function will handle potential errors, translate
6351 	 * the response and will do a callback to a target driver.
6352 	 * If it was synchronous, check execution status using the same
6353 	 * framework callback.
6354 	 */
6355 	if (synch) {
6356 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6357 		    "synchronous execution status %x\n",
6358 		    spx->txlt_sata_pkt->satapkt_reason);
6359 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
6360 	}
6361 	return (TRAN_ACCEPT);
6362 }
6363 
6364 
6365 /*
6366  * SATA translate command: Write (various types)
6367  * Translated into appropriate type of ATA WRITE command
6368  * for SATA hard disks.
6369  * Both the device capabilities and requested operation mode are
6370  * considered.
6371  *
6372  * Following scsi cdb fields are ignored:
6373  * rwprotect, dpo, fua, fua_nv, group_number.
6374  *
6375  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
6376  * enable variable sata_func_enable), the capability of the controller and
6377  * capability of a device are checked and if both support queueing, write
6378  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
6379  * command rather than plain WRITE_XXX command.
6380  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
6381  * both the controller and device suport such functionality, the write
6382  * request will be translated to WRITE_FPDMA_QUEUED command.
6383  * In both cases the maximum queue depth is derived as minimum of:
6384  * HBA capability,device capability and sata_max_queue_depth variable setting.
6385  * The value passed to HBA driver is decremented by 1, because only 5 bits are
6386  * used to pass max queue depth value, and the maximum possible queue depth
6387  * is 32.
6388  *
6389  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6390  * appropriate values in scsi_pkt fields.
6391  */
6392 static int
6393 sata_txlt_write(sata_pkt_txlate_t *spx)
6394 {
6395 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6396 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6397 	sata_drive_info_t *sdinfo;
6398 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6399 	uint16_t sec_count;
6400 	uint64_t lba;
6401 	int rval, reason;
6402 	int synch;
6403 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
6404 
6405 	mutex_enter(cport_mutex);
6406 
6407 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
6408 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6409 		mutex_exit(cport_mutex);
6410 		return (rval);
6411 	}
6412 
6413 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6414 	    &spx->txlt_sata_pkt->satapkt_device);
6415 
6416 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
6417 	/*
6418 	 * Extract LBA and sector count from scsi CDB
6419 	 */
6420 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
6421 	case SCMD_WRITE:
6422 		/* 6-byte scsi read cmd : 0x0A */
6423 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
6424 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
6425 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6426 		sec_count = scsipkt->pkt_cdbp[4];
6427 		/* sec_count 0 will be interpreted as 256 by a device */
6428 		break;
6429 	case SCMD_WRITE_G1:
6430 		/* 10-bytes scsi write command : 0x2A */
6431 		lba = scsipkt->pkt_cdbp[2];
6432 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6433 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6434 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6435 		sec_count = scsipkt->pkt_cdbp[7];
6436 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
6437 		break;
6438 	case SCMD_WRITE_G5:
6439 		/* 12-bytes scsi read command : 0xAA */
6440 		lba = scsipkt->pkt_cdbp[2];
6441 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6442 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6443 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6444 		sec_count = scsipkt->pkt_cdbp[6];
6445 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
6446 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
6447 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
6448 		break;
6449 	case SCMD_WRITE_G4:
6450 		/* 16-bytes scsi write command : 0x8A */
6451 		lba = scsipkt->pkt_cdbp[2];
6452 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6453 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6454 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6455 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
6456 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
6457 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
6458 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
6459 		sec_count = scsipkt->pkt_cdbp[10];
6460 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
6461 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
6462 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
6463 		break;
6464 	default:
6465 		/* Unsupported command */
6466 		mutex_exit(cport_mutex);
6467 		return (sata_txlt_invalid_command(spx));
6468 	}
6469 
6470 	/*
6471 	 * Check if specified address and length exceeds device capacity
6472 	 */
6473 	if ((lba >= sdinfo->satadrv_capacity) ||
6474 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
6475 		/* LBA out of range */
6476 		mutex_exit(cport_mutex);
6477 		return (sata_txlt_lba_out_of_range(spx));
6478 	}
6479 
6480 	/*
6481 	 * For zero-length transfer, emulate good completion of the command
6482 	 * (reasons for rejecting the command were already checked).
6483 	 * No DMA resources were allocated.
6484 	 */
6485 	if (spx->txlt_dma_cookie_list == NULL) {
6486 		mutex_exit(cport_mutex);
6487 		return (sata_emul_rw_completion(spx));
6488 	}
6489 
6490 	/*
6491 	 * Build cmd block depending on the device capability and
6492 	 * requested operation mode.
6493 	 * Do not bother with non-dma mode- we are working only with
6494 	 * devices supporting DMA.
6495 	 */
6496 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
6497 	scmd->satacmd_device_reg = SATA_ADH_LBA;
6498 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
6499 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
6500 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
6501 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
6502 		scmd->satacmd_sec_count_msb = sec_count >> 8;
6503 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
6504 #ifndef __lock_lint
6505 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
6506 		scmd->satacmd_lba_high_msb = lba >> 40;
6507 #endif
6508 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
6509 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
6510 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
6511 	}
6512 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
6513 	scmd->satacmd_lba_low_lsb = lba & 0xff;
6514 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
6515 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
6516 	scmd->satacmd_features_reg = 0;
6517 	scmd->satacmd_status_reg = 0;
6518 	scmd->satacmd_error_reg = 0;
6519 
6520 	/*
6521 	 * Check if queueing commands should be used and switch
6522 	 * to appropriate command if possible
6523 	 */
6524 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
6525 		boolean_t using_queuing;
6526 
6527 		/* Queuing supported by controller and device? */
6528 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
6529 		    (sdinfo->satadrv_features_support &
6530 		    SATA_DEV_F_NCQ) &&
6531 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6532 		    SATA_CTLF_NCQ)) {
6533 			using_queuing = B_TRUE;
6534 
6535 			/* NCQ supported - use FPDMA WRITE */
6536 			scmd->satacmd_cmd_reg =
6537 			    SATAC_WRITE_FPDMA_QUEUED;
6538 			scmd->satacmd_features_reg_ext =
6539 			    scmd->satacmd_sec_count_msb;
6540 			scmd->satacmd_sec_count_msb = 0;
6541 		} else if ((sdinfo->satadrv_features_support &
6542 		    SATA_DEV_F_TCQ) &&
6543 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6544 		    SATA_CTLF_QCMD)) {
6545 			using_queuing = B_TRUE;
6546 
6547 			/* Legacy queueing */
6548 			if (sdinfo->satadrv_features_support &
6549 			    SATA_DEV_F_LBA48) {
6550 				scmd->satacmd_cmd_reg =
6551 				    SATAC_WRITE_DMA_QUEUED_EXT;
6552 				scmd->satacmd_features_reg_ext =
6553 				    scmd->satacmd_sec_count_msb;
6554 				scmd->satacmd_sec_count_msb = 0;
6555 			} else {
6556 				scmd->satacmd_cmd_reg =
6557 				    SATAC_WRITE_DMA_QUEUED;
6558 			}
6559 		} else	/*  NCQ nor legacy queuing not supported */
6560 			using_queuing = B_FALSE;
6561 
6562 		if (using_queuing) {
6563 			scmd->satacmd_features_reg =
6564 			    scmd->satacmd_sec_count_lsb;
6565 			scmd->satacmd_sec_count_lsb = 0;
6566 			scmd->satacmd_flags.sata_queued = B_TRUE;
6567 			/* Set-up maximum queue depth */
6568 			scmd->satacmd_flags.sata_max_queue_depth =
6569 			    sdinfo->satadrv_max_queue_depth - 1;
6570 		} else if (sdinfo->satadrv_features_enabled &
6571 		    SATA_DEV_F_E_UNTAGGED_QING) {
6572 			/*
6573 			 * Although NCQ/TCQ is not enabled, untagged queuing
6574 			 * may be still used.
6575 			 * Set-up the maximum untagged queue depth.
6576 			 * Use controller's queue depth from sata_hba_tran.
6577 			 * SATA HBA drivers may ignore this value and rely on
6578 			 * the internal limits. For drivera that do not
6579 			 * ignore untaged queue depth, limit the value to
6580 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
6581 			 * largest value that can be passed via
6582 			 * satacmd_flags.sata_max_queue_depth.
6583 			 */
6584 			scmd->satacmd_flags.sata_max_queue_depth =
6585 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
6586 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
6587 
6588 		} else {
6589 			scmd->satacmd_flags.sata_max_queue_depth = 0;
6590 		}
6591 	} else
6592 		scmd->satacmd_flags.sata_max_queue_depth = 0;
6593 
6594 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6595 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
6596 	    scmd->satacmd_cmd_reg, lba, sec_count);
6597 
6598 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6599 		/* Need callback function */
6600 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
6601 		synch = FALSE;
6602 	} else
6603 		synch = TRUE;
6604 
6605 	/* Transfer command to HBA */
6606 	if (sata_hba_start(spx, &rval) != 0) {
6607 		/* Pkt not accepted for execution */
6608 		mutex_exit(cport_mutex);
6609 		return (rval);
6610 	}
6611 	mutex_exit(cport_mutex);
6612 
6613 	/*
6614 	 * If execution is non-synchronous,
6615 	 * a callback function will handle potential errors, translate
6616 	 * the response and will do a callback to a target driver.
6617 	 * If it was synchronous, check execution status using the same
6618 	 * framework callback.
6619 	 */
6620 	if (synch) {
6621 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6622 		    "synchronous execution status %x\n",
6623 		    spx->txlt_sata_pkt->satapkt_reason);
6624 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
6625 	}
6626 	return (TRAN_ACCEPT);
6627 }
6628 
6629 
6630 /*
6631  * Implements SCSI SBC WRITE BUFFER command download microcode option
6632  */
6633 static int
6634 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
6635 {
6636 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
6637 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
6638 
6639 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6640 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
6641 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6642 
6643 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6644 	struct scsi_extended_sense *sense;
6645 	int rval, mode, sector_count, reason;
6646 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
6647 
6648 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
6649 
6650 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6651 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
6652 
6653 	mutex_enter(cport_mutex);
6654 
6655 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6656 	    TRAN_ACCEPT) {
6657 		mutex_exit(cport_mutex);
6658 		return (rval);
6659 	}
6660 
6661 	/* Use synchronous mode */
6662 	spx->txlt_sata_pkt->satapkt_op_mode
6663 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
6664 
6665 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
6666 
6667 	scsipkt->pkt_reason = CMD_CMPLT;
6668 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6669 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6670 
6671 	/*
6672 	 * The SCSI to ATA translation specification only calls
6673 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
6674 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
6675 	 * ATA 8 (draft) got rid of download microcode for temp
6676 	 * and it is even optional for ATA 7, so it may be aborted.
6677 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
6678 	 * it is not specified and the buffer offset for SCSI is a 16-bit
6679 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
6680 	 * sectors.  Thus the offset really doesn't buy us anything.
6681 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
6682 	 * is revised, this can be revisisted.
6683 	 */
6684 	/* Reject not supported request */
6685 	switch (mode) {
6686 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
6687 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
6688 		break;
6689 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
6690 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
6691 		break;
6692 	default:
6693 		goto bad_param;
6694 	}
6695 
6696 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
6697 
6698 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
6699 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
6700 		goto bad_param;
6701 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
6702 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
6703 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
6704 	scmd->satacmd_lba_mid_lsb = 0;
6705 	scmd->satacmd_lba_high_lsb = 0;
6706 	scmd->satacmd_device_reg = 0;
6707 	spx->txlt_sata_pkt->satapkt_comp = NULL;
6708 	scmd->satacmd_addr_type = 0;
6709 
6710 	/* Transfer command to HBA */
6711 	if (sata_hba_start(spx, &rval) != 0) {
6712 		/* Pkt not accepted for execution */
6713 		mutex_exit(cport_mutex);
6714 		return (rval);
6715 	}
6716 
6717 	mutex_exit(cport_mutex);
6718 
6719 	/* Then we need synchronous check the status of the disk */
6720 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6721 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6722 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6723 		scsipkt->pkt_reason = CMD_CMPLT;
6724 
6725 		/* Download commmand succeed, so probe and identify device */
6726 		sata_reidentify_device(spx);
6727 	} else {
6728 		/* Something went wrong, microcode download command failed */
6729 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6730 		*scsipkt->pkt_scbp = STATUS_CHECK;
6731 		sense = sata_arq_sense(spx);
6732 		switch (sata_pkt->satapkt_reason) {
6733 		case SATA_PKT_PORT_ERROR:
6734 			/*
6735 			 * We have no device data. Assume no data transfered.
6736 			 */
6737 			sense->es_key = KEY_HARDWARE_ERROR;
6738 			break;
6739 
6740 		case SATA_PKT_DEV_ERROR:
6741 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6742 			    SATA_STATUS_ERR) {
6743 				/*
6744 				 * determine dev error reason from error
6745 				 * reg content
6746 				 */
6747 				sata_decode_device_error(spx, sense);
6748 				break;
6749 			}
6750 			/* No extended sense key - no info available */
6751 			break;
6752 
6753 		case SATA_PKT_TIMEOUT:
6754 			scsipkt->pkt_reason = CMD_TIMEOUT;
6755 			scsipkt->pkt_statistics |=
6756 			    STAT_TIMEOUT | STAT_DEV_RESET;
6757 			/* No extended sense key ? */
6758 			break;
6759 
6760 		case SATA_PKT_ABORTED:
6761 			scsipkt->pkt_reason = CMD_ABORTED;
6762 			scsipkt->pkt_statistics |= STAT_ABORTED;
6763 			/* No extended sense key ? */
6764 			break;
6765 
6766 		case SATA_PKT_RESET:
6767 			/* pkt aborted by an explicit reset from a host */
6768 			scsipkt->pkt_reason = CMD_RESET;
6769 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6770 			break;
6771 
6772 		default:
6773 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6774 			    "sata_txlt_nodata_cmd_completion: "
6775 			    "invalid packet completion reason %d",
6776 			    sata_pkt->satapkt_reason));
6777 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6778 			break;
6779 		}
6780 
6781 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6782 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6783 
6784 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6785 			/* scsi callback required */
6786 			scsi_hba_pkt_comp(scsipkt);
6787 	}
6788 	return (TRAN_ACCEPT);
6789 
6790 bad_param:
6791 	mutex_exit(cport_mutex);
6792 	*scsipkt->pkt_scbp = STATUS_CHECK;
6793 	sense = sata_arq_sense(spx);
6794 	sense->es_key = KEY_ILLEGAL_REQUEST;
6795 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6796 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6797 	    scsipkt->pkt_comp != NULL) {
6798 		/* scsi callback required */
6799 		if (servicing_interrupt()) {
6800 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6801 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6802 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6803 				return (TRAN_BUSY);
6804 			}
6805 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6806 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6807 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6808 			/* Scheduling the callback failed */
6809 			return (TRAN_BUSY);
6810 		}
6811 	}
6812 	return (rval);
6813 }
6814 
6815 /*
6816  * Re-identify device after doing a firmware download.
6817  */
6818 static void
6819 sata_reidentify_device(sata_pkt_txlate_t *spx)
6820 {
6821 #define	DOWNLOAD_WAIT_TIME_SECS	60
6822 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
6823 	int rval;
6824 	int retry_cnt;
6825 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6826 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6827 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
6828 	sata_drive_info_t *sdinfo;
6829 
6830 	/*
6831 	 * Before returning good status, probe device.
6832 	 * Device probing will get IDENTIFY DEVICE data, if possible.
6833 	 * The assumption is that the new microcode is applied by the
6834 	 * device. It is a caller responsibility to verify this.
6835 	 */
6836 	for (retry_cnt = 0;
6837 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
6838 	    retry_cnt++) {
6839 		rval = sata_probe_device(sata_hba_inst, &sata_device);
6840 
6841 		if (rval == SATA_SUCCESS) { /* Set default features */
6842 			sdinfo = sata_get_device_info(sata_hba_inst,
6843 			    &sata_device);
6844 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
6845 			    SATA_SUCCESS) {
6846 				/* retry */
6847 				rval = sata_initialize_device(sata_hba_inst,
6848 				    sdinfo);
6849 				if (rval == SATA_RETRY)
6850 					sata_log(sata_hba_inst, CE_WARN,
6851 					    "SATA device at port %d pmport %d -"
6852 					    " default device features could not"
6853 					    " be set. Device may not operate "
6854 					    "as expected.",
6855 					    sata_device.satadev_addr.cport,
6856 					    sata_device.satadev_addr.pmport);
6857 			}
6858 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6859 				scsi_hba_pkt_comp(scsipkt);
6860 			return;
6861 		} else if (rval == SATA_RETRY) {
6862 			delay(drv_usectohz(1000000 *
6863 			    DOWNLOAD_WAIT_INTERVAL_SECS));
6864 			continue;
6865 		} else	/* failed - no reason to retry */
6866 			break;
6867 	}
6868 
6869 	/*
6870 	 * Something went wrong, device probing failed.
6871 	 */
6872 	SATA_LOG_D((sata_hba_inst, CE_WARN,
6873 	    "Cannot probe device after downloading microcode\n"));
6874 
6875 	/* Reset device to force retrying the probe. */
6876 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
6877 	    (SATA_DIP(sata_hba_inst), &sata_device);
6878 
6879 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6880 		scsi_hba_pkt_comp(scsipkt);
6881 }
6882 
6883 
6884 /*
6885  * Translate command: Synchronize Cache.
6886  * Translates into Flush Cache command for SATA hard disks.
6887  *
6888  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6889  * appropriate values in scsi_pkt fields.
6890  */
6891 static 	int
6892 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
6893 {
6894 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6895 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
6896 	int rval, reason;
6897 	int synch;
6898 
6899 	mutex_enter(cport_mutex);
6900 
6901 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6902 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6903 		mutex_exit(cport_mutex);
6904 		return (rval);
6905 	}
6906 
6907 	scmd->satacmd_addr_type = 0;
6908 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
6909 	scmd->satacmd_device_reg = 0;
6910 	scmd->satacmd_sec_count_lsb = 0;
6911 	scmd->satacmd_lba_low_lsb = 0;
6912 	scmd->satacmd_lba_mid_lsb = 0;
6913 	scmd->satacmd_lba_high_lsb = 0;
6914 	scmd->satacmd_features_reg = 0;
6915 	scmd->satacmd_status_reg = 0;
6916 	scmd->satacmd_error_reg = 0;
6917 
6918 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6919 	    "sata_txlt_synchronize_cache\n", NULL);
6920 
6921 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6922 		/* Need to set-up a callback function */
6923 		spx->txlt_sata_pkt->satapkt_comp =
6924 		    sata_txlt_nodata_cmd_completion;
6925 		synch = FALSE;
6926 	} else
6927 		synch = TRUE;
6928 
6929 	/* Transfer command to HBA */
6930 	if (sata_hba_start(spx, &rval) != 0) {
6931 		/* Pkt not accepted for execution */
6932 		mutex_exit(cport_mutex);
6933 		return (rval);
6934 	}
6935 	mutex_exit(cport_mutex);
6936 
6937 	/*
6938 	 * If execution non-synchronous, it had to be completed
6939 	 * a callback function will handle potential errors, translate
6940 	 * the response and will do a callback to a target driver.
6941 	 * If it was synchronous, check status, using the same
6942 	 * framework callback.
6943 	 */
6944 	if (synch) {
6945 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6946 		    "synchronous execution status %x\n",
6947 		    spx->txlt_sata_pkt->satapkt_reason);
6948 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
6949 	}
6950 	return (TRAN_ACCEPT);
6951 }
6952 
6953 
6954 /*
6955  * Send pkt to SATA HBA driver
6956  *
6957  * This function may be called only if the operation is requested by scsi_pkt,
6958  * i.e. scsi_pkt is not NULL.
6959  *
6960  * This function has to be called with cport mutex held. It does release
6961  * the mutex when it calls HBA driver sata_tran_start function and
6962  * re-acquires it afterwards.
6963  *
6964  * If return value is 0, pkt was accepted, -1 otherwise
6965  * rval is set to appropriate sata_scsi_start return value.
6966  *
6967  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
6968  * have called the sata_pkt callback function for this packet.
6969  *
6970  * The scsi callback has to be performed by the caller of this routine.
6971  */
6972 static int
6973 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
6974 {
6975 	int stat;
6976 	uint8_t cport = SATA_TXLT_CPORT(spx);
6977 	uint8_t pmport = SATA_TXLT_PMPORT(spx);
6978 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6979 	sata_drive_info_t *sdinfo;
6980 	sata_pmult_info_t *pminfo;
6981 	sata_pmport_info_t *pmportinfo = NULL;
6982 	sata_device_t *sata_device = NULL;
6983 	uint8_t cmd;
6984 	struct sata_cmd_flags cmd_flags;
6985 
6986 	ASSERT(spx->txlt_sata_pkt != NULL);
6987 
6988 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6989 
6990 	sdinfo = sata_get_device_info(sata_hba_inst,
6991 	    &spx->txlt_sata_pkt->satapkt_device);
6992 	ASSERT(sdinfo != NULL);
6993 
6994 	/* Clear device reset state? */
6995 	/* qual should be XXX_DPMPORT, but add XXX_PMPORT in case */
6996 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT ||
6997 	    sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT) {
6998 
6999 		/*
7000 		 * Get the pmult_info of the its parent port multiplier, all
7001 		 * sub-devices share a common device reset flags on in
7002 		 * pmult_info.
7003 		 */
7004 		pminfo = SATA_PMULT_INFO(sata_hba_inst, cport);
7005 		pmportinfo = pminfo->pmult_dev_port[pmport];
7006 		ASSERT(pminfo != NULL);
7007 		if (pminfo->pmult_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
7008 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
7009 			    sata_clear_dev_reset = B_TRUE;
7010 			pminfo->pmult_event_flags &=
7011 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
7012 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
7013 			    "sata_hba_start: clearing device reset state"
7014 			    "on pmult.\n", NULL);
7015 		}
7016 	} else {
7017 		if (sdinfo->satadrv_event_flags &
7018 		    SATA_EVNT_CLEAR_DEVICE_RESET) {
7019 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
7020 			    sata_clear_dev_reset = B_TRUE;
7021 			sdinfo->satadrv_event_flags &=
7022 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
7023 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
7024 			    "sata_hba_start: clearing device reset state\n",
7025 			    NULL);
7026 		}
7027 	}
7028 
7029 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
7030 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
7031 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
7032 
7033 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
7034 
7035 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7036 	    "Sata cmd 0x%2x\n", cmd);
7037 
7038 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
7039 	    spx->txlt_sata_pkt);
7040 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
7041 	/*
7042 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
7043 	 * with the sata callback, the sata_pkt could be already destroyed
7044 	 * by the time we check ther return status from the hba_start()
7045 	 * function, because sata_scsi_destroy_pkt() could have been already
7046 	 * called (perhaps in the interrupt context). So, in such case, there
7047 	 * should be no references to it. In other cases, sata_pkt still
7048 	 * exists.
7049 	 */
7050 	if (stat == SATA_TRAN_ACCEPTED) {
7051 		/*
7052 		 * pkt accepted for execution.
7053 		 * If it was executed synchronously, it is already completed
7054 		 * and pkt completion_reason indicates completion status.
7055 		 */
7056 		*rval = TRAN_ACCEPT;
7057 		return (0);
7058 	}
7059 
7060 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
7061 	switch (stat) {
7062 	case SATA_TRAN_QUEUE_FULL:
7063 		/*
7064 		 * Controller detected queue full condition.
7065 		 */
7066 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
7067 		    "sata_hba_start: queue full\n", NULL);
7068 
7069 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
7070 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
7071 
7072 		*rval = TRAN_BUSY;
7073 		break;
7074 
7075 	case SATA_TRAN_PORT_ERROR:
7076 		/*
7077 		 * Communication/link with device or general port error
7078 		 * detected before pkt execution begun.
7079 		 */
7080 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
7081 		    SATA_ADDR_CPORT ||
7082 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
7083 		    SATA_ADDR_DCPORT)
7084 			sata_log(sata_hba_inst, CE_CONT,
7085 			    "SATA port %d error",
7086 			    sata_device->satadev_addr.cport);
7087 		else
7088 			sata_log(sata_hba_inst, CE_CONT,
7089 			    "SATA port %d:%d error\n",
7090 			    sata_device->satadev_addr.cport,
7091 			    sata_device->satadev_addr.pmport);
7092 
7093 		/*
7094 		 * Update the port/device structure.
7095 		 * sata_pkt should be still valid. Since port error is
7096 		 * returned, sata_device content should reflect port
7097 		 * state - it means, that sata address have been changed,
7098 		 * because original packet's sata address refered to a device
7099 		 * attached to some port.
7100 		 */
7101 		if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT ||
7102 		    sata_device->satadev_addr.qual == SATA_ADDR_PMPORT) {
7103 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
7104 			mutex_enter(&pmportinfo->pmport_mutex);
7105 			sata_update_pmport_info(sata_hba_inst, sata_device);
7106 			mutex_exit(&pmportinfo->pmport_mutex);
7107 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
7108 		} else {
7109 			sata_update_port_info(sata_hba_inst, sata_device);
7110 		}
7111 
7112 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
7113 		*rval = TRAN_FATAL_ERROR;
7114 		break;
7115 
7116 	case SATA_TRAN_CMD_UNSUPPORTED:
7117 		/*
7118 		 * Command rejected by HBA as unsupported. It was HBA driver
7119 		 * that rejected the command, command was not sent to
7120 		 * an attached device.
7121 		 */
7122 		if ((sdinfo != NULL) &&
7123 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
7124 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
7125 			    "sat_hba_start: cmd 0x%2x rejected "
7126 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
7127 
7128 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
7129 		(void) sata_txlt_invalid_command(spx);
7130 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
7131 
7132 		*rval = TRAN_ACCEPT;
7133 		break;
7134 
7135 	case SATA_TRAN_BUSY:
7136 		/*
7137 		 * Command rejected by HBA because other operation prevents
7138 		 * accepting the packet, or device is in RESET condition.
7139 		 */
7140 		if (sdinfo != NULL) {
7141 			sdinfo->satadrv_state =
7142 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
7143 
7144 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
7145 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
7146 				    "sata_hba_start: cmd 0x%2x rejected "
7147 				    "because of device reset condition\n",
7148 				    cmd);
7149 			} else {
7150 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
7151 				    "sata_hba_start: cmd 0x%2x rejected "
7152 				    "with SATA_TRAN_BUSY status\n",
7153 				    cmd);
7154 			}
7155 		}
7156 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
7157 		*rval = TRAN_BUSY;
7158 		break;
7159 
7160 	default:
7161 		/* Unrecognized HBA response */
7162 		SATA_LOG_D((sata_hba_inst, CE_WARN,
7163 		    "sata_hba_start: unrecognized HBA response "
7164 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
7165 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
7166 		*rval = TRAN_FATAL_ERROR;
7167 		break;
7168 	}
7169 
7170 	/*
7171 	 * If we got here, the packet was rejected.
7172 	 * Check if we need to remember reset state clearing request
7173 	 */
7174 	if (cmd_flags.sata_clear_dev_reset) {
7175 		/*
7176 		 * Check if device is still configured - it may have
7177 		 * disapeared from the configuration
7178 		 */
7179 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
7180 		if (sdinfo != NULL) {
7181 			/*
7182 			 * Restore the flag that requests clearing of
7183 			 * the device reset state,
7184 			 * so the next sata packet may carry it to HBA.
7185 			 */
7186 			if (sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT ||
7187 			    sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT) {
7188 				pminfo->pmult_event_flags |=
7189 				    SATA_EVNT_CLEAR_DEVICE_RESET;
7190 			} else {
7191 				sdinfo->satadrv_event_flags |=
7192 				    SATA_EVNT_CLEAR_DEVICE_RESET;
7193 			}
7194 		}
7195 	}
7196 	return (-1);
7197 }
7198 
7199 /*
7200  * Scsi response setup for invalid LBA
7201  *
7202  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
7203  */
7204 static int
7205 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
7206 {
7207 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7208 	struct scsi_extended_sense *sense;
7209 
7210 	scsipkt->pkt_reason = CMD_CMPLT;
7211 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7212 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7213 	*scsipkt->pkt_scbp = STATUS_CHECK;
7214 
7215 	*scsipkt->pkt_scbp = STATUS_CHECK;
7216 	sense = sata_arq_sense(spx);
7217 	sense->es_key = KEY_ILLEGAL_REQUEST;
7218 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
7219 
7220 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7221 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7222 
7223 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
7224 	    scsipkt->pkt_comp != NULL) {
7225 		/* scsi callback required */
7226 		if (servicing_interrupt()) {
7227 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7228 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7229 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
7230 				return (TRAN_BUSY);
7231 			}
7232 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7233 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7234 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
7235 			/* Scheduling the callback failed */
7236 			return (TRAN_BUSY);
7237 		}
7238 	}
7239 	return (TRAN_ACCEPT);
7240 }
7241 
7242 
7243 /*
7244  * Analyze device status and error registers and translate them into
7245  * appropriate scsi sense codes.
7246  * NOTE: non-packet commands only for now
7247  */
7248 static void
7249 sata_decode_device_error(sata_pkt_txlate_t *spx,
7250     struct scsi_extended_sense *sense)
7251 {
7252 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
7253 
7254 	ASSERT(sense != NULL);
7255 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
7256 	    SATA_STATUS_ERR);
7257 
7258 
7259 	if (err_reg & SATA_ERROR_ICRC) {
7260 		sense->es_key = KEY_ABORTED_COMMAND;
7261 		sense->es_add_code = 0x08; /* Communication failure */
7262 		return;
7263 	}
7264 
7265 	if (err_reg & SATA_ERROR_UNC) {
7266 		sense->es_key = KEY_MEDIUM_ERROR;
7267 		/* Information bytes (LBA) need to be set by a caller */
7268 		return;
7269 	}
7270 
7271 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
7272 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
7273 		sense->es_key = KEY_UNIT_ATTENTION;
7274 		sense->es_add_code = 0x3a; /* No media present */
7275 		return;
7276 	}
7277 
7278 	if (err_reg & SATA_ERROR_IDNF) {
7279 		if (err_reg & SATA_ERROR_ABORT) {
7280 			sense->es_key = KEY_ABORTED_COMMAND;
7281 		} else {
7282 			sense->es_key = KEY_ILLEGAL_REQUEST;
7283 			sense->es_add_code = 0x21; /* LBA out of range */
7284 		}
7285 		return;
7286 	}
7287 
7288 	if (err_reg & SATA_ERROR_ABORT) {
7289 		ASSERT(spx->txlt_sata_pkt != NULL);
7290 		sense->es_key = KEY_ABORTED_COMMAND;
7291 		return;
7292 	}
7293 }
7294 
7295 /*
7296  * Extract error LBA from sata_pkt.satapkt_cmd register fields
7297  */
7298 static void
7299 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
7300 {
7301 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
7302 
7303 	*lba = 0;
7304 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
7305 		*lba = sata_cmd->satacmd_lba_high_msb;
7306 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
7307 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
7308 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
7309 		*lba = sata_cmd->satacmd_device_reg & 0xf;
7310 	}
7311 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
7312 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
7313 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
7314 }
7315 
7316 /*
7317  * This is fixed sense format - if LBA exceeds the info field size,
7318  * no valid info will be returned (valid bit in extended sense will
7319  * be set to 0).
7320  */
7321 static struct scsi_extended_sense *
7322 sata_arq_sense(sata_pkt_txlate_t *spx)
7323 {
7324 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7325 	struct scsi_arq_status *arqs;
7326 	struct scsi_extended_sense *sense;
7327 
7328 	/* Fill ARQ sense data */
7329 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7330 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
7331 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
7332 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
7333 	arqs->sts_rqpkt_reason = CMD_CMPLT;
7334 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7335 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7336 	arqs->sts_rqpkt_resid = 0;
7337 	sense = &arqs->sts_sensedata;
7338 	bzero(sense, sizeof (struct scsi_extended_sense));
7339 	sata_fixed_sense_data_preset(sense);
7340 	return (sense);
7341 }
7342 
7343 /*
7344  * ATA Pass Through support
7345  * Sets flags indicating that an invalid value was found in some
7346  * field in the command.  It could be something illegal according to
7347  * the SAT-2 spec or it could be a feature that is not (yet?)
7348  * supported.
7349  */
7350 static int
7351 sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *spx)
7352 {
7353 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7354 	struct scsi_extended_sense *sense = sata_arq_sense(spx);
7355 
7356 	scsipkt->pkt_reason = CMD_CMPLT;
7357 	*scsipkt->pkt_scbp = STATUS_CHECK;
7358 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7359 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7360 
7361 	sense = sata_arq_sense(spx);
7362 	sense->es_key = KEY_ILLEGAL_REQUEST;
7363 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7364 
7365 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
7366 	    scsipkt->pkt_comp != NULL) {
7367 		/* scsi callback required */
7368 		if (servicing_interrupt()) {
7369 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7370 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7371 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
7372 				return (TRAN_BUSY);
7373 			}
7374 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7375 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7376 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
7377 			/* Scheduling the callback failed */
7378 			return (TRAN_BUSY);
7379 		}
7380 	}
7381 
7382 	return (TRAN_ACCEPT);
7383 }
7384 
7385 /*
7386  * The UNMAP command considers it not to be an error if the parameter length
7387  * or block descriptor length is 0.  For this case, there is nothing for TRIM
7388  * to do so just complete the command.
7389  */
7390 static int
7391 sata_txlt_unmap_nodata_cmd(sata_pkt_txlate_t *spx)
7392 {
7393 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7394 
7395 	scsipkt->pkt_reason = CMD_CMPLT;
7396 	*scsipkt->pkt_scbp = STATUS_GOOD;
7397 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7398 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7399 
7400 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
7401 	    scsipkt->pkt_comp != NULL) {
7402 		/* scsi callback required */
7403 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7404 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7405 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
7406 			/* Scheduling the callback failed */
7407 			return (TRAN_BUSY);
7408 		}
7409 	}
7410 
7411 	return (TRAN_ACCEPT);
7412 }
7413 
7414 /*
7415  * Emulated SATA Read/Write command completion for zero-length requests.
7416  * This request always succedes, so in synchronous mode it always returns
7417  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
7418  * callback cannot be scheduled.
7419  */
7420 static int
7421 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
7422 {
7423 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7424 
7425 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7426 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7427 	scsipkt->pkt_reason = CMD_CMPLT;
7428 	*scsipkt->pkt_scbp = STATUS_GOOD;
7429 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
7430 		/* scsi callback required - have to schedule it */
7431 		if (servicing_interrupt()) {
7432 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7433 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7434 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
7435 				return (TRAN_BUSY);
7436 			}
7437 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7438 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7439 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
7440 			/* Scheduling the callback failed */
7441 			return (TRAN_BUSY);
7442 		}
7443 	}
7444 	return (TRAN_ACCEPT);
7445 }
7446 
7447 
7448 /*
7449  * Translate completion status of SATA read/write commands into scsi response.
7450  * pkt completion_reason is checked to determine the completion status.
7451  * Do scsi callback if necessary.
7452  *
7453  * Note: this function may be called also for synchronously executed
7454  * commands.
7455  * This function may be used only if scsi_pkt is non-NULL.
7456  */
7457 static void
7458 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
7459 {
7460 	sata_pkt_txlate_t *spx =
7461 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7462 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7463 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7464 	struct scsi_extended_sense *sense;
7465 	uint64_t lba;
7466 	struct buf *bp;
7467 	int rval;
7468 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7469 		/* Normal completion */
7470 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7471 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
7472 		scsipkt->pkt_reason = CMD_CMPLT;
7473 		*scsipkt->pkt_scbp = STATUS_GOOD;
7474 		if (spx->txlt_tmp_buf != NULL) {
7475 			/* Temporary buffer was used */
7476 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7477 			if (bp->b_flags & B_READ) {
7478 				rval = ddi_dma_sync(
7479 				    spx->txlt_buf_dma_handle, 0, 0,
7480 				    DDI_DMA_SYNC_FORCPU);
7481 				ASSERT(rval == DDI_SUCCESS);
7482 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7483 				    bp->b_bcount);
7484 			}
7485 		}
7486 	} else {
7487 		/*
7488 		 * Something went wrong - analyze return
7489 		 */
7490 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7491 		    STATE_SENT_CMD | STATE_GOT_STATUS;
7492 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7493 		*scsipkt->pkt_scbp = STATUS_CHECK;
7494 		sense = sata_arq_sense(spx);
7495 		ASSERT(sense != NULL);
7496 
7497 		/*
7498 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
7499 		 * extract from device registers the failing LBA.
7500 		 */
7501 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
7502 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
7503 			    (scmd->satacmd_lba_mid_msb != 0 ||
7504 			    scmd->satacmd_lba_high_msb != 0)) {
7505 				/*
7506 				 * We have problem reporting this cmd LBA
7507 				 * in fixed sense data format, because of
7508 				 * the size of the scsi LBA fields.
7509 				 */
7510 				sense->es_valid = 0;
7511 			} else {
7512 				sata_extract_error_lba(spx, &lba);
7513 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
7514 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
7515 				sense->es_info_3 = (lba & 0xFF00) >> 8;
7516 				sense->es_info_4 = lba & 0xFF;
7517 			}
7518 		} else {
7519 			/* Invalid extended sense info */
7520 			sense->es_valid = 0;
7521 		}
7522 
7523 		switch (sata_pkt->satapkt_reason) {
7524 		case SATA_PKT_PORT_ERROR:
7525 			/* We may want to handle DEV GONE state as well */
7526 			/*
7527 			 * We have no device data. Assume no data transfered.
7528 			 */
7529 			sense->es_key = KEY_HARDWARE_ERROR;
7530 			break;
7531 
7532 		case SATA_PKT_DEV_ERROR:
7533 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7534 			    SATA_STATUS_ERR) {
7535 				/*
7536 				 * determine dev error reason from error
7537 				 * reg content
7538 				 */
7539 				sata_decode_device_error(spx, sense);
7540 				if (sense->es_key == KEY_MEDIUM_ERROR) {
7541 					switch (scmd->satacmd_cmd_reg) {
7542 					case SATAC_READ_DMA:
7543 					case SATAC_READ_DMA_EXT:
7544 					case SATAC_READ_DMA_QUEUED:
7545 					case SATAC_READ_DMA_QUEUED_EXT:
7546 					case SATAC_READ_FPDMA_QUEUED:
7547 						/* Unrecovered read error */
7548 						sense->es_add_code =
7549 						    SD_SCSI_ASC_UNREC_READ_ERR;
7550 						break;
7551 					case SATAC_WRITE_DMA:
7552 					case SATAC_WRITE_DMA_EXT:
7553 					case SATAC_WRITE_DMA_QUEUED:
7554 					case SATAC_WRITE_DMA_QUEUED_EXT:
7555 					case SATAC_WRITE_FPDMA_QUEUED:
7556 						/* Write error */
7557 						sense->es_add_code =
7558 						    SD_SCSI_ASC_WRITE_ERR;
7559 						break;
7560 					default:
7561 						/* Internal error */
7562 						SATA_LOG_D((
7563 						    spx->txlt_sata_hba_inst,
7564 						    CE_WARN,
7565 						    "sata_txlt_rw_completion :"
7566 						    "internal error - invalid "
7567 						    "command 0x%2x",
7568 						    scmd->satacmd_cmd_reg));
7569 						break;
7570 					}
7571 				}
7572 				break;
7573 			}
7574 			/* No extended sense key - no info available */
7575 			scsipkt->pkt_reason = CMD_INCOMPLETE;
7576 			break;
7577 
7578 		case SATA_PKT_TIMEOUT:
7579 			scsipkt->pkt_reason = CMD_TIMEOUT;
7580 			scsipkt->pkt_statistics |=
7581 			    STAT_TIMEOUT | STAT_DEV_RESET;
7582 			sense->es_key = KEY_ABORTED_COMMAND;
7583 			break;
7584 
7585 		case SATA_PKT_ABORTED:
7586 			scsipkt->pkt_reason = CMD_ABORTED;
7587 			scsipkt->pkt_statistics |= STAT_ABORTED;
7588 			sense->es_key = KEY_ABORTED_COMMAND;
7589 			break;
7590 
7591 		case SATA_PKT_RESET:
7592 			scsipkt->pkt_reason = CMD_RESET;
7593 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7594 			sense->es_key = KEY_ABORTED_COMMAND;
7595 			break;
7596 
7597 		default:
7598 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7599 			    "sata_txlt_rw_completion: "
7600 			    "invalid packet completion reason"));
7601 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7602 			break;
7603 		}
7604 	}
7605 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7606 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7607 
7608 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7609 		/* scsi callback required */
7610 		scsi_hba_pkt_comp(scsipkt);
7611 }
7612 
7613 
7614 /*
7615  * Translate completion status of non-data commands (i.e. commands returning
7616  * no data).
7617  * pkt completion_reason is checked to determine the completion status.
7618  * Do scsi callback if necessary (FLAG_NOINTR == 0)
7619  *
7620  * Note: this function may be called also for synchronously executed
7621  * commands.
7622  * This function may be used only if scsi_pkt is non-NULL.
7623  */
7624 
7625 static	void
7626 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
7627 {
7628 	sata_pkt_txlate_t *spx =
7629 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7630 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7631 
7632 	sata_set_arq_data(sata_pkt);
7633 
7634 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7635 		/* scsi callback required */
7636 		scsi_hba_pkt_comp(scsipkt);
7637 }
7638 
7639 /*
7640  * Completion handler for ATA Pass Through command
7641  */
7642 static void
7643 sata_txlt_apt_completion(sata_pkt_t *sata_pkt)
7644 {
7645 	sata_pkt_txlate_t *spx =
7646 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7647 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7648 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7649 	struct buf *bp;
7650 	uint8_t sense_key = 0, addl_sense_code = 0, addl_sense_qual = 0;
7651 
7652 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7653 		/* Normal completion */
7654 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7655 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
7656 		scsipkt->pkt_reason = CMD_CMPLT;
7657 		*scsipkt->pkt_scbp = STATUS_GOOD;
7658 
7659 		/*
7660 		 * If the command has CK_COND set
7661 		 */
7662 		if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
7663 			*scsipkt->pkt_scbp = STATUS_CHECK;
7664 			sata_fill_ata_return_desc(sata_pkt,
7665 			    KEY_RECOVERABLE_ERROR,
7666 			    SD_SCSI_ASC_APT_INFO_AVAIL, 0x1d);
7667 		}
7668 
7669 		if (spx->txlt_tmp_buf != NULL) {
7670 			/* Temporary buffer was used */
7671 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7672 			if (bp->b_flags & B_READ) {
7673 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7674 				    bp->b_bcount);
7675 			}
7676 		}
7677 	} else {
7678 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7679 		    STATE_SENT_CMD | STATE_GOT_STATUS;
7680 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7681 		*scsipkt->pkt_scbp = STATUS_CHECK;
7682 
7683 		/*
7684 		 * If DF or ERR was set, the HBA should have copied out the
7685 		 * status and error registers to the satacmd structure.
7686 		 */
7687 		if (scmd->satacmd_status_reg & SATA_STATUS_DF) {
7688 			sense_key = KEY_HARDWARE_ERROR;
7689 			addl_sense_code = SD_SCSI_ASC_INTERNAL_TARGET_FAILURE;
7690 			addl_sense_qual = 0;
7691 		} else if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
7692 			if (scmd->satacmd_error_reg & SATA_ERROR_NM) {
7693 				sense_key = KEY_NOT_READY;
7694 				addl_sense_code =
7695 				    SD_SCSI_ASC_MEDIUM_NOT_PRESENT;
7696 				addl_sense_qual = 0;
7697 			} else if (scmd->satacmd_error_reg & SATA_ERROR_UNC) {
7698 				sense_key = KEY_MEDIUM_ERROR;
7699 				addl_sense_code = SD_SCSI_ASC_UNREC_READ_ERR;
7700 				addl_sense_qual = 0;
7701 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ILI) {
7702 				sense_key = KEY_DATA_PROTECT;
7703 				addl_sense_code = SD_SCSI_ASC_WRITE_PROTECTED;
7704 				addl_sense_qual = 0;
7705 			} else if (scmd->satacmd_error_reg & SATA_ERROR_IDNF) {
7706 				sense_key = KEY_ILLEGAL_REQUEST;
7707 				addl_sense_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
7708 				addl_sense_qual = 0;
7709 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
7710 				sense_key = KEY_ABORTED_COMMAND;
7711 				addl_sense_code = SD_SCSI_ASC_NO_ADD_SENSE;
7712 				addl_sense_qual = 0;
7713 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MC) {
7714 				sense_key = KEY_UNIT_ATTENTION;
7715 				addl_sense_code =
7716 				    SD_SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED;
7717 				addl_sense_qual = 0;
7718 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MCR) {
7719 				sense_key = KEY_UNIT_ATTENTION;
7720 				addl_sense_code = SD_SCSI_ASC_OP_MEDIUM_REM_REQ;
7721 				addl_sense_qual = 0;
7722 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ICRC) {
7723 				sense_key = KEY_ABORTED_COMMAND;
7724 				addl_sense_code =
7725 				    SD_SCSI_ASC_INFO_UNIT_IUCRC_ERR;
7726 				addl_sense_qual = 0;
7727 			}
7728 		}
7729 
7730 		sata_fill_ata_return_desc(sata_pkt, sense_key, addl_sense_code,
7731 		    addl_sense_qual);
7732 	}
7733 
7734 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7735 		/* scsi callback required */
7736 		scsi_hba_pkt_comp(scsipkt);
7737 }
7738 
7739 /*
7740  * Completion handler for unmap translation command
7741  */
7742 static void
7743 sata_txlt_unmap_completion(sata_pkt_t *sata_pkt)
7744 {
7745 	sata_pkt_txlate_t *spx =
7746 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7747 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7748 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7749 	struct buf *bp;
7750 	uint8_t sense_key = 0, addl_sense_code = 0, addl_sense_qual = 0;
7751 
7752 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7753 		/* Normal completion */
7754 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7755 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
7756 		scsipkt->pkt_reason = CMD_CMPLT;
7757 		*scsipkt->pkt_scbp = STATUS_GOOD;
7758 
7759 		if (spx->txlt_tmp_buf != NULL) {
7760 			/* Temporary buffer was used */
7761 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7762 			if (bp->b_flags & B_READ) {
7763 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7764 				    bp->b_bcount);
7765 			}
7766 		}
7767 	} else {
7768 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7769 		    STATE_SENT_CMD | STATE_GOT_STATUS;
7770 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7771 		*scsipkt->pkt_scbp = STATUS_CHECK;
7772 
7773 		/*
7774 		 * If DF or ERR was set, the HBA should have copied out the
7775 		 * status and error registers to the satacmd structure.
7776 		 */
7777 		if (scmd->satacmd_status_reg & SATA_STATUS_DF) {
7778 			sense_key = KEY_HARDWARE_ERROR;
7779 			addl_sense_code = SD_SCSI_ASC_INTERNAL_TARGET_FAILURE;
7780 			addl_sense_qual = 0;
7781 		} else if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
7782 			if (scmd->satacmd_error_reg & SATA_ERROR_NM) {
7783 				sense_key = KEY_NOT_READY;
7784 				addl_sense_code =
7785 				    SD_SCSI_ASC_MEDIUM_NOT_PRESENT;
7786 				addl_sense_qual = 0;
7787 			} else if (scmd->satacmd_error_reg & SATA_ERROR_UNC) {
7788 				sense_key = KEY_MEDIUM_ERROR;
7789 				addl_sense_code = SD_SCSI_ASC_WRITE_ERR;
7790 				addl_sense_qual = 0;
7791 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ILI) {
7792 				sense_key = KEY_DATA_PROTECT;
7793 				addl_sense_code = SD_SCSI_ASC_WRITE_PROTECTED;
7794 				addl_sense_qual = 0;
7795 			} else if (scmd->satacmd_error_reg & SATA_ERROR_IDNF) {
7796 				sense_key = KEY_ILLEGAL_REQUEST;
7797 				addl_sense_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
7798 				addl_sense_qual = 0;
7799 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
7800 				sense_key = KEY_ABORTED_COMMAND;
7801 				addl_sense_code = SD_SCSI_ASC_NO_ADD_SENSE;
7802 				addl_sense_qual = 0;
7803 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MC) {
7804 				sense_key = KEY_UNIT_ATTENTION;
7805 				addl_sense_code =
7806 				    SD_SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED;
7807 				addl_sense_qual = 0;
7808 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MCR) {
7809 				sense_key = KEY_UNIT_ATTENTION;
7810 				addl_sense_code = SD_SCSI_ASC_OP_MEDIUM_REM_REQ;
7811 				addl_sense_qual = 0;
7812 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ICRC) {
7813 				sense_key = KEY_ABORTED_COMMAND;
7814 				addl_sense_code =
7815 				    SD_SCSI_ASC_INFO_UNIT_IUCRC_ERR;
7816 				addl_sense_qual = 0;
7817 			}
7818 		}
7819 
7820 		sata_fill_ata_return_desc(sata_pkt, sense_key, addl_sense_code,
7821 		    addl_sense_qual);
7822 	}
7823 
7824 	sata_free_local_buffer(spx);
7825 
7826 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7827 		/* scsi callback required */
7828 		scsi_hba_pkt_comp(scsipkt);
7829 }
7830 
7831 /*
7832  *
7833  */
7834 static void
7835 sata_fill_ata_return_desc(sata_pkt_t *sata_pkt, uint8_t sense_key,
7836     uint8_t addl_sense_code, uint8_t addl_sense_qual)
7837 {
7838 	sata_pkt_txlate_t *spx =
7839 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7840 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7841 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7842 	struct sata_apt_sense_data *apt_sd =
7843 	    (struct sata_apt_sense_data *)scsipkt->pkt_scbp;
7844 	struct scsi_descr_sense_hdr *sds = &(apt_sd->apt_sd_hdr);
7845 	struct scsi_ata_status_ret_sense_descr *ata_ret_desc =
7846 	    &(apt_sd->apt_sd_sense);
7847 	int extend = 0;
7848 
7849 	if ((scsipkt->pkt_cdbp[0] == SPC3_CMD_ATA_COMMAND_PASS_THROUGH16) &&
7850 	    (scsipkt->pkt_cdbp[2] & SATL_APT_BM_EXTEND))
7851 		extend = 1;
7852 
7853 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7854 
7855 	/* update the residual count */
7856 	*(uchar_t *)&apt_sd->apt_status = STATUS_CHECK;
7857 	*(uchar_t *)&apt_sd->apt_rqpkt_status = STATUS_GOOD;
7858 	apt_sd->apt_rqpkt_reason = CMD_CMPLT;
7859 	apt_sd->apt_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7860 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7861 	apt_sd->apt_rqpkt_resid = scsipkt->pkt_scblen -
7862 	    sizeof (struct sata_apt_sense_data);
7863 
7864 	/*
7865 	 * Fill in the Descriptor sense header
7866 	 */
7867 	bzero(sds, sizeof (struct scsi_descr_sense_hdr));
7868 	sds->ds_code = CODE_FMT_DESCR_CURRENT;
7869 	sds->ds_class = CLASS_EXTENDED_SENSE;
7870 	sds->ds_key = sense_key & 0xf;
7871 	sds->ds_add_code = addl_sense_code;
7872 	sds->ds_qual_code = addl_sense_qual;
7873 	sds->ds_addl_sense_length =
7874 	    sizeof (struct scsi_ata_status_ret_sense_descr);
7875 
7876 	/*
7877 	 * Fill in the ATA Return descriptor sense data
7878 	 */
7879 	bzero(ata_ret_desc, sizeof (struct scsi_ata_status_ret_sense_descr));
7880 	ata_ret_desc->ars_descr_type = DESCR_ATA_STATUS_RETURN;
7881 	ata_ret_desc->ars_addl_length = 0xc;
7882 	ata_ret_desc->ars_error = scmd->satacmd_error_reg;
7883 	ata_ret_desc->ars_sec_count_lsb = scmd->satacmd_sec_count_lsb;
7884 	ata_ret_desc->ars_lba_low_lsb = scmd->satacmd_lba_low_lsb;
7885 	ata_ret_desc->ars_lba_mid_lsb = scmd->satacmd_lba_mid_lsb;
7886 	ata_ret_desc->ars_lba_high_lsb = scmd->satacmd_lba_high_lsb;
7887 	ata_ret_desc->ars_device = scmd->satacmd_device_reg;
7888 	ata_ret_desc->ars_status = scmd->satacmd_status_reg;
7889 
7890 	if (extend == 1) {
7891 		ata_ret_desc->ars_extend = 1;
7892 		ata_ret_desc->ars_sec_count_msb = scmd->satacmd_sec_count_msb;
7893 		ata_ret_desc->ars_lba_low_msb = scmd->satacmd_lba_low_msb;
7894 		ata_ret_desc->ars_lba_mid_msb = scmd->satacmd_lba_mid_msb;
7895 		ata_ret_desc->ars_lba_high_msb = scmd->satacmd_lba_high_msb;
7896 	} else {
7897 		ata_ret_desc->ars_extend = 0;
7898 		ata_ret_desc->ars_sec_count_msb = 0;
7899 		ata_ret_desc->ars_lba_low_msb = 0;
7900 		ata_ret_desc->ars_lba_mid_msb = 0;
7901 		ata_ret_desc->ars_lba_high_msb = 0;
7902 	}
7903 }
7904 
7905 static	void
7906 sata_set_arq_data(sata_pkt_t *sata_pkt)
7907 {
7908 	sata_pkt_txlate_t *spx =
7909 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7910 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7911 	struct scsi_extended_sense *sense;
7912 
7913 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7914 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7915 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7916 		/* Normal completion */
7917 		scsipkt->pkt_reason = CMD_CMPLT;
7918 		*scsipkt->pkt_scbp = STATUS_GOOD;
7919 	} else {
7920 		/* Something went wrong */
7921 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7922 		*scsipkt->pkt_scbp = STATUS_CHECK;
7923 		sense = sata_arq_sense(spx);
7924 		switch (sata_pkt->satapkt_reason) {
7925 		case SATA_PKT_PORT_ERROR:
7926 			/*
7927 			 * We have no device data. Assume no data transfered.
7928 			 */
7929 			sense->es_key = KEY_HARDWARE_ERROR;
7930 			break;
7931 
7932 		case SATA_PKT_DEV_ERROR:
7933 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7934 			    SATA_STATUS_ERR) {
7935 				/*
7936 				 * determine dev error reason from error
7937 				 * reg content
7938 				 */
7939 				sata_decode_device_error(spx, sense);
7940 				break;
7941 			}
7942 			/* No extended sense key - no info available */
7943 			break;
7944 
7945 		case SATA_PKT_TIMEOUT:
7946 			scsipkt->pkt_reason = CMD_TIMEOUT;
7947 			scsipkt->pkt_statistics |=
7948 			    STAT_TIMEOUT | STAT_DEV_RESET;
7949 			/* No extended sense key ? */
7950 			break;
7951 
7952 		case SATA_PKT_ABORTED:
7953 			scsipkt->pkt_reason = CMD_ABORTED;
7954 			scsipkt->pkt_statistics |= STAT_ABORTED;
7955 			/* No extended sense key ? */
7956 			break;
7957 
7958 		case SATA_PKT_RESET:
7959 			/* pkt aborted by an explicit reset from a host */
7960 			scsipkt->pkt_reason = CMD_RESET;
7961 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7962 			break;
7963 
7964 		default:
7965 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7966 			    "sata_txlt_nodata_cmd_completion: "
7967 			    "invalid packet completion reason %d",
7968 			    sata_pkt->satapkt_reason));
7969 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7970 			break;
7971 		}
7972 
7973 	}
7974 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7975 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7976 }
7977 
7978 
7979 /*
7980  * Build Mode sense R/W recovery page
7981  * NOT IMPLEMENTED
7982  */
7983 
7984 static int
7985 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7986 {
7987 #ifndef __lock_lint
7988 	_NOTE(ARGUNUSED(sdinfo))
7989 	_NOTE(ARGUNUSED(pcntrl))
7990 	_NOTE(ARGUNUSED(buf))
7991 #endif
7992 	return (0);
7993 }
7994 
7995 /*
7996  * Build Mode sense caching page  -  scsi-3 implementation.
7997  * Page length distinguishes previous format from scsi-3 format.
7998  * buf must have space for 0x12 bytes.
7999  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
8000  *
8001  */
8002 static int
8003 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
8004 {
8005 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
8006 	sata_id_t *sata_id = &sdinfo->satadrv_id;
8007 
8008 	/*
8009 	 * Most of the fields are set to 0, being not supported and/or disabled
8010 	 */
8011 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
8012 
8013 	/* Saved paramters not supported */
8014 	if (pcntrl == 3)
8015 		return (0);
8016 	if (pcntrl == 0 || pcntrl == 2) {
8017 		/*
8018 		 * For now treat current and default parameters as same
8019 		 * That may have to change, if target driver will complain
8020 		 */
8021 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
8022 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
8023 
8024 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
8025 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
8026 			page->dra = 1;		/* Read Ahead disabled */
8027 			page->rcd = 1;		/* Read Cache disabled */
8028 		}
8029 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
8030 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
8031 			page->wce = 1;		/* Write Cache enabled */
8032 	} else {
8033 		/* Changeable parameters */
8034 		page->mode_page.code = MODEPAGE_CACHING;
8035 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
8036 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
8037 			page->dra = 1;
8038 			page->rcd = 1;
8039 		}
8040 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
8041 			page->wce = 1;
8042 	}
8043 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
8044 	    sizeof (struct mode_page));
8045 }
8046 
8047 /*
8048  * Build Mode sense exception cntrl page
8049  */
8050 static int
8051 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
8052 {
8053 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
8054 	sata_id_t *sata_id = &sdinfo->satadrv_id;
8055 
8056 	/*
8057 	 * Most of the fields are set to 0, being not supported and/or disabled
8058 	 */
8059 	bzero(buf, PAGELENGTH_INFO_EXCPT);
8060 
8061 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
8062 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
8063 
8064 	/* Indicate that this is page is saveable */
8065 	page->mode_page.ps = 1;
8066 
8067 	/*
8068 	 * We will return the same data for default, current and saved page.
8069 	 * The only changeable bit is dexcpt and that bit is required
8070 	 * by the ATA specification to be preserved across power cycles.
8071 	 */
8072 	if (pcntrl != 1) {
8073 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
8074 		page->mrie = MRIE_ONLY_ON_REQUEST;
8075 	}
8076 	else
8077 		page->dexcpt = 1;	/* Only changeable parameter */
8078 
8079 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page));
8080 }
8081 
8082 
8083 static int
8084 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
8085 {
8086 	struct mode_acoustic_management *page =
8087 	    (struct mode_acoustic_management *)buf;
8088 	sata_id_t *sata_id = &sdinfo->satadrv_id;
8089 
8090 	/*
8091 	 * Most of the fields are set to 0, being not supported and/or disabled
8092 	 */
8093 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
8094 
8095 	switch (pcntrl) {
8096 	case P_CNTRL_DEFAULT:
8097 		/*  default paramters not supported */
8098 		return (0);
8099 
8100 	case P_CNTRL_CURRENT:
8101 	case P_CNTRL_SAVED:
8102 		/* Saved and current are supported and are identical */
8103 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
8104 		page->mode_page.length =
8105 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
8106 		page->mode_page.ps = 1;
8107 
8108 		/* Word 83 indicates if feature is supported */
8109 		/* If feature is not supported */
8110 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
8111 			page->acoustic_manag_enable =
8112 			    ACOUSTIC_DISABLED;
8113 		} else {
8114 			page->acoustic_manag_enable =
8115 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
8116 			    != 0);
8117 			/* Word 94 inidicates the value */
8118 #ifdef	_LITTLE_ENDIAN
8119 			page->acoustic_manag_level =
8120 			    (uchar_t)sata_id->ai_acoustic;
8121 			page->vendor_recommended_value =
8122 			    sata_id->ai_acoustic >> 8;
8123 #else
8124 			page->acoustic_manag_level =
8125 			    sata_id->ai_acoustic >> 8;
8126 			page->vendor_recommended_value =
8127 			    (uchar_t)sata_id->ai_acoustic;
8128 #endif
8129 		}
8130 		break;
8131 
8132 	case P_CNTRL_CHANGEABLE:
8133 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
8134 		page->mode_page.length =
8135 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
8136 		page->mode_page.ps = 1;
8137 
8138 		/* Word 83 indicates if the feature is supported */
8139 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
8140 			page->acoustic_manag_enable =
8141 			    ACOUSTIC_ENABLED;
8142 			page->acoustic_manag_level = 0xff;
8143 		}
8144 		break;
8145 	}
8146 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
8147 	    sizeof (struct mode_page));
8148 }
8149 
8150 
8151 /*
8152  * Build Mode sense power condition page.
8153  */
8154 static int
8155 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
8156 {
8157 	struct mode_info_power_cond *page = (struct mode_info_power_cond *)buf;
8158 	sata_id_t *sata_id = &sdinfo->satadrv_id;
8159 
8160 	/*
8161 	 * Most of the fields are set to 0, being not supported and/or disabled
8162 	 * power condition page length was 0x0a
8163 	 */
8164 	bzero(buf, sizeof (struct mode_info_power_cond));
8165 
8166 	if (pcntrl == P_CNTRL_DEFAULT) {
8167 		/*  default paramters not supported */
8168 		return (0);
8169 	}
8170 
8171 	page->mode_page.code = MODEPAGE_POWER_COND;
8172 	page->mode_page.length = sizeof (struct mode_info_power_cond);
8173 
8174 	if (sata_id->ai_cap & SATA_STANDBYTIMER) {
8175 		page->standby = 1;
8176 		bcopy(sdinfo->satadrv_standby_timer, page->standby_cond_timer,
8177 		    sizeof (uchar_t) * 4);
8178 	}
8179 
8180 	return (sizeof (struct mode_info_power_cond));
8181 }
8182 
8183 /*
8184  * Process mode select caching page 8 (scsi3 format only).
8185  * Read Ahead (same as read cache) and Write Cache may be turned on and off
8186  * if these features are supported by the device. If these features are not
8187  * supported, the command will be terminated with STATUS_CHECK.
8188  * This function fails only if the SET FEATURE command sent to
8189  * the device fails. The page format is not verified, assuming that the
8190  * target driver operates correctly - if parameters length is too short,
8191  * we just drop the page.
8192  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
8193  * setting have to be changed.
8194  * SET FEATURE command is executed synchronously, i.e. we wait here until
8195  * it is completed, regardless of the scsi pkt directives.
8196  *
8197  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
8198  * changing DRA will change RCD.
8199  *
8200  * More than one SATA command may be executed to perform operations specified
8201  * by mode select pages. The first error terminates further execution.
8202  * Operations performed successully are not backed-up in such case.
8203  *
8204  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
8205  * If operation resulted in changing device setup, dmod flag should be set to
8206  * one (1). If parameters were not changed, dmod flag should be set to 0.
8207  * Upon return, if operation required sending command to the device, the rval
8208  * should be set to the value returned by sata_hba_start. If operation
8209  * did not require device access, rval should be set to TRAN_ACCEPT.
8210  * The pagelen should be set to the length of the page.
8211  *
8212  * This function has to be called with a port mutex held.
8213  *
8214  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
8215  */
8216 int
8217 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
8218     int parmlen, int *pagelen, int *rval, int *dmod)
8219 {
8220 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8221 	sata_drive_info_t *sdinfo;
8222 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8223 	sata_id_t *sata_id;
8224 	struct scsi_extended_sense *sense;
8225 	int wce, dra;	/* Current settings */
8226 
8227 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
8228 	    &spx->txlt_sata_pkt->satapkt_device);
8229 	sata_id = &sdinfo->satadrv_id;
8230 	*dmod = 0;
8231 
8232 	/* Verify parameters length. If too short, drop it */
8233 	if ((PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
8234 	    sizeof (struct mode_page)) > parmlen) {
8235 		*scsipkt->pkt_scbp = STATUS_CHECK;
8236 		sense = sata_arq_sense(spx);
8237 		sense->es_key = KEY_ILLEGAL_REQUEST;
8238 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8239 		*pagelen = parmlen;
8240 		*rval = TRAN_ACCEPT;
8241 		return (SATA_FAILURE);
8242 	}
8243 
8244 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
8245 
8246 	/* Current setting of Read Ahead (and Read Cache) */
8247 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
8248 		dra = 0;	/* 0 == not disabled */
8249 	else
8250 		dra = 1;
8251 	/* Current setting of Write Cache */
8252 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
8253 		wce = 1;
8254 	else
8255 		wce = 0;
8256 
8257 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
8258 		/* nothing to do */
8259 		*rval = TRAN_ACCEPT;
8260 		return (SATA_SUCCESS);
8261 	}
8262 
8263 	/*
8264 	 * Need to flip some setting
8265 	 * Set-up Internal SET FEATURES command(s)
8266 	 */
8267 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
8268 	scmd->satacmd_addr_type = 0;
8269 	scmd->satacmd_device_reg = 0;
8270 	scmd->satacmd_status_reg = 0;
8271 	scmd->satacmd_error_reg = 0;
8272 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
8273 	if (page->dra != dra || page->rcd != dra) {
8274 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
8275 			/* Need to flip read ahead setting */
8276 			if (dra == 0)
8277 				/* Disable read ahead / read cache */
8278 				scmd->satacmd_features_reg =
8279 				    SATAC_SF_DISABLE_READ_AHEAD;
8280 			else
8281 				/* Enable read ahead  / read cache */
8282 				scmd->satacmd_features_reg =
8283 				    SATAC_SF_ENABLE_READ_AHEAD;
8284 
8285 			/* Transfer command to HBA */
8286 			if (sata_hba_start(spx, rval) != 0)
8287 				/*
8288 				 * Pkt not accepted for execution.
8289 				 */
8290 				return (SATA_FAILURE);
8291 
8292 			*dmod = 1;
8293 
8294 			/* Now process return */
8295 			if (spx->txlt_sata_pkt->satapkt_reason !=
8296 			    SATA_PKT_COMPLETED) {
8297 				goto failure;	/* Terminate */
8298 			}
8299 		} else {
8300 			*scsipkt->pkt_scbp = STATUS_CHECK;
8301 			sense = sata_arq_sense(spx);
8302 			sense->es_key = KEY_ILLEGAL_REQUEST;
8303 			sense->es_add_code =
8304 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8305 			*pagelen = parmlen;
8306 			*rval = TRAN_ACCEPT;
8307 			return (SATA_FAILURE);
8308 		}
8309 	}
8310 
8311 	/* Note that the packet is not removed, so it could be re-used */
8312 	if (page->wce != wce) {
8313 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
8314 			/* Need to flip Write Cache setting */
8315 			if (page->wce == 1)
8316 				/* Enable write cache */
8317 				scmd->satacmd_features_reg =
8318 				    SATAC_SF_ENABLE_WRITE_CACHE;
8319 			else
8320 				/* Disable write cache */
8321 				scmd->satacmd_features_reg =
8322 				    SATAC_SF_DISABLE_WRITE_CACHE;
8323 
8324 			/* Transfer command to HBA */
8325 			if (sata_hba_start(spx, rval) != 0)
8326 				/*
8327 				 * Pkt not accepted for execution.
8328 				 */
8329 				return (SATA_FAILURE);
8330 
8331 			*dmod = 1;
8332 
8333 			/* Now process return */
8334 			if (spx->txlt_sata_pkt->satapkt_reason !=
8335 			    SATA_PKT_COMPLETED) {
8336 				goto failure;
8337 			}
8338 		} else {
8339 			*scsipkt->pkt_scbp = STATUS_CHECK;
8340 			sense = sata_arq_sense(spx);
8341 			sense->es_key = KEY_ILLEGAL_REQUEST;
8342 			sense->es_add_code =
8343 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8344 			*pagelen = parmlen;
8345 			*rval = TRAN_ACCEPT;
8346 			return (SATA_FAILURE);
8347 		}
8348 	}
8349 	return (SATA_SUCCESS);
8350 
8351 failure:
8352 	sata_xlate_errors(spx);
8353 
8354 	return (SATA_FAILURE);
8355 }
8356 
8357 /*
8358  * Process mode select informational exceptions control page 0x1c
8359  *
8360  * The only changeable bit is dexcpt (disable exceptions).
8361  * MRIE (method of reporting informational exceptions) must be
8362  * "only on request".
8363  * This page applies to informational exceptions that report
8364  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
8365  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
8366  * Informational exception conditions occur as the result of background scan
8367  * errors, background self-test errors, or vendor specific events within a
8368  * logical unit. An informational exception condition may occur asynchronous
8369  * to any commands.
8370  *
8371  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
8372  * If operation resulted in changing device setup, dmod flag should be set to
8373  * one (1). If parameters were not changed, dmod flag should be set to 0.
8374  * Upon return, if operation required sending command to the device, the rval
8375  * should be set to the value returned by sata_hba_start. If operation
8376  * did not require device access, rval should be set to TRAN_ACCEPT.
8377  * The pagelen should be set to the length of the page.
8378  *
8379  * This function has to be called with a port mutex held.
8380  *
8381  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
8382  *
8383  * Cannot be called in the interrupt context.
8384  */
8385 static	int
8386 sata_mode_select_page_1c(
8387 	sata_pkt_txlate_t *spx,
8388 	struct mode_info_excpt_page *page,
8389 	int parmlen,
8390 	int *pagelen,
8391 	int *rval,
8392 	int *dmod)
8393 {
8394 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8395 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8396 	sata_drive_info_t *sdinfo;
8397 	sata_id_t *sata_id;
8398 	struct scsi_extended_sense *sense;
8399 
8400 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
8401 	    &spx->txlt_sata_pkt->satapkt_device);
8402 	sata_id = &sdinfo->satadrv_id;
8403 
8404 	*dmod = 0;
8405 
8406 	/* Verify parameters length. If too short, drop it */
8407 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) > parmlen) ||
8408 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
8409 		*scsipkt->pkt_scbp = STATUS_CHECK;
8410 		sense = sata_arq_sense(spx);
8411 		sense->es_key = KEY_ILLEGAL_REQUEST;
8412 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8413 		*pagelen = parmlen;
8414 		*rval = TRAN_ACCEPT;
8415 		return (SATA_FAILURE);
8416 	}
8417 
8418 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
8419 
8420 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
8421 		*scsipkt->pkt_scbp = STATUS_CHECK;
8422 		sense = sata_arq_sense(spx);
8423 		sense->es_key = KEY_ILLEGAL_REQUEST;
8424 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
8425 		*pagelen = parmlen;
8426 		*rval = TRAN_ACCEPT;
8427 		return (SATA_FAILURE);
8428 	}
8429 
8430 	/* If already in the state requested, we are done */
8431 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
8432 		/* nothing to do */
8433 		*rval = TRAN_ACCEPT;
8434 		return (SATA_SUCCESS);
8435 	}
8436 
8437 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
8438 
8439 	/* Build SMART_ENABLE or SMART_DISABLE command */
8440 	scmd->satacmd_addr_type = 0;		/* N/A */
8441 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
8442 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
8443 	scmd->satacmd_features_reg = page->dexcpt ?
8444 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
8445 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
8446 	scmd->satacmd_cmd_reg = SATAC_SMART;
8447 
8448 	/* Transfer command to HBA */
8449 	if (sata_hba_start(spx, rval) != 0)
8450 		/*
8451 		 * Pkt not accepted for execution.
8452 		 */
8453 		return (SATA_FAILURE);
8454 
8455 	*dmod = 1;	/* At least may have been modified */
8456 
8457 	/* Now process return */
8458 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
8459 		return (SATA_SUCCESS);
8460 
8461 	/* Packet did not complete successfully */
8462 	sata_xlate_errors(spx);
8463 
8464 	return (SATA_FAILURE);
8465 }
8466 
8467 /*
8468  * Process mode select acoustic management control page 0x30
8469  *
8470  *
8471  * This function has to be called with a port mutex held.
8472  *
8473  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
8474  *
8475  * Cannot be called in the interrupt context.
8476  */
8477 int
8478 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
8479     mode_acoustic_management *page, int parmlen, int *pagelen,
8480     int *rval, int *dmod)
8481 {
8482 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8483 	sata_drive_info_t *sdinfo;
8484 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8485 	sata_id_t *sata_id;
8486 	struct scsi_extended_sense *sense;
8487 
8488 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
8489 	    &spx->txlt_sata_pkt->satapkt_device);
8490 	sata_id = &sdinfo->satadrv_id;
8491 	*dmod = 0;
8492 
8493 	/* If parmlen is too short or the feature is not supported, drop it */
8494 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
8495 	    sizeof (struct mode_page)) > parmlen) ||
8496 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
8497 		*scsipkt->pkt_scbp = STATUS_CHECK;
8498 		sense = sata_arq_sense(spx);
8499 		sense->es_key = KEY_ILLEGAL_REQUEST;
8500 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8501 		*pagelen = parmlen;
8502 		*rval = TRAN_ACCEPT;
8503 		return (SATA_FAILURE);
8504 	}
8505 
8506 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
8507 	    sizeof (struct mode_page);
8508 
8509 	/*
8510 	 * We can enable and disable acoustice management and
8511 	 * set the acoustic management level.
8512 	 */
8513 
8514 	/*
8515 	 * Set-up Internal SET FEATURES command(s)
8516 	 */
8517 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
8518 	scmd->satacmd_addr_type = 0;
8519 	scmd->satacmd_device_reg = 0;
8520 	scmd->satacmd_status_reg = 0;
8521 	scmd->satacmd_error_reg = 0;
8522 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
8523 	if (page->acoustic_manag_enable) {
8524 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
8525 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
8526 	} else {	/* disabling acoustic management */
8527 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
8528 	}
8529 
8530 	/* Transfer command to HBA */
8531 	if (sata_hba_start(spx, rval) != 0)
8532 		/*
8533 		 * Pkt not accepted for execution.
8534 		 */
8535 		return (SATA_FAILURE);
8536 
8537 	/* Now process return */
8538 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
8539 		sata_xlate_errors(spx);
8540 		return (SATA_FAILURE);
8541 	}
8542 
8543 	*dmod = 1;
8544 
8545 	return (SATA_SUCCESS);
8546 }
8547 
8548 /*
8549  * Process mode select power condition page 0x1a
8550  *
8551  * This function has to be called with a port mutex held.
8552  *
8553  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
8554  *
8555  * Cannot be called in the interrupt context.
8556  */
8557 int
8558 sata_mode_select_page_1a(sata_pkt_txlate_t *spx, struct
8559     mode_info_power_cond *page, int parmlen, int *pagelen,
8560     int *rval, int *dmod)
8561 {
8562 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8563 	sata_drive_info_t *sdinfo;
8564 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8565 	sata_id_t *sata_id;
8566 	struct scsi_extended_sense *sense;
8567 	uint8_t ata_count;
8568 	int i, len;
8569 
8570 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
8571 	    &spx->txlt_sata_pkt->satapkt_device);
8572 	sata_id = &sdinfo->satadrv_id;
8573 	*dmod = 0;
8574 
8575 	len = sizeof (struct mode_info_power_cond);
8576 	len += sizeof (struct mode_page);
8577 
8578 	/* If parmlen is too short or the feature is not supported, drop it */
8579 	if ((len < parmlen) || (page->idle == 1) ||
8580 	    (!(sata_id->ai_cap & SATA_STANDBYTIMER) && page->standby == 1)) {
8581 		*scsipkt->pkt_scbp = STATUS_CHECK;
8582 		sense = sata_arq_sense(spx);
8583 		sense->es_key = KEY_ILLEGAL_REQUEST;
8584 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8585 		*pagelen = parmlen;
8586 		*rval = TRAN_ACCEPT;
8587 		return (SATA_FAILURE);
8588 	}
8589 
8590 	*pagelen = len;
8591 
8592 	/*
8593 	 * Set-up Internal STANDBY command(s)
8594 	 */
8595 	if (page->standby == 0)
8596 		goto out;
8597 
8598 	ata_count = sata_get_standby_timer(page->standby_cond_timer);
8599 
8600 	scmd->satacmd_addr_type = 0;
8601 	scmd->satacmd_sec_count_lsb = ata_count;
8602 	scmd->satacmd_lba_low_lsb = 0;
8603 	scmd->satacmd_lba_mid_lsb = 0;
8604 	scmd->satacmd_lba_high_lsb = 0;
8605 	scmd->satacmd_features_reg = 0;
8606 	scmd->satacmd_device_reg = 0;
8607 	scmd->satacmd_status_reg = 0;
8608 	scmd->satacmd_cmd_reg = SATAC_STANDBY;
8609 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8610 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
8611 
8612 	/* Transfer command to HBA */
8613 	if (sata_hba_start(spx, rval) != 0) {
8614 		return (SATA_FAILURE);
8615 	} else {
8616 		if ((scmd->satacmd_error_reg != 0) ||
8617 		    (spx->txlt_sata_pkt->satapkt_reason !=
8618 		    SATA_PKT_COMPLETED)) {
8619 			sata_xlate_errors(spx);
8620 			return (SATA_FAILURE);
8621 		}
8622 	}
8623 
8624 	for (i = 0; i < 4; i++) {
8625 		sdinfo->satadrv_standby_timer[i] = page->standby_cond_timer[i];
8626 	}
8627 out:
8628 	*dmod = 1;
8629 	return (SATA_SUCCESS);
8630 }
8631 
8632 /*
8633  * sata_build_lsense_page0() is used to create the
8634  * SCSI LOG SENSE page 0 (supported log pages)
8635  *
8636  * Currently supported pages are 0, 0x10, 0x2f, 0x30 and 0x0e
8637  * (supported log pages, self-test results, informational exceptions
8638  * Sun vendor specific ATA SMART data, and start stop cycle counter).
8639  *
8640  * Takes a sata_drive_info t * and the address of a buffer
8641  * in which to create the page information.
8642  *
8643  * Returns the number of bytes valid in the buffer.
8644  */
8645 static	int
8646 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
8647 {
8648 	struct log_parameter *lpp = (struct log_parameter *)buf;
8649 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
8650 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
8651 	sata_id_t *sata_id = &sdinfo->satadrv_id;
8652 
8653 	lpp->param_code[0] = 0;
8654 	lpp->param_code[1] = 0;
8655 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8656 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
8657 
8658 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
8659 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
8660 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
8661 			++num_pages_supported;
8662 		}
8663 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
8664 		++num_pages_supported;
8665 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
8666 		++num_pages_supported;
8667 		*page_ptr++ = PAGE_CODE_START_STOP_CYCLE_COUNTER;
8668 		++num_pages_supported;
8669 	}
8670 
8671 	lpp->param_len = num_pages_supported;
8672 
8673 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
8674 	    num_pages_supported);
8675 }
8676 
8677 /*
8678  * sata_build_lsense_page_10() is used to create the
8679  * SCSI LOG SENSE page 0x10 (self-test results)
8680  *
8681  * Takes a sata_drive_info t * and the address of a buffer
8682  * in which to create the page information as well as a sata_hba_inst_t *.
8683  *
8684  * Returns the number of bytes valid in the buffer.
8685  *
8686  * Note: Self test and SMART data is accessible in device log pages.
8687  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
8688  * of data can be transferred by a single command), or by the General Purpose
8689  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
8690  * - approximately 33MB - can be transferred by a single command.
8691  * The SCT Command response (either error or command) is the same for both
8692  * the SMART and GPL methods of issuing commands.
8693  * This function uses READ LOG EXT command when drive supports LBA48, and
8694  * SMART READ command otherwise.
8695  *
8696  * Since above commands are executed in a synchronous mode, this function
8697  * should not be called in an interrupt context.
8698  */
8699 static	int
8700 sata_build_lsense_page_10(
8701 	sata_drive_info_t *sdinfo,
8702 	uint8_t *buf,
8703 	sata_hba_inst_t *sata_hba_inst)
8704 {
8705 	struct log_parameter *lpp = (struct log_parameter *)buf;
8706 	int rval;
8707 
8708 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
8709 		struct smart_ext_selftest_log *ext_selftest_log;
8710 
8711 		ext_selftest_log = kmem_zalloc(
8712 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
8713 
8714 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
8715 		    ext_selftest_log, 0);
8716 		if (rval == 0) {
8717 			int index, start_index;
8718 			struct smart_ext_selftest_log_entry *entry;
8719 			static const struct smart_ext_selftest_log_entry empty =
8720 			    {0};
8721 			uint16_t block_num;
8722 			int count;
8723 			boolean_t only_one_block = B_FALSE;
8724 
8725 			index = ext_selftest_log->
8726 			    smart_ext_selftest_log_index[0];
8727 			index |= ext_selftest_log->
8728 			    smart_ext_selftest_log_index[1] << 8;
8729 			if (index == 0)
8730 				goto out;
8731 
8732 			--index;	/* Correct for 0 origin */
8733 			start_index = index;	/* remember where we started */
8734 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8735 			if (block_num != 0) {
8736 				rval = sata_ext_smart_selftest_read_log(
8737 				    sata_hba_inst, sdinfo, ext_selftest_log,
8738 				    block_num);
8739 				if (rval != 0)
8740 					goto out;
8741 			}
8742 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8743 			entry =
8744 			    &ext_selftest_log->
8745 			    smart_ext_selftest_log_entries[index];
8746 
8747 			for (count = 1;
8748 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8749 			    ++count) {
8750 				uint8_t status;
8751 				uint8_t code;
8752 				uint8_t sense_key;
8753 				uint8_t add_sense_code;
8754 				uint8_t add_sense_code_qual;
8755 
8756 				/* If this is an unused entry, we are done */
8757 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
8758 					/* Broken firmware on some disks */
8759 					if (index + 1 ==
8760 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
8761 						--entry;
8762 						--index;
8763 						if (bcmp(entry, &empty,
8764 						    sizeof (empty)) == 0)
8765 							goto out;
8766 					} else
8767 						goto out;
8768 				}
8769 
8770 				if (only_one_block &&
8771 				    start_index == index)
8772 					goto out;
8773 
8774 				lpp->param_code[0] = 0;
8775 				lpp->param_code[1] = count;
8776 				lpp->param_ctrl_flags =
8777 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8778 				lpp->param_len =
8779 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8780 
8781 				status = entry->smart_ext_selftest_log_status;
8782 				status >>= 4;
8783 				switch (status) {
8784 				case 0:
8785 				default:
8786 					sense_key = KEY_NO_SENSE;
8787 					add_sense_code =
8788 					    SD_SCSI_ASC_NO_ADD_SENSE;
8789 					add_sense_code_qual = 0;
8790 					break;
8791 				case 1:
8792 					sense_key = KEY_ABORTED_COMMAND;
8793 					add_sense_code =
8794 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8795 					add_sense_code_qual = SCSI_COMPONENT_81;
8796 					break;
8797 				case 2:
8798 					sense_key = KEY_ABORTED_COMMAND;
8799 					add_sense_code =
8800 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8801 					add_sense_code_qual = SCSI_COMPONENT_82;
8802 					break;
8803 				case 3:
8804 					sense_key = KEY_ABORTED_COMMAND;
8805 					add_sense_code =
8806 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8807 					add_sense_code_qual = SCSI_COMPONENT_83;
8808 					break;
8809 				case 4:
8810 					sense_key = KEY_HARDWARE_ERROR;
8811 					add_sense_code =
8812 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8813 					add_sense_code_qual = SCSI_COMPONENT_84;
8814 					break;
8815 				case 5:
8816 					sense_key = KEY_HARDWARE_ERROR;
8817 					add_sense_code =
8818 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8819 					add_sense_code_qual = SCSI_COMPONENT_85;
8820 					break;
8821 				case 6:
8822 					sense_key = KEY_HARDWARE_ERROR;
8823 					add_sense_code =
8824 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8825 					add_sense_code_qual = SCSI_COMPONENT_86;
8826 					break;
8827 				case 7:
8828 					sense_key = KEY_MEDIUM_ERROR;
8829 					add_sense_code =
8830 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8831 					add_sense_code_qual = SCSI_COMPONENT_87;
8832 					break;
8833 				case 8:
8834 					sense_key = KEY_HARDWARE_ERROR;
8835 					add_sense_code =
8836 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8837 					add_sense_code_qual = SCSI_COMPONENT_88;
8838 					break;
8839 				}
8840 				code = 0;	/* unspecified */
8841 				status |= (code << 4);
8842 				lpp->param_values[0] = status;
8843 				lpp->param_values[1] = 0; /* unspecified */
8844 				lpp->param_values[2] = entry->
8845 				    smart_ext_selftest_log_timestamp[1];
8846 				lpp->param_values[3] = entry->
8847 				    smart_ext_selftest_log_timestamp[0];
8848 				if (status != 0) {
8849 					lpp->param_values[4] = 0;
8850 					lpp->param_values[5] = 0;
8851 					lpp->param_values[6] = entry->
8852 					    smart_ext_selftest_log_failing_lba
8853 					    [5];
8854 					lpp->param_values[7] = entry->
8855 					    smart_ext_selftest_log_failing_lba
8856 					    [4];
8857 					lpp->param_values[8] = entry->
8858 					    smart_ext_selftest_log_failing_lba
8859 					    [3];
8860 					lpp->param_values[9] = entry->
8861 					    smart_ext_selftest_log_failing_lba
8862 					    [2];
8863 					lpp->param_values[10] = entry->
8864 					    smart_ext_selftest_log_failing_lba
8865 					    [1];
8866 					lpp->param_values[11] = entry->
8867 					    smart_ext_selftest_log_failing_lba
8868 					    [0];
8869 				} else {	/* No bad block address */
8870 					lpp->param_values[4] = 0xff;
8871 					lpp->param_values[5] = 0xff;
8872 					lpp->param_values[6] = 0xff;
8873 					lpp->param_values[7] = 0xff;
8874 					lpp->param_values[8] = 0xff;
8875 					lpp->param_values[9] = 0xff;
8876 					lpp->param_values[10] = 0xff;
8877 					lpp->param_values[11] = 0xff;
8878 				}
8879 
8880 				lpp->param_values[12] = sense_key;
8881 				lpp->param_values[13] = add_sense_code;
8882 				lpp->param_values[14] = add_sense_code_qual;
8883 				lpp->param_values[15] = 0; /* undefined */
8884 
8885 				lpp = (struct log_parameter *)
8886 				    (((uint8_t *)lpp) +
8887 				    SCSI_LOG_PARAM_HDR_LEN +
8888 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8889 
8890 				--index;	/* Back up to previous entry */
8891 				if (index < 0) {
8892 					if (block_num > 0) {
8893 						--block_num;
8894 					} else {
8895 						struct read_log_ext_directory
8896 						    logdir;
8897 
8898 						rval =
8899 						    sata_read_log_ext_directory(
8900 						    sata_hba_inst, sdinfo,
8901 						    &logdir);
8902 						if (rval == -1)
8903 							goto out;
8904 						if ((logdir.read_log_ext_vers
8905 						    [0] == 0) &&
8906 						    (logdir.read_log_ext_vers
8907 						    [1] == 0))
8908 							goto out;
8909 						block_num =
8910 						    logdir.read_log_ext_nblks
8911 						    [EXT_SMART_SELFTEST_LOG_PAGE
8912 						    - 1][0];
8913 						block_num |= logdir.
8914 						    read_log_ext_nblks
8915 						    [EXT_SMART_SELFTEST_LOG_PAGE
8916 						    - 1][1] << 8;
8917 						--block_num;
8918 						only_one_block =
8919 						    (block_num == 0);
8920 					}
8921 					rval = sata_ext_smart_selftest_read_log(
8922 					    sata_hba_inst, sdinfo,
8923 					    ext_selftest_log, block_num);
8924 					if (rval != 0)
8925 						goto out;
8926 
8927 					index =
8928 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
8929 					    1;
8930 				}
8931 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8932 				entry = &ext_selftest_log->
8933 				    smart_ext_selftest_log_entries[index];
8934 			}
8935 		}
8936 out:
8937 		kmem_free(ext_selftest_log,
8938 		    sizeof (struct smart_ext_selftest_log));
8939 	} else {
8940 		struct smart_selftest_log *selftest_log;
8941 
8942 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
8943 		    KM_SLEEP);
8944 
8945 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
8946 		    selftest_log);
8947 
8948 		if (rval == 0) {
8949 			int index;
8950 			int count;
8951 			struct smart_selftest_log_entry *entry;
8952 			static const struct smart_selftest_log_entry empty =
8953 			    { 0 };
8954 
8955 			index = selftest_log->smart_selftest_log_index;
8956 			if (index == 0)
8957 				goto done;
8958 			--index;	/* Correct for 0 origin */
8959 			entry = &selftest_log->
8960 			    smart_selftest_log_entries[index];
8961 			for (count = 1;
8962 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8963 			    ++count) {
8964 				uint8_t status;
8965 				uint8_t code;
8966 				uint8_t sense_key;
8967 				uint8_t add_sense_code;
8968 				uint8_t add_sense_code_qual;
8969 
8970 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
8971 					goto done;
8972 
8973 				lpp->param_code[0] = 0;
8974 				lpp->param_code[1] = count;
8975 				lpp->param_ctrl_flags =
8976 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8977 				lpp->param_len =
8978 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8979 
8980 				status = entry->smart_selftest_log_status;
8981 				status >>= 4;
8982 				switch (status) {
8983 				case 0:
8984 				default:
8985 					sense_key = KEY_NO_SENSE;
8986 					add_sense_code =
8987 					    SD_SCSI_ASC_NO_ADD_SENSE;
8988 					break;
8989 				case 1:
8990 					sense_key = KEY_ABORTED_COMMAND;
8991 					add_sense_code =
8992 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8993 					add_sense_code_qual = SCSI_COMPONENT_81;
8994 					break;
8995 				case 2:
8996 					sense_key = KEY_ABORTED_COMMAND;
8997 					add_sense_code =
8998 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8999 					add_sense_code_qual = SCSI_COMPONENT_82;
9000 					break;
9001 				case 3:
9002 					sense_key = KEY_ABORTED_COMMAND;
9003 					add_sense_code =
9004 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9005 					add_sense_code_qual = SCSI_COMPONENT_83;
9006 					break;
9007 				case 4:
9008 					sense_key = KEY_HARDWARE_ERROR;
9009 					add_sense_code =
9010 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9011 					add_sense_code_qual = SCSI_COMPONENT_84;
9012 					break;
9013 				case 5:
9014 					sense_key = KEY_HARDWARE_ERROR;
9015 					add_sense_code =
9016 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9017 					add_sense_code_qual = SCSI_COMPONENT_85;
9018 					break;
9019 				case 6:
9020 					sense_key = KEY_HARDWARE_ERROR;
9021 					add_sense_code =
9022 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9023 					add_sense_code_qual = SCSI_COMPONENT_86;
9024 					break;
9025 				case 7:
9026 					sense_key = KEY_MEDIUM_ERROR;
9027 					add_sense_code =
9028 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9029 					add_sense_code_qual = SCSI_COMPONENT_87;
9030 					break;
9031 				case 8:
9032 					sense_key = KEY_HARDWARE_ERROR;
9033 					add_sense_code =
9034 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
9035 					add_sense_code_qual = SCSI_COMPONENT_88;
9036 					break;
9037 				}
9038 				code = 0;	/* unspecified */
9039 				status |= (code << 4);
9040 				lpp->param_values[0] = status;
9041 				lpp->param_values[1] = 0; /* unspecified */
9042 				lpp->param_values[2] = entry->
9043 				    smart_selftest_log_timestamp[1];
9044 				lpp->param_values[3] = entry->
9045 				    smart_selftest_log_timestamp[0];
9046 				if (status != 0) {
9047 					lpp->param_values[4] = 0;
9048 					lpp->param_values[5] = 0;
9049 					lpp->param_values[6] = 0;
9050 					lpp->param_values[7] = 0;
9051 					lpp->param_values[8] = entry->
9052 					    smart_selftest_log_failing_lba[3];
9053 					lpp->param_values[9] = entry->
9054 					    smart_selftest_log_failing_lba[2];
9055 					lpp->param_values[10] = entry->
9056 					    smart_selftest_log_failing_lba[1];
9057 					lpp->param_values[11] = entry->
9058 					    smart_selftest_log_failing_lba[0];
9059 				} else {	/* No block address */
9060 					lpp->param_values[4] = 0xff;
9061 					lpp->param_values[5] = 0xff;
9062 					lpp->param_values[6] = 0xff;
9063 					lpp->param_values[7] = 0xff;
9064 					lpp->param_values[8] = 0xff;
9065 					lpp->param_values[9] = 0xff;
9066 					lpp->param_values[10] = 0xff;
9067 					lpp->param_values[11] = 0xff;
9068 				}
9069 				lpp->param_values[12] = sense_key;
9070 				lpp->param_values[13] = add_sense_code;
9071 				lpp->param_values[14] = add_sense_code_qual;
9072 				lpp->param_values[15] = 0; /* undefined */
9073 
9074 				lpp = (struct log_parameter *)
9075 				    (((uint8_t *)lpp) +
9076 				    SCSI_LOG_PARAM_HDR_LEN +
9077 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
9078 				--index;	/* back up to previous entry */
9079 				if (index < 0) {
9080 					index =
9081 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
9082 				}
9083 				entry = &selftest_log->
9084 				    smart_selftest_log_entries[index];
9085 			}
9086 		}
9087 done:
9088 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
9089 	}
9090 
9091 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
9092 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
9093 }
9094 
9095 /*
9096  * sata_build_lsense_page_2f() is used to create the
9097  * SCSI LOG SENSE page 0x2f (informational exceptions)
9098  *
9099  * Takes a sata_drive_info t * and the address of a buffer
9100  * in which to create the page information as well as a sata_hba_inst_t *.
9101  *
9102  * Returns the number of bytes valid in the buffer.
9103  *
9104  * Because it invokes function(s) that send synchronously executed command
9105  * to the HBA, it cannot be called in the interrupt context.
9106  */
9107 static	int
9108 sata_build_lsense_page_2f(
9109 	sata_drive_info_t *sdinfo,
9110 	uint8_t *buf,
9111 	sata_hba_inst_t *sata_hba_inst)
9112 {
9113 	struct log_parameter *lpp = (struct log_parameter *)buf;
9114 	int rval;
9115 	uint8_t *smart_data;
9116 	uint8_t temp;
9117 	sata_id_t *sata_id;
9118 #define	SMART_NO_TEMP	0xff
9119 
9120 	lpp->param_code[0] = 0;
9121 	lpp->param_code[1] = 0;
9122 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
9123 
9124 	/* Now get the SMART status w.r.t. threshold exceeded */
9125 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
9126 	switch (rval) {
9127 	case 1:
9128 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
9129 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
9130 		break;
9131 	case 0:
9132 	case -1:	/* failed to get data */
9133 		lpp->param_values[0] = 0;	/* No failure predicted */
9134 		lpp->param_values[1] = 0;
9135 		break;
9136 #if defined(SATA_DEBUG)
9137 	default:
9138 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
9139 		/* NOTREACHED */
9140 #endif
9141 	}
9142 
9143 	sata_id = &sdinfo->satadrv_id;
9144 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
9145 		temp = SMART_NO_TEMP;
9146 	else {
9147 		/* Now get the temperature */
9148 		smart_data = kmem_zalloc(512, KM_SLEEP);
9149 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
9150 		    SCT_STATUS_LOG_PAGE, 1);
9151 		if (rval == -1)
9152 			temp = SMART_NO_TEMP;
9153 		else {
9154 			temp = smart_data[200];
9155 			if (temp & 0x80) {
9156 				if (temp & 0x7f)
9157 					temp = 0;
9158 				else
9159 					temp = SMART_NO_TEMP;
9160 			}
9161 		}
9162 		kmem_free(smart_data, 512);
9163 	}
9164 
9165 	lpp->param_values[2] = temp;	/* most recent temperature */
9166 	lpp->param_values[3] = 0;	/* required vendor specific byte */
9167 
9168 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
9169 
9170 
9171 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
9172 }
9173 
9174 /*
9175  * sata_build_lsense_page_30() is used to create the
9176  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
9177  *
9178  * Takes a sata_drive_info t * and the address of a buffer
9179  * in which to create the page information as well as a sata_hba_inst_t *.
9180  *
9181  * Returns the number of bytes valid in the buffer.
9182  */
9183 static int
9184 sata_build_lsense_page_30(
9185 	sata_drive_info_t *sdinfo,
9186 	uint8_t *buf,
9187 	sata_hba_inst_t *sata_hba_inst)
9188 {
9189 	struct smart_data *smart_data = (struct smart_data *)buf;
9190 	int rval;
9191 
9192 	/* Now do the SMART READ DATA */
9193 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
9194 	if (rval == -1)
9195 		return (0);
9196 
9197 	return (sizeof (struct smart_data));
9198 }
9199 
9200 /*
9201  * sata_build_lsense_page_0e() is used to create the
9202  * SCSI LOG SENSE page 0e (start-stop cycle counter page)
9203  *
9204  * Date of Manufacture (0x0001)
9205  *	YEAR = "0000"
9206  *	WEEK = "00"
9207  * Accounting Date (0x0002)
9208  *	6 ASCII space character(20h)
9209  * Specified cycle count over device lifetime
9210  *	VALUE - THRESH - the delta between max and min;
9211  * Accumulated start-stop cycles
9212  *	VALUE - WORST - the accumulated cycles;
9213  *
9214  * ID FLAG THRESH VALUE WORST RAW on start/stop counter attribute
9215  *
9216  * Takes a sata_drive_info t * and the address of a buffer
9217  * in which to create the page information as well as a sata_hba_inst_t *.
9218  *
9219  * Returns the number of bytes valid in the buffer.
9220  */
9221 static	int
9222 sata_build_lsense_page_0e(sata_drive_info_t *sdinfo, uint8_t *buf,
9223     sata_pkt_txlate_t *spx)
9224 {
9225 	struct start_stop_cycle_counter_log *log_page;
9226 	int i, rval, index;
9227 	uint8_t smart_data[512], id, value, worst, thresh;
9228 	uint32_t max_count, cycles;
9229 
9230 	/* Now do the SMART READ DATA */
9231 	rval = sata_fetch_smart_data(spx->txlt_sata_hba_inst, sdinfo,
9232 	    (struct smart_data *)smart_data);
9233 	if (rval == -1)
9234 		return (0);
9235 	for (i = 0, id = 0; i < SMART_START_STOP_COUNT_ID * 2; i++) {
9236 		index = (i * 12) + 2;
9237 		id = smart_data[index];
9238 		if (id != SMART_START_STOP_COUNT_ID)
9239 			continue;
9240 		else {
9241 			thresh = smart_data[index + 2];
9242 			value = smart_data[index + 3];
9243 			worst = smart_data[index + 4];
9244 			break;
9245 		}
9246 	}
9247 	if (id != SMART_START_STOP_COUNT_ID)
9248 		return (0);
9249 	max_count = value - thresh;
9250 	cycles = value - worst;
9251 
9252 	log_page = (struct start_stop_cycle_counter_log *)buf;
9253 	bzero(log_page, sizeof (struct start_stop_cycle_counter_log));
9254 	log_page->code = 0x0e;
9255 	log_page->page_len_low = 0x24;
9256 
9257 	log_page->manufactor_date_low = 0x1;
9258 	log_page->param_1.fmt_link = 0x1; /* 01b */
9259 	log_page->param_len_1 = 0x06;
9260 	for (i = 0; i < 4; i++) {
9261 		log_page->year_manu[i] = 0x30;
9262 		if (i < 2)
9263 			log_page->week_manu[i] = 0x30;
9264 	}
9265 
9266 	log_page->account_date_low = 0x02;
9267 	log_page->param_2.fmt_link = 0x01; /* 01b */
9268 	log_page->param_len_2 = 0x06;
9269 	for (i = 0; i < 4; i++) {
9270 		log_page->year_account[i] = 0x20;
9271 		if (i < 2)
9272 			log_page->week_account[i] = 0x20;
9273 	}
9274 
9275 	log_page->lifetime_code_low = 0x03;
9276 	log_page->param_3.fmt_link = 0x03; /* 11b */
9277 	log_page->param_len_3 = 0x04;
9278 	/* VALUE - THRESH - the delta between max and min */
9279 	log_page->cycle_code_low = 0x04;
9280 	log_page->param_4.fmt_link = 0x03; /* 11b */
9281 	log_page->param_len_4 = 0x04;
9282 	/* WORST - THRESH - the distance from 'now' to min */
9283 
9284 	for (i = 0; i < 4; i++) {
9285 		log_page->cycle_lifetime[i] =
9286 		    (max_count >> (8 * (3 - i))) & 0xff;
9287 		log_page->cycle_accumulated[i] =
9288 		    (cycles >> (8 * (3 - i))) & 0xff;
9289 	}
9290 
9291 	return (sizeof (struct start_stop_cycle_counter_log));
9292 }
9293 
9294 /*
9295  * This function was used for build a ATA read verify sector command
9296  */
9297 static void
9298 sata_build_read_verify_cmd(sata_cmd_t *scmd, uint16_t sec, uint64_t lba)
9299 {
9300 	scmd->satacmd_cmd_reg = SATAC_RDVER;
9301 	scmd->satacmd_addr_type = ATA_ADDR_LBA28;
9302 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
9303 
9304 	scmd->satacmd_sec_count_lsb = sec & 0xff;
9305 	scmd->satacmd_lba_low_lsb = lba & 0xff;
9306 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
9307 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
9308 	scmd->satacmd_device_reg = (SATA_ADH_LBA | (lba >> 24) & 0xf);
9309 	scmd->satacmd_features_reg = 0;
9310 	scmd->satacmd_status_reg = 0;
9311 	scmd->satacmd_error_reg = 0;
9312 }
9313 
9314 /*
9315  * This function was used for building an ATA
9316  * command, and only command register need to
9317  * be defined, other register will be zero or na.
9318  */
9319 static void
9320 sata_build_generic_cmd(sata_cmd_t *scmd, uint8_t cmd)
9321 {
9322 	scmd->satacmd_addr_type = 0;
9323 	scmd->satacmd_cmd_reg = cmd;
9324 	scmd->satacmd_device_reg = 0;
9325 	scmd->satacmd_sec_count_lsb = 0;
9326 	scmd->satacmd_lba_low_lsb = 0;
9327 	scmd->satacmd_lba_mid_lsb = 0;
9328 	scmd->satacmd_lba_high_lsb = 0;
9329 	scmd->satacmd_features_reg = 0;
9330 	scmd->satacmd_status_reg = 0;
9331 	scmd->satacmd_error_reg = 0;
9332 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
9333 }
9334 
9335 /*
9336  * This function was used for changing the standby
9337  * timer format from SCSI to ATA.
9338  */
9339 static uint8_t
9340 sata_get_standby_timer(uint8_t *timer)
9341 {
9342 	uint32_t i = 0, count = 0;
9343 	uint8_t ata_count;
9344 
9345 	for (i = 0; i < 4; i++) {
9346 		count = count << 8 | timer[i];
9347 	}
9348 
9349 	if (count == 0)
9350 		return (0);
9351 
9352 	if (count >= 1 && count <= 12000)
9353 		ata_count = (count -1) / 50 + 1;
9354 	else if (count > 12000 && count <= 12600)
9355 		ata_count = 0xfc;
9356 	else if (count > 12601 && count <= 12750)
9357 		ata_count = 0xff;
9358 	else if (count > 12750 && count <= 17999)
9359 		ata_count = 0xf1;
9360 	else if (count > 18000 && count <= 198000)
9361 		ata_count = count / 18000 + 240;
9362 	else
9363 		ata_count = 0xfd;
9364 	return (ata_count);
9365 }
9366 
9367 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
9368 
9369 /*
9370  * Start command for ATAPI device.
9371  * This function processes scsi_pkt requests.
9372  * Now CD/DVD, tape and ATAPI disk devices are supported.
9373  * Most commands are packet without any translation into Packet Command.
9374  * Some may be trapped and executed as SATA commands (not clear which one).
9375  *
9376  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
9377  * execution).
9378  * Returns other TRAN_XXXX codes if command is not accepted or completed
9379  * (see return values for sata_hba_start()).
9380  *
9381  * Note:
9382  * Inquiry cdb format differs between transport version 2 and 3.
9383  * However, the transport version 3 devices that were checked did not adhere
9384  * to the specification (ignored MSB of the allocation length). Therefore,
9385  * the transport version is not checked, but Inquiry allocation length is
9386  * truncated to 255 bytes if the original allocation length set-up by the
9387  * target driver is greater than 255 bytes.
9388  */
9389 static int
9390 sata_txlt_atapi(sata_pkt_txlate_t *spx)
9391 {
9392 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
9393 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
9394 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
9395 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
9396 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
9397 	    &spx->txlt_sata_pkt->satapkt_device);
9398 	kmutex_t *cport_mutex = &(SATA_TXLT_CPORT_MUTEX(spx));
9399 	int cdblen;
9400 	int rval, reason;
9401 	int synch;
9402 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
9403 
9404 	mutex_enter(cport_mutex);
9405 
9406 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
9407 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
9408 		mutex_exit(cport_mutex);
9409 		return (rval);
9410 	}
9411 
9412 	/*
9413 	 * ATAPI device executes some ATA commands in addition to those
9414 	 * commands sent via PACKET command. These ATA commands may be
9415 	 * executed by the regular SATA translation functions. None needs
9416 	 * to be captured now.
9417 	 *
9418 	 * Commands sent via PACKET command include:
9419 	 *	MMC command set for ATAPI CD/DVD device
9420 	 *	SSC command set for ATAPI TAPE device
9421 	 *	SBC command set for ATAPI disk device
9422 	 *
9423 	 */
9424 
9425 	/* Check the size of cdb */
9426 
9427 	switch (GETGROUP(cdbp)) {
9428 	case CDB_GROUPID_3:   /* Reserved, per SPC-4 */
9429 		/*
9430 		 * opcodes 0x7e and 0x7f identify variable-length CDBs and
9431 		 * therefore require special handling.  Return failure, for now.
9432 		 */
9433 		mutex_exit(cport_mutex);
9434 		return (TRAN_BADPKT);
9435 
9436 	case CDB_GROUPID_6:   /* Vendor-specific, per SPC-4 */
9437 	case CDB_GROUPID_7:   /* Vendor-specific, per SPC-4 */
9438 		/* obtain length from the scsi_pkt */
9439 		cdblen = scsipkt->pkt_cdblen;
9440 		break;
9441 
9442 	default:
9443 		/* CDB's length is statically known, per SPC-4 */
9444 		cdblen = scsi_cdb_size[GETGROUP(cdbp)];
9445 		break;
9446 	}
9447 
9448 	if (cdblen <= 0 || cdblen > sdinfo->satadrv_atapi_cdb_len) {
9449 		sata_log(NULL, CE_WARN,
9450 		    "sata: invalid ATAPI cdb length %d",
9451 		    cdblen);
9452 		mutex_exit(cport_mutex);
9453 		return (TRAN_BADPKT);
9454 	}
9455 
9456 	SATAATAPITRACE(spx, cdblen);
9457 
9458 	/*
9459 	 * For non-read/write commands we need to
9460 	 * map buffer
9461 	 */
9462 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
9463 	case SCMD_READ:
9464 	case SCMD_READ_G1:
9465 	case SCMD_READ_G5:
9466 	case SCMD_READ_G4:
9467 	case SCMD_WRITE:
9468 	case SCMD_WRITE_G1:
9469 	case SCMD_WRITE_G5:
9470 	case SCMD_WRITE_G4:
9471 		break;
9472 	default:
9473 		if (bp != NULL) {
9474 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
9475 				bp_mapin(bp);
9476 		}
9477 		break;
9478 	}
9479 	/*
9480 	 * scmd->satacmd_flags.sata_data_direction default -
9481 	 * SATA_DIR_NODATA_XFER - is set by
9482 	 * sata_txlt_generic_pkt_info().
9483 	 */
9484 	if (scmd->satacmd_bp) {
9485 		if (scmd->satacmd_bp->b_flags & B_READ) {
9486 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9487 		} else {
9488 			scmd->satacmd_flags.sata_data_direction =
9489 			    SATA_DIR_WRITE;
9490 		}
9491 	}
9492 
9493 	/*
9494 	 * Set up ATAPI packet command.
9495 	 */
9496 
9497 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9498 
9499 	/* Copy cdb into sata_cmd */
9500 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9501 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9502 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
9503 
9504 	/* See note in the command header */
9505 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
9506 		if (scmd->satacmd_acdb[3] != 0)
9507 			scmd->satacmd_acdb[4] = 255;
9508 	}
9509 
9510 #ifdef SATA_DEBUG
9511 	if (sata_debug_flags & SATA_DBG_ATAPI) {
9512 		uint8_t *p = scmd->satacmd_acdb;
9513 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
9514 
9515 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
9516 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
9517 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
9518 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9519 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9520 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
9521 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
9522 	}
9523 #endif
9524 
9525 	/*
9526 	 * Preset request sense data to NO SENSE.
9527 	 * If there is no way to get error information via Request Sense,
9528 	 * the packet request sense data would not have to be modified by HBA,
9529 	 * but it could be returned as is.
9530 	 */
9531 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
9532 	sata_fixed_sense_data_preset(
9533 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9534 
9535 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
9536 		/* Need callback function */
9537 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
9538 		synch = FALSE;
9539 	} else
9540 		synch = TRUE;
9541 
9542 	/* Transfer command to HBA */
9543 	if (sata_hba_start(spx, &rval) != 0) {
9544 		/* Pkt not accepted for execution */
9545 		mutex_exit(cport_mutex);
9546 		return (rval);
9547 	}
9548 	mutex_exit(cport_mutex);
9549 	/*
9550 	 * If execution is non-synchronous,
9551 	 * a callback function will handle potential errors, translate
9552 	 * the response and will do a callback to a target driver.
9553 	 * If it was synchronous, use the same framework callback to check
9554 	 * an execution status.
9555 	 */
9556 	if (synch) {
9557 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
9558 		    "synchronous execution status %x\n",
9559 		    spx->txlt_sata_pkt->satapkt_reason);
9560 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
9561 	}
9562 	return (TRAN_ACCEPT);
9563 }
9564 
9565 
9566 /*
9567  * ATAPI Packet command completion.
9568  *
9569  * Failure of the command passed via Packet command are considered device
9570  * error. SATA HBA driver would have to retrieve error data (via Request
9571  * Sense command delivered via error retrieval sata packet) and copy it
9572  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
9573  */
9574 static void
9575 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
9576 {
9577 	sata_pkt_txlate_t *spx =
9578 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
9579 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
9580 	struct scsi_extended_sense *sense;
9581 	struct buf *bp;
9582 	int rval;
9583 
9584 #ifdef SATA_DEBUG
9585 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
9586 #endif
9587 
9588 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
9589 	    STATE_SENT_CMD | STATE_GOT_STATUS;
9590 
9591 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
9592 		/* Normal completion */
9593 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
9594 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
9595 		scsipkt->pkt_reason = CMD_CMPLT;
9596 		*scsipkt->pkt_scbp = STATUS_GOOD;
9597 		if (spx->txlt_tmp_buf != NULL) {
9598 			/* Temporary buffer was used */
9599 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
9600 			if (bp->b_flags & B_READ) {
9601 				rval = ddi_dma_sync(
9602 				    spx->txlt_buf_dma_handle, 0, 0,
9603 				    DDI_DMA_SYNC_FORCPU);
9604 				ASSERT(rval == DDI_SUCCESS);
9605 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
9606 				    bp->b_bcount);
9607 			}
9608 		}
9609 	} else {
9610 		/*
9611 		 * Something went wrong - analyze return
9612 		 */
9613 		*scsipkt->pkt_scbp = STATUS_CHECK;
9614 		sense = sata_arq_sense(spx);
9615 
9616 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9617 			/*
9618 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
9619 			 * Under this condition ERR bit is set for ATA command,
9620 			 * and CHK bit set for ATAPI command.
9621 			 *
9622 			 * Please check st_intr & sdintr about how pkt_reason
9623 			 * is used.
9624 			 */
9625 			scsipkt->pkt_reason = CMD_CMPLT;
9626 
9627 			/*
9628 			 * We may not have ARQ data if there was a double
9629 			 * error. But sense data in sata packet was pre-set
9630 			 * with NO SENSE so it is valid even if HBA could
9631 			 * not retrieve a real sense data.
9632 			 * Just copy this sense data into scsi pkt sense area.
9633 			 */
9634 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
9635 			    SATA_ATAPI_MIN_RQSENSE_LEN);
9636 #ifdef SATA_DEBUG
9637 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
9638 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9639 				    "sata_txlt_atapi_completion: %02x\n"
9640 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
9641 				    "          %02x %02x %02x %02x %02x %02x "
9642 				    "          %02x %02x %02x %02x %02x %02x\n",
9643 				    scsipkt->pkt_reason,
9644 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9645 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9646 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9647 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9648 				    rqsp[16], rqsp[17]);
9649 			}
9650 #endif
9651 		} else {
9652 			switch (sata_pkt->satapkt_reason) {
9653 			case SATA_PKT_PORT_ERROR:
9654 				/*
9655 				 * We have no device data.
9656 				 */
9657 				scsipkt->pkt_reason = CMD_INCOMPLETE;
9658 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
9659 				    STATE_GOT_TARGET | STATE_SENT_CMD |
9660 				    STATE_GOT_STATUS);
9661 				sense->es_key = KEY_HARDWARE_ERROR;
9662 				break;
9663 
9664 			case SATA_PKT_TIMEOUT:
9665 				scsipkt->pkt_reason = CMD_TIMEOUT;
9666 				scsipkt->pkt_statistics |=
9667 				    STAT_TIMEOUT | STAT_DEV_RESET;
9668 				/*
9669 				 * Need to check if HARDWARE_ERROR/
9670 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
9671 				 * appropriate.
9672 				 */
9673 				break;
9674 
9675 			case SATA_PKT_ABORTED:
9676 				scsipkt->pkt_reason = CMD_ABORTED;
9677 				scsipkt->pkt_statistics |= STAT_ABORTED;
9678 				/* Should we set key COMMAND_ABPRTED? */
9679 				break;
9680 
9681 			case SATA_PKT_RESET:
9682 				scsipkt->pkt_reason = CMD_RESET;
9683 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
9684 				/*
9685 				 * May be we should set Unit Attention /
9686 				 * Reset. Perhaps the same should be
9687 				 * returned for disks....
9688 				 */
9689 				sense->es_key = KEY_UNIT_ATTENTION;
9690 				sense->es_add_code = SD_SCSI_ASC_RESET;
9691 				break;
9692 
9693 			default:
9694 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9695 				    "sata_txlt_atapi_completion: "
9696 				    "invalid packet completion reason"));
9697 				scsipkt->pkt_reason = CMD_TRAN_ERR;
9698 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
9699 				    STATE_GOT_TARGET | STATE_SENT_CMD |
9700 				    STATE_GOT_STATUS);
9701 				break;
9702 			}
9703 		}
9704 	}
9705 
9706 	SATAATAPITRACE(spx, 0);
9707 
9708 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
9709 	    scsipkt->pkt_comp != NULL) {
9710 		/* scsi callback required */
9711 		(*scsipkt->pkt_comp)(scsipkt);
9712 	}
9713 }
9714 
9715 /*
9716  * Set up error retrieval sata command for ATAPI Packet Command error data
9717  * recovery.
9718  *
9719  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
9720  * returns SATA_FAILURE otherwise.
9721  */
9722 
9723 static int
9724 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
9725 {
9726 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
9727 	sata_cmd_t *scmd;
9728 	struct buf *bp;
9729 
9730 	/*
9731 	 * Allocate dma-able buffer error data.
9732 	 * Buffer allocation will take care of buffer alignment and other DMA
9733 	 * attributes.
9734 	 */
9735 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
9736 	if (bp == NULL) {
9737 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
9738 		    "sata_get_err_retrieval_pkt: "
9739 		    "cannot allocate buffer for error data", NULL);
9740 		return (SATA_FAILURE);
9741 	}
9742 	bp_mapin(bp); /* make data buffer accessible */
9743 
9744 	/* Operation modes are up to the caller */
9745 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9746 
9747 	/* Synchronous mode, no callback - may be changed by the caller */
9748 	spkt->satapkt_comp = NULL;
9749 	spkt->satapkt_time = sata_default_pkt_time;
9750 
9751 	scmd = &spkt->satapkt_cmd;
9752 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9753 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9754 
9755 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9756 
9757 	/*
9758 	 * Set-up acdb. Request Sense CDB (packet command content) is
9759 	 * not in DMA-able buffer. Its handling is HBA-specific (how
9760 	 * it is transfered into packet FIS).
9761 	 */
9762 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9763 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
9764 	/* Following zeroing of pad bytes may not be necessary */
9765 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
9766 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
9767 
9768 	/*
9769 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
9770 	 * before accessing it. Handle is in usual place in translate struct.
9771 	 */
9772 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
9773 
9774 	/*
9775 	 * Preset request sense data to NO SENSE.
9776 	 * Here it is redundant, only for a symetry with scsi-originated
9777 	 * packets. It should not be used for anything but debugging.
9778 	 */
9779 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
9780 	sata_fixed_sense_data_preset(
9781 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9782 
9783 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9784 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9785 
9786 	return (SATA_SUCCESS);
9787 }
9788 
9789 /*
9790  * Set-up ATAPI packet command.
9791  * Data transfer direction has to be set-up in sata_cmd structure prior to
9792  * calling this function.
9793  *
9794  * Returns void
9795  */
9796 
9797 static void
9798 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
9799 {
9800 	scmd->satacmd_addr_type = 0;		/* N/A */
9801 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
9802 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
9803 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
9804 	scmd->satacmd_lba_high_lsb =
9805 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
9806 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
9807 
9808 	/*
9809 	 * We want all data to be transfered via DMA.
9810 	 * But specify it only if drive supports DMA and DMA mode is
9811 	 * selected - some drives are sensitive about it.
9812 	 * Hopefully it wil work for all drives....
9813 	 */
9814 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
9815 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
9816 
9817 	/*
9818 	 * Features register requires special care for devices that use
9819 	 * Serial ATA bridge - they need an explicit specification of
9820 	 * the data transfer direction for Packet DMA commands.
9821 	 * Setting this bit is harmless if DMA is not used.
9822 	 *
9823 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
9824 	 * spec they follow.
9825 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
9826 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
9827 	 * ATA/ATAPI-7 support is explicitly indicated.
9828 	 */
9829 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
9830 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
9831 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
9832 		/*
9833 		 * Specification of major version is valid and version 7
9834 		 * is supported. It does automatically imply that all
9835 		 * spec features are supported. For now, we assume that
9836 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
9837 		 */
9838 		if ((sdinfo->satadrv_id.ai_dirdma &
9839 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
9840 			if (scmd->satacmd_flags.sata_data_direction ==
9841 			    SATA_DIR_READ)
9842 			scmd->satacmd_features_reg |=
9843 			    SATA_ATAPI_F_DATA_DIR_READ;
9844 		}
9845 	}
9846 }
9847 
9848 
9849 #ifdef SATA_DEBUG
9850 
9851 /* Display 18 bytes of Inquiry data */
9852 static void
9853 sata_show_inqry_data(uint8_t *buf)
9854 {
9855 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
9856 	uint8_t *p;
9857 
9858 	cmn_err(CE_NOTE, "Inquiry data:");
9859 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
9860 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
9861 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
9862 	cmn_err(CE_NOTE, "ATAPI transport version %d",
9863 	    SATA_ATAPI_TRANS_VERSION(inq));
9864 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
9865 	    inq->inq_rdf, inq->inq_aenc);
9866 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
9867 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
9868 	p = (uint8_t *)inq->inq_vid;
9869 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
9870 	    "%02x %02x %02x %02x",
9871 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9872 	p = (uint8_t *)inq->inq_vid;
9873 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
9874 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9875 
9876 	p = (uint8_t *)inq->inq_pid;
9877 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
9878 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
9879 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9880 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9881 	p = (uint8_t *)inq->inq_pid;
9882 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
9883 	    "%c %c %c %c %c %c %c %c",
9884 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9885 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9886 
9887 	p = (uint8_t *)inq->inq_revision;
9888 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
9889 	    p[0], p[1], p[2], p[3]);
9890 	p = (uint8_t *)inq->inq_revision;
9891 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
9892 	    p[0], p[1], p[2], p[3]);
9893 
9894 }
9895 
9896 
9897 static void
9898 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
9899 {
9900 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
9901 
9902 	if (scsi_pkt == NULL)
9903 		return;
9904 	if (count != 0) {
9905 		/* saving cdb */
9906 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
9907 		    SATA_ATAPI_MAX_CDB_LEN);
9908 		bcopy(scsi_pkt->pkt_cdbp,
9909 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
9910 	} else {
9911 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
9912 		    sts_sensedata,
9913 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
9914 		    SATA_ATAPI_MIN_RQSENSE_LEN);
9915 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
9916 		    scsi_pkt->pkt_reason;
9917 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
9918 		    spx->txlt_sata_pkt->satapkt_reason;
9919 
9920 		if (++sata_atapi_trace_index >= 64)
9921 			sata_atapi_trace_index = 0;
9922 	}
9923 }
9924 
9925 #endif
9926 
9927 /*
9928  * Fetch inquiry data from ATAPI device
9929  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
9930  *
9931  * Note:
9932  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
9933  * where the caller expects to see the inquiry data.
9934  *
9935  */
9936 
9937 static int
9938 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
9939     sata_address_t *saddr, struct scsi_inquiry *inq)
9940 {
9941 	sata_pkt_txlate_t *spx;
9942 	sata_pkt_t *spkt;
9943 	struct buf *bp;
9944 	sata_drive_info_t *sdinfo;
9945 	sata_cmd_t *scmd;
9946 	int rval;
9947 	uint8_t *rqsp;
9948 	dev_info_t *dip = SATA_DIP(sata_hba);
9949 #ifdef SATA_DEBUG
9950 	char msg_buf[MAXPATHLEN];
9951 #endif
9952 	kmutex_t *cport_mutex;
9953 
9954 	ASSERT(sata_hba != NULL);
9955 
9956 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9957 	spx->txlt_sata_hba_inst = sata_hba;
9958 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9959 	spkt = sata_pkt_alloc(spx, NULL);
9960 	if (spkt == NULL) {
9961 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9962 		return (SATA_FAILURE);
9963 	}
9964 	/* address is needed now */
9965 	spkt->satapkt_device.satadev_addr = *saddr;
9966 
9967 	/* scsi_inquiry size buffer */
9968 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
9969 	if (bp == NULL) {
9970 		sata_pkt_free(spx);
9971 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9972 		SATA_LOG_D((sata_hba, CE_WARN,
9973 		    "sata_get_atapi_inquiry_data: "
9974 		    "cannot allocate data buffer"));
9975 		return (SATA_FAILURE);
9976 	}
9977 	bp_mapin(bp); /* make data buffer accessible */
9978 
9979 	scmd = &spkt->satapkt_cmd;
9980 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9981 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9982 
9983 	/* Use synchronous mode */
9984 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9985 	spkt->satapkt_comp = NULL;
9986 	spkt->satapkt_time = sata_default_pkt_time;
9987 
9988 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9989 
9990 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9991 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9992 
9993 	cport_mutex = &(SATA_CPORT_MUTEX(sata_hba, saddr->cport));
9994 	mutex_enter(cport_mutex);
9995 	sdinfo = sata_get_device_info(sata_hba,
9996 	    &spx->txlt_sata_pkt->satapkt_device);
9997 	if (sdinfo == NULL) {
9998 		/* we have to be carefull about the disapearing device */
9999 		mutex_exit(cport_mutex);
10000 		rval = SATA_FAILURE;
10001 		goto cleanup;
10002 	}
10003 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
10004 
10005 	/*
10006 	 * Set-up acdb. This works for atapi transport version 2 and later.
10007 	 */
10008 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
10009 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
10010 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
10011 	scmd->satacmd_acdb[1] = 0x00;
10012 	scmd->satacmd_acdb[2] = 0x00;
10013 	scmd->satacmd_acdb[3] = 0x00;
10014 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
10015 	scmd->satacmd_acdb[5] = 0x00;
10016 
10017 	sata_fixed_sense_data_preset(
10018 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
10019 
10020 	/* Transfer command to HBA */
10021 	if (sata_hba_start(spx, &rval) != 0) {
10022 		/* Pkt not accepted for execution */
10023 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
10024 		    "sata_get_atapi_inquiry_data: "
10025 		    "Packet not accepted for execution - ret: %02x", rval);
10026 		mutex_exit(cport_mutex);
10027 		rval = SATA_FAILURE;
10028 		goto cleanup;
10029 	}
10030 	mutex_exit(cport_mutex);
10031 
10032 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
10033 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
10034 		    "sata_get_atapi_inquiry_data: "
10035 		    "Packet completed successfully - ret: %02x", rval);
10036 		if (spx->txlt_buf_dma_handle != NULL) {
10037 			/*
10038 			 * Sync buffer. Handle is in usual place in translate
10039 			 * struct.
10040 			 */
10041 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
10042 			    DDI_DMA_SYNC_FORCPU);
10043 			ASSERT(rval == DDI_SUCCESS);
10044 		}
10045 
10046 		if (sata_check_for_dma_error(dip, spx)) {
10047 			ddi_fm_service_impact(dip, DDI_SERVICE_UNAFFECTED);
10048 			rval = SATA_FAILURE;
10049 		} else {
10050 			/*
10051 			 * Normal completion - copy data into caller's buffer
10052 			 */
10053 			bcopy(bp->b_un.b_addr, (uint8_t *)inq,
10054 			    sizeof (struct scsi_inquiry));
10055 #ifdef SATA_DEBUG
10056 			if (sata_debug_flags & SATA_DBG_ATAPI) {
10057 				sata_show_inqry_data((uint8_t *)inq);
10058 			}
10059 #endif
10060 			rval = SATA_SUCCESS;
10061 		}
10062 	} else {
10063 		/*
10064 		 * Something went wrong - analyze return - check rqsense data
10065 		 */
10066 		rval = SATA_FAILURE;
10067 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
10068 			/*
10069 			 * ARQ data hopefull show something other than NO SENSE
10070 			 */
10071 			rqsp = scmd->satacmd_rqsense;
10072 #ifdef SATA_DEBUG
10073 			if (sata_debug_flags & SATA_DBG_ATAPI) {
10074 				msg_buf[0] = '\0';
10075 				(void) snprintf(msg_buf, MAXPATHLEN,
10076 				    "ATAPI packet completion reason: %02x\n"
10077 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
10078 				    "          %02x %02x %02x %02x %02x %02x\n"
10079 				    "          %02x %02x %02x %02x %02x %02x",
10080 				    spkt->satapkt_reason,
10081 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
10082 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
10083 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
10084 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
10085 				    rqsp[16], rqsp[17]);
10086 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
10087 				    "%s", msg_buf);
10088 			}
10089 #endif
10090 		} else {
10091 			switch (spkt->satapkt_reason) {
10092 			case SATA_PKT_PORT_ERROR:
10093 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
10094 				    "sata_get_atapi_inquiry_data: "
10095 				    "packet reason: port error", NULL);
10096 				break;
10097 
10098 			case SATA_PKT_TIMEOUT:
10099 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
10100 				    "sata_get_atapi_inquiry_data: "
10101 				    "packet reason: timeout", NULL);
10102 				break;
10103 
10104 			case SATA_PKT_ABORTED:
10105 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
10106 				    "sata_get_atapi_inquiry_data: "
10107 				    "packet reason: aborted", NULL);
10108 				break;
10109 
10110 			case SATA_PKT_RESET:
10111 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
10112 				    "sata_get_atapi_inquiry_data: "
10113 				    "packet reason: reset\n", NULL);
10114 				break;
10115 			default:
10116 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
10117 				    "sata_get_atapi_inquiry_data: "
10118 				    "invalid packet reason: %02x\n",
10119 				    spkt->satapkt_reason);
10120 				break;
10121 			}
10122 		}
10123 	}
10124 cleanup:
10125 	sata_free_local_buffer(spx);
10126 	sata_pkt_free(spx);
10127 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
10128 	return (rval);
10129 }
10130 
10131 
10132 
10133 
10134 
10135 #if 0
10136 #ifdef SATA_DEBUG
10137 
10138 /*
10139  * Test ATAPI packet command.
10140  * Single threaded test: send packet command in synch mode, process completion
10141  *
10142  */
10143 static void
10144 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
10145 {
10146 	sata_pkt_txlate_t *spx;
10147 	sata_pkt_t *spkt;
10148 	struct buf *bp;
10149 	sata_device_t sata_device;
10150 	sata_drive_info_t *sdinfo;
10151 	sata_cmd_t *scmd;
10152 	int rval;
10153 	uint8_t *rqsp;
10154 
10155 	ASSERT(sata_hba_inst != NULL);
10156 	sata_device.satadev_addr.cport = cport;
10157 	sata_device.satadev_addr.pmport = 0;
10158 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
10159 	sata_device.satadev_rev = SATA_DEVICE_REV;
10160 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10161 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
10162 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10163 	if (sdinfo == NULL) {
10164 		sata_log(sata_hba_inst, CE_WARN,
10165 		    "sata_test_atapi_packet_command: "
10166 		    "no device info for cport %d",
10167 		    sata_device.satadev_addr.cport);
10168 		return;
10169 	}
10170 
10171 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
10172 	spx->txlt_sata_hba_inst = sata_hba_inst;
10173 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
10174 	spkt = sata_pkt_alloc(spx, NULL);
10175 	if (spkt == NULL) {
10176 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
10177 		return;
10178 	}
10179 	/* address is needed now */
10180 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
10181 
10182 	/* 1024k buffer */
10183 	bp = sata_alloc_local_buffer(spx, 1024);
10184 	if (bp == NULL) {
10185 		sata_pkt_free(spx);
10186 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
10187 		sata_log(sata_hba_inst, CE_WARN,
10188 		    "sata_test_atapi_packet_command: "
10189 		    "cannot allocate data buffer");
10190 		return;
10191 	}
10192 	bp_mapin(bp); /* make data buffer accessible */
10193 
10194 	scmd = &spkt->satapkt_cmd;
10195 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
10196 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
10197 
10198 	/* Use synchronous mode */
10199 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
10200 
10201 	/* Synchronous mode, no callback - may be changed by the caller */
10202 	spkt->satapkt_comp = NULL;
10203 	spkt->satapkt_time = sata_default_pkt_time;
10204 
10205 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
10206 
10207 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
10208 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
10209 
10210 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
10211 
10212 	/* Set-up acdb. */
10213 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
10214 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
10215 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
10216 	scmd->satacmd_acdb[1] = 0x00;
10217 	scmd->satacmd_acdb[2] = 0x00;
10218 	scmd->satacmd_acdb[3] = 0x00;
10219 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
10220 	scmd->satacmd_acdb[5] = 0x00;
10221 
10222 	sata_fixed_sense_data_preset(
10223 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
10224 
10225 	/* Transfer command to HBA */
10226 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10227 	if (sata_hba_start(spx, &rval) != 0) {
10228 		/* Pkt not accepted for execution */
10229 		sata_log(sata_hba_inst, CE_WARN,
10230 		    "sata_test_atapi_packet_command: "
10231 		    "Packet not accepted for execution - ret: %02x", rval);
10232 		mutex_exit(
10233 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10234 		goto cleanup;
10235 	}
10236 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
10237 
10238 	if (spx->txlt_buf_dma_handle != NULL) {
10239 		/*
10240 		 * Sync buffer. Handle is in usual place in translate struct.
10241 		 */
10242 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
10243 		    DDI_DMA_SYNC_FORCPU);
10244 		ASSERT(rval == DDI_SUCCESS);
10245 	}
10246 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
10247 		sata_log(sata_hba_inst, CE_WARN,
10248 		    "sata_test_atapi_packet_command: "
10249 		    "Packet completed successfully");
10250 		/*
10251 		 * Normal completion - show inquiry data
10252 		 */
10253 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
10254 	} else {
10255 		/*
10256 		 * Something went wrong - analyze return - check rqsense data
10257 		 */
10258 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
10259 			/*
10260 			 * ARQ data hopefull show something other than NO SENSE
10261 			 */
10262 			rqsp = scmd->satacmd_rqsense;
10263 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
10264 			    "ATAPI packet completion reason: %02x\n"
10265 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
10266 			    "          %02x %02x %02x %02x %02x %02x "
10267 			    "          %02x %02x %02x %02x %02x %02x\n",
10268 			    spkt->satapkt_reason,
10269 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
10270 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
10271 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
10272 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
10273 			    rqsp[16], rqsp[17]);
10274 		} else {
10275 			switch (spkt->satapkt_reason) {
10276 			case SATA_PKT_PORT_ERROR:
10277 				sata_log(sata_hba_inst, CE_WARN,
10278 				    "sata_test_atapi_packet_command: "
10279 				    "packet reason: port error\n");
10280 				break;
10281 
10282 			case SATA_PKT_TIMEOUT:
10283 				sata_log(sata_hba_inst, CE_WARN,
10284 				    "sata_test_atapi_packet_command: "
10285 				    "packet reason: timeout\n");
10286 				break;
10287 
10288 			case SATA_PKT_ABORTED:
10289 				sata_log(sata_hba_inst, CE_WARN,
10290 				    "sata_test_atapi_packet_command: "
10291 				    "packet reason: aborted\n");
10292 				break;
10293 
10294 			case SATA_PKT_RESET:
10295 				sata_log(sata_hba_inst, CE_WARN,
10296 				    "sata_test_atapi_packet_command: "
10297 				    "packet reason: reset\n");
10298 				break;
10299 			default:
10300 				sata_log(sata_hba_inst, CE_WARN,
10301 				    "sata_test_atapi_packet_command: "
10302 				    "invalid packet reason: %02x\n",
10303 				    spkt->satapkt_reason);
10304 				break;
10305 			}
10306 		}
10307 	}
10308 cleanup:
10309 	sata_free_local_buffer(spx);
10310 	sata_pkt_free(spx);
10311 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
10312 }
10313 
10314 #endif /* SATA_DEBUG */
10315 #endif /* 1 */
10316 
10317 
10318 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
10319 
10320 /*
10321  * Validate sata_tran info
10322  * SATA_FAILURE returns if structure is inconsistent or structure revision
10323  * does not match one used by the framework.
10324  *
10325  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
10326  * required function pointers.
10327  * Returns SATA_FAILURE otherwise.
10328  */
10329 static int
10330 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
10331 {
10332 	/*
10333 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
10334 	 * of the SATA interface.
10335 	 */
10336 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
10337 		sata_log(NULL, CE_WARN,
10338 		    "sata: invalid sata_hba_tran version %d for driver %s",
10339 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
10340 		return (SATA_FAILURE);
10341 	}
10342 
10343 	if (dip != sata_tran->sata_tran_hba_dip) {
10344 		SATA_LOG_D((NULL, CE_WARN,
10345 		    "sata: inconsistent sata_tran_hba_dip "
10346 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
10347 		return (SATA_FAILURE);
10348 	}
10349 
10350 	if (sata_tran->sata_tran_probe_port == NULL ||
10351 	    sata_tran->sata_tran_start == NULL ||
10352 	    sata_tran->sata_tran_abort == NULL ||
10353 	    sata_tran->sata_tran_reset_dport == NULL ||
10354 	    sata_tran->sata_tran_hotplug_ops == NULL ||
10355 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
10356 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
10357 	    NULL) {
10358 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
10359 		    "required functions"));
10360 	}
10361 	return (SATA_SUCCESS);
10362 }
10363 
10364 /*
10365  * Remove HBA instance from sata_hba_list.
10366  */
10367 static void
10368 sata_remove_hba_instance(dev_info_t *dip)
10369 {
10370 	sata_hba_inst_t	*sata_hba_inst;
10371 
10372 	mutex_enter(&sata_mutex);
10373 	for (sata_hba_inst = sata_hba_list;
10374 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
10375 	    sata_hba_inst = sata_hba_inst->satahba_next) {
10376 		if (sata_hba_inst->satahba_dip == dip)
10377 			break;
10378 	}
10379 
10380 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
10381 #ifdef SATA_DEBUG
10382 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
10383 		    "unknown HBA instance\n");
10384 #endif
10385 		ASSERT(FALSE);
10386 	}
10387 	if (sata_hba_inst == sata_hba_list) {
10388 		sata_hba_list = sata_hba_inst->satahba_next;
10389 		if (sata_hba_list) {
10390 			sata_hba_list->satahba_prev =
10391 			    (struct sata_hba_inst *)NULL;
10392 		}
10393 		if (sata_hba_inst == sata_hba_list_tail) {
10394 			sata_hba_list_tail = NULL;
10395 		}
10396 	} else if (sata_hba_inst == sata_hba_list_tail) {
10397 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
10398 		if (sata_hba_list_tail) {
10399 			sata_hba_list_tail->satahba_next =
10400 			    (struct sata_hba_inst *)NULL;
10401 		}
10402 	} else {
10403 		sata_hba_inst->satahba_prev->satahba_next =
10404 		    sata_hba_inst->satahba_next;
10405 		sata_hba_inst->satahba_next->satahba_prev =
10406 		    sata_hba_inst->satahba_prev;
10407 	}
10408 	mutex_exit(&sata_mutex);
10409 }
10410 
10411 /*
10412  * Probe all SATA ports of the specified HBA instance.
10413  * The assumption is that there are no target and attachment point minor nodes
10414  * created by the boot subsystems, so we do not need to prune device tree.
10415  *
10416  * This function is called only from sata_hba_attach(). It does not have to
10417  * be protected by controller mutex, because the hba_attached flag is not set
10418  * yet and no one would be touching this HBA instance other than this thread.
10419  * Determines if port is active and what type of the device is attached
10420  * (if any). Allocates necessary structures for each port.
10421  *
10422  * An AP (Attachement Point) node is created for each SATA device port even
10423  * when there is no device attached.
10424  */
10425 
10426 static 	void
10427 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
10428 {
10429 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
10430 	int			ncport;
10431 	sata_cport_info_t 	*cportinfo;
10432 	sata_drive_info_t	*drive;
10433 	sata_device_t		sata_device;
10434 	int			rval;
10435 	dev_t			minor_number;
10436 	char			name[16];
10437 	clock_t			start_time, cur_time;
10438 
10439 	/*
10440 	 * Probe controller ports first, to find port status and
10441 	 * any port multiplier attached.
10442 	 */
10443 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
10444 		/* allocate cport structure */
10445 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
10446 		ASSERT(cportinfo != NULL);
10447 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
10448 
10449 		mutex_enter(&cportinfo->cport_mutex);
10450 
10451 		cportinfo->cport_addr.cport = ncport;
10452 		cportinfo->cport_addr.pmport = 0;
10453 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
10454 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10455 		cportinfo->cport_state |= SATA_STATE_PROBING;
10456 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
10457 
10458 		/*
10459 		 * Regardless if a port is usable or not, create
10460 		 * an attachment point
10461 		 */
10462 		mutex_exit(&cportinfo->cport_mutex);
10463 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
10464 		    ncport, 0, SATA_ADDR_CPORT);
10465 		(void) sprintf(name, "%d", ncport);
10466 		if (ddi_create_minor_node(dip, name, S_IFCHR,
10467 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
10468 		    DDI_SUCCESS) {
10469 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
10470 			    "cannot create SATA attachment point for port %d",
10471 			    ncport);
10472 		}
10473 
10474 		/* Probe port */
10475 		start_time = ddi_get_lbolt();
10476 	reprobe_cport:
10477 		sata_device.satadev_addr.cport = ncport;
10478 		sata_device.satadev_addr.pmport = 0;
10479 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
10480 		sata_device.satadev_rev = SATA_DEVICE_REV;
10481 
10482 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10483 		    (dip, &sata_device);
10484 
10485 		mutex_enter(&cportinfo->cport_mutex);
10486 		cportinfo->cport_scr = sata_device.satadev_scr;
10487 		if (rval != SATA_SUCCESS) {
10488 			/* Something went wrong? Fail the port */
10489 			cportinfo->cport_state = SATA_PSTATE_FAILED;
10490 			mutex_exit(&cportinfo->cport_mutex);
10491 			continue;
10492 		}
10493 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
10494 		cportinfo->cport_state |= SATA_STATE_PROBED;
10495 		cportinfo->cport_dev_type = sata_device.satadev_type;
10496 
10497 		cportinfo->cport_state |= SATA_STATE_READY;
10498 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
10499 			mutex_exit(&cportinfo->cport_mutex);
10500 			continue;
10501 		}
10502 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
10503 			/*
10504 			 * There is some device attached.
10505 			 * Allocate device info structure
10506 			 */
10507 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
10508 				mutex_exit(&cportinfo->cport_mutex);
10509 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
10510 				    kmem_zalloc(sizeof (sata_drive_info_t),
10511 				    KM_SLEEP);
10512 				mutex_enter(&cportinfo->cport_mutex);
10513 			}
10514 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
10515 			drive->satadrv_addr = cportinfo->cport_addr;
10516 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
10517 			drive->satadrv_type = cportinfo->cport_dev_type;
10518 			drive->satadrv_state = SATA_STATE_UNKNOWN;
10519 
10520 			mutex_exit(&cportinfo->cport_mutex);
10521 			if (sata_add_device(dip, sata_hba_inst, &sata_device) !=
10522 			    SATA_SUCCESS) {
10523 				/*
10524 				 * Plugged device was not correctly identified.
10525 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
10526 				 */
10527 				cur_time = ddi_get_lbolt();
10528 				if ((cur_time - start_time) <
10529 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
10530 					/* sleep for a while */
10531 					delay(drv_usectohz(
10532 					    SATA_DEV_RETRY_DLY));
10533 					goto reprobe_cport;
10534 				}
10535 			}
10536 		} else { /* SATA_DTYPE_PMULT */
10537 			mutex_exit(&cportinfo->cport_mutex);
10538 
10539 			/* Allocate sata_pmult_info and sata_pmport_info */
10540 			if (sata_alloc_pmult(sata_hba_inst, &sata_device) !=
10541 			    SATA_SUCCESS)
10542 				continue;
10543 
10544 			/* Log the information of the port multiplier */
10545 			sata_show_pmult_info(sata_hba_inst, &sata_device);
10546 
10547 			/* Probe its pmports */
10548 			sata_probe_pmports(sata_hba_inst, ncport);
10549 		}
10550 	}
10551 }
10552 
10553 /*
10554  * Probe all device ports behind a port multiplier.
10555  *
10556  * PMult-related structure should be allocated before by sata_alloc_pmult().
10557  *
10558  * NOTE1: Only called from sata_probe_ports()
10559  * NOTE2: No mutex should be hold.
10560  */
10561 static void
10562 sata_probe_pmports(sata_hba_inst_t *sata_hba_inst, uint8_t ncport)
10563 {
10564 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
10565 	sata_pmult_info_t	*pmultinfo = NULL;
10566 	sata_pmport_info_t 	*pmportinfo = NULL;
10567 	sata_drive_info_t	*drive = NULL;
10568 	sata_device_t		sata_device;
10569 
10570 	clock_t			start_time, cur_time;
10571 	int			npmport;
10572 	int			rval;
10573 
10574 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, ncport);
10575 
10576 	/* Probe Port Multiplier ports */
10577 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports; npmport++) {
10578 		pmportinfo = pmultinfo->pmult_dev_port[npmport];
10579 		start_time = ddi_get_lbolt();
10580 reprobe_pmport:
10581 		sata_device.satadev_addr.cport = ncport;
10582 		sata_device.satadev_addr.pmport = npmport;
10583 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
10584 		sata_device.satadev_rev = SATA_DEVICE_REV;
10585 
10586 		/* Let HBA driver probe it. */
10587 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10588 		    (dip, &sata_device);
10589 		mutex_enter(&pmportinfo->pmport_mutex);
10590 
10591 		pmportinfo->pmport_scr = sata_device.satadev_scr;
10592 
10593 		if (rval != SATA_SUCCESS) {
10594 			pmportinfo->pmport_state =
10595 			    SATA_PSTATE_FAILED;
10596 			mutex_exit(&pmportinfo->pmport_mutex);
10597 			continue;
10598 		}
10599 		pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
10600 		pmportinfo->pmport_state |= SATA_STATE_PROBED;
10601 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
10602 
10603 		pmportinfo->pmport_state |= SATA_STATE_READY;
10604 		if (pmportinfo->pmport_dev_type ==
10605 		    SATA_DTYPE_NONE) {
10606 			SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
10607 			    "no device found at port %d:%d", ncport, npmport);
10608 			mutex_exit(&pmportinfo->pmport_mutex);
10609 			continue;
10610 		}
10611 		/* Port multipliers cannot be chained */
10612 		ASSERT(pmportinfo->pmport_dev_type != SATA_DTYPE_PMULT);
10613 		/*
10614 		 * There is something attached to Port
10615 		 * Multiplier device port
10616 		 * Allocate device info structure
10617 		 */
10618 		if (pmportinfo->pmport_sata_drive == NULL) {
10619 			mutex_exit(&pmportinfo->pmport_mutex);
10620 			pmportinfo->pmport_sata_drive =
10621 			    kmem_zalloc(sizeof (sata_drive_info_t), KM_SLEEP);
10622 			mutex_enter(&pmportinfo->pmport_mutex);
10623 		}
10624 		drive = pmportinfo->pmport_sata_drive;
10625 		drive->satadrv_addr.cport = pmportinfo->pmport_addr.cport;
10626 		drive->satadrv_addr.pmport = npmport;
10627 		drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
10628 		drive->satadrv_type = pmportinfo-> pmport_dev_type;
10629 		drive->satadrv_state = SATA_STATE_UNKNOWN;
10630 
10631 		mutex_exit(&pmportinfo->pmport_mutex);
10632 		rval = sata_add_device(dip, sata_hba_inst, &sata_device);
10633 
10634 		if (rval != SATA_SUCCESS) {
10635 			/*
10636 			 * Plugged device was not correctly identified.
10637 			 * Retry, within the SATA_DEV_IDENTIFY_TIMEOUT
10638 			 */
10639 			cur_time = ddi_get_lbolt();
10640 			if ((cur_time - start_time) < drv_usectohz(
10641 			    SATA_DEV_IDENTIFY_TIMEOUT)) {
10642 				/* sleep for a while */
10643 				delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10644 				goto reprobe_pmport;
10645 			}
10646 		}
10647 	}
10648 }
10649 
10650 /*
10651  * Add SATA device for specified HBA instance & port (SCSI target
10652  * device nodes).
10653  * This function is called (indirectly) only from sata_hba_attach().
10654  * A target node is created when there is a supported type device attached,
10655  * but may be removed if it cannot be put online.
10656  *
10657  * This function cannot be called from an interrupt context.
10658  *
10659  * Create target nodes for disk, CD/DVD, Tape and ATAPI disk devices
10660  *
10661  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
10662  * device identification failed - adding a device could be retried.
10663  *
10664  */
10665 static 	int
10666 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst,
10667     sata_device_t *sata_device)
10668 {
10669 	sata_cport_info_t 	*cportinfo;
10670 	sata_pmult_info_t	*pminfo;
10671 	sata_pmport_info_t	*pmportinfo;
10672 	dev_info_t		*cdip;		/* child dip */
10673 	sata_address_t		*saddr = &sata_device->satadev_addr;
10674 	uint8_t			cport, pmport;
10675 	int			rval;
10676 
10677 	cport = saddr->cport;
10678 	pmport = saddr->pmport;
10679 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10680 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
10681 
10682 	/*
10683 	 * Some device is attached to a controller port.
10684 	 * We rely on controllers distinquishing between no-device,
10685 	 * attached port multiplier and other kind of attached device.
10686 	 * We need to get Identify Device data and determine
10687 	 * positively the dev type before trying to attach
10688 	 * the target driver.
10689 	 */
10690 	sata_device->satadev_rev = SATA_DEVICE_REV;
10691 	switch (saddr->qual) {
10692 	case SATA_ADDR_CPORT:
10693 		/*
10694 		 * Add a non-port-multiplier device at controller port.
10695 		 */
10696 		saddr->qual = SATA_ADDR_DCPORT;
10697 
10698 		rval = sata_probe_device(sata_hba_inst, sata_device);
10699 		if (rval != SATA_SUCCESS ||
10700 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN)
10701 			return (SATA_FAILURE);
10702 
10703 		mutex_enter(&cportinfo->cport_mutex);
10704 		sata_show_drive_info(sata_hba_inst,
10705 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
10706 
10707 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10708 			/*
10709 			 * Could not determine device type or
10710 			 * a device is not supported.
10711 			 * Degrade this device to unknown.
10712 			 */
10713 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10714 			mutex_exit(&cportinfo->cport_mutex);
10715 			return (SATA_SUCCESS);
10716 		}
10717 		cportinfo->cport_dev_type = sata_device->satadev_type;
10718 		cportinfo->cport_tgtnode_clean = B_TRUE;
10719 		mutex_exit(&cportinfo->cport_mutex);
10720 
10721 		/*
10722 		 * Initialize device to the desired state. Even if it
10723 		 * fails, the device will still attach but syslog
10724 		 * will show the warning.
10725 		 */
10726 		if (sata_initialize_device(sata_hba_inst,
10727 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
10728 			/* Retry */
10729 			rval = sata_initialize_device(sata_hba_inst,
10730 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
10731 
10732 			if (rval == SATA_RETRY)
10733 				sata_log(sata_hba_inst, CE_WARN,
10734 				    "SATA device at port %d - "
10735 				    "default device features could not be set."
10736 				    " Device may not operate as expected.",
10737 				    cport);
10738 		}
10739 
10740 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10741 		if (cdip == NULL) {
10742 			/*
10743 			 * Attaching target node failed.
10744 			 * We retain sata_drive_info structure...
10745 			 */
10746 			return (SATA_SUCCESS);
10747 		}
10748 
10749 		mutex_enter(&cportinfo->cport_mutex);
10750 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
10751 		    satadrv_state = SATA_STATE_READY;
10752 		mutex_exit(&cportinfo->cport_mutex);
10753 
10754 		break;
10755 
10756 	case SATA_ADDR_PMPORT:
10757 		saddr->qual = SATA_ADDR_DPMPORT;
10758 
10759 		mutex_enter(&cportinfo->cport_mutex);
10760 		/* It must be a Port Multiplier at the controller port */
10761 		ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
10762 
10763 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
10764 		pmportinfo = pminfo->pmult_dev_port[saddr->pmport];
10765 		mutex_exit(&cportinfo->cport_mutex);
10766 
10767 		rval = sata_probe_device(sata_hba_inst, sata_device);
10768 		if (rval != SATA_SUCCESS ||
10769 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
10770 			return (SATA_FAILURE);
10771 		}
10772 
10773 		mutex_enter(&pmportinfo->pmport_mutex);
10774 		sata_show_drive_info(sata_hba_inst,
10775 		    SATA_PMPORTINFO_DRV_INFO(pmportinfo));
10776 
10777 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10778 			/*
10779 			 * Could not determine device type.
10780 			 * Degrade this device to unknown.
10781 			 */
10782 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
10783 			mutex_exit(&pmportinfo->pmport_mutex);
10784 			return (SATA_SUCCESS);
10785 		}
10786 		pmportinfo->pmport_dev_type = sata_device->satadev_type;
10787 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
10788 		mutex_exit(&pmportinfo->pmport_mutex);
10789 
10790 		/*
10791 		 * Initialize device to the desired state.
10792 		 * Even if it fails, the device will still
10793 		 * attach but syslog will show the warning.
10794 		 */
10795 		if (sata_initialize_device(sata_hba_inst,
10796 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
10797 			/* Retry */
10798 			rval = sata_initialize_device(sata_hba_inst,
10799 			    pmportinfo->pmport_sata_drive);
10800 
10801 			if (rval == SATA_RETRY)
10802 				sata_log(sata_hba_inst, CE_WARN,
10803 				    "SATA device at port %d:%d - "
10804 				    "default device features could not be set."
10805 				    " Device may not operate as expected.",
10806 				    cport, pmport);
10807 		}
10808 
10809 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10810 		if (cdip == NULL) {
10811 			/*
10812 			 * Attaching target node failed.
10813 			 * We retain sata_drive_info structure...
10814 			 */
10815 			return (SATA_SUCCESS);
10816 		}
10817 		mutex_enter(&pmportinfo->pmport_mutex);
10818 		pmportinfo->pmport_sata_drive->satadrv_state |=
10819 		    SATA_STATE_READY;
10820 		mutex_exit(&pmportinfo->pmport_mutex);
10821 
10822 		break;
10823 
10824 	default:
10825 		return (SATA_FAILURE);
10826 	}
10827 
10828 	return (SATA_SUCCESS);
10829 }
10830 
10831 /*
10832  * Clean up target node at specific address.
10833  *
10834  * NOTE: No Mutex should be hold.
10835  */
10836 static int
10837 sata_offline_device(sata_hba_inst_t *sata_hba_inst,
10838     sata_device_t *sata_device, sata_drive_info_t *sdinfo)
10839 {
10840 	uint8_t cport, pmport, qual;
10841 	dev_info_t *tdip;
10842 
10843 	cport = sata_device->satadev_addr.cport;
10844 	pmport = sata_device->satadev_addr.pmport;
10845 	qual = sata_device->satadev_addr.qual;
10846 
10847 	if (qual == SATA_ADDR_DCPORT) {
10848 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10849 		    "sata_hba_ioctl: disconnect device at port %d", cport));
10850 	} else {
10851 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10852 		    "sata_hba_ioctl: disconnect device at port %d:%d",
10853 		    cport, pmport));
10854 	}
10855 
10856 	/* We are addressing attached device, not a port */
10857 	sata_device->satadev_addr.qual =
10858 	    sdinfo->satadrv_addr.qual;
10859 	tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
10860 	    &sata_device->satadev_addr);
10861 	if (tdip != NULL && ndi_devi_offline(tdip,
10862 	    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10863 		/*
10864 		 * Problem :
10865 		 * The target node remained attached.
10866 		 * This happens when the device file was open
10867 		 * or a node was waiting for resources.
10868 		 * Cannot do anything about it.
10869 		 */
10870 		if (qual == SATA_ADDR_DCPORT) {
10871 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10872 			    "sata_hba_ioctl: disconnect: could "
10873 			    "not unconfigure device before "
10874 			    "disconnecting the SATA port %d",
10875 			    cport));
10876 		} else {
10877 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10878 			    "sata_hba_ioctl: disconnect: could "
10879 			    "not unconfigure device before "
10880 			    "disconnecting the SATA port %d:%d",
10881 			    cport, pmport));
10882 		}
10883 		/*
10884 		 * Set DEVICE REMOVED state in the target
10885 		 * node. It will prevent access to the device
10886 		 * even when a new device is attached, until
10887 		 * the old target node is released, removed and
10888 		 * recreated for a new  device.
10889 		 */
10890 		sata_set_device_removed(tdip);
10891 
10892 		/*
10893 		 * Instruct event daemon to try the target
10894 		 * node cleanup later.
10895 		 */
10896 		sata_set_target_node_cleanup(
10897 		    sata_hba_inst, &sata_device->satadev_addr);
10898 	}
10899 
10900 
10901 	return (SATA_SUCCESS);
10902 }
10903 
10904 
10905 /*
10906  * Create scsi target node for attached device, create node properties and
10907  * attach the node.
10908  * The node could be removed if the device onlining fails.
10909  *
10910  * A dev_info_t pointer is returned if operation is successful, NULL is
10911  * returned otherwise.
10912  */
10913 
10914 static dev_info_t *
10915 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
10916     sata_address_t *sata_addr)
10917 {
10918 	dev_info_t *cdip = NULL;
10919 	int rval;
10920 	char *nname = NULL;
10921 	char **compatible = NULL;
10922 	int ncompatible;
10923 	struct scsi_inquiry inq;
10924 	sata_device_t sata_device;
10925 	sata_drive_info_t *sdinfo;
10926 	int target;
10927 	int i;
10928 
10929 	sata_device.satadev_rev = SATA_DEVICE_REV;
10930 	sata_device.satadev_addr = *sata_addr;
10931 
10932 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
10933 
10934 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
10935 
10936 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
10937 	    sata_addr->pmport, sata_addr->qual);
10938 
10939 	if (sdinfo == NULL) {
10940 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10941 		    sata_addr->cport)));
10942 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10943 		    "sata_create_target_node: no sdinfo for target %x",
10944 		    target));
10945 		return (NULL);
10946 	}
10947 
10948 	/*
10949 	 * create or get scsi inquiry data, expected by
10950 	 * scsi_hba_nodename_compatible_get()
10951 	 * SATA hard disks get Identify Data translated into Inguiry Data.
10952 	 * ATAPI devices respond directly to Inquiry request.
10953 	 */
10954 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10955 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
10956 		    (uint8_t *)&inq);
10957 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10958 		    sata_addr->cport)));
10959 	} else { /* Assume supported ATAPI device */
10960 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10961 		    sata_addr->cport)));
10962 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
10963 		    &inq) == SATA_FAILURE)
10964 			return (NULL);
10965 		/*
10966 		 * Save supported ATAPI transport version
10967 		 */
10968 		sdinfo->satadrv_atapi_trans_ver =
10969 		    SATA_ATAPI_TRANS_VERSION(&inq);
10970 	}
10971 
10972 	/* determine the node name and compatible */
10973 	scsi_hba_nodename_compatible_get(&inq, NULL,
10974 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
10975 
10976 #ifdef SATA_DEBUG
10977 	if (sata_debug_flags & SATA_DBG_NODES) {
10978 		if (nname == NULL) {
10979 			cmn_err(CE_NOTE, "sata_create_target_node: "
10980 			    "cannot determine nodename for target %d\n",
10981 			    target);
10982 		} else {
10983 			cmn_err(CE_WARN, "sata_create_target_node: "
10984 			    "target %d nodename: %s\n", target, nname);
10985 		}
10986 		if (compatible == NULL) {
10987 			cmn_err(CE_WARN,
10988 			    "sata_create_target_node: no compatible name\n");
10989 		} else {
10990 			for (i = 0; i < ncompatible; i++) {
10991 				cmn_err(CE_WARN, "sata_create_target_node: "
10992 				    "compatible name: %s\n", compatible[i]);
10993 			}
10994 		}
10995 	}
10996 #endif
10997 
10998 	/* if nodename can't be determined, log error and exit */
10999 	if (nname == NULL) {
11000 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11001 		    "sata_create_target_node: cannot determine nodename "
11002 		    "for target %d\n", target));
11003 		scsi_hba_nodename_compatible_free(nname, compatible);
11004 		return (NULL);
11005 	}
11006 	/*
11007 	 * Create scsi target node
11008 	 */
11009 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
11010 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
11011 	    "device-type", "scsi");
11012 
11013 	if (rval != DDI_PROP_SUCCESS) {
11014 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
11015 		    "updating device_type prop failed %d", rval));
11016 		goto fail;
11017 	}
11018 
11019 	/*
11020 	 * Create target node properties: target & lun
11021 	 */
11022 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
11023 	if (rval != DDI_PROP_SUCCESS) {
11024 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
11025 		    "updating target prop failed %d", rval));
11026 		goto fail;
11027 	}
11028 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
11029 	if (rval != DDI_PROP_SUCCESS) {
11030 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
11031 		    "updating target prop failed %d", rval));
11032 		goto fail;
11033 	}
11034 
11035 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
11036 		/*
11037 		 * Add "variant" property
11038 		 */
11039 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
11040 		    "variant", "atapi");
11041 		if (rval != DDI_PROP_SUCCESS) {
11042 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11043 			    "sata_create_target_node: variant atapi "
11044 			    "property could not be created: %d", rval));
11045 			goto fail;
11046 		}
11047 	}
11048 	/* decorate the node with compatible */
11049 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
11050 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
11051 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11052 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
11053 		    (void *)cdip));
11054 		goto fail;
11055 	}
11056 
11057 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11058 		/*
11059 		 * Add "sata-phy" property
11060 		 */
11061 		if (ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "sata-phy",
11062 		    (int)sata_addr->cport) != DDI_PROP_SUCCESS) {
11063 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11064 			    "sata_create_target_node: failed to create "
11065 			    "\"sata-phy\" property: port %d",
11066 			    sata_addr->cport));
11067 		}
11068 	}
11069 
11070 
11071 	/*
11072 	 * Now, try to attach the driver. If probing of the device fails,
11073 	 * the target node may be removed
11074 	 */
11075 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
11076 
11077 	scsi_hba_nodename_compatible_free(nname, compatible);
11078 
11079 	if (rval == NDI_SUCCESS)
11080 		return (cdip);
11081 
11082 	/* target node was removed - are we sure? */
11083 	return (NULL);
11084 
11085 fail:
11086 	scsi_hba_nodename_compatible_free(nname, compatible);
11087 	ddi_prop_remove_all(cdip);
11088 	rval = ndi_devi_free(cdip);
11089 	if (rval != NDI_SUCCESS) {
11090 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
11091 		    "node removal failed %d", rval));
11092 	}
11093 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
11094 	    "cannot create target node for SATA device at port %d",
11095 	    sata_addr->cport);
11096 	return (NULL);
11097 }
11098 
11099 /*
11100  * Remove a target node.
11101  */
11102 static void
11103 sata_remove_target_node(sata_hba_inst_t *sata_hba_inst,
11104     sata_address_t *sata_addr)
11105 {
11106 	dev_info_t *tdip;
11107 	uint8_t cport = sata_addr->cport;
11108 	uint8_t pmport = sata_addr->pmport;
11109 	uint8_t qual = sata_addr->qual;
11110 
11111 	/* Note the sata daemon uses the address of the port/pmport */
11112 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
11113 
11114 	/* Remove target node */
11115 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), cport, pmport);
11116 	if (tdip != NULL) {
11117 		/*
11118 		 * Target node exists.  Unconfigure device
11119 		 * then remove the target node (one ndi
11120 		 * operation).
11121 		 */
11122 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11123 			/*
11124 			 * PROBLEM - no device, but target node remained. This
11125 			 * happens when the file was open or node was waiting
11126 			 * for resources.
11127 			 */
11128 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11129 			    "sata_remove_target_node: "
11130 			    "Failed to remove target node for "
11131 			    "detached SATA device."));
11132 			/*
11133 			 * Set target node state to DEVI_DEVICE_REMOVED. But
11134 			 * re-check first that the node still exists.
11135 			 */
11136 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
11137 			    cport, pmport);
11138 			if (tdip != NULL) {
11139 				sata_set_device_removed(tdip);
11140 				/*
11141 				 * Instruct event daemon to retry the cleanup
11142 				 * later.
11143 				 */
11144 				sata_set_target_node_cleanup(sata_hba_inst,
11145 				    sata_addr);
11146 			}
11147 		}
11148 
11149 		if (qual == SATA_ADDR_CPORT)
11150 			sata_log(sata_hba_inst, CE_WARN,
11151 			    "SATA device detached at port %d", cport);
11152 		else
11153 			sata_log(sata_hba_inst, CE_WARN,
11154 			    "SATA device detached at port %d:%d",
11155 			    cport, pmport);
11156 	}
11157 #ifdef SATA_DEBUG
11158 	else {
11159 		if (qual == SATA_ADDR_CPORT)
11160 			sata_log(sata_hba_inst, CE_WARN,
11161 			    "target node not found at port %d", cport);
11162 		else
11163 			sata_log(sata_hba_inst, CE_WARN,
11164 			    "target node not found at port %d:%d",
11165 			    cport, pmport);
11166 	}
11167 #endif
11168 }
11169 
11170 
11171 /*
11172  * Re-probe sata port, check for a device and attach info
11173  * structures when necessary. Identify Device data is fetched, if possible.
11174  * Assumption: sata address is already validated.
11175  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
11176  * the presence of a device and its type.
11177  *
11178  * flag arg specifies that the function should try multiple times to identify
11179  * device type and to initialize it, or it should return immediately on failure.
11180  * SATA_DEV_IDENTIFY_RETRY - retry
11181  * SATA_DEV_IDENTIFY_NORETRY - no retry
11182  *
11183  * SATA_FAILURE is returned if one of the operations failed.
11184  *
11185  * This function cannot be called in interrupt context - it may sleep.
11186  *
11187  * Note: Port multiplier is supported.
11188  */
11189 static int
11190 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
11191     int flag)
11192 {
11193 	sata_cport_info_t *cportinfo;
11194 	sata_pmult_info_t *pmultinfo;
11195 	sata_drive_info_t *sdinfo, *osdinfo;
11196 	boolean_t init_device = B_FALSE;
11197 	int prev_device_type = SATA_DTYPE_NONE;
11198 	int prev_device_settings = 0;
11199 	int prev_device_state = 0;
11200 	clock_t start_time;
11201 	int retry = B_FALSE;
11202 	uint8_t cport = sata_device->satadev_addr.cport;
11203 	int rval_probe, rval_init;
11204 
11205 	/*
11206 	 * If target is pmport, sata_reprobe_pmport() will handle it.
11207 	 */
11208 	if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT ||
11209 	    sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT)
11210 		return (sata_reprobe_pmport(sata_hba_inst, sata_device, flag));
11211 
11212 	/* We only care about host sata cport for now */
11213 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
11214 	    sata_device->satadev_addr.cport);
11215 
11216 	/*
11217 	 * If a port multiplier was previously attached (we have no idea it
11218 	 * still there or not), sata_reprobe_pmult() will handle it.
11219 	 */
11220 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT)
11221 		return (sata_reprobe_pmult(sata_hba_inst, sata_device, flag));
11222 
11223 	/* Store sata_drive_info when a non-pmult device was attached. */
11224 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11225 	if (osdinfo != NULL) {
11226 		/*
11227 		 * We are re-probing port with a previously attached device.
11228 		 * Save previous device type and settings.
11229 		 */
11230 		prev_device_type = cportinfo->cport_dev_type;
11231 		prev_device_settings = osdinfo->satadrv_settings;
11232 		prev_device_state = osdinfo->satadrv_state;
11233 	}
11234 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
11235 		start_time = ddi_get_lbolt();
11236 		retry = B_TRUE;
11237 	}
11238 retry_probe:
11239 
11240 	/* probe port */
11241 	mutex_enter(&cportinfo->cport_mutex);
11242 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11243 	cportinfo->cport_state |= SATA_STATE_PROBING;
11244 	mutex_exit(&cportinfo->cport_mutex);
11245 
11246 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11247 	    (SATA_DIP(sata_hba_inst), sata_device);
11248 
11249 	mutex_enter(&cportinfo->cport_mutex);
11250 	if (rval_probe != SATA_SUCCESS) {
11251 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11252 		mutex_exit(&cportinfo->cport_mutex);
11253 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
11254 		    "SATA port %d probing failed",
11255 		    cportinfo->cport_addr.cport));
11256 		return (SATA_FAILURE);
11257 	}
11258 
11259 	/*
11260 	 * update sata port state and set device type
11261 	 */
11262 	sata_update_port_info(sata_hba_inst, sata_device);
11263 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
11264 
11265 	/*
11266 	 * Sanity check - Port is active? Is the link active?
11267 	 * Is there any device attached?
11268 	 */
11269 	if ((cportinfo->cport_state &
11270 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11271 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11272 	    SATA_PORT_DEVLINK_UP) {
11273 		/*
11274 		 * Port in non-usable state or no link active/no device.
11275 		 * Free info structure if necessary (direct attached drive
11276 		 * only, for now!
11277 		 */
11278 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11279 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11280 		/* Add here differentiation for device attached or not */
11281 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11282 		mutex_exit(&cportinfo->cport_mutex);
11283 		if (sdinfo != NULL)
11284 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11285 		return (SATA_SUCCESS);
11286 	}
11287 
11288 	cportinfo->cport_state |= SATA_STATE_READY;
11289 	cportinfo->cport_state |= SATA_STATE_PROBED;
11290 
11291 	cportinfo->cport_dev_type = sata_device->satadev_type;
11292 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11293 
11294 	/*
11295 	 * If we are re-probing the port, there may be
11296 	 * sata_drive_info structure attached
11297 	 */
11298 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
11299 
11300 		/*
11301 		 * There is no device, so remove device info structure,
11302 		 * if necessary.
11303 		 */
11304 		/* Device change: Drive -> None */
11305 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11306 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11307 		if (sdinfo != NULL) {
11308 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11309 			sata_log(sata_hba_inst, CE_WARN,
11310 			    "SATA device detached "
11311 			    "from port %d", cportinfo->cport_addr.cport);
11312 		}
11313 		mutex_exit(&cportinfo->cport_mutex);
11314 		return (SATA_SUCCESS);
11315 
11316 	}
11317 
11318 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
11319 
11320 		/* Device (may) change: Drive -> Drive */
11321 		if (sdinfo == NULL) {
11322 			/*
11323 			 * There is some device attached, but there is
11324 			 * no sata_drive_info structure - allocate one
11325 			 */
11326 			mutex_exit(&cportinfo->cport_mutex);
11327 			sdinfo = kmem_zalloc(
11328 			    sizeof (sata_drive_info_t), KM_SLEEP);
11329 			mutex_enter(&cportinfo->cport_mutex);
11330 			/*
11331 			 * Recheck, that the port state did not change when we
11332 			 * released mutex.
11333 			 */
11334 			if (cportinfo->cport_state & SATA_STATE_READY) {
11335 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
11336 				sdinfo->satadrv_addr = cportinfo->cport_addr;
11337 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
11338 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11339 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11340 			} else {
11341 				/*
11342 				 * Port is not in ready state, we
11343 				 * cannot attach a device.
11344 				 */
11345 				mutex_exit(&cportinfo->cport_mutex);
11346 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
11347 				return (SATA_SUCCESS);
11348 			}
11349 			/*
11350 			 * Since we are adding device, presumably new one,
11351 			 * indicate that it  should be initalized,
11352 			 * as well as some internal framework states).
11353 			 */
11354 			init_device = B_TRUE;
11355 		}
11356 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11357 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
11358 	} else {
11359 		/* Device change: Drive -> PMult */
11360 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11361 		if (sdinfo != NULL) {
11362 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11363 			sata_log(sata_hba_inst, CE_WARN,
11364 			    "SATA device detached "
11365 			    "from port %d", cportinfo->cport_addr.cport);
11366 		}
11367 
11368 		sata_log(sata_hba_inst, CE_WARN,
11369 		    "SATA port multiplier detected at port %d",
11370 		    cportinfo->cport_addr.cport);
11371 
11372 		mutex_exit(&cportinfo->cport_mutex);
11373 		if (sata_alloc_pmult(sata_hba_inst, sata_device) !=
11374 		    SATA_SUCCESS)
11375 			return (SATA_FAILURE);
11376 		sata_show_pmult_info(sata_hba_inst, sata_device);
11377 		mutex_enter(&cportinfo->cport_mutex);
11378 
11379 		/*
11380 		 * Mark all the port multiplier port behind the port
11381 		 * multiplier behind with link events, so that the sata daemon
11382 		 * will update their status.
11383 		 */
11384 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
11385 		pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
11386 		mutex_exit(&cportinfo->cport_mutex);
11387 		return (SATA_SUCCESS);
11388 	}
11389 	mutex_exit(&cportinfo->cport_mutex);
11390 
11391 	/*
11392 	 * Figure out what kind of device we are really
11393 	 * dealing with. Failure of identifying device does not fail this
11394 	 * function.
11395 	 */
11396 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
11397 	rval_init = SATA_FAILURE;
11398 	mutex_enter(&cportinfo->cport_mutex);
11399 	if (rval_probe == SATA_SUCCESS) {
11400 		/*
11401 		 * If we are dealing with the same type of a device as before,
11402 		 * restore its settings flags.
11403 		 */
11404 		if (osdinfo != NULL &&
11405 		    sata_device->satadev_type == prev_device_type)
11406 			sdinfo->satadrv_settings = prev_device_settings;
11407 
11408 		mutex_exit(&cportinfo->cport_mutex);
11409 		rval_init = SATA_SUCCESS;
11410 		/* Set initial device features, if necessary */
11411 		if (init_device == B_TRUE) {
11412 			rval_init = sata_initialize_device(sata_hba_inst,
11413 			    sdinfo);
11414 		}
11415 		if (rval_init == SATA_SUCCESS)
11416 			return (rval_init);
11417 		/* else we will retry if retry was asked for */
11418 
11419 	} else {
11420 		/*
11421 		 * If there was some device info before we probe the device,
11422 		 * restore previous device setting, so we can retry from scratch
11423 		 * later. Providing, of course, that device has not disapear
11424 		 * during probing process.
11425 		 */
11426 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
11427 			if (osdinfo != NULL) {
11428 				cportinfo->cport_dev_type = prev_device_type;
11429 				sdinfo->satadrv_type = prev_device_type;
11430 				sdinfo->satadrv_state = prev_device_state;
11431 			}
11432 		} else {
11433 			/* device is gone */
11434 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11435 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11436 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
11437 			mutex_exit(&cportinfo->cport_mutex);
11438 			return (SATA_SUCCESS);
11439 		}
11440 		mutex_exit(&cportinfo->cport_mutex);
11441 	}
11442 
11443 	if (retry) {
11444 		clock_t cur_time = ddi_get_lbolt();
11445 		/*
11446 		 * A device was not successfully identified or initialized.
11447 		 * Track retry time for device identification.
11448 		 */
11449 		if ((cur_time - start_time) <
11450 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11451 			/* sleep for a while */
11452 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11453 			goto retry_probe;
11454 		}
11455 		/* else no more retries */
11456 		mutex_enter(&cportinfo->cport_mutex);
11457 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
11458 			if (rval_init == SATA_RETRY) {
11459 				/*
11460 				 * Setting drive features have failed, but
11461 				 * because the drive is still accessible,
11462 				 * keep it and emit a warning message.
11463 				 */
11464 				sata_log(sata_hba_inst, CE_WARN,
11465 				    "SATA device at port %d - desired "
11466 				    "drive features could not be set. "
11467 				    "Device may not operate as expected.",
11468 				    cportinfo->cport_addr.cport);
11469 			} else {
11470 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
11471 				    satadrv_state = SATA_DSTATE_FAILED;
11472 			}
11473 		}
11474 		mutex_exit(&cportinfo->cport_mutex);
11475 	}
11476 	return (SATA_SUCCESS);
11477 }
11478 
11479 /*
11480  * Reprobe a controller port that connected to a port multiplier.
11481  *
11482  * NOTE: No Mutex should be hold.
11483  */
11484 static int
11485 sata_reprobe_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
11486     int flag)
11487 {
11488 	_NOTE(ARGUNUSED(flag))
11489 	sata_cport_info_t *cportinfo;
11490 	sata_pmult_info_t *pmultinfo;
11491 	uint8_t cport = sata_device->satadev_addr.cport;
11492 	int rval_probe;
11493 
11494 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11495 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
11496 
11497 	/* probe port */
11498 	mutex_enter(&cportinfo->cport_mutex);
11499 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11500 	cportinfo->cport_state |= SATA_STATE_PROBING;
11501 	mutex_exit(&cportinfo->cport_mutex);
11502 
11503 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11504 	    (SATA_DIP(sata_hba_inst), sata_device);
11505 
11506 	mutex_enter(&cportinfo->cport_mutex);
11507 	if (rval_probe != SATA_SUCCESS) {
11508 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11509 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmult: "
11510 		    "SATA port %d probing failed", cport));
11511 		sata_log(sata_hba_inst, CE_WARN,
11512 		    "SATA port multiplier detached at port %d", cport);
11513 		mutex_exit(&cportinfo->cport_mutex);
11514 		sata_free_pmult(sata_hba_inst, sata_device);
11515 		return (SATA_FAILURE);
11516 	}
11517 
11518 	/*
11519 	 * update sata port state and set device type
11520 	 */
11521 	sata_update_port_info(sata_hba_inst, sata_device);
11522 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
11523 	cportinfo->cport_state |= SATA_STATE_PROBED;
11524 
11525 	/*
11526 	 * Sanity check - Port is active? Is the link active?
11527 	 * Is there any device attached?
11528 	 */
11529 	if ((cportinfo->cport_state &
11530 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11531 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11532 	    SATA_PORT_DEVLINK_UP ||
11533 	    (sata_device->satadev_type == SATA_DTYPE_NONE)) {
11534 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11535 		mutex_exit(&cportinfo->cport_mutex);
11536 		sata_free_pmult(sata_hba_inst, sata_device);
11537 		sata_log(sata_hba_inst, CE_WARN,
11538 		    "SATA port multiplier detached at port %d", cport);
11539 		return (SATA_SUCCESS);
11540 	}
11541 
11542 	/*
11543 	 * Device changed: PMult -> Non-PMult
11544 	 *
11545 	 * This situation is uncommon, most possibly being caused by errors
11546 	 * after which the port multiplier is not correct initialized and
11547 	 * recognized. In that case the new device will be marked as unknown
11548 	 * and will not be automatically probed in this routine. Instead
11549 	 * system administrator could manually restart it via cfgadm(1M).
11550 	 */
11551 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
11552 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11553 		mutex_exit(&cportinfo->cport_mutex);
11554 		sata_free_pmult(sata_hba_inst, sata_device);
11555 		sata_log(sata_hba_inst, CE_WARN,
11556 		    "SATA port multiplier detached at port %d", cport);
11557 		return (SATA_FAILURE);
11558 	}
11559 
11560 	/*
11561 	 * Now we know it is a port multiplier. However, if this is not the
11562 	 * previously attached port multiplier - they may have different
11563 	 * pmport numbers - we need to re-allocate data structures for every
11564 	 * pmport and drive.
11565 	 *
11566 	 * Port multipliers of the same model have identical values in these
11567 	 * registers, so it is still necessary to update the information of
11568 	 * all drives attached to the previous port multiplier afterwards.
11569 	 */
11570 	/* Device changed: PMult -> another PMult */
11571 	mutex_exit(&cportinfo->cport_mutex);
11572 	sata_free_pmult(sata_hba_inst, sata_device);
11573 	if (sata_alloc_pmult(sata_hba_inst, sata_device) != SATA_SUCCESS)
11574 		return (SATA_FAILURE);
11575 	mutex_enter(&cportinfo->cport_mutex);
11576 
11577 	SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11578 	    "SATA port multiplier [changed] at port %d", cport);
11579 	sata_log(sata_hba_inst, CE_WARN,
11580 	    "SATA port multiplier detected at port %d", cport);
11581 
11582 	/*
11583 	 * Mark all the port multiplier port behind the port
11584 	 * multiplier behind with link events, so that the sata daemon
11585 	 * will update their status.
11586 	 */
11587 	pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
11588 	mutex_exit(&cportinfo->cport_mutex);
11589 
11590 	return (SATA_SUCCESS);
11591 }
11592 
11593 /*
11594  * Re-probe a port multiplier port, check for a device and attach info
11595  * structures when necessary. Identify Device data is fetched, if possible.
11596  * Assumption: sata address is already validated as port multiplier port.
11597  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
11598  * the presence of a device and its type.
11599  *
11600  * flag arg specifies that the function should try multiple times to identify
11601  * device type and to initialize it, or it should return immediately on failure.
11602  * SATA_DEV_IDENTIFY_RETRY - retry
11603  * SATA_DEV_IDENTIFY_NORETRY - no retry
11604  *
11605  * SATA_FAILURE is returned if one of the operations failed.
11606  *
11607  * This function cannot be called in interrupt context - it may sleep.
11608  *
11609  * NOTE: Should be only called by sata_probe_port() in case target port is a
11610  *       port multiplier port.
11611  * NOTE: No Mutex should be hold.
11612  */
11613 static int
11614 sata_reprobe_pmport(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
11615     int flag)
11616 {
11617 	sata_cport_info_t *cportinfo = NULL;
11618 	sata_pmport_info_t *pmportinfo = NULL;
11619 	sata_drive_info_t *sdinfo, *osdinfo;
11620 	sata_device_t sdevice;
11621 	boolean_t init_device = B_FALSE;
11622 	int prev_device_type = SATA_DTYPE_NONE;
11623 	int prev_device_settings = 0;
11624 	int prev_device_state = 0;
11625 	clock_t start_time;
11626 	uint8_t cport = sata_device->satadev_addr.cport;
11627 	uint8_t pmport = sata_device->satadev_addr.pmport;
11628 	int rval;
11629 
11630 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11631 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11632 	osdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11633 
11634 	if (osdinfo != NULL) {
11635 		/*
11636 		 * We are re-probing port with a previously attached device.
11637 		 * Save previous device type and settings.
11638 		 */
11639 		prev_device_type = pmportinfo->pmport_dev_type;
11640 		prev_device_settings = osdinfo->satadrv_settings;
11641 		prev_device_state = osdinfo->satadrv_state;
11642 	}
11643 
11644 	start_time = ddi_get_lbolt();
11645 
11646 	/* check parent status */
11647 	mutex_enter(&cportinfo->cport_mutex);
11648 	if ((cportinfo->cport_state &
11649 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11650 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11651 	    SATA_PORT_DEVLINK_UP) {
11652 		mutex_exit(&cportinfo->cport_mutex);
11653 		return (SATA_FAILURE);
11654 	}
11655 	mutex_exit(&cportinfo->cport_mutex);
11656 
11657 retry_probe_pmport:
11658 
11659 	/* probe port */
11660 	mutex_enter(&pmportinfo->pmport_mutex);
11661 	pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11662 	pmportinfo->pmport_state |= SATA_STATE_PROBING;
11663 	mutex_exit(&pmportinfo->pmport_mutex);
11664 
11665 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11666 	    (SATA_DIP(sata_hba_inst), sata_device);
11667 
11668 	/* might need retry because we cannot touch registers. */
11669 	if (rval == SATA_FAILURE) {
11670 		mutex_enter(&pmportinfo->pmport_mutex);
11671 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
11672 		mutex_exit(&pmportinfo->pmport_mutex);
11673 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
11674 		    "SATA port %d:%d probing failed",
11675 		    cport, pmport));
11676 		return (SATA_FAILURE);
11677 	} else if (rval == SATA_RETRY) {
11678 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
11679 		    "SATA port %d:%d probing failed, retrying...",
11680 		    cport, pmport));
11681 		clock_t cur_time = ddi_get_lbolt();
11682 		/*
11683 		 * A device was not successfully identified or initialized.
11684 		 * Track retry time for device identification.
11685 		 */
11686 		if ((cur_time - start_time) <
11687 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11688 			/* sleep for a while */
11689 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11690 			goto retry_probe_pmport;
11691 		} else {
11692 			mutex_enter(&pmportinfo->pmport_mutex);
11693 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11694 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11695 				    satadrv_state = SATA_DSTATE_FAILED;
11696 			mutex_exit(&pmportinfo->pmport_mutex);
11697 			return (SATA_SUCCESS);
11698 		}
11699 	}
11700 
11701 	/*
11702 	 * Sanity check - Controller port is active? Is the link active?
11703 	 * Is it still a port multiplier?
11704 	 */
11705 	if ((cportinfo->cport_state &
11706 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11707 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11708 	    SATA_PORT_DEVLINK_UP ||
11709 	    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
11710 		/*
11711 		 * Port in non-usable state or no link active/no
11712 		 * device. Free info structure.
11713 		 */
11714 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11715 
11716 		sdevice.satadev_addr.cport = cport;
11717 		sdevice.satadev_addr.pmport = pmport;
11718 		sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
11719 		mutex_exit(&cportinfo->cport_mutex);
11720 
11721 		sata_free_pmult(sata_hba_inst, &sdevice);
11722 		return (SATA_FAILURE);
11723 	}
11724 
11725 	/* SATA_SUCCESS NOW */
11726 	/*
11727 	 * update sata port state and set device type
11728 	 */
11729 	mutex_enter(&pmportinfo->pmport_mutex);
11730 	sata_update_pmport_info(sata_hba_inst, sata_device);
11731 	pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
11732 
11733 	/*
11734 	 * Sanity check - Port is active? Is the link active?
11735 	 * Is there any device attached?
11736 	 */
11737 	if ((pmportinfo->pmport_state &
11738 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11739 	    (pmportinfo->pmport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11740 	    SATA_PORT_DEVLINK_UP) {
11741 		/*
11742 		 * Port in non-usable state or no link active/no device.
11743 		 * Free info structure if necessary (direct attached drive
11744 		 * only, for now!
11745 		 */
11746 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11747 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11748 		/* Add here differentiation for device attached or not */
11749 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11750 		mutex_exit(&pmportinfo->pmport_mutex);
11751 		if (sdinfo != NULL)
11752 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11753 		return (SATA_SUCCESS);
11754 	}
11755 
11756 	pmportinfo->pmport_state |= SATA_STATE_READY;
11757 	pmportinfo->pmport_dev_type = sata_device->satadev_type;
11758 	sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11759 
11760 	/*
11761 	 * If we are re-probing the port, there may be
11762 	 * sata_drive_info structure attached
11763 	 * (or sata_pm_info, if PMult is supported).
11764 	 */
11765 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
11766 		/*
11767 		 * There is no device, so remove device info structure,
11768 		 * if necessary.
11769 		 */
11770 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11771 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11772 		if (sdinfo != NULL) {
11773 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11774 			sata_log(sata_hba_inst, CE_WARN,
11775 			    "SATA device detached from port %d:%d",
11776 			    cport, pmport);
11777 		}
11778 		mutex_exit(&pmportinfo->pmport_mutex);
11779 		return (SATA_SUCCESS);
11780 	}
11781 
11782 	/* this should not be a pmult */
11783 	ASSERT(sata_device->satadev_type != SATA_DTYPE_PMULT);
11784 	if (sdinfo == NULL) {
11785 		/*
11786 		 * There is some device attached, but there is
11787 		 * no sata_drive_info structure - allocate one
11788 		 */
11789 		mutex_exit(&pmportinfo->pmport_mutex);
11790 		sdinfo = kmem_zalloc(sizeof (sata_drive_info_t),
11791 		    KM_SLEEP);
11792 		mutex_enter(&pmportinfo->pmport_mutex);
11793 		/*
11794 		 * Recheck, that the port state did not change when we
11795 		 * released mutex.
11796 		 */
11797 		if (pmportinfo->pmport_state & SATA_STATE_READY) {
11798 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = sdinfo;
11799 			sdinfo->satadrv_addr = pmportinfo->pmport_addr;
11800 			sdinfo->satadrv_addr.qual = SATA_ADDR_DPMPORT;
11801 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11802 			sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11803 		} else {
11804 			/*
11805 			 * Port is not in ready state, we
11806 			 * cannot attach a device.
11807 			 */
11808 			mutex_exit(&pmportinfo->pmport_mutex);
11809 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11810 			return (SATA_SUCCESS);
11811 		}
11812 		/*
11813 		 * Since we are adding device, presumably new one,
11814 		 * indicate that it  should be initalized,
11815 		 * as well as some internal framework states).
11816 		 */
11817 		init_device = B_TRUE;
11818 	}
11819 
11820 	pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
11821 	sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
11822 
11823 	mutex_exit(&pmportinfo->pmport_mutex);
11824 	/*
11825 	 * Figure out what kind of device we are really
11826 	 * dealing with.
11827 	 */
11828 	rval = sata_probe_device(sata_hba_inst, sata_device);
11829 
11830 	mutex_enter(&pmportinfo->pmport_mutex);
11831 	if (rval == SATA_SUCCESS) {
11832 		/*
11833 		 * If we are dealing with the same type of a device as before,
11834 		 * restore its settings flags.
11835 		 */
11836 		if (osdinfo != NULL &&
11837 		    sata_device->satadev_type == prev_device_type)
11838 			sdinfo->satadrv_settings = prev_device_settings;
11839 
11840 		mutex_exit(&pmportinfo->pmport_mutex);
11841 		/* Set initial device features, if necessary */
11842 		if (init_device == B_TRUE) {
11843 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
11844 		}
11845 		if (rval == SATA_SUCCESS)
11846 			return (rval);
11847 	} else {
11848 		/*
11849 		 * If there was some device info before we probe the device,
11850 		 * restore previous device setting, so we can retry from scratch
11851 		 * later. Providing, of course, that device has not disappeared
11852 		 * during probing process.
11853 		 */
11854 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
11855 			if (osdinfo != NULL) {
11856 				pmportinfo->pmport_dev_type = prev_device_type;
11857 				sdinfo->satadrv_type = prev_device_type;
11858 				sdinfo->satadrv_state = prev_device_state;
11859 			}
11860 		} else {
11861 			/* device is gone */
11862 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11863 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11864 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11865 			mutex_exit(&pmportinfo->pmport_mutex);
11866 			return (SATA_SUCCESS);
11867 		}
11868 		mutex_exit(&pmportinfo->pmport_mutex);
11869 	}
11870 
11871 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
11872 		clock_t cur_time = ddi_get_lbolt();
11873 		/*
11874 		 * A device was not successfully identified or initialized.
11875 		 * Track retry time for device identification.
11876 		 */
11877 		if ((cur_time - start_time) <
11878 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11879 			/* sleep for a while */
11880 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11881 			goto retry_probe_pmport;
11882 		} else {
11883 			mutex_enter(&pmportinfo->pmport_mutex);
11884 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11885 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11886 				    satadrv_state = SATA_DSTATE_FAILED;
11887 			mutex_exit(&pmportinfo->pmport_mutex);
11888 		}
11889 	}
11890 	return (SATA_SUCCESS);
11891 }
11892 
11893 /*
11894  * Allocated related structure for a port multiplier and its device ports
11895  *
11896  * Port multiplier should be ready and probed, and related information like
11897  * the number of the device ports should be store in sata_device_t.
11898  *
11899  * NOTE: No Mutex should be hold.
11900  */
11901 static int
11902 sata_alloc_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11903 {
11904 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
11905 	sata_cport_info_t *cportinfo = NULL;
11906 	sata_pmult_info_t *pmultinfo = NULL;
11907 	sata_pmport_info_t *pmportinfo = NULL;
11908 	sata_device_t sd;
11909 	dev_t minor_number;
11910 	char name[16];
11911 	uint8_t cport = sata_device->satadev_addr.cport;
11912 	int rval;
11913 	int npmport;
11914 
11915 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11916 
11917 	/* This function might be called while a port-mult is hot-plugged. */
11918 	mutex_enter(&cportinfo->cport_mutex);
11919 
11920 	/* dev_type's not updated when get called from sata_reprobe_port() */
11921 	if (SATA_CPORTINFO_PMULT_INFO(cportinfo) == NULL) {
11922 		/* Create a pmult_info structure */
11923 		SATA_CPORTINFO_PMULT_INFO(cportinfo) =
11924 		    kmem_zalloc(sizeof (sata_pmult_info_t), KM_SLEEP);
11925 	}
11926 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11927 
11928 	pmultinfo->pmult_addr = sata_device->satadev_addr;
11929 	pmultinfo->pmult_addr.qual = SATA_ADDR_PMULT;
11930 	pmultinfo->pmult_state = SATA_STATE_PROBING;
11931 
11932 	/*
11933 	 * Probe the port multiplier with qualifier SATA_ADDR_PMULT_SPEC,
11934 	 * The HBA driver should initialize and register the port multiplier,
11935 	 * sata_register_pmult() will fill following fields,
11936 	 *   + sata_pmult_info.pmult_gscr
11937 	 *   + sata_pmult_info.pmult_num_dev_ports
11938 	 */
11939 	sd.satadev_addr = sata_device->satadev_addr;
11940 	sd.satadev_addr.qual = SATA_ADDR_PMULT_SPEC;
11941 	mutex_exit(&cportinfo->cport_mutex);
11942 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11943 	    (SATA_DIP(sata_hba_inst), &sd);
11944 	mutex_enter(&cportinfo->cport_mutex);
11945 
11946 	if (rval != SATA_SUCCESS ||
11947 	    (sd.satadev_type != SATA_DTYPE_PMULT) ||
11948 	    !(sd.satadev_state & SATA_DSTATE_PMULT_INIT)) {
11949 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
11950 		kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11951 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11952 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11953 		mutex_exit(&cportinfo->cport_mutex);
11954 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11955 		    "sata_alloc_pmult: failed to initialize pmult "
11956 		    "at port %d.", cport)
11957 		return (SATA_FAILURE);
11958 	}
11959 
11960 	/* Initialize pmport_info structure */
11961 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11962 	    npmport++) {
11963 
11964 		/* if everything is allocated, skip */
11965 		if (SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) != NULL)
11966 			continue;
11967 
11968 		pmportinfo = kmem_zalloc(sizeof (sata_pmport_info_t), KM_SLEEP);
11969 		mutex_init(&pmportinfo->pmport_mutex, NULL, MUTEX_DRIVER, NULL);
11970 		mutex_exit(&cportinfo->cport_mutex);
11971 
11972 		mutex_enter(&pmportinfo->pmport_mutex);
11973 		pmportinfo->pmport_addr.cport = cport;
11974 		pmportinfo->pmport_addr.pmport = (uint8_t)npmport;
11975 		pmportinfo->pmport_addr.qual = SATA_ADDR_PMPORT;
11976 		pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11977 		mutex_exit(&pmportinfo->pmport_mutex);
11978 
11979 		mutex_enter(&cportinfo->cport_mutex);
11980 		SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) = pmportinfo;
11981 
11982 		/* Create an attachment point */
11983 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
11984 		    cport, (uint8_t)npmport, SATA_ADDR_PMPORT);
11985 		(void) sprintf(name, "%d.%d", cport, npmport);
11986 
11987 		if (ddi_create_minor_node(dip, name, S_IFCHR, minor_number,
11988 		    DDI_NT_SATA_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
11989 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
11990 			    "cannot create SATA attachment point for "
11991 			    "port %d:%d", cport, npmport);
11992 		}
11993 	}
11994 
11995 	pmultinfo->pmult_state &= ~SATA_STATE_PROBING;
11996 	pmultinfo->pmult_state |= (SATA_STATE_PROBED|SATA_STATE_READY);
11997 	cportinfo->cport_dev_type = SATA_DTYPE_PMULT;
11998 
11999 	mutex_exit(&cportinfo->cport_mutex);
12000 	return (SATA_SUCCESS);
12001 }
12002 
12003 /*
12004  * Free data structures when a port multiplier is removed.
12005  *
12006  * NOTE: No Mutex should be hold.
12007  */
12008 static void
12009 sata_free_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
12010 {
12011 	sata_cport_info_t *cportinfo;
12012 	sata_pmult_info_t *pmultinfo;
12013 	sata_pmport_info_t *pmportinfo;
12014 	sata_device_t pmport_device;
12015 	sata_drive_info_t *sdinfo;
12016 	dev_info_t *tdip;
12017 	char name[16];
12018 	uint8_t cport = sata_device->satadev_addr.cport;
12019 	int npmport;
12020 
12021 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
12022 
12023 	/* This function might be called while port-mult is hot plugged. */
12024 	mutex_enter(&cportinfo->cport_mutex);
12025 
12026 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
12027 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
12028 	ASSERT(pmultinfo != NULL);
12029 
12030 	/* Free pmport_info structure */
12031 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
12032 	    npmport++) {
12033 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
12034 		if (pmportinfo == NULL)
12035 			continue;
12036 		mutex_exit(&cportinfo->cport_mutex);
12037 
12038 		mutex_enter(&pmportinfo->pmport_mutex);
12039 		sdinfo = pmportinfo->pmport_sata_drive;
12040 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
12041 		mutex_exit(&pmportinfo->pmport_mutex);
12042 
12043 		/* Remove attachment point. */
12044 		name[0] = '\0';
12045 		(void) sprintf(name, "%d.%d", cport, npmport);
12046 		ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
12047 		sata_log(sata_hba_inst, CE_NOTE,
12048 		    "Remove attachment point of port %d:%d",
12049 		    cport, npmport);
12050 
12051 		/*
12052 		 * Rumove target node
12053 		 */
12054 		bzero(&pmport_device, sizeof (sata_device_t));
12055 		pmport_device.satadev_rev = SATA_DEVICE_REV;
12056 		pmport_device.satadev_addr.cport = cport;
12057 		pmport_device.satadev_addr.pmport = (uint8_t)npmport;
12058 		pmport_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
12059 
12060 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
12061 		    &(pmport_device.satadev_addr));
12062 		if (tdip != NULL && ndi_devi_offline(tdip,
12063 		    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
12064 			/*
12065 			 * Problem :
12066 			 * The target node remained attached.
12067 			 * This happens when the device file was open
12068 			 * or a node was waiting for resources.
12069 			 * Cannot do anything about it.
12070 			 */
12071 			SATA_LOG_D((sata_hba_inst, CE_WARN,
12072 			    "sata_free_pmult: could not unconfigure device "
12073 			    "before disconnecting the SATA port %d:%d",
12074 			    cport, npmport));
12075 
12076 			/*
12077 			 * Set DEVICE REMOVED state in the target
12078 			 * node. It will prevent access to the device
12079 			 * even when a new device is attached, until
12080 			 * the old target node is released, removed and
12081 			 * recreated for a new  device.
12082 			 */
12083 			sata_set_device_removed(tdip);
12084 
12085 			/*
12086 			 * Instruct event daemon to try the target
12087 			 * node cleanup later.
12088 			 */
12089 			sata_set_target_node_cleanup(
12090 			    sata_hba_inst, &(pmport_device.satadev_addr));
12091 
12092 		}
12093 		mutex_enter(&cportinfo->cport_mutex);
12094 
12095 		/*
12096 		 * Add here differentiation for device attached or not
12097 		 */
12098 		if (sdinfo != NULL)  {
12099 			sata_log(sata_hba_inst, CE_WARN,
12100 			    "SATA device detached from port %d:%d",
12101 			    cport, npmport);
12102 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
12103 		}
12104 
12105 		mutex_destroy(&pmportinfo->pmport_mutex);
12106 		kmem_free(pmportinfo, sizeof (sata_pmport_info_t));
12107 	}
12108 
12109 	kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
12110 
12111 	cportinfo->cport_devp.cport_sata_pmult = NULL;
12112 
12113 	sata_log(sata_hba_inst, CE_WARN,
12114 	    "SATA port multiplier detached at port %d", cport);
12115 
12116 	mutex_exit(&cportinfo->cport_mutex);
12117 }
12118 
12119 /*
12120  * Initialize device
12121  * Specified device is initialized to a default state.
12122  *
12123  * Returns SATA_SUCCESS if all device features are set successfully,
12124  * SATA_RETRY if device is accessible but device features were not set
12125  * successfully, and SATA_FAILURE otherwise.
12126  */
12127 static int
12128 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
12129     sata_drive_info_t *sdinfo)
12130 {
12131 	int rval;
12132 
12133 	sata_save_drive_settings(sdinfo);
12134 
12135 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
12136 
12137 	sata_init_write_cache_mode(sdinfo);
12138 
12139 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
12140 
12141 	/* Determine current data transfer mode */
12142 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
12143 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
12144 	} else if ((sdinfo->satadrv_id.ai_validinfo &
12145 	    SATA_VALIDINFO_88) != 0 &&
12146 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
12147 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
12148 	} else if ((sdinfo->satadrv_id.ai_dworddma &
12149 	    SATA_MDMA_SEL_MASK) != 0) {
12150 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
12151 	} else
12152 		/* DMA supported, not no DMA transfer mode is selected !? */
12153 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
12154 
12155 	if ((sdinfo->satadrv_id.ai_cmdset83 & 0x20) &&
12156 	    (sdinfo->satadrv_id.ai_features86 & 0x20))
12157 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
12158 	else
12159 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
12160 
12161 	return (rval);
12162 }
12163 
12164 
12165 /*
12166  * Initialize write cache mode.
12167  *
12168  * The default write cache setting for SATA HDD is provided by sata_write_cache
12169  * static variable. ATAPI CD/DVDs devices have write cache default is
12170  * determined by sata_atapicdvd_write_cache static variable.
12171  * ATAPI tape devices have write cache default is determined by
12172  * sata_atapitape_write_cache static variable.
12173  * ATAPI disk devices have write cache default is determined by
12174  * sata_atapidisk_write_cache static variable.
12175  * 1 - enable
12176  * 0 - disable
12177  * any other value - current drive setting
12178  *
12179  * Although there is not reason to disable write cache on CD/DVD devices,
12180  * tape devices and ATAPI disk devices, the default setting control is provided
12181  * for the maximun flexibility.
12182  *
12183  * In the future, it may be overridden by the
12184  * disk-write-cache-enable property setting, if it is defined.
12185  * Returns SATA_SUCCESS if all device features are set successfully,
12186  * SATA_FAILURE otherwise.
12187  */
12188 static void
12189 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
12190 {
12191 	switch (sdinfo->satadrv_type) {
12192 	case SATA_DTYPE_ATADISK:
12193 		if (sata_write_cache == 1)
12194 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12195 		else if (sata_write_cache == 0)
12196 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12197 		/*
12198 		 * When sata_write_cache value is not 0 or 1,
12199 		 * a current setting of the drive's write cache is used.
12200 		 */
12201 		break;
12202 	case SATA_DTYPE_ATAPICD:
12203 		if (sata_atapicdvd_write_cache == 1)
12204 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12205 		else if (sata_atapicdvd_write_cache == 0)
12206 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12207 		/*
12208 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
12209 		 * a current setting of the drive's write cache is used.
12210 		 */
12211 		break;
12212 	case SATA_DTYPE_ATAPITAPE:
12213 		if (sata_atapitape_write_cache == 1)
12214 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12215 		else if (sata_atapitape_write_cache == 0)
12216 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12217 		/*
12218 		 * When sata_atapitape_write_cache value is not 0 or 1,
12219 		 * a current setting of the drive's write cache is used.
12220 		 */
12221 		break;
12222 	case SATA_DTYPE_ATAPIDISK:
12223 		if (sata_atapidisk_write_cache == 1)
12224 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12225 		else if (sata_atapidisk_write_cache == 0)
12226 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12227 		/*
12228 		 * When sata_atapidisk_write_cache value is not 0 or 1,
12229 		 * a current setting of the drive's write cache is used.
12230 		 */
12231 		break;
12232 	}
12233 }
12234 
12235 
12236 /*
12237  * Validate sata address.
12238  * Specified cport, pmport and qualifier has to match
12239  * passed sata_scsi configuration info.
12240  * The presence of an attached device is not verified.
12241  *
12242  * Returns 0 when address is valid, -1 otherwise.
12243  */
12244 static int
12245 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
12246     int pmport, int qual)
12247 {
12248 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
12249 		goto invalid_address;
12250 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
12251 		goto invalid_address;
12252 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
12253 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
12254 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
12255 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
12256 		goto invalid_address;
12257 
12258 	return (0);
12259 
12260 invalid_address:
12261 	return (-1);
12262 
12263 }
12264 
12265 /*
12266  * Validate scsi address
12267  * SCSI target address is translated into SATA cport/pmport and compared
12268  * with a controller port/device configuration. LUN has to be 0.
12269  * Returns 0 if a scsi target refers to an attached device,
12270  * returns 1 if address is valid but no valid device is attached,
12271  * returns 2 if address is valid but device type is unknown (not valid device),
12272  * returns -1 if bad address or device is of an unsupported type.
12273  * Upon return sata_device argument is set.
12274  *
12275  * Port multiplier is supported now.
12276  */
12277 static int
12278 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
12279     struct scsi_address *ap, sata_device_t *sata_device)
12280 {
12281 	int cport, pmport, qual, rval;
12282 
12283 	rval = -1;	/* Invalid address */
12284 	if (ap->a_lun != 0)
12285 		goto out;
12286 
12287 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
12288 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
12289 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
12290 
12291 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
12292 		goto out;
12293 
12294 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
12295 	    0) {
12296 
12297 		sata_cport_info_t *cportinfo;
12298 		sata_pmult_info_t *pmultinfo;
12299 		sata_drive_info_t *sdinfo = NULL;
12300 
12301 		sata_device->satadev_addr.qual = qual;
12302 		sata_device->satadev_addr.cport = cport;
12303 		sata_device->satadev_addr.pmport = pmport;
12304 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
12305 
12306 		rval = 1;	/* Valid sata address */
12307 
12308 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
12309 		if (qual == SATA_ADDR_DCPORT) {
12310 			if (cportinfo == NULL ||
12311 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
12312 				goto out;
12313 
12314 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
12315 			if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN &&
12316 			    sdinfo != NULL) {
12317 				rval = 2;
12318 				goto out;
12319 			}
12320 
12321 			if ((cportinfo->cport_dev_type &
12322 			    SATA_VALID_DEV_TYPE) == 0) {
12323 				rval = -1;
12324 				goto out;
12325 			}
12326 
12327 		} else if (qual == SATA_ADDR_DPMPORT) {
12328 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
12329 			if (pmultinfo == NULL) {
12330 				rval = -1;
12331 				goto out;
12332 			}
12333 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
12334 			    NULL ||
12335 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
12336 			    pmport) == SATA_DTYPE_NONE)
12337 				goto out;
12338 
12339 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
12340 			    pmport);
12341 			if (SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
12342 			    pmport) == SATA_DTYPE_UNKNOWN && sdinfo != NULL) {
12343 				rval = 2;
12344 				goto out;
12345 			}
12346 
12347 			if ((SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
12348 			    pmport) & SATA_VALID_DEV_TYPE) == 0) {
12349 				rval = -1;
12350 				goto out;
12351 			}
12352 
12353 		} else {
12354 			rval = -1;
12355 			goto out;
12356 		}
12357 		if ((sdinfo == NULL) ||
12358 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
12359 			goto out;
12360 
12361 		sata_device->satadev_type = sdinfo->satadrv_type;
12362 
12363 		return (0);
12364 	}
12365 out:
12366 	if (rval > 0) {
12367 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
12368 		    "sata_validate_scsi_address: no valid target %x lun %x",
12369 		    ap->a_target, ap->a_lun);
12370 	}
12371 	return (rval);
12372 }
12373 
12374 /*
12375  * Find dip corresponding to passed device number
12376  *
12377  * Returns NULL if invalid device number is passed or device cannot be found,
12378  * Returns dip is device is found.
12379  */
12380 static dev_info_t *
12381 sata_devt_to_devinfo(dev_t dev)
12382 {
12383 	dev_info_t *dip;
12384 #ifndef __lock_lint
12385 	struct devnames *dnp;
12386 	major_t major = getmajor(dev);
12387 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
12388 
12389 	if (major >= devcnt)
12390 		return (NULL);
12391 
12392 	dnp = &devnamesp[major];
12393 	LOCK_DEV_OPS(&(dnp->dn_lock));
12394 	dip = dnp->dn_head;
12395 	while (dip && (ddi_get_instance(dip) != instance)) {
12396 		dip = ddi_get_next(dip);
12397 	}
12398 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
12399 #endif
12400 
12401 	return (dip);
12402 }
12403 
12404 
12405 /*
12406  * Probe device.
12407  * This function issues Identify Device command and initializes local
12408  * sata_drive_info structure if the device can be identified.
12409  * The device type is determined by examining Identify Device
12410  * command response.
12411  * If the sata_hba_inst has linked drive info structure for this
12412  * device address, the Identify Device data is stored into sata_drive_info
12413  * structure linked to the port info structure.
12414  *
12415  * sata_device has to refer to the valid sata port(s) for HBA described
12416  * by sata_hba_inst structure.
12417  *
12418  * Returns:
12419  *	SATA_SUCCESS if device type was successfully probed and port-linked
12420  *		drive info structure was updated;
12421  * 	SATA_FAILURE if there is no device, or device was not probed
12422  *		successully;
12423  *	SATA_RETRY if device probe can be retried later.
12424  * If a device cannot be identified, sata_device's dev_state and dev_type
12425  * fields are set to unknown.
12426  * There are no retries in this function. Any retries should be managed by
12427  * the caller.
12428  */
12429 
12430 
12431 static int
12432 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
12433 {
12434 	sata_pmport_info_t *pmportinfo;
12435 	sata_drive_info_t *sdinfo;
12436 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
12437 	int rval;
12438 
12439 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
12440 	    sata_device->satadev_addr.cport) &
12441 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
12442 
12443 	sata_device->satadev_type = SATA_DTYPE_NONE;
12444 
12445 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12446 	    sata_device->satadev_addr.cport)));
12447 
12448 	if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT) {
12449 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
12450 		    sata_device->satadev_addr.cport,
12451 		    sata_device->satadev_addr.pmport);
12452 		ASSERT(pmportinfo != NULL);
12453 	}
12454 
12455 	/* Get pointer to port-linked sata device info structure */
12456 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12457 	if (sdinfo != NULL) {
12458 		sdinfo->satadrv_state &=
12459 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
12460 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
12461 	} else {
12462 		/* No device to probe */
12463 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12464 		    sata_device->satadev_addr.cport)));
12465 		sata_device->satadev_type = SATA_DTYPE_NONE;
12466 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
12467 		return (SATA_FAILURE);
12468 	}
12469 	/*
12470 	 * Need to issue both types of identify device command and
12471 	 * determine device type by examining retreived data/status.
12472 	 * First, ATA Identify Device.
12473 	 */
12474 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
12475 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
12476 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12477 	    sata_device->satadev_addr.cport)));
12478 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
12479 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
12480 	if (rval == SATA_RETRY) {
12481 		/* We may try to check for ATAPI device */
12482 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
12483 			/*
12484 			 * HBA supports ATAPI - try to issue Identify Packet
12485 			 * Device command.
12486 			 */
12487 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
12488 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
12489 		}
12490 	}
12491 	if (rval == SATA_SUCCESS) {
12492 		/*
12493 		 * Got something responding positively to ATA Identify Device
12494 		 * or to Identify Packet Device cmd.
12495 		 * Save last used device type.
12496 		 */
12497 		sata_device->satadev_type = new_sdinfo.satadrv_type;
12498 
12499 		/* save device info, if possible */
12500 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12501 		    sata_device->satadev_addr.cport)));
12502 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12503 		if (sdinfo == NULL) {
12504 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12505 			    sata_device->satadev_addr.cport)));
12506 			return (SATA_FAILURE);
12507 		}
12508 		/*
12509 		 * Copy drive info into the port-linked drive info structure.
12510 		 */
12511 		*sdinfo = new_sdinfo;
12512 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
12513 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
12514 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
12515 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
12516 			    sata_device->satadev_addr.cport) =
12517 			    sdinfo->satadrv_type;
12518 		else { /* SATA_ADDR_DPMPORT */
12519 			mutex_enter(&pmportinfo->pmport_mutex);
12520 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
12521 			    sata_device->satadev_addr.cport,
12522 			    sata_device->satadev_addr.pmport) =
12523 			    sdinfo->satadrv_type;
12524 			mutex_exit(&pmportinfo->pmport_mutex);
12525 		}
12526 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12527 		    sata_device->satadev_addr.cport)));
12528 		return (SATA_SUCCESS);
12529 	}
12530 
12531 	/*
12532 	 * It may be SATA_RETRY or SATA_FAILURE return.
12533 	 * Looks like we cannot determine the device type at this time.
12534 	 */
12535 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12536 	    sata_device->satadev_addr.cport)));
12537 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12538 	if (sdinfo != NULL) {
12539 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
12540 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12541 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
12542 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
12543 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
12544 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
12545 			    sata_device->satadev_addr.cport) =
12546 			    SATA_DTYPE_UNKNOWN;
12547 		else {
12548 			/* SATA_ADDR_DPMPORT */
12549 			mutex_enter(&pmportinfo->pmport_mutex);
12550 			if ((SATA_PMULT_INFO(sata_hba_inst,
12551 			    sata_device->satadev_addr.cport) != NULL) &&
12552 			    (SATA_PMPORT_INFO(sata_hba_inst,
12553 			    sata_device->satadev_addr.cport,
12554 			    sata_device->satadev_addr.pmport) != NULL))
12555 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
12556 				    sata_device->satadev_addr.cport,
12557 				    sata_device->satadev_addr.pmport) =
12558 				    SATA_DTYPE_UNKNOWN;
12559 			mutex_exit(&pmportinfo->pmport_mutex);
12560 		}
12561 	}
12562 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12563 	    sata_device->satadev_addr.cport)));
12564 	return (rval);
12565 }
12566 
12567 
12568 /*
12569  * Get pointer to sata_drive_info structure.
12570  *
12571  * The sata_device has to contain address (cport, pmport and qualifier) for
12572  * specified sata_scsi structure.
12573  *
12574  * Returns NULL if device address is not valid for this HBA configuration.
12575  * Otherwise, returns a pointer to sata_drive_info structure.
12576  *
12577  * This function should be called with a port mutex held.
12578  */
12579 static sata_drive_info_t *
12580 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
12581     sata_device_t *sata_device)
12582 {
12583 	uint8_t cport = sata_device->satadev_addr.cport;
12584 	uint8_t pmport = sata_device->satadev_addr.pmport;
12585 	uint8_t qual = sata_device->satadev_addr.qual;
12586 
12587 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
12588 		return (NULL);
12589 
12590 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
12591 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
12592 		/* Port not probed yet */
12593 		return (NULL);
12594 
12595 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
12596 		return (NULL);
12597 
12598 	if (qual == SATA_ADDR_DCPORT) {
12599 		/* Request for a device on a controller port */
12600 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
12601 		    SATA_DTYPE_PMULT)
12602 			/* Port multiplier attached */
12603 			return (NULL);
12604 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
12605 	}
12606 	if (qual == SATA_ADDR_DPMPORT) {
12607 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
12608 		    SATA_DTYPE_PMULT)
12609 			return (NULL);
12610 
12611 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
12612 			return (NULL);
12613 
12614 		if (!(SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) &
12615 		    (SATA_STATE_PROBED | SATA_STATE_READY)))
12616 			/* Port multiplier port not probed yet */
12617 			return (NULL);
12618 
12619 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
12620 	}
12621 
12622 	/* we should not get here */
12623 	return (NULL);
12624 }
12625 
12626 
12627 /*
12628  * sata_identify_device.
12629  * Send Identify Device command to SATA HBA driver.
12630  * If command executes successfully, update sata_drive_info structure pointed
12631  * to by sdinfo argument, including Identify Device data.
12632  * If command fails, invalidate data in sata_drive_info.
12633  *
12634  * Cannot be called from interrupt level.
12635  *
12636  * Returns:
12637  * SATA_SUCCESS if the device was identified as a supported device,
12638  * SATA_RETRY if the device was not identified but could be retried,
12639  * SATA_FAILURE if the device was not identified and identify attempt
12640  *	should not be retried.
12641  */
12642 static int
12643 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
12644     sata_drive_info_t *sdinfo)
12645 {
12646 	uint16_t cfg_word;
12647 	int rval;
12648 
12649 	/* fetch device identify data */
12650 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
12651 	    sdinfo)) != SATA_SUCCESS)
12652 		goto fail_unknown;
12653 
12654 	cfg_word = sdinfo->satadrv_id.ai_config;
12655 
12656 	/* Set the correct device type */
12657 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
12658 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
12659 	} else if (cfg_word == SATA_CFA_TYPE) {
12660 		/* It's a Compact Flash media via CF-to-SATA HDD adapter */
12661 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
12662 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
12663 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
12664 		case SATA_ATAPI_CDROM_DEV:
12665 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
12666 			break;
12667 		case SATA_ATAPI_SQACC_DEV:
12668 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
12669 			break;
12670 		case SATA_ATAPI_DIRACC_DEV:
12671 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
12672 			break;
12673 		case SATA_ATAPI_PROC_DEV:
12674 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIPROC;
12675 			break;
12676 		default:
12677 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12678 		}
12679 	} else {
12680 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12681 	}
12682 
12683 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12684 		if (sdinfo->satadrv_capacity == 0) {
12685 			/* Non-LBA disk. Too bad... */
12686 			sata_log(sata_hba_inst, CE_WARN,
12687 			    "SATA disk device at port %d does not support LBA",
12688 			    sdinfo->satadrv_addr.cport);
12689 			rval = SATA_FAILURE;
12690 			goto fail_unknown;
12691 		}
12692 	}
12693 #if 0
12694 	/* Left for historical reason */
12695 	/*
12696 	 * Some initial version of SATA spec indicated that at least
12697 	 * UDMA mode 4 has to be supported. It is not metioned in
12698 	 * SerialATA 2.6, so this restriction is removed.
12699 	 */
12700 	/* Check for Ultra DMA modes 6 through 0 being supported */
12701 	for (i = 6; i >= 0; --i) {
12702 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
12703 			break;
12704 	}
12705 
12706 	/*
12707 	 * At least UDMA 4 mode has to be supported. If mode 4 or
12708 	 * higher are not supported by the device, fail this
12709 	 * device.
12710 	 */
12711 	if (i < 4) {
12712 		/* No required Ultra DMA mode supported */
12713 		sata_log(sata_hba_inst, CE_WARN,
12714 		    "SATA disk device at port %d does not support UDMA "
12715 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
12716 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12717 		    "mode 4 or higher required, %d supported", i));
12718 		rval = SATA_FAILURE;
12719 		goto fail_unknown;
12720 	}
12721 #endif
12722 
12723 	/*
12724 	 * For Disk devices, if it doesn't support UDMA mode, we would
12725 	 * like to return failure directly.
12726 	 */
12727 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
12728 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
12729 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
12730 		sata_log(sata_hba_inst, CE_WARN,
12731 		    "SATA disk device at port %d does not support UDMA",
12732 		    sdinfo->satadrv_addr.cport);
12733 		rval = SATA_FAILURE;
12734 		goto fail_unknown;
12735 	}
12736 
12737 	return (SATA_SUCCESS);
12738 
12739 fail_unknown:
12740 	/* Invalidate sata_drive_info ? */
12741 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12742 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
12743 	return (rval);
12744 }
12745 
12746 /*
12747  * Log/display device information
12748  */
12749 static void
12750 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
12751     sata_drive_info_t *sdinfo)
12752 {
12753 	int valid_version;
12754 	char msg_buf[MAXPATHLEN];
12755 	int i;
12756 
12757 	/* Show HBA path */
12758 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
12759 
12760 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
12761 
12762 	switch (sdinfo->satadrv_type) {
12763 	case SATA_DTYPE_ATADISK:
12764 		(void) sprintf(msg_buf, "SATA disk device at");
12765 		break;
12766 
12767 	case SATA_DTYPE_ATAPICD:
12768 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
12769 		break;
12770 
12771 	case SATA_DTYPE_ATAPITAPE:
12772 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
12773 		break;
12774 
12775 	case SATA_DTYPE_ATAPIDISK:
12776 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
12777 		break;
12778 
12779 	case SATA_DTYPE_ATAPIPROC:
12780 		(void) sprintf(msg_buf, "SATA processor (ATAPI) device at");
12781 		break;
12782 
12783 	case SATA_DTYPE_UNKNOWN:
12784 		(void) sprintf(msg_buf,
12785 		    "Unsupported SATA device type (cfg 0x%x) at ",
12786 		    sdinfo->satadrv_id.ai_config);
12787 		break;
12788 	}
12789 
12790 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
12791 		cmn_err(CE_CONT, "?\t%s port %d\n",
12792 		    msg_buf, sdinfo->satadrv_addr.cport);
12793 	else
12794 		cmn_err(CE_CONT, "?\t%s port %d:%d\n",
12795 		    msg_buf, sdinfo->satadrv_addr.cport,
12796 		    sdinfo->satadrv_addr.pmport);
12797 
12798 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
12799 	    sizeof (sdinfo->satadrv_id.ai_model));
12800 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
12801 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
12802 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
12803 
12804 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
12805 	    sizeof (sdinfo->satadrv_id.ai_fw));
12806 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
12807 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
12808 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
12809 
12810 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
12811 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12812 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
12813 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
12814 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12815 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12816 	} else {
12817 		/*
12818 		 * Some drives do not implement serial number and may
12819 		 * violate the spec by providing spaces rather than zeros
12820 		 * in serial number field. Scan the buffer to detect it.
12821 		 */
12822 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
12823 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
12824 				break;
12825 		}
12826 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
12827 			cmn_err(CE_CONT, "?\tserial number - none\n");
12828 		} else {
12829 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12830 		}
12831 	}
12832 
12833 #ifdef SATA_DEBUG
12834 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
12835 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
12836 		int i;
12837 		for (i = 14; i >= 2; i--) {
12838 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
12839 				valid_version = i;
12840 				break;
12841 			}
12842 		}
12843 		cmn_err(CE_CONT,
12844 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
12845 		    valid_version,
12846 		    sdinfo->satadrv_id.ai_majorversion,
12847 		    sdinfo->satadrv_id.ai_minorversion);
12848 	}
12849 #endif
12850 	/* Log some info */
12851 	cmn_err(CE_CONT, "?\tsupported features:\n");
12852 	msg_buf[0] = '\0';
12853 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12854 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
12855 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
12856 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
12857 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
12858 	}
12859 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
12860 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
12861 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
12862 		(void) strlcat(msg_buf, ", Native Command Queueing",
12863 		    MAXPATHLEN);
12864 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
12865 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
12866 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
12867 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
12868 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
12869 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
12870 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
12871 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
12872 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
12873 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA3)
12874 		cmn_err(CE_CONT, "?\tSATA Gen3 signaling speed (6.0Gbps)\n");
12875 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
12876 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
12877 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
12878 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
12879 	if (sdinfo->satadrv_features_support &
12880 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
12881 		msg_buf[0] = '\0';
12882 		(void) snprintf(msg_buf, MAXPATHLEN,
12883 		    "Supported queue depth %d",
12884 		    sdinfo->satadrv_queue_depth);
12885 		if (!(sata_func_enable &
12886 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
12887 			(void) strlcat(msg_buf,
12888 			    " - queueing disabled globally", MAXPATHLEN);
12889 		else if (sdinfo->satadrv_queue_depth >
12890 		    sdinfo->satadrv_max_queue_depth) {
12891 			(void) snprintf(&msg_buf[strlen(msg_buf)],
12892 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
12893 			    (int)sdinfo->satadrv_max_queue_depth);
12894 		}
12895 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
12896 	}
12897 
12898 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12899 #ifdef __i386
12900 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
12901 		    sdinfo->satadrv_capacity);
12902 #else
12903 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
12904 		    sdinfo->satadrv_capacity);
12905 #endif
12906 		cmn_err(CE_CONT, "?%s", msg_buf);
12907 	}
12908 }
12909 
12910 /*
12911  * Log/display port multiplier information
12912  * No Mutex should be hold.
12913  */
12914 static void
12915 sata_show_pmult_info(sata_hba_inst_t *sata_hba_inst,
12916     sata_device_t *sata_device)
12917 {
12918 	_NOTE(ARGUNUSED(sata_hba_inst))
12919 
12920 	int cport = sata_device->satadev_addr.cport;
12921 	sata_pmult_info_t *pmultinfo;
12922 	char msg_buf[MAXPATHLEN];
12923 	uint32_t gscr0, gscr1, gscr2, gscr64;
12924 
12925 	mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12926 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
12927 	if (pmultinfo == NULL) {
12928 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12929 		return;
12930 	}
12931 
12932 	gscr0 = pmultinfo->pmult_gscr.gscr0;
12933 	gscr1 = pmultinfo->pmult_gscr.gscr1;
12934 	gscr2 = pmultinfo->pmult_gscr.gscr2;
12935 	gscr64 = pmultinfo->pmult_gscr.gscr64;
12936 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12937 
12938 	cmn_err(CE_CONT, "?Port Multiplier %d device-ports found at port %d",
12939 	    sata_device->satadev_add_info, sata_device->satadev_addr.cport);
12940 
12941 	(void) sprintf(msg_buf, "\tVendor_ID 0x%04x, Module_ID 0x%04x",
12942 	    gscr0 & 0xffff, (gscr0 >> 16) & 0xffff);
12943 	cmn_err(CE_CONT, "?%s", msg_buf);
12944 
12945 	(void) strcpy(msg_buf, "\tSupport SATA PMP Spec ");
12946 	if (gscr1 & (1 << 3))
12947 		(void) strlcat(msg_buf, "1.2", MAXPATHLEN);
12948 	else if (gscr1 & (1 << 2))
12949 		(void) strlcat(msg_buf, "1.1", MAXPATHLEN);
12950 	else if (gscr1 & (1 << 1))
12951 		(void) strlcat(msg_buf, "1.0", MAXPATHLEN);
12952 	else
12953 		(void) strlcat(msg_buf, "unknown", MAXPATHLEN);
12954 	cmn_err(CE_CONT, "?%s", msg_buf);
12955 
12956 	(void) strcpy(msg_buf, "\tSupport ");
12957 	if (gscr64 & (1 << 3))
12958 		(void) strlcat(msg_buf, "Asy-Notif, ",
12959 		    MAXPATHLEN);
12960 	if (gscr64 & (1 << 2))
12961 		(void) strlcat(msg_buf, "Dyn-SSC, ", MAXPATHLEN);
12962 	if (gscr64 & (1 << 1))
12963 		(void) strlcat(msg_buf, "Iss-PMREQ, ", MAXPATHLEN);
12964 	if (gscr64 & (1 << 0))
12965 		(void) strlcat(msg_buf, "BIST", MAXPATHLEN);
12966 	if ((gscr64 & 0xf) == 0)
12967 		(void) strlcat(msg_buf, "nothing", MAXPATHLEN);
12968 	cmn_err(CE_CONT, "?%s", msg_buf);
12969 
12970 	(void) sprintf(msg_buf, "\tNumber of exposed device fan-out ports: %d",
12971 	    gscr2 & SATA_PMULT_PORTNUM_MASK);
12972 	cmn_err(CE_CONT, "?%s", msg_buf);
12973 }
12974 
12975 /*
12976  * sata_save_drive_settings extracts current setting of the device and stores
12977  * it for future reference, in case the device setup would need to be restored
12978  * after the device reset.
12979  *
12980  * For all devices read ahead and write cache settings are saved, if the
12981  * device supports these features at all.
12982  * For ATAPI devices the Removable Media Status Notification setting is saved.
12983  */
12984 static void
12985 sata_save_drive_settings(sata_drive_info_t *sdinfo)
12986 {
12987 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
12988 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
12989 
12990 		/* Current setting of Read Ahead (and Read Cache) */
12991 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
12992 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
12993 		else
12994 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
12995 
12996 		/* Current setting of Write Cache */
12997 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
12998 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12999 		else
13000 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
13001 	}
13002 
13003 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
13004 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
13005 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
13006 		else
13007 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
13008 	}
13009 }
13010 
13011 
13012 /*
13013  * sata_check_capacity function determines a disk capacity
13014  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
13015  *
13016  * NOTE: CHS mode is not supported! If a device does not support LBA,
13017  * this function is not called.
13018  *
13019  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
13020  */
13021 static uint64_t
13022 sata_check_capacity(sata_drive_info_t *sdinfo)
13023 {
13024 	uint64_t capacity = 0;
13025 	int i;
13026 
13027 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
13028 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
13029 		/* Capacity valid only for LBA-addressable disk devices */
13030 		return (0);
13031 
13032 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
13033 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
13034 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
13035 		/* LBA48 mode supported and enabled */
13036 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
13037 		    SATA_DEV_F_LBA28;
13038 		for (i = 3;  i >= 0;  --i) {
13039 			capacity <<= 16;
13040 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
13041 		}
13042 	} else {
13043 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
13044 		capacity <<= 16;
13045 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
13046 		if (capacity >= 0x1000000)
13047 			/* LBA28 mode */
13048 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
13049 	}
13050 	return (capacity);
13051 }
13052 
13053 
13054 /*
13055  * Allocate consistent buffer for DMA transfer
13056  *
13057  * Cannot be called from interrupt level or with mutex held - it may sleep.
13058  *
13059  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
13060  */
13061 static struct buf *
13062 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
13063 {
13064 	struct scsi_address ap;
13065 	struct buf *bp;
13066 	ddi_dma_attr_t	cur_dma_attr;
13067 
13068 	ASSERT(spx->txlt_sata_pkt != NULL);
13069 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
13070 	ap.a_target = SATA_TO_SCSI_TARGET(
13071 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
13072 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
13073 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
13074 	ap.a_lun = 0;
13075 
13076 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
13077 	    B_READ, SLEEP_FUNC, NULL);
13078 
13079 	if (bp != NULL) {
13080 		/* Allocate DMA resources for this buffer */
13081 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
13082 		/*
13083 		 * We use a local version of the dma_attr, to account
13084 		 * for a device addressing limitations.
13085 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
13086 		 * will cause dma attributes to be adjusted to a lowest
13087 		 * acceptable level.
13088 		 */
13089 		sata_adjust_dma_attr(NULL,
13090 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
13091 
13092 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
13093 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
13094 			scsi_free_consistent_buf(bp);
13095 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
13096 			bp = NULL;
13097 		}
13098 	}
13099 	return (bp);
13100 }
13101 
13102 /*
13103  * Release local buffer (consistent buffer for DMA transfer) allocated
13104  * via sata_alloc_local_buffer().
13105  */
13106 static void
13107 sata_free_local_buffer(sata_pkt_txlate_t *spx)
13108 {
13109 	ASSERT(spx->txlt_sata_pkt != NULL);
13110 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
13111 
13112 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
13113 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
13114 
13115 	sata_common_free_dma_rsrcs(spx);
13116 
13117 	/* Free buffer */
13118 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
13119 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
13120 }
13121 
13122 /*
13123  * Allocate sata_pkt
13124  * Pkt structure version and embedded strcutures version are initialized.
13125  * sata_pkt and sata_pkt_txlate structures are cross-linked.
13126  *
13127  * Since this may be called in interrupt context by sata_scsi_init_pkt,
13128  * callback argument determines if it can sleep or not.
13129  * Hence, it should not be called from interrupt context.
13130  *
13131  * If successful, non-NULL pointer to a sata pkt is returned.
13132  * Upon failure, NULL pointer is returned.
13133  */
13134 static sata_pkt_t *
13135 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
13136 {
13137 	sata_pkt_t *spkt;
13138 	int kmsflag;
13139 
13140 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
13141 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
13142 	if (spkt == NULL) {
13143 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
13144 		    "sata_pkt_alloc: failed"));
13145 		return (NULL);
13146 	}
13147 	spkt->satapkt_rev = SATA_PKT_REV;
13148 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
13149 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
13150 	spkt->satapkt_framework_private = spx;
13151 	spx->txlt_sata_pkt = spkt;
13152 	return (spkt);
13153 }
13154 
13155 /*
13156  * Free sata pkt allocated via sata_pkt_alloc()
13157  */
13158 static void
13159 sata_pkt_free(sata_pkt_txlate_t *spx)
13160 {
13161 	ASSERT(spx->txlt_sata_pkt != NULL);
13162 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
13163 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
13164 	spx->txlt_sata_pkt = NULL;
13165 }
13166 
13167 
13168 /*
13169  * Adjust DMA attributes.
13170  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
13171  * from 8 bits to 16 bits, depending on a command being used.
13172  * Limiting max block count arbitrarily to 256 for all read/write
13173  * commands may affects performance, so check both the device and
13174  * controller capability before adjusting dma attributes.
13175  */
13176 void
13177 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
13178     ddi_dma_attr_t *adj_dma_attr)
13179 {
13180 	uint32_t count_max;
13181 
13182 	/* Copy original attributes */
13183 	*adj_dma_attr = *dma_attr;
13184 	/*
13185 	 * Things to consider: device addressing capability,
13186 	 * "excessive" controller DMA capabilities.
13187 	 * If a device is being probed/initialized, there are
13188 	 * no device info - use default limits then.
13189 	 */
13190 	if (sdinfo == NULL) {
13191 		count_max = dma_attr->dma_attr_granular * 0x100;
13192 		if (dma_attr->dma_attr_count_max > count_max)
13193 			adj_dma_attr->dma_attr_count_max = count_max;
13194 		if (dma_attr->dma_attr_maxxfer > count_max)
13195 			adj_dma_attr->dma_attr_maxxfer = count_max;
13196 		return;
13197 	}
13198 
13199 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
13200 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
13201 			/*
13202 			 * 16-bit sector count may be used - we rely on
13203 			 * the assumption that only read and write cmds
13204 			 * will request more than 256 sectors worth of data
13205 			 */
13206 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
13207 		} else {
13208 			/*
13209 			 * 8-bit sector count will be used - default limits
13210 			 * for dma attributes
13211 			 */
13212 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
13213 		}
13214 		/*
13215 		 * Adjust controler dma attributes, if necessary
13216 		 */
13217 		if (dma_attr->dma_attr_count_max > count_max)
13218 			adj_dma_attr->dma_attr_count_max = count_max;
13219 		if (dma_attr->dma_attr_maxxfer > count_max)
13220 			adj_dma_attr->dma_attr_maxxfer = count_max;
13221 	}
13222 }
13223 
13224 
13225 /*
13226  * Allocate DMA resources for the buffer
13227  * This function handles initial DMA resource allocation as well as
13228  * DMA window shift and may be called repeatedly for the same DMA window
13229  * until all DMA cookies in the DMA window are processed.
13230  * To guarantee that there is always a coherent set of cookies to process
13231  * by SATA HBA driver (observing alignment, device granularity, etc.),
13232  * the number of slots for DMA cookies is equal to lesser of  a number of
13233  * cookies in a DMA window and a max number of scatter/gather entries.
13234  *
13235  * Returns DDI_SUCCESS upon successful operation.
13236  * Return failure code of a failing command or DDI_FAILURE when
13237  * internal cleanup failed.
13238  */
13239 static int
13240 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
13241     int (*callback)(caddr_t), caddr_t arg,
13242     ddi_dma_attr_t *cur_dma_attr)
13243 {
13244 	int	rval;
13245 	off_t	offset;
13246 	size_t	size;
13247 	int	max_sg_len, req_len, i;
13248 	uint_t	dma_flags;
13249 	struct buf	*bp;
13250 	uint64_t	cur_txfer_len;
13251 
13252 
13253 	ASSERT(spx->txlt_sata_pkt != NULL);
13254 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
13255 	ASSERT(bp != NULL);
13256 
13257 
13258 	if (spx->txlt_buf_dma_handle == NULL) {
13259 		/*
13260 		 * No DMA resources allocated so far - this is a first call
13261 		 * for this sata pkt.
13262 		 */
13263 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
13264 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
13265 
13266 		if (rval != DDI_SUCCESS) {
13267 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
13268 			    "sata_dma_buf_setup: no buf DMA resources %x",
13269 			    rval));
13270 			return (rval);
13271 		}
13272 
13273 		if (bp->b_flags & B_READ)
13274 			dma_flags = DDI_DMA_READ;
13275 		else
13276 			dma_flags = DDI_DMA_WRITE;
13277 
13278 		if (flags & PKT_CONSISTENT)
13279 			dma_flags |= DDI_DMA_CONSISTENT;
13280 
13281 		if (flags & PKT_DMA_PARTIAL)
13282 			dma_flags |= DDI_DMA_PARTIAL;
13283 
13284 		/*
13285 		 * Check buffer alignment and size against dma attributes
13286 		 * Consider dma_attr_align only. There may be requests
13287 		 * with the size lower than device granularity, but they
13288 		 * will not read/write from/to the device, so no adjustment
13289 		 * is necessary. The dma_attr_minxfer theoretically should
13290 		 * be considered, but no HBA driver is checking it.
13291 		 */
13292 		if (IS_P2ALIGNED(bp->b_un.b_addr,
13293 		    cur_dma_attr->dma_attr_align)) {
13294 			rval = ddi_dma_buf_bind_handle(
13295 			    spx->txlt_buf_dma_handle,
13296 			    bp, dma_flags, callback, arg,
13297 			    &spx->txlt_dma_cookie,
13298 			    &spx->txlt_curwin_num_dma_cookies);
13299 		} else { /* Buffer is not aligned */
13300 
13301 			int	(*ddicallback)(caddr_t);
13302 			size_t	bufsz;
13303 
13304 			/* Check id sleeping is allowed */
13305 			ddicallback = (callback == NULL_FUNC) ?
13306 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
13307 
13308 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
13309 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
13310 			    (void *)bp->b_un.b_addr, bp->b_bcount);
13311 
13312 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
13313 				/*
13314 				 * CPU will need to access data in the buffer
13315 				 * (for copying) so map it.
13316 				 */
13317 				bp_mapin(bp);
13318 
13319 			ASSERT(spx->txlt_tmp_buf == NULL);
13320 
13321 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
13322 			rval = ddi_dma_mem_alloc(
13323 			    spx->txlt_buf_dma_handle,
13324 			    bp->b_bcount,
13325 			    &sata_acc_attr,
13326 			    DDI_DMA_STREAMING,
13327 			    ddicallback, NULL,
13328 			    &spx->txlt_tmp_buf,
13329 			    &bufsz,
13330 			    &spx->txlt_tmp_buf_handle);
13331 
13332 			if (rval != DDI_SUCCESS) {
13333 				/* DMA mapping failed */
13334 				(void) ddi_dma_free_handle(
13335 				    &spx->txlt_buf_dma_handle);
13336 				spx->txlt_buf_dma_handle = NULL;
13337 #ifdef SATA_DEBUG
13338 				mbuffail_count++;
13339 #endif
13340 				SATADBG1(SATA_DBG_DMA_SETUP,
13341 				    spx->txlt_sata_hba_inst,
13342 				    "sata_dma_buf_setup: "
13343 				    "buf dma mem alloc failed %x\n", rval);
13344 				return (rval);
13345 			}
13346 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
13347 			    cur_dma_attr->dma_attr_align));
13348 
13349 #ifdef SATA_DEBUG
13350 			mbuf_count++;
13351 
13352 			if (bp->b_bcount != bufsz)
13353 				/*
13354 				 * This will require special handling, because
13355 				 * DMA cookies will be based on the temporary
13356 				 * buffer size, not the original buffer
13357 				 * b_bcount, so the residue may have to
13358 				 * be counted differently.
13359 				 */
13360 				SATADBG2(SATA_DBG_DMA_SETUP,
13361 				    spx->txlt_sata_hba_inst,
13362 				    "sata_dma_buf_setup: bp size %x != "
13363 				    "bufsz %x\n", bp->b_bcount, bufsz);
13364 #endif
13365 			if (dma_flags & DDI_DMA_WRITE) {
13366 				/*
13367 				 * Write operation - copy data into
13368 				 * an aligned temporary buffer. Buffer will be
13369 				 * synced for device by ddi_dma_addr_bind_handle
13370 				 */
13371 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
13372 				    bp->b_bcount);
13373 			}
13374 
13375 			rval = ddi_dma_addr_bind_handle(
13376 			    spx->txlt_buf_dma_handle,
13377 			    NULL,
13378 			    spx->txlt_tmp_buf,
13379 			    bufsz, dma_flags, ddicallback, 0,
13380 			    &spx->txlt_dma_cookie,
13381 			    &spx->txlt_curwin_num_dma_cookies);
13382 		}
13383 
13384 		switch (rval) {
13385 		case DDI_DMA_PARTIAL_MAP:
13386 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
13387 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
13388 			/*
13389 			 * Partial DMA mapping.
13390 			 * Retrieve number of DMA windows for this request.
13391 			 */
13392 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
13393 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
13394 				if (spx->txlt_tmp_buf != NULL) {
13395 					ddi_dma_mem_free(
13396 					    &spx->txlt_tmp_buf_handle);
13397 					spx->txlt_tmp_buf = NULL;
13398 				}
13399 				(void) ddi_dma_unbind_handle(
13400 				    spx->txlt_buf_dma_handle);
13401 				(void) ddi_dma_free_handle(
13402 				    &spx->txlt_buf_dma_handle);
13403 				spx->txlt_buf_dma_handle = NULL;
13404 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
13405 				    "sata_dma_buf_setup: numwin failed\n"));
13406 				return (DDI_FAILURE);
13407 			}
13408 			SATADBG2(SATA_DBG_DMA_SETUP,
13409 			    spx->txlt_sata_hba_inst,
13410 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
13411 			    spx->txlt_num_dma_win,
13412 			    spx->txlt_curwin_num_dma_cookies);
13413 			spx->txlt_cur_dma_win = 0;
13414 			break;
13415 
13416 		case DDI_DMA_MAPPED:
13417 			/* DMA fully mapped */
13418 			spx->txlt_num_dma_win = 1;
13419 			spx->txlt_cur_dma_win = 0;
13420 			SATADBG1(SATA_DBG_DMA_SETUP,
13421 			    spx->txlt_sata_hba_inst,
13422 			    "sata_dma_buf_setup: windows: 1 "
13423 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
13424 			break;
13425 
13426 		default:
13427 			/* DMA mapping failed */
13428 			if (spx->txlt_tmp_buf != NULL) {
13429 				ddi_dma_mem_free(
13430 				    &spx->txlt_tmp_buf_handle);
13431 				spx->txlt_tmp_buf = NULL;
13432 			}
13433 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
13434 			spx->txlt_buf_dma_handle = NULL;
13435 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
13436 			    "sata_dma_buf_setup: buf dma handle binding "
13437 			    "failed %x\n", rval));
13438 			return (rval);
13439 		}
13440 		spx->txlt_curwin_processed_dma_cookies = 0;
13441 		spx->txlt_dma_cookie_list = NULL;
13442 	} else {
13443 		/*
13444 		 * DMA setup is reused. Check if we need to process more
13445 		 * cookies in current window, or to get next window, if any.
13446 		 */
13447 
13448 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
13449 		    spx->txlt_curwin_num_dma_cookies);
13450 
13451 		if (spx->txlt_curwin_processed_dma_cookies ==
13452 		    spx->txlt_curwin_num_dma_cookies) {
13453 			/*
13454 			 * All cookies from current DMA window were processed.
13455 			 * Get next DMA window.
13456 			 */
13457 			spx->txlt_cur_dma_win++;
13458 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
13459 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
13460 				    spx->txlt_cur_dma_win, &offset, &size,
13461 				    &spx->txlt_dma_cookie,
13462 				    &spx->txlt_curwin_num_dma_cookies);
13463 				spx->txlt_curwin_processed_dma_cookies = 0;
13464 			} else {
13465 				/* No more windows! End of request! */
13466 				/* What to do? - panic for now */
13467 				ASSERT(spx->txlt_cur_dma_win >=
13468 				    spx->txlt_num_dma_win);
13469 
13470 				spx->txlt_curwin_num_dma_cookies = 0;
13471 				spx->txlt_curwin_processed_dma_cookies = 0;
13472 				spx->txlt_sata_pkt->
13473 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
13474 				return (DDI_SUCCESS);
13475 			}
13476 		}
13477 	}
13478 	/* There better be at least one DMA cookie outstanding */
13479 	ASSERT((spx->txlt_curwin_num_dma_cookies -
13480 	    spx->txlt_curwin_processed_dma_cookies) > 0);
13481 
13482 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
13483 		/* The default cookie slot was used in previous run */
13484 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
13485 		spx->txlt_dma_cookie_list = NULL;
13486 		spx->txlt_dma_cookie_list_len = 0;
13487 	}
13488 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
13489 		/*
13490 		 * Processing a new DMA window - set-up dma cookies list.
13491 		 * We may reuse previously allocated cookie array if it is
13492 		 * possible.
13493 		 */
13494 		if (spx->txlt_dma_cookie_list != NULL &&
13495 		    spx->txlt_dma_cookie_list_len <
13496 		    spx->txlt_curwin_num_dma_cookies) {
13497 			/*
13498 			 * New DMA window contains more cookies than
13499 			 * the previous one. We need larger cookie list - free
13500 			 * the old one.
13501 			 */
13502 			(void) kmem_free(spx->txlt_dma_cookie_list,
13503 			    spx->txlt_dma_cookie_list_len *
13504 			    sizeof (ddi_dma_cookie_t));
13505 			spx->txlt_dma_cookie_list = NULL;
13506 			spx->txlt_dma_cookie_list_len = 0;
13507 		}
13508 		if (spx->txlt_dma_cookie_list == NULL) {
13509 			/*
13510 			 * Calculate lesser of number of cookies in this
13511 			 * DMA window and number of s/g entries.
13512 			 */
13513 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
13514 			req_len = MIN(max_sg_len,
13515 			    spx->txlt_curwin_num_dma_cookies);
13516 
13517 			/* Allocate new dma cookie array if necessary */
13518 			if (req_len == 1) {
13519 				/* Only one cookie - no need for a list */
13520 				spx->txlt_dma_cookie_list =
13521 				    &spx->txlt_dma_cookie;
13522 				spx->txlt_dma_cookie_list_len = 1;
13523 			} else {
13524 				/*
13525 				 * More than one cookie - try to allocate space.
13526 				 */
13527 				spx->txlt_dma_cookie_list = kmem_zalloc(
13528 				    sizeof (ddi_dma_cookie_t) * req_len,
13529 				    callback == NULL_FUNC ? KM_NOSLEEP :
13530 				    KM_SLEEP);
13531 				if (spx->txlt_dma_cookie_list == NULL) {
13532 					SATADBG1(SATA_DBG_DMA_SETUP,
13533 					    spx->txlt_sata_hba_inst,
13534 					    "sata_dma_buf_setup: cookie list "
13535 					    "allocation failed\n", NULL);
13536 					/*
13537 					 * We could not allocate space for
13538 					 * neccessary number of dma cookies in
13539 					 * this window, so we fail this request.
13540 					 * Next invocation would try again to
13541 					 * allocate space for cookie list.
13542 					 * Note:Packet residue was not modified.
13543 					 */
13544 					return (DDI_DMA_NORESOURCES);
13545 				} else {
13546 					spx->txlt_dma_cookie_list_len = req_len;
13547 				}
13548 			}
13549 		}
13550 		/*
13551 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
13552 		 * First cookie was already fetched.
13553 		 */
13554 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
13555 		cur_txfer_len =
13556 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
13557 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
13558 		spx->txlt_curwin_processed_dma_cookies++;
13559 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
13560 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
13561 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
13562 			    &spx->txlt_dma_cookie_list[i]);
13563 			cur_txfer_len +=
13564 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
13565 			spx->txlt_curwin_processed_dma_cookies++;
13566 			spx->txlt_sata_pkt->
13567 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
13568 		}
13569 	} else {
13570 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
13571 		    "sata_dma_buf_setup: sliding within DMA window, "
13572 		    "cur cookie %d, total cookies %d\n",
13573 		    spx->txlt_curwin_processed_dma_cookies,
13574 		    spx->txlt_curwin_num_dma_cookies);
13575 
13576 		/*
13577 		 * Not all cookies from the current dma window were used because
13578 		 * of s/g limitation.
13579 		 * There is no need to re-size the list - it was set at
13580 		 * optimal size, or only default entry is used (s/g = 1).
13581 		 */
13582 		if (spx->txlt_dma_cookie_list == NULL) {
13583 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
13584 			spx->txlt_dma_cookie_list_len = 1;
13585 		}
13586 		/*
13587 		 * Since we are processing remaining cookies in a DMA window,
13588 		 * there may be less of them than the number of entries in the
13589 		 * current dma cookie list.
13590 		 */
13591 		req_len = MIN(spx->txlt_dma_cookie_list_len,
13592 		    (spx->txlt_curwin_num_dma_cookies -
13593 		    spx->txlt_curwin_processed_dma_cookies));
13594 
13595 		/* Fetch the next batch of cookies */
13596 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
13597 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
13598 			    &spx->txlt_dma_cookie_list[i]);
13599 			cur_txfer_len +=
13600 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
13601 			spx->txlt_sata_pkt->
13602 			    satapkt_cmd.satacmd_num_dma_cookies++;
13603 			spx->txlt_curwin_processed_dma_cookies++;
13604 		}
13605 	}
13606 
13607 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
13608 
13609 	/* Point sata_cmd to the cookie list */
13610 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
13611 	    &spx->txlt_dma_cookie_list[0];
13612 
13613 	/* Remember number of DMA cookies passed in sata packet */
13614 	spx->txlt_num_dma_cookies =
13615 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
13616 
13617 	ASSERT(cur_txfer_len != 0);
13618 	if (cur_txfer_len <= bp->b_bcount)
13619 		spx->txlt_total_residue -= cur_txfer_len;
13620 	else {
13621 		/*
13622 		 * Temporary DMA buffer has been padded by
13623 		 * ddi_dma_mem_alloc()!
13624 		 * This requires special handling, because DMA cookies are
13625 		 * based on the temporary buffer size, not the b_bcount,
13626 		 * and we have extra bytes to transfer - but the packet
13627 		 * residue has to stay correct because we will copy only
13628 		 * the requested number of bytes.
13629 		 */
13630 		spx->txlt_total_residue -= bp->b_bcount;
13631 	}
13632 
13633 	return (DDI_SUCCESS);
13634 }
13635 
13636 /*
13637  * Common routine for releasing DMA resources
13638  */
13639 static void
13640 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
13641 {
13642 	if (spx->txlt_buf_dma_handle != NULL) {
13643 		if (spx->txlt_tmp_buf != NULL)  {
13644 			/*
13645 			 * Intermediate DMA buffer was allocated.
13646 			 * Free allocated buffer and associated access handle.
13647 			 */
13648 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
13649 			spx->txlt_tmp_buf = NULL;
13650 		}
13651 		/*
13652 		 * Free DMA resources - cookies and handles
13653 		 */
13654 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
13655 		if (spx->txlt_dma_cookie_list != NULL) {
13656 			if (spx->txlt_dma_cookie_list !=
13657 			    &spx->txlt_dma_cookie) {
13658 				(void) kmem_free(spx->txlt_dma_cookie_list,
13659 				    spx->txlt_dma_cookie_list_len *
13660 				    sizeof (ddi_dma_cookie_t));
13661 				spx->txlt_dma_cookie_list = NULL;
13662 			}
13663 		}
13664 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
13665 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
13666 		spx->txlt_buf_dma_handle = NULL;
13667 	}
13668 }
13669 
13670 /*
13671  * Free DMA resources
13672  * Used by the HBA driver to release DMA resources that it does not use.
13673  *
13674  * Returns Void
13675  */
13676 void
13677 sata_free_dma_resources(sata_pkt_t *sata_pkt)
13678 {
13679 	sata_pkt_txlate_t *spx;
13680 
13681 	if (sata_pkt == NULL)
13682 		return;
13683 
13684 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
13685 
13686 	sata_common_free_dma_rsrcs(spx);
13687 }
13688 
13689 /*
13690  * Fetch Device Identify data.
13691  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
13692  * command to a device and get the device identify data.
13693  * The device_info structure has to be set to device type (for selecting proper
13694  * device identify command).
13695  *
13696  * Returns:
13697  * SATA_SUCCESS if cmd succeeded
13698  * SATA_RETRY if cmd was rejected and could be retried,
13699  * SATA_FAILURE if cmd failed and should not be retried (port error)
13700  *
13701  * Cannot be called in an interrupt context.
13702  */
13703 
13704 static int
13705 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
13706     sata_drive_info_t *sdinfo)
13707 {
13708 	struct buf *bp;
13709 	sata_pkt_t *spkt;
13710 	sata_cmd_t *scmd;
13711 	sata_pkt_txlate_t *spx;
13712 	int rval;
13713 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
13714 
13715 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13716 	spx->txlt_sata_hba_inst = sata_hba_inst;
13717 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13718 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13719 	if (spkt == NULL) {
13720 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13721 		return (SATA_RETRY); /* may retry later */
13722 	}
13723 	/* address is needed now */
13724 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13725 
13726 	/*
13727 	 * Allocate buffer for Identify Data return data
13728 	 */
13729 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
13730 	if (bp == NULL) {
13731 		sata_pkt_free(spx);
13732 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13733 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13734 		    "sata_fetch_device_identify_data: "
13735 		    "cannot allocate buffer for ID"));
13736 		return (SATA_RETRY); /* may retry later */
13737 	}
13738 
13739 	/* Fill sata_pkt */
13740 	sdinfo->satadrv_state = SATA_STATE_PROBING;
13741 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13742 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13743 	/* Synchronous mode, no callback */
13744 	spkt->satapkt_comp = NULL;
13745 	/* Timeout 30s */
13746 	spkt->satapkt_time = sata_default_pkt_time;
13747 
13748 	scmd = &spkt->satapkt_cmd;
13749 	scmd->satacmd_bp = bp;
13750 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13751 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13752 
13753 	/* Build Identify Device cmd in the sata_pkt */
13754 	scmd->satacmd_addr_type = 0;		/* N/A */
13755 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
13756 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
13757 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
13758 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
13759 	scmd->satacmd_features_reg = 0;		/* N/A */
13760 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13761 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
13762 		/* Identify Packet Device cmd */
13763 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
13764 	} else {
13765 		/* Identify Device cmd - mandatory for all other devices */
13766 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
13767 	}
13768 
13769 	/* Send pkt to SATA HBA driver */
13770 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
13771 
13772 #ifdef SATA_INJECT_FAULTS
13773 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13774 #endif
13775 
13776 	if (rval == SATA_TRAN_ACCEPTED &&
13777 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
13778 		if (spx->txlt_buf_dma_handle != NULL) {
13779 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13780 			    DDI_DMA_SYNC_FORKERNEL);
13781 			ASSERT(rval == DDI_SUCCESS);
13782 			if (sata_check_for_dma_error(dip, spx)) {
13783 				ddi_fm_service_impact(dip,
13784 				    DDI_SERVICE_UNAFFECTED);
13785 				rval = SATA_RETRY;
13786 				goto fail;
13787 			}
13788 
13789 		}
13790 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
13791 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
13792 			SATA_LOG_D((sata_hba_inst, CE_WARN,
13793 			    "SATA disk device at port %d - "
13794 			    "partial Identify Data",
13795 			    sdinfo->satadrv_addr.cport));
13796 			rval = SATA_RETRY; /* may retry later */
13797 			goto fail;
13798 		}
13799 		/* Update sata_drive_info */
13800 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
13801 		    sizeof (sata_id_t));
13802 
13803 		sdinfo->satadrv_features_support = 0;
13804 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
13805 			/*
13806 			 * Retrieve capacity (disks only) and addressing mode
13807 			 */
13808 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
13809 		} else {
13810 			/*
13811 			 * For ATAPI devices one would have to issue
13812 			 * Get Capacity cmd for media capacity. Not here.
13813 			 */
13814 			sdinfo->satadrv_capacity = 0;
13815 			/*
13816 			 * Check what cdb length is supported
13817 			 */
13818 			if ((sdinfo->satadrv_id.ai_config &
13819 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
13820 				sdinfo->satadrv_atapi_cdb_len = 16;
13821 			else
13822 				sdinfo->satadrv_atapi_cdb_len = 12;
13823 		}
13824 		/* Setup supported features flags */
13825 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
13826 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
13827 
13828 		/* Check for SATA GEN and NCQ support */
13829 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
13830 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
13831 			/* SATA compliance */
13832 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
13833 				sdinfo->satadrv_features_support |=
13834 				    SATA_DEV_F_NCQ;
13835 			if (sdinfo->satadrv_id.ai_satacap &
13836 			    (SATA_1_SPEED | SATA_2_SPEED | SATA_3_SPEED)) {
13837 				if (sdinfo->satadrv_id.ai_satacap &
13838 				    SATA_3_SPEED)
13839 					sdinfo->satadrv_features_support |=
13840 					    SATA_DEV_F_SATA3;
13841 				if (sdinfo->satadrv_id.ai_satacap &
13842 				    SATA_2_SPEED)
13843 					sdinfo->satadrv_features_support |=
13844 					    SATA_DEV_F_SATA2;
13845 				if (sdinfo->satadrv_id.ai_satacap &
13846 				    SATA_1_SPEED)
13847 					sdinfo->satadrv_features_support |=
13848 					    SATA_DEV_F_SATA1;
13849 			} else {
13850 				sdinfo->satadrv_features_support |=
13851 				    SATA_DEV_F_SATA1;
13852 			}
13853 		}
13854 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
13855 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
13856 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
13857 
13858 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
13859 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
13860 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
13861 			++sdinfo->satadrv_queue_depth;
13862 			/* Adjust according to controller capabilities */
13863 			sdinfo->satadrv_max_queue_depth = MIN(
13864 			    sdinfo->satadrv_queue_depth,
13865 			    SATA_QDEPTH(sata_hba_inst));
13866 			/* Adjust according to global queue depth limit */
13867 			sdinfo->satadrv_max_queue_depth = MIN(
13868 			    sdinfo->satadrv_max_queue_depth,
13869 			    sata_current_max_qdepth);
13870 			if (sdinfo->satadrv_max_queue_depth == 0)
13871 				sdinfo->satadrv_max_queue_depth = 1;
13872 		} else
13873 			sdinfo->satadrv_max_queue_depth = 1;
13874 
13875 		rval = SATA_SUCCESS;
13876 	} else {
13877 		/*
13878 		 * Woops, no Identify Data.
13879 		 */
13880 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
13881 			rval = SATA_RETRY; /* may retry later */
13882 		} else if (rval == SATA_TRAN_ACCEPTED) {
13883 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
13884 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
13885 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
13886 			    spkt->satapkt_reason == SATA_PKT_RESET)
13887 				rval = SATA_RETRY; /* may retry later */
13888 			else
13889 				rval = SATA_FAILURE;
13890 		} else {
13891 			rval = SATA_FAILURE;
13892 		}
13893 	}
13894 fail:
13895 	/* Free allocated resources */
13896 	sata_free_local_buffer(spx);
13897 	sata_pkt_free(spx);
13898 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13899 
13900 	return (rval);
13901 }
13902 
13903 
13904 /*
13905  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
13906  * UDMA mode is checked first, followed by MWDMA mode.
13907  * set correctly, so this function is setting it to the highest supported level.
13908  * Older SATA spec required that the device supports at least DMA 4 mode and
13909  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
13910  * restriction has been removed.
13911  *
13912  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
13913  * Returns SATA_FAILURE if proper DMA mode could not be selected.
13914  *
13915  * NOTE: This function should be called only if DMA mode is supported.
13916  */
13917 static int
13918 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
13919 {
13920 	sata_pkt_t *spkt;
13921 	sata_cmd_t *scmd;
13922 	sata_pkt_txlate_t *spx;
13923 	int i, mode;
13924 	uint8_t subcmd;
13925 	int rval = SATA_SUCCESS;
13926 
13927 	ASSERT(sdinfo != NULL);
13928 	ASSERT(sata_hba_inst != NULL);
13929 
13930 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
13931 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
13932 		/* Find highest Ultra DMA mode supported */
13933 		for (mode = 6; mode >= 0; --mode) {
13934 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
13935 				break;
13936 		}
13937 #if 0
13938 		/* Left for historical reasons */
13939 		/*
13940 		 * Some initial version of SATA spec indicated that at least
13941 		 * UDMA mode 4 has to be supported. It is not mentioned in
13942 		 * SerialATA 2.6, so this restriction is removed.
13943 		 */
13944 		if (mode < 4)
13945 			return (SATA_FAILURE);
13946 #endif
13947 
13948 		/*
13949 		 * For disk, we're still going to set DMA mode whatever is
13950 		 * selected by default
13951 		 *
13952 		 * We saw an old maxtor sata drive will select Ultra DMA and
13953 		 * Multi-Word DMA simultaneouly by default, which is going
13954 		 * to cause DMA command timed out, so we need to select DMA
13955 		 * mode even when it's already done by default
13956 		 */
13957 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13958 
13959 			/* Find UDMA mode currently selected */
13960 			for (i = 6; i >= 0; --i) {
13961 				if (sdinfo->satadrv_id.ai_ultradma &
13962 				    (1 << (i + 8)))
13963 					break;
13964 			}
13965 			if (i >= mode)
13966 				/* Nothing to do */
13967 				return (SATA_SUCCESS);
13968 		}
13969 
13970 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
13971 
13972 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
13973 		/* Find highest MultiWord DMA mode supported */
13974 		for (mode = 2; mode >= 0; --mode) {
13975 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
13976 				break;
13977 		}
13978 
13979 		/*
13980 		 * For disk, We're still going to set DMA mode whatever is
13981 		 * selected by default
13982 		 *
13983 		 * We saw an old maxtor sata drive will select Ultra DMA and
13984 		 * Multi-Word DMA simultaneouly by default, which is going
13985 		 * to cause DMA command timed out, so we need to select DMA
13986 		 * mode even when it's already done by default
13987 		 */
13988 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13989 
13990 			/* Find highest MultiWord DMA mode selected */
13991 			for (i = 2; i >= 0; --i) {
13992 				if (sdinfo->satadrv_id.ai_dworddma &
13993 				    (1 << (i + 8)))
13994 					break;
13995 			}
13996 			if (i >= mode)
13997 				/* Nothing to do */
13998 				return (SATA_SUCCESS);
13999 		}
14000 
14001 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
14002 	} else
14003 		return (SATA_SUCCESS);
14004 
14005 	/*
14006 	 * Set DMA mode via SET FEATURES COMMAND.
14007 	 * Prepare packet for SET FEATURES COMMAND.
14008 	 */
14009 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
14010 	spx->txlt_sata_hba_inst = sata_hba_inst;
14011 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
14012 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
14013 	if (spkt == NULL) {
14014 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14015 		    "sata_set_dma_mode: could not set DMA mode %d", mode));
14016 		rval = SATA_FAILURE;
14017 		goto done;
14018 	}
14019 	/* Fill sata_pkt */
14020 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
14021 	/* Timeout 30s */
14022 	spkt->satapkt_time = sata_default_pkt_time;
14023 	/* Synchronous mode, no callback, interrupts */
14024 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
14025 	spkt->satapkt_comp = NULL;
14026 	scmd = &spkt->satapkt_cmd;
14027 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
14028 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
14029 	scmd->satacmd_addr_type = 0;
14030 	scmd->satacmd_device_reg = 0;
14031 	scmd->satacmd_status_reg = 0;
14032 	scmd->satacmd_error_reg = 0;
14033 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
14034 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
14035 	scmd->satacmd_sec_count_lsb = subcmd | mode;
14036 
14037 	/* Transfer command to HBA */
14038 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
14039 	    spkt) != SATA_TRAN_ACCEPTED ||
14040 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
14041 		/* Pkt execution failed */
14042 		rval = SATA_FAILURE;
14043 	}
14044 done:
14045 
14046 	/* Free allocated resources */
14047 	if (spkt != NULL)
14048 		sata_pkt_free(spx);
14049 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
14050 
14051 	return (rval);
14052 }
14053 
14054 
14055 /*
14056  * Set device caching mode.
14057  * One of the following operations should be specified:
14058  * SATAC_SF_ENABLE_READ_AHEAD
14059  * SATAC_SF_DISABLE_READ_AHEAD
14060  * SATAC_SF_ENABLE_WRITE_CACHE
14061  * SATAC_SF_DISABLE_WRITE_CACHE
14062  *
14063  * If operation fails, system log messgage is emitted.
14064  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
14065  * command was sent but did not succeed, and SATA_FAILURE otherwise.
14066  */
14067 
14068 static int
14069 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
14070     int cache_op)
14071 {
14072 	sata_pkt_t *spkt;
14073 	sata_cmd_t *scmd;
14074 	sata_pkt_txlate_t *spx;
14075 	int rval = SATA_SUCCESS;
14076 	int hba_rval;
14077 	char *infop;
14078 
14079 	ASSERT(sdinfo != NULL);
14080 	ASSERT(sata_hba_inst != NULL);
14081 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
14082 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
14083 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
14084 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
14085 
14086 
14087 	/* Prepare packet for SET FEATURES COMMAND */
14088 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
14089 	spx->txlt_sata_hba_inst = sata_hba_inst;
14090 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
14091 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
14092 	if (spkt == NULL) {
14093 		rval = SATA_FAILURE;
14094 		goto failure;
14095 	}
14096 	/* Fill sata_pkt */
14097 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
14098 	/* Timeout 30s */
14099 	spkt->satapkt_time = sata_default_pkt_time;
14100 	/* Synchronous mode, no callback, interrupts */
14101 	spkt->satapkt_op_mode =
14102 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
14103 	spkt->satapkt_comp = NULL;
14104 	scmd = &spkt->satapkt_cmd;
14105 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
14106 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
14107 	scmd->satacmd_addr_type = 0;
14108 	scmd->satacmd_device_reg = 0;
14109 	scmd->satacmd_status_reg = 0;
14110 	scmd->satacmd_error_reg = 0;
14111 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
14112 	scmd->satacmd_features_reg = cache_op;
14113 
14114 	/* Transfer command to HBA */
14115 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
14116 	    SATA_DIP(sata_hba_inst), spkt);
14117 
14118 #ifdef SATA_INJECT_FAULTS
14119 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
14120 #endif
14121 
14122 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
14123 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
14124 		/* Pkt execution failed */
14125 		switch (cache_op) {
14126 		case SATAC_SF_ENABLE_READ_AHEAD:
14127 			infop = "enabling read ahead failed";
14128 			break;
14129 		case SATAC_SF_DISABLE_READ_AHEAD:
14130 			infop = "disabling read ahead failed";
14131 			break;
14132 		case SATAC_SF_ENABLE_WRITE_CACHE:
14133 			infop = "enabling write cache failed";
14134 			break;
14135 		case SATAC_SF_DISABLE_WRITE_CACHE:
14136 			infop = "disabling write cache failed";
14137 			break;
14138 		}
14139 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
14140 		rval = SATA_RETRY;
14141 	}
14142 failure:
14143 	/* Free allocated resources */
14144 	if (spkt != NULL)
14145 		sata_pkt_free(spx);
14146 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
14147 	return (rval);
14148 }
14149 
14150 /*
14151  * Set Removable Media Status Notification (enable/disable)
14152  * state == 0 , disable
14153  * state != 0 , enable
14154  *
14155  * If operation fails, system log messgage is emitted.
14156  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
14157  */
14158 
14159 static int
14160 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
14161     int state)
14162 {
14163 	sata_pkt_t *spkt;
14164 	sata_cmd_t *scmd;
14165 	sata_pkt_txlate_t *spx;
14166 	int rval = SATA_SUCCESS;
14167 	char *infop;
14168 
14169 	ASSERT(sdinfo != NULL);
14170 	ASSERT(sata_hba_inst != NULL);
14171 
14172 	/* Prepare packet for SET FEATURES COMMAND */
14173 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
14174 	spx->txlt_sata_hba_inst = sata_hba_inst;
14175 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
14176 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
14177 	if (spkt == NULL) {
14178 		rval = SATA_FAILURE;
14179 		goto failure;
14180 	}
14181 	/* Fill sata_pkt */
14182 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
14183 	/* Timeout 30s */
14184 	spkt->satapkt_time = sata_default_pkt_time;
14185 	/* Synchronous mode, no callback, interrupts */
14186 	spkt->satapkt_op_mode =
14187 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
14188 	spkt->satapkt_comp = NULL;
14189 	scmd = &spkt->satapkt_cmd;
14190 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
14191 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
14192 	scmd->satacmd_addr_type = 0;
14193 	scmd->satacmd_device_reg = 0;
14194 	scmd->satacmd_status_reg = 0;
14195 	scmd->satacmd_error_reg = 0;
14196 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
14197 	if (state == 0)
14198 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
14199 	else
14200 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
14201 
14202 	/* Transfer command to HBA */
14203 	if (((*SATA_START_FUNC(sata_hba_inst))(
14204 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
14205 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
14206 		/* Pkt execution failed */
14207 		if (state == 0)
14208 			infop = "disabling Removable Media Status "
14209 			    "Notification failed";
14210 		else
14211 			infop = "enabling Removable Media Status "
14212 			    "Notification failed";
14213 
14214 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
14215 		rval = SATA_FAILURE;
14216 	}
14217 failure:
14218 	/* Free allocated resources */
14219 	if (spkt != NULL)
14220 		sata_pkt_free(spx);
14221 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
14222 	return (rval);
14223 }
14224 
14225 
14226 /*
14227  * Update state and copy port ss* values from passed sata_device structure.
14228  * sata_address is validated - if not valid, nothing is changed in sata_scsi
14229  * configuration struct.
14230  *
14231  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
14232  * regardless of the state in device argument.
14233  *
14234  * Port mutex should be held while calling this function.
14235  */
14236 static void
14237 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
14238     sata_device_t *sata_device)
14239 {
14240 	sata_cport_info_t *cportinfo;
14241 
14242 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
14243 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
14244 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
14245 		    sata_device->satadev_addr.cport)
14246 			return;
14247 
14248 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
14249 		    sata_device->satadev_addr.cport);
14250 
14251 		ASSERT(mutex_owned(&cportinfo->cport_mutex));
14252 		cportinfo->cport_scr = sata_device->satadev_scr;
14253 
14254 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
14255 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
14256 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
14257 		cportinfo->cport_state |=
14258 		    sata_device->satadev_state & SATA_PSTATE_VALID;
14259 	}
14260 }
14261 
14262 void
14263 sata_update_pmport_info(sata_hba_inst_t *sata_hba_inst,
14264     sata_device_t *sata_device)
14265 {
14266 	sata_pmport_info_t *pmportinfo;
14267 
14268 	if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT &&
14269 	    sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
14270 	    SATA_NUM_PMPORTS(sata_hba_inst,
14271 	    sata_device->satadev_addr.cport) <
14272 	    sata_device->satadev_addr.pmport) {
14273 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
14274 		    "sata_update_port_info: error address %p.",
14275 		    &sata_device->satadev_addr);
14276 		return;
14277 	}
14278 
14279 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
14280 	    sata_device->satadev_addr.cport,
14281 	    sata_device->satadev_addr.pmport);
14282 
14283 	ASSERT(mutex_owned(&pmportinfo->pmport_mutex));
14284 	pmportinfo->pmport_scr = sata_device->satadev_scr;
14285 
14286 	/* Preserve SATA_PSTATE_SHUTDOWN flag */
14287 	pmportinfo->pmport_state &=
14288 	    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
14289 	pmportinfo->pmport_state |=
14290 	    sata_device->satadev_state & SATA_PSTATE_VALID;
14291 }
14292 
14293 /*
14294  * Extract SATA port specification from an IOCTL argument.
14295  *
14296  * This function return the port the user land send us as is, unless it
14297  * cannot retrieve port spec, then -1 is returned.
14298  *
14299  * Support port multiplier.
14300  */
14301 static int32_t
14302 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
14303 {
14304 	int32_t port;
14305 
14306 	/* Extract port number from nvpair in dca structure  */
14307 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
14308 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
14309 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
14310 		    port));
14311 		port = -1;
14312 	}
14313 
14314 	return (port);
14315 }
14316 
14317 /*
14318  * Get dev_info_t pointer to the device node pointed to by port argument.
14319  * NOTE: target argument is a value used in ioctls to identify
14320  * the AP - it is not a sata_address.
14321  * It is a combination of cport, pmport and address qualifier, encodded same
14322  * way as a scsi target number.
14323  * At this moment it carries only cport number.
14324  *
14325  * PMult hotplug is supported now.
14326  *
14327  * Returns dev_info_t pointer if target device was found, NULL otherwise.
14328  */
14329 
14330 static dev_info_t *
14331 sata_get_target_dip(dev_info_t *dip, uint8_t cport, uint8_t pmport)
14332 {
14333 	dev_info_t	*cdip = NULL;
14334 	int		target, tgt;
14335 	int 		circ;
14336 	uint8_t		qual;
14337 
14338 	sata_hba_inst_t	*sata_hba_inst;
14339 	scsi_hba_tran_t *scsi_hba_tran;
14340 
14341 	/* Get target id */
14342 	scsi_hba_tran = ddi_get_driver_private(dip);
14343 	if (scsi_hba_tran == NULL)
14344 		return (NULL);
14345 
14346 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
14347 
14348 	if (sata_hba_inst == NULL)
14349 		return (NULL);
14350 
14351 	/* Identify a port-mult by cport_info.cport_dev_type */
14352 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT)
14353 		qual = SATA_ADDR_DPMPORT;
14354 	else
14355 		qual = SATA_ADDR_DCPORT;
14356 
14357 	target = SATA_TO_SCSI_TARGET(cport, pmport, qual);
14358 
14359 	/* Retrieve target dip */
14360 	ndi_devi_enter(dip, &circ);
14361 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
14362 		dev_info_t *next = ddi_get_next_sibling(cdip);
14363 
14364 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
14365 		    DDI_PROP_DONTPASS, "target", -1);
14366 		if (tgt == -1) {
14367 			/*
14368 			 * This is actually an error condition, but not
14369 			 * a fatal one. Just continue the search.
14370 			 */
14371 			cdip = next;
14372 			continue;
14373 		}
14374 
14375 		if (tgt == target)
14376 			break;
14377 
14378 		cdip = next;
14379 	}
14380 	ndi_devi_exit(dip, circ);
14381 
14382 	return (cdip);
14383 }
14384 
14385 /*
14386  * Get dev_info_t pointer to the device node pointed to by port argument.
14387  * NOTE: target argument is a value used in ioctls to identify
14388  * the AP - it is not a sata_address.
14389  * It is a combination of cport, pmport and address qualifier, encoded same
14390  * way as a scsi target number.
14391  *
14392  * Returns dev_info_t pointer if target device was found, NULL otherwise.
14393  */
14394 
14395 static dev_info_t *
14396 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
14397 {
14398 	dev_info_t	*cdip = NULL;
14399 	int		target, tgt;
14400 	int 		circ;
14401 
14402 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
14403 
14404 	ndi_devi_enter(dip, &circ);
14405 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
14406 		dev_info_t *next = ddi_get_next_sibling(cdip);
14407 
14408 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
14409 		    DDI_PROP_DONTPASS, "target", -1);
14410 		if (tgt == -1) {
14411 			/*
14412 			 * This is actually an error condition, but not
14413 			 * a fatal one. Just continue the search.
14414 			 */
14415 			cdip = next;
14416 			continue;
14417 		}
14418 
14419 		if (tgt == target)
14420 			break;
14421 
14422 		cdip = next;
14423 	}
14424 	ndi_devi_exit(dip, circ);
14425 
14426 	return (cdip);
14427 }
14428 
14429 /*
14430  * Process sata port disconnect request.
14431  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
14432  * before this request. Nevertheless, if a device is still configured,
14433  * we need to attempt to offline and unconfigure device.
14434  * Regardless of the unconfigure operation results the port is marked as
14435  * deactivated and no access to the attached device is possible.
14436  * If the target node remains because unconfigure operation failed, its state
14437  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
14438  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
14439  * the device and remove old target node.
14440  *
14441  * This function invokes sata_hba_inst->satahba_tran->
14442  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
14443  * If successful, the device structure (if any) attached to the specified port
14444  * is removed and state of the port marked appropriately.
14445  * Failure of the port_deactivate may keep port in the physically active state,
14446  * or may fail the port.
14447  *
14448  * NOTE: Port multiplier is supported.
14449  */
14450 
14451 static int
14452 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
14453     sata_device_t *sata_device)
14454 {
14455 	sata_drive_info_t *sdinfo = NULL, *subsdinfo = NULL;
14456 	sata_cport_info_t *cportinfo = NULL;
14457 	sata_pmport_info_t *pmportinfo = NULL;
14458 	sata_pmult_info_t *pmultinfo = NULL;
14459 	sata_device_t subsdevice;
14460 	int cport, pmport, qual;
14461 	int rval = SATA_SUCCESS;
14462 	int npmport = 0;
14463 	int rv = 0;
14464 
14465 	cport = sata_device->satadev_addr.cport;
14466 	pmport = sata_device->satadev_addr.pmport;
14467 	qual = sata_device->satadev_addr.qual;
14468 
14469 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14470 	if (qual == SATA_ADDR_DCPORT)
14471 		qual = SATA_ADDR_CPORT;
14472 	else
14473 		qual = SATA_ADDR_PMPORT;
14474 
14475 	/*
14476 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
14477 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
14478 	 * Do the sanity check.
14479 	 */
14480 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
14481 		/* No physical port deactivation supported. */
14482 		return (EINVAL);
14483 	}
14484 
14485 	/* Check the current state of the port */
14486 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14487 	    (SATA_DIP(sata_hba_inst), sata_device);
14488 
14489 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14490 
14491 	/*
14492 	 * Processing port mulitiplier
14493 	 */
14494 	if (qual == SATA_ADDR_CPORT &&
14495 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
14496 		mutex_enter(&cportinfo->cport_mutex);
14497 
14498 		/* Check controller port status */
14499 		sata_update_port_info(sata_hba_inst, sata_device);
14500 		if (rval != SATA_SUCCESS ||
14501 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14502 			/*
14503 			 * Device port status is unknown or it is in failed
14504 			 * state
14505 			 */
14506 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14507 			    SATA_PSTATE_FAILED;
14508 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14509 			    "sata_hba_ioctl: connect: failed to deactivate "
14510 			    "SATA port %d", cport);
14511 			mutex_exit(&cportinfo->cport_mutex);
14512 			return (EIO);
14513 		}
14514 
14515 		/* Disconnect all sub-devices. */
14516 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14517 		if (pmultinfo != NULL) {
14518 
14519 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
14520 			    sata_hba_inst, cport); npmport ++) {
14521 				subsdinfo = SATA_PMPORT_DRV_INFO(
14522 				    sata_hba_inst, cport, npmport);
14523 				if (subsdinfo == NULL)
14524 					continue;
14525 
14526 				subsdevice.satadev_addr = subsdinfo->
14527 				    satadrv_addr;
14528 
14529 				mutex_exit(&cportinfo->cport_mutex);
14530 				if (sata_ioctl_disconnect(sata_hba_inst,
14531 				    &subsdevice) == SATA_SUCCESS) {
14532 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14533 					"[Remove] device at port %d:%d "
14534 					"successfully.", cport, npmport);
14535 				}
14536 				mutex_enter(&cportinfo->cport_mutex);
14537 			}
14538 		}
14539 
14540 		/* Disconnect the port multiplier */
14541 		cportinfo->cport_state &= ~SATA_STATE_READY;
14542 		mutex_exit(&cportinfo->cport_mutex);
14543 
14544 		sata_device->satadev_addr.qual = qual;
14545 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14546 		    (SATA_DIP(sata_hba_inst), sata_device);
14547 
14548 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14549 		    SE_NO_HINT);
14550 
14551 		mutex_enter(&cportinfo->cport_mutex);
14552 		sata_update_port_info(sata_hba_inst, sata_device);
14553 		if (rval != SATA_SUCCESS &&
14554 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14555 			cportinfo->cport_state = SATA_PSTATE_FAILED;
14556 			rv = EIO;
14557 		} else {
14558 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14559 		}
14560 		mutex_exit(&cportinfo->cport_mutex);
14561 
14562 		return (rv);
14563 	}
14564 
14565 	/*
14566 	 * Process non-port-multiplier device - it could be a drive connected
14567 	 * to a port multiplier port or a controller port.
14568 	 */
14569 	if (qual == SATA_ADDR_PMPORT) {
14570 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14571 		mutex_enter(&pmportinfo->pmport_mutex);
14572 		sata_update_pmport_info(sata_hba_inst, sata_device);
14573 		if (rval != SATA_SUCCESS ||
14574 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14575 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
14576 			    SATA_PSTATE_FAILED;
14577 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
14578 			    "sata_hba_ioctl: connect: failed to deactivate "
14579 			    "SATA port %d:%d", cport, pmport);
14580 			mutex_exit(&pmportinfo->pmport_mutex);
14581 			return (EIO);
14582 		}
14583 
14584 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
14585 			sdinfo = pmportinfo->pmport_sata_drive;
14586 			ASSERT(sdinfo != NULL);
14587 		}
14588 
14589 		/*
14590 		 * Set port's dev_state to not ready - this will disable
14591 		 * an access to a potentially attached device.
14592 		 */
14593 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
14594 
14595 		/* Remove and release sata_drive info structure. */
14596 		if (sdinfo != NULL) {
14597 			if ((sdinfo->satadrv_type &
14598 			    SATA_VALID_DEV_TYPE) != 0) {
14599 				/*
14600 				 * If a target node exists, try to offline
14601 				 * a device and remove target node.
14602 				 */
14603 				mutex_exit(&pmportinfo->pmport_mutex);
14604 				(void) sata_offline_device(sata_hba_inst,
14605 				    sata_device, sdinfo);
14606 				mutex_enter(&pmportinfo->pmport_mutex);
14607 			}
14608 
14609 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
14610 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
14611 			(void) kmem_free((void *)sdinfo,
14612 			    sizeof (sata_drive_info_t));
14613 		}
14614 		mutex_exit(&pmportinfo->pmport_mutex);
14615 
14616 	} else if (qual == SATA_ADDR_CPORT) {
14617 		mutex_enter(&cportinfo->cport_mutex);
14618 		sata_update_port_info(sata_hba_inst, sata_device);
14619 		if (rval != SATA_SUCCESS ||
14620 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14621 			/*
14622 			 * Device port status is unknown or it is in failed
14623 			 * state
14624 			 */
14625 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14626 			    SATA_PSTATE_FAILED;
14627 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14628 			    "sata_hba_ioctl: connect: failed to deactivate "
14629 			    "SATA port %d", cport);
14630 			mutex_exit(&cportinfo->cport_mutex);
14631 			return (EIO);
14632 		}
14633 
14634 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
14635 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14636 			ASSERT(pmultinfo != NULL);
14637 		} else if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14638 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14639 			ASSERT(sdinfo != NULL);
14640 		}
14641 		cportinfo->cport_state &= ~SATA_STATE_READY;
14642 
14643 		if (sdinfo != NULL) {
14644 			if ((sdinfo->satadrv_type &
14645 			    SATA_VALID_DEV_TYPE) != 0) {
14646 				/*
14647 				 * If a target node exists, try to offline
14648 				 * a device and remove target node.
14649 				 */
14650 				mutex_exit(&cportinfo->cport_mutex);
14651 				(void) sata_offline_device(sata_hba_inst,
14652 				    sata_device, sdinfo);
14653 				mutex_enter(&cportinfo->cport_mutex);
14654 			}
14655 
14656 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14657 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14658 			(void) kmem_free((void *)sdinfo,
14659 			    sizeof (sata_drive_info_t));
14660 		}
14661 		mutex_exit(&cportinfo->cport_mutex);
14662 	}
14663 
14664 	/* Just ask HBA driver to deactivate port */
14665 	sata_device->satadev_addr.qual = qual;
14666 
14667 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14668 	    (SATA_DIP(sata_hba_inst), sata_device);
14669 
14670 	/*
14671 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14672 	 * without the hint (to force listener to investivate the state).
14673 	 */
14674 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14675 	    SE_NO_HINT);
14676 
14677 	if (qual == SATA_ADDR_PMPORT) {
14678 		mutex_enter(&pmportinfo->pmport_mutex);
14679 		sata_update_pmport_info(sata_hba_inst, sata_device);
14680 
14681 		if (rval != SATA_SUCCESS &&
14682 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14683 			/*
14684 			 * Port deactivation failure - do not change port
14685 			 * state unless the state returned by HBA indicates a
14686 			 * port failure.
14687 			 *
14688 			 * NOTE: device structures were released, so devices
14689 			 * now are invisible! Port reset is needed to
14690 			 * re-enumerate devices.
14691 			 */
14692 			pmportinfo->pmport_state = SATA_PSTATE_FAILED;
14693 			rv = EIO;
14694 		} else {
14695 			/*
14696 			 * Deactivation succeded. From now on the sata framework
14697 			 * will not care what is happening to the device, until
14698 			 * the port is activated again.
14699 			 */
14700 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14701 		}
14702 		mutex_exit(&pmportinfo->pmport_mutex);
14703 	} else if (qual == SATA_ADDR_CPORT) {
14704 		mutex_enter(&cportinfo->cport_mutex);
14705 		sata_update_port_info(sata_hba_inst, sata_device);
14706 
14707 		if (rval != SATA_SUCCESS &&
14708 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14709 			cportinfo->cport_state = SATA_PSTATE_FAILED;
14710 			rv = EIO;
14711 		} else {
14712 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14713 		}
14714 		mutex_exit(&cportinfo->cport_mutex);
14715 	}
14716 
14717 	return (rv);
14718 }
14719 
14720 
14721 
14722 /*
14723  * Process sata port connect request
14724  * The sata cfgadm pluging will invoke this operation only if port was found
14725  * in the disconnect state (failed state is also treated as the disconnected
14726  * state).
14727  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
14728  * sata_tran_hotplug_ops->sata_tran_port_activate().
14729  * If successful and a device is found attached to the port,
14730  * the initialization sequence is executed to attach a device structure to
14731  * a port structure. The state of the port and a device would be set
14732  * appropriately.
14733  * The device is not set in configured state (system-wise) by this operation.
14734  *
14735  * Note, that activating the port may generate link events,
14736  * so it is important that following processing and the
14737  * event processing does not interfere with each other!
14738  *
14739  * This operation may remove port failed state and will
14740  * try to make port active and in good standing.
14741  *
14742  * NOTE: Port multiplier is supported.
14743  */
14744 
14745 static int
14746 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
14747     sata_device_t *sata_device)
14748 {
14749 	sata_pmport_info_t	*pmportinfo = NULL;
14750 	uint8_t cport, pmport, qual;
14751 	int rv = 0;
14752 
14753 	cport = sata_device->satadev_addr.cport;
14754 	pmport = sata_device->satadev_addr.pmport;
14755 	qual = sata_device->satadev_addr.qual;
14756 
14757 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14758 	if (qual == SATA_ADDR_DCPORT)
14759 		qual = SATA_ADDR_CPORT;
14760 	else
14761 		qual = SATA_ADDR_PMPORT;
14762 
14763 	if (qual == SATA_ADDR_PMPORT)
14764 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14765 
14766 	/*
14767 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
14768 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
14769 	 * Perform sanity check now.
14770 	 */
14771 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
14772 		/* No physical port activation supported. */
14773 		return (EINVAL);
14774 	}
14775 
14776 	/* Just ask HBA driver to activate port */
14777 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14778 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14779 		/*
14780 		 * Port activation failure.
14781 		 */
14782 		if (qual == SATA_ADDR_CPORT) {
14783 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14784 			    cport)->cport_mutex);
14785 			sata_update_port_info(sata_hba_inst, sata_device);
14786 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14787 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14788 				    SATA_PSTATE_FAILED;
14789 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14790 				    "sata_hba_ioctl: connect: failed to "
14791 				    "activate SATA port %d", cport);
14792 			}
14793 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14794 			    cport)->cport_mutex);
14795 		} else { /* port multiplier device port */
14796 			mutex_enter(&pmportinfo->pmport_mutex);
14797 			sata_update_pmport_info(sata_hba_inst, sata_device);
14798 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14799 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14800 				    pmport) = SATA_PSTATE_FAILED;
14801 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
14802 				    "sata_hba_ioctl: connect: failed to "
14803 				    "activate SATA port %d:%d", cport, pmport);
14804 			}
14805 			mutex_exit(&pmportinfo->pmport_mutex);
14806 		}
14807 		return (EIO);
14808 	}
14809 
14810 	/* Virgin port state - will be updated by the port re-probe. */
14811 	if (qual == SATA_ADDR_CPORT) {
14812 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14813 		    cport)->cport_mutex);
14814 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
14815 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14816 		    cport)->cport_mutex);
14817 	} else { /* port multiplier device port */
14818 		mutex_enter(&pmportinfo->pmport_mutex);
14819 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
14820 		mutex_exit(&pmportinfo->pmport_mutex);
14821 	}
14822 
14823 	/*
14824 	 * Probe the port to find its state and attached device.
14825 	 */
14826 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14827 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
14828 		rv = EIO;
14829 
14830 	/*
14831 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14832 	 * without the hint
14833 	 */
14834 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14835 	    SE_NO_HINT);
14836 
14837 	/*
14838 	 * If there is a device attached to the port, emit
14839 	 * a message.
14840 	 */
14841 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
14842 
14843 		if (qual == SATA_ADDR_CPORT) {
14844 			if (sata_device->satadev_type == SATA_DTYPE_PMULT) {
14845 				sata_log(sata_hba_inst, CE_WARN,
14846 				    "SATA port multiplier detected "
14847 				    "at port %d", cport);
14848 			} else {
14849 				sata_log(sata_hba_inst, CE_WARN,
14850 				    "SATA device detected at port %d", cport);
14851 				if (sata_device->satadev_type ==
14852 				    SATA_DTYPE_UNKNOWN) {
14853 				/*
14854 				 * A device was not successfully identified
14855 				 */
14856 				sata_log(sata_hba_inst, CE_WARN,
14857 				    "Could not identify SATA "
14858 				    "device at port %d", cport);
14859 				}
14860 			}
14861 		} else { /* port multiplier device port */
14862 			sata_log(sata_hba_inst, CE_WARN,
14863 			    "SATA device detected at port %d:%d",
14864 			    cport, pmport);
14865 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14866 				/*
14867 				 * A device was not successfully identified
14868 				 */
14869 				sata_log(sata_hba_inst, CE_WARN,
14870 				    "Could not identify SATA "
14871 				    "device at port %d:%d", cport, pmport);
14872 			}
14873 		}
14874 	}
14875 
14876 	return (rv);
14877 }
14878 
14879 
14880 /*
14881  * Process sata device unconfigure request.
14882  * The unconfigure operation uses generic nexus operation to
14883  * offline a device. It leaves a target device node attached.
14884  * and obviously sata_drive_info attached as well, because
14885  * from the hardware point of view nothing has changed.
14886  */
14887 static int
14888 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
14889     sata_device_t *sata_device)
14890 {
14891 	int rv = 0;
14892 	dev_info_t *tdip;
14893 
14894 	/* We are addressing attached device, not a port */
14895 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
14896 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14897 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
14898 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14899 
14900 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14901 	    &sata_device->satadev_addr)) != NULL) {
14902 
14903 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
14904 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14905 			    "sata_hba_ioctl: unconfigure: "
14906 			    "failed to unconfigure device at SATA port %d:%d",
14907 			    sata_device->satadev_addr.cport,
14908 			    sata_device->satadev_addr.pmport));
14909 			rv = EIO;
14910 		}
14911 		/*
14912 		 * The target node devi_state should be marked with
14913 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
14914 		 * This would be the indication for cfgadm that
14915 		 * the AP node occupant state is 'unconfigured'.
14916 		 */
14917 
14918 	} else {
14919 		/*
14920 		 * This would indicate a failure on the part of cfgadm
14921 		 * to detect correct state of the node prior to this
14922 		 * call - one cannot unconfigure non-existing device.
14923 		 */
14924 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14925 		    "sata_hba_ioctl: unconfigure: "
14926 		    "attempt to unconfigure non-existing device "
14927 		    "at SATA port %d:%d",
14928 		    sata_device->satadev_addr.cport,
14929 		    sata_device->satadev_addr.pmport));
14930 		rv = ENXIO;
14931 	}
14932 	return (rv);
14933 }
14934 
14935 /*
14936  * Process sata device configure request
14937  * If port is in a failed state, operation is aborted - one has to use
14938  * an explicit connect or port activate request to try to get a port into
14939  * non-failed mode. Port reset wil also work in such situation.
14940  * If the port is in disconnected (shutdown) state, the connect operation is
14941  * attempted prior to any other action.
14942  * When port is in the active state, there is a device attached and the target
14943  * node exists, a device was most likely offlined.
14944  * If target node does not exist, a new target node is created. In both cases
14945  * an attempt is made to online (configure) the device.
14946  *
14947  * NOTE: Port multiplier is supported.
14948  */
14949 static int
14950 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
14951     sata_device_t *sata_device)
14952 {
14953 	int cport, pmport, qual;
14954 	int rval;
14955 	boolean_t target = B_TRUE;
14956 	sata_cport_info_t *cportinfo;
14957 	sata_pmport_info_t *pmportinfo = NULL;
14958 	dev_info_t *tdip;
14959 	sata_drive_info_t *sdinfo;
14960 
14961 	cport = sata_device->satadev_addr.cport;
14962 	pmport = sata_device->satadev_addr.pmport;
14963 	qual = sata_device->satadev_addr.qual;
14964 
14965 	/* Get current port state */
14966 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14967 	    (SATA_DIP(sata_hba_inst), sata_device);
14968 
14969 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14970 	if (qual == SATA_ADDR_DPMPORT) {
14971 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14972 		mutex_enter(&pmportinfo->pmport_mutex);
14973 		sata_update_pmport_info(sata_hba_inst, sata_device);
14974 		if (rval != SATA_SUCCESS ||
14975 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14976 			/*
14977 			 * Obviously, device on a failed port is not visible
14978 			 */
14979 			mutex_exit(&pmportinfo->pmport_mutex);
14980 			return (ENXIO);
14981 		}
14982 		mutex_exit(&pmportinfo->pmport_mutex);
14983 	} else {
14984 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14985 		    cport)->cport_mutex);
14986 		sata_update_port_info(sata_hba_inst, sata_device);
14987 		if (rval != SATA_SUCCESS ||
14988 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14989 			/*
14990 			 * Obviously, device on a failed port is not visible
14991 			 */
14992 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14993 			    cport)->cport_mutex);
14994 			return (ENXIO);
14995 		}
14996 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14997 		    cport)->cport_mutex);
14998 	}
14999 
15000 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
15001 		/* need to activate port */
15002 		target = B_FALSE;
15003 
15004 		/* Sanity check */
15005 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
15006 			return (ENXIO);
15007 
15008 		/* Just let HBA driver to activate port */
15009 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
15010 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15011 			/*
15012 			 * Port activation failure - do not change port state
15013 			 * unless the state returned by HBA indicates a port
15014 			 * failure.
15015 			 */
15016 			if (qual == SATA_ADDR_DPMPORT) {
15017 				mutex_enter(&pmportinfo->pmport_mutex);
15018 				sata_update_pmport_info(sata_hba_inst,
15019 				    sata_device);
15020 				if (sata_device->satadev_state &
15021 				    SATA_PSTATE_FAILED)
15022 					pmportinfo->pmport_state =
15023 					    SATA_PSTATE_FAILED;
15024 				mutex_exit(&pmportinfo->pmport_mutex);
15025 			} else {
15026 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15027 				    cport)->cport_mutex);
15028 				sata_update_port_info(sata_hba_inst,
15029 				    sata_device);
15030 				if (sata_device->satadev_state &
15031 				    SATA_PSTATE_FAILED)
15032 					cportinfo->cport_state =
15033 					    SATA_PSTATE_FAILED;
15034 				mutex_exit(&SATA_CPORT_INFO(
15035 				    sata_hba_inst, cport)->cport_mutex);
15036 			}
15037 		}
15038 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15039 		    "sata_hba_ioctl: configure: "
15040 		    "failed to activate SATA port %d:%d",
15041 		    cport, pmport));
15042 		return (EIO);
15043 	}
15044 	/*
15045 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
15046 	 * without the hint.
15047 	 */
15048 	sata_gen_sysevent(sata_hba_inst,
15049 	    &sata_device->satadev_addr, SE_NO_HINT);
15050 
15051 	/* Virgin port state */
15052 	if (qual == SATA_ADDR_DPMPORT) {
15053 		mutex_enter(&pmportinfo->pmport_mutex);
15054 		pmportinfo->pmport_state = 0;
15055 		mutex_exit(&pmportinfo->pmport_mutex);
15056 	} else {
15057 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15058 		    cport)-> cport_mutex);
15059 		cportinfo->cport_state = 0;
15060 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15061 		    cport)->cport_mutex);
15062 	}
15063 	/*
15064 	 * Always reprobe port, to get current device info.
15065 	 */
15066 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15067 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15068 		return (EIO);
15069 
15070 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == B_FALSE) {
15071 		if (qual == SATA_ADDR_DPMPORT) {
15072 			/*
15073 			 * That's the transition from "inactive" port
15074 			 * to active one with device attached.
15075 			 */
15076 			sata_log(sata_hba_inst, CE_WARN,
15077 			    "SATA device detected at port %d:%d",
15078 			    cport, pmport);
15079 		} else {
15080 			/*
15081 			 * When PM is attached to the cport and cport is
15082 			 * activated, every PM device port needs to be reprobed.
15083 			 * We need to emit message for all devices detected
15084 			 * at port multiplier's device ports.
15085 			 * Add such code here.
15086 			 * For now, just inform about device attached to
15087 			 * cport.
15088 			 */
15089 			sata_log(sata_hba_inst, CE_WARN,
15090 			    "SATA device detected at port %d", cport);
15091 		}
15092 	}
15093 
15094 	/*
15095 	 * This is where real configuration operation starts.
15096 	 *
15097 	 * When PM is attached to the cport and cport is activated,
15098 	 * devices attached PM device ports may have to be configured
15099 	 * explicitly. This may change when port multiplier is supported.
15100 	 * For now, configure only disks and other valid target devices.
15101 	 */
15102 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
15103 		if (qual == SATA_ADDR_DCPORT) {
15104 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
15105 				/*
15106 				 * A device was not successfully identified
15107 				 */
15108 				sata_log(sata_hba_inst, CE_WARN,
15109 				    "Could not identify SATA "
15110 				    "device at port %d", cport);
15111 			}
15112 		} else { /* port multiplier device port */
15113 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
15114 				/*
15115 				 * A device was not successfully identified
15116 				 */
15117 				sata_log(sata_hba_inst, CE_WARN,
15118 				    "Could not identify SATA "
15119 				    "device at port %d:%d", cport, pmport);
15120 			}
15121 		}
15122 		return (ENXIO);		/* No device to configure */
15123 	}
15124 
15125 	/*
15126 	 * Here we may have a device in reset condition,
15127 	 * but because we are just configuring it, there is
15128 	 * no need to process the reset other than just
15129 	 * to clear device reset condition in the HBA driver.
15130 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
15131 	 * cause a first command sent the HBA driver with the request
15132 	 * to clear device reset condition.
15133 	 */
15134 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15135 	if (qual == SATA_ADDR_DPMPORT)
15136 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
15137 	else
15138 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
15139 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
15140 	if (sdinfo == NULL) {
15141 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15142 		return (ENXIO);
15143 	}
15144 	if (sdinfo->satadrv_event_flags &
15145 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
15146 		sdinfo->satadrv_event_flags = 0;
15147 	}
15148 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
15149 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15150 
15151 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
15152 	    &sata_device->satadev_addr)) != NULL) {
15153 		/*
15154 		 * Target node exists. Verify, that it belongs
15155 		 * to existing, attached device and not to
15156 		 * a removed device.
15157 		 */
15158 		if (sata_check_device_removed(tdip) == B_TRUE) {
15159 			if (qual == SATA_ADDR_DPMPORT)
15160 				sata_log(sata_hba_inst, CE_WARN,
15161 				    "SATA device at port %d cannot be "
15162 				    "configured. "
15163 				    "Application(s) accessing "
15164 				    "previously attached device "
15165 				    "have to release it before newly "
15166 				    "inserted device can be made accessible.",
15167 				    cport);
15168 			else
15169 				sata_log(sata_hba_inst, CE_WARN,
15170 				    "SATA device at port %d:%d cannot be"
15171 				    "configured. "
15172 				    "Application(s) accessing "
15173 				    "previously attached device "
15174 				    "have to release it before newly "
15175 				    "inserted device can be made accessible.",
15176 				    cport, pmport);
15177 			return (EIO);
15178 		}
15179 		/*
15180 		 * Device was not removed and re-inserted.
15181 		 * Try to online it.
15182 		 */
15183 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
15184 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15185 			    "sata_hba_ioctl: configure: "
15186 			    "onlining device at SATA port "
15187 			    "%d:%d failed", cport, pmport));
15188 			return (EIO);
15189 		}
15190 
15191 		if (qual == SATA_ADDR_DPMPORT) {
15192 			mutex_enter(&pmportinfo->pmport_mutex);
15193 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
15194 			mutex_exit(&pmportinfo->pmport_mutex);
15195 		} else {
15196 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15197 			    cport)->cport_mutex);
15198 			cportinfo-> cport_tgtnode_clean = B_TRUE;
15199 			mutex_exit(&SATA_CPORT_INFO(
15200 			    sata_hba_inst, cport)->cport_mutex);
15201 		}
15202 	} else {
15203 		/*
15204 		 * No target node - need to create a new target node.
15205 		 */
15206 		if (qual == SATA_ADDR_DPMPORT) {
15207 			mutex_enter(&pmportinfo->pmport_mutex);
15208 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
15209 			mutex_exit(&pmportinfo->pmport_mutex);
15210 		} else {
15211 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15212 			    cport_mutex);
15213 			cportinfo-> cport_tgtnode_clean = B_TRUE;
15214 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15215 			    cport_mutex);
15216 		}
15217 
15218 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
15219 		    sata_hba_inst, &sata_device->satadev_addr);
15220 		if (tdip == NULL) {
15221 			/* Configure operation failed */
15222 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15223 			    "sata_hba_ioctl: configure: "
15224 			    "configuring SATA device at port %d:%d "
15225 			    "failed", cport, pmport));
15226 			return (EIO);
15227 		}
15228 	}
15229 	return (0);
15230 }
15231 
15232 
15233 /*
15234  * Process ioctl deactivate port request.
15235  * Arbitrarily unconfigure attached device, if any.
15236  * Even if the unconfigure fails, proceed with the
15237  * port deactivation.
15238  *
15239  * NOTE: Port Multiplier is supported now.
15240  */
15241 
15242 static int
15243 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
15244     sata_device_t *sata_device)
15245 {
15246 	int cport, pmport, qual;
15247 	int rval, rv = 0;
15248 	int npmport;
15249 	sata_cport_info_t *cportinfo;
15250 	sata_pmport_info_t *pmportinfo;
15251 	sata_pmult_info_t *pmultinfo;
15252 	dev_info_t *tdip;
15253 	sata_drive_info_t *sdinfo = NULL;
15254 	sata_device_t subsdevice;
15255 
15256 	/* Sanity check */
15257 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
15258 		return (ENOTSUP);
15259 
15260 	cport = sata_device->satadev_addr.cport;
15261 	pmport = sata_device->satadev_addr.pmport;
15262 	qual = sata_device->satadev_addr.qual;
15263 
15264 	/* SCSI_TO_SATA_ADDR_QUAL() translate ap_id into a device qualifier */
15265 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
15266 	if (qual == SATA_ADDR_DCPORT)
15267 		qual = SATA_ADDR_CPORT;
15268 	else
15269 		qual = SATA_ADDR_PMPORT;
15270 
15271 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
15272 	if (qual == SATA_ADDR_PMPORT)
15273 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
15274 
15275 	/*
15276 	 * Processing port multiplier
15277 	 */
15278 	if (qual == SATA_ADDR_CPORT &&
15279 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
15280 		mutex_enter(&cportinfo->cport_mutex);
15281 
15282 		/* Deactivate all sub-deices */
15283 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
15284 		if (pmultinfo != NULL) {
15285 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
15286 			    sata_hba_inst, cport); npmport++) {
15287 
15288 				subsdevice.satadev_addr.cport = cport;
15289 				subsdevice.satadev_addr.pmport =
15290 				    (uint8_t)npmport;
15291 				subsdevice.satadev_addr.qual =
15292 				    SATA_ADDR_DPMPORT;
15293 
15294 				SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
15295 				    "sata_hba_ioctl: deactivate: trying to "
15296 				    "deactivate SATA port %d:%d",
15297 				    cport, npmport);
15298 
15299 				mutex_exit(&cportinfo->cport_mutex);
15300 				if (sata_ioctl_deactivate(sata_hba_inst,
15301 				    &subsdevice) == SATA_SUCCESS) {
15302 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
15303 					    "[Deactivate] device at port %d:%d "
15304 					    "successfully.", cport, npmport);
15305 				}
15306 				mutex_enter(&cportinfo->cport_mutex);
15307 			}
15308 		}
15309 
15310 		/* Deactivate the port multiplier now. */
15311 		cportinfo->cport_state &= ~SATA_STATE_READY;
15312 		mutex_exit(&cportinfo->cport_mutex);
15313 
15314 		sata_device->satadev_addr.qual = qual;
15315 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
15316 		    (SATA_DIP(sata_hba_inst), sata_device);
15317 
15318 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
15319 		    SE_NO_HINT);
15320 
15321 		mutex_enter(&cportinfo->cport_mutex);
15322 		sata_update_port_info(sata_hba_inst, sata_device);
15323 		if (rval != SATA_SUCCESS) {
15324 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
15325 				cportinfo->cport_state = SATA_PSTATE_FAILED;
15326 			}
15327 			rv = EIO;
15328 		} else {
15329 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
15330 		}
15331 		mutex_exit(&cportinfo->cport_mutex);
15332 
15333 		return (rv);
15334 	}
15335 
15336 	/*
15337 	 * Process non-port-multiplier device - it could be a drive connected
15338 	 * to a port multiplier port or a controller port.
15339 	 */
15340 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15341 	if (qual == SATA_ADDR_CPORT) {
15342 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
15343 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
15344 			/* deal only with valid devices */
15345 			if ((cportinfo->cport_dev_type &
15346 			    SATA_VALID_DEV_TYPE) != 0)
15347 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
15348 		}
15349 		cportinfo->cport_state &= ~SATA_STATE_READY;
15350 	} else {
15351 		/* Port multiplier device port */
15352 		mutex_enter(&pmportinfo->pmport_mutex);
15353 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
15354 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
15355 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
15356 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
15357 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
15358 		mutex_exit(&pmportinfo->pmport_mutex);
15359 	}
15360 
15361 	if (sdinfo != NULL) {
15362 		/*
15363 		 * If a target node exists, try to offline a device and
15364 		 * to remove a target node.
15365 		 */
15366 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15367 		    cport_mutex);
15368 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
15369 		    &sata_device->satadev_addr);
15370 		if (tdip != NULL) {
15371 			/* target node exist */
15372 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
15373 			    "sata_hba_ioctl: port deactivate: "
15374 			    "target node exists.", NULL);
15375 
15376 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
15377 			    NDI_SUCCESS) {
15378 				SATA_LOG_D((sata_hba_inst, CE_WARN,
15379 				    "sata_hba_ioctl: port deactivate: "
15380 				    "failed to unconfigure device at port "
15381 				    "%d:%d before deactivating the port",
15382 				    cport, pmport));
15383 				/*
15384 				 * Set DEVICE REMOVED state in the target
15385 				 * node. It will prevent an access to
15386 				 * the device even when a new device is
15387 				 * attached, until the old target node is
15388 				 * released, removed and recreated for a new
15389 				 * device.
15390 				 */
15391 				sata_set_device_removed(tdip);
15392 
15393 				/*
15394 				 * Instruct the event daemon to try the
15395 				 * target node cleanup later.
15396 				 */
15397 				sata_set_target_node_cleanup(sata_hba_inst,
15398 				    &sata_device->satadev_addr);
15399 			}
15400 		}
15401 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15402 		    cport_mutex);
15403 		/*
15404 		 * In any case, remove and release sata_drive_info
15405 		 * structure.
15406 		 */
15407 		if (qual == SATA_ADDR_CPORT) {
15408 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
15409 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
15410 		} else { /* port multiplier device port */
15411 			mutex_enter(&pmportinfo->pmport_mutex);
15412 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
15413 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
15414 			mutex_exit(&pmportinfo->pmport_mutex);
15415 		}
15416 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
15417 	}
15418 
15419 	if (qual == SATA_ADDR_CPORT) {
15420 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
15421 		    SATA_STATE_PROBING);
15422 	} else if (qual == SATA_ADDR_PMPORT) {
15423 		mutex_enter(&pmportinfo->pmport_mutex);
15424 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
15425 		    SATA_STATE_PROBING);
15426 		mutex_exit(&pmportinfo->pmport_mutex);
15427 	}
15428 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15429 
15430 	/* Just let HBA driver to deactivate port */
15431 	sata_device->satadev_addr.qual = qual;
15432 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
15433 	    (SATA_DIP(sata_hba_inst), sata_device);
15434 
15435 	/*
15436 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
15437 	 * without the hint
15438 	 */
15439 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
15440 	    SE_NO_HINT);
15441 
15442 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15443 	sata_update_port_info(sata_hba_inst, sata_device);
15444 	if (qual == SATA_ADDR_CPORT) {
15445 		if (rval != SATA_SUCCESS) {
15446 			/*
15447 			 * Port deactivation failure - do not change port state
15448 			 * unless the state returned by HBA indicates a port
15449 			 * failure.
15450 			 */
15451 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
15452 				SATA_CPORT_STATE(sata_hba_inst, cport) =
15453 				    SATA_PSTATE_FAILED;
15454 			}
15455 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15456 			    "sata_hba_ioctl: port deactivate: "
15457 			    "cannot deactivate SATA port %d", cport));
15458 			rv = EIO;
15459 		} else {
15460 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
15461 		}
15462 	} else {
15463 		mutex_enter(&pmportinfo->pmport_mutex);
15464 		if (rval != SATA_SUCCESS) {
15465 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
15466 				SATA_PMPORT_STATE(sata_hba_inst, cport,
15467 				    pmport) = SATA_PSTATE_FAILED;
15468 			}
15469 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15470 			    "sata_hba_ioctl: port deactivate: "
15471 			    "cannot deactivate SATA port %d:%d",
15472 			    cport, pmport));
15473 			rv = EIO;
15474 		} else {
15475 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
15476 		}
15477 		mutex_exit(&pmportinfo->pmport_mutex);
15478 	}
15479 
15480 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15481 
15482 	return (rv);
15483 }
15484 
15485 /*
15486  * Process ioctl port activate request.
15487  *
15488  * NOTE: Port multiplier is supported now.
15489  */
15490 static int
15491 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
15492     sata_device_t *sata_device)
15493 {
15494 	int cport, pmport, qual;
15495 	sata_cport_info_t *cportinfo;
15496 	sata_pmport_info_t *pmportinfo = NULL;
15497 	boolean_t dev_existed = B_TRUE;
15498 
15499 	/* Sanity check */
15500 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
15501 		return (ENOTSUP);
15502 
15503 	cport = sata_device->satadev_addr.cport;
15504 	pmport = sata_device->satadev_addr.pmport;
15505 	qual = sata_device->satadev_addr.qual;
15506 
15507 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
15508 
15509 	/*
15510 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
15511 	 * is a device. But what we are dealing with is port/pmport.
15512 	 */
15513 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
15514 	if (qual == SATA_ADDR_DCPORT)
15515 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
15516 	else
15517 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
15518 
15519 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15520 	if (qual == SATA_ADDR_PMPORT) {
15521 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
15522 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
15523 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
15524 			dev_existed = B_FALSE;
15525 	} else { /* cport */
15526 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
15527 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
15528 			dev_existed = B_FALSE;
15529 	}
15530 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15531 
15532 	/* Just let HBA driver to activate port, if necessary */
15533 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
15534 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15535 		/*
15536 		 * Port activation failure - do not change port state unless
15537 		 * the state returned by HBA indicates a port failure.
15538 		 */
15539 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15540 		    cport)->cport_mutex);
15541 		sata_update_port_info(sata_hba_inst, sata_device);
15542 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
15543 			if (qual == SATA_ADDR_PMPORT) {
15544 				mutex_enter(&pmportinfo->pmport_mutex);
15545 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
15546 				mutex_exit(&pmportinfo->pmport_mutex);
15547 			} else
15548 				cportinfo->cport_state = SATA_PSTATE_FAILED;
15549 
15550 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15551 			    cport)->cport_mutex);
15552 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15553 			    "sata_hba_ioctl: port activate: cannot activate "
15554 			    "SATA port %d:%d", cport, pmport));
15555 			return (EIO);
15556 		}
15557 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15558 	}
15559 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15560 	if (qual == SATA_ADDR_PMPORT) {
15561 		mutex_enter(&pmportinfo->pmport_mutex);
15562 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
15563 		mutex_exit(&pmportinfo->pmport_mutex);
15564 	} else
15565 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
15566 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15567 
15568 	/*
15569 	 * Re-probe port to find its current state and possibly attached device.
15570 	 * Port re-probing may change the cportinfo device type if device is
15571 	 * found attached.
15572 	 * If port probing failed, the device type would be set to
15573 	 * SATA_DTYPE_NONE.
15574 	 */
15575 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
15576 	    SATA_DEV_IDENTIFY_RETRY);
15577 
15578 	/*
15579 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
15580 	 * without the hint.
15581 	 */
15582 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
15583 	    SE_NO_HINT);
15584 
15585 	if (dev_existed == B_FALSE) {
15586 		if (qual == SATA_ADDR_PMPORT &&
15587 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
15588 			/*
15589 			 * That's the transition from the "inactive" port state
15590 			 * or the active port without a device attached to the
15591 			 * active port state with a device attached.
15592 			 */
15593 			sata_log(sata_hba_inst, CE_WARN,
15594 			    "SATA device detected at port %d:%d",
15595 			    cport, pmport);
15596 		} else if (qual == SATA_ADDR_CPORT &&
15597 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
15598 			/*
15599 			 * That's the transition from the "inactive" port state
15600 			 * or the active port without a device attached to the
15601 			 * active port state with a device attached.
15602 			 */
15603 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
15604 				sata_log(sata_hba_inst, CE_WARN,
15605 				    "SATA device detected at port %d", cport);
15606 			} else {
15607 				sata_log(sata_hba_inst, CE_WARN,
15608 				    "SATA port multiplier detected at port %d",
15609 				    cport);
15610 			}
15611 		}
15612 	}
15613 	return (0);
15614 }
15615 
15616 
15617 
15618 /*
15619  * Process ioctl reset port request.
15620  *
15621  * NOTE: Port-Multiplier is supported.
15622  */
15623 static int
15624 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
15625     sata_device_t *sata_device)
15626 {
15627 	int cport, pmport, qual;
15628 	int rv = 0;
15629 
15630 	cport = sata_device->satadev_addr.cport;
15631 	pmport = sata_device->satadev_addr.pmport;
15632 	qual = sata_device->satadev_addr.qual;
15633 
15634 	/*
15635 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
15636 	 * is a device. But what we are dealing with is port/pmport.
15637 	 */
15638 	if (qual == SATA_ADDR_DCPORT)
15639 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
15640 	else
15641 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
15642 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
15643 
15644 	/* Sanity check */
15645 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15646 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15647 		    "sata_hba_ioctl: sata_hba_tran missing required "
15648 		    "function sata_tran_reset_dport"));
15649 		return (ENOTSUP);
15650 	}
15651 
15652 	/* Ask HBA to reset port */
15653 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
15654 	    sata_device) != SATA_SUCCESS) {
15655 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15656 		    "sata_hba_ioctl: reset port: failed %d:%d",
15657 		    cport, pmport));
15658 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15659 		    cport_mutex);
15660 		sata_update_port_info(sata_hba_inst, sata_device);
15661 		if (qual == SATA_ADDR_CPORT)
15662 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15663 			    SATA_PSTATE_FAILED;
15664 		else {
15665 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
15666 			    pmport));
15667 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15668 			    SATA_PSTATE_FAILED;
15669 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
15670 			    pmport));
15671 		}
15672 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15673 		    cport_mutex);
15674 		rv = EIO;
15675 	}
15676 
15677 	return (rv);
15678 }
15679 
15680 /*
15681  * Process ioctl reset device request.
15682  *
15683  * NOTE: Port multiplier is supported.
15684  */
15685 static int
15686 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
15687     sata_device_t *sata_device)
15688 {
15689 	sata_drive_info_t *sdinfo = NULL;
15690 	sata_pmult_info_t *pmultinfo = NULL;
15691 	int cport, pmport;
15692 	int rv = 0;
15693 
15694 	/* Sanity check */
15695 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15696 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15697 		    "sata_hba_ioctl: sata_hba_tran missing required "
15698 		    "function sata_tran_reset_dport"));
15699 		return (ENOTSUP);
15700 	}
15701 
15702 	cport = sata_device->satadev_addr.cport;
15703 	pmport = sata_device->satadev_addr.pmport;
15704 
15705 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15706 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
15707 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
15708 		    SATA_DTYPE_PMULT)
15709 			pmultinfo = SATA_CPORT_INFO(sata_hba_inst, cport)->
15710 			    cport_devp.cport_sata_pmult;
15711 		else
15712 			sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15713 			    sata_device->satadev_addr.cport);
15714 	} else { /* port multiplier */
15715 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
15716 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15717 		    sata_device->satadev_addr.cport,
15718 		    sata_device->satadev_addr.pmport);
15719 	}
15720 	if (sdinfo == NULL && pmultinfo == NULL) {
15721 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15722 		return (EINVAL);
15723 	}
15724 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15725 
15726 	/* Ask HBA to reset device */
15727 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15728 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15729 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15730 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
15731 		    cport, pmport));
15732 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15733 		    cport_mutex);
15734 		sata_update_port_info(sata_hba_inst, sata_device);
15735 		/*
15736 		 * Device info structure remains attached. Another device reset
15737 		 * or port disconnect/connect and re-probing is
15738 		 * needed to change it's state
15739 		 */
15740 		if (sdinfo != NULL) {
15741 			sdinfo->satadrv_state &= ~SATA_STATE_READY;
15742 			sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
15743 		} else if (pmultinfo != NULL) {
15744 			pmultinfo->pmult_state &= ~SATA_STATE_READY;
15745 			pmultinfo->pmult_state |= SATA_DSTATE_FAILED;
15746 		}
15747 
15748 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15749 		rv = EIO;
15750 	}
15751 	/*
15752 	 * If attached device was a port multiplier, some extra processing
15753 	 * may be needed to bring it back. SATA specification requies a
15754 	 * mandatory software reset on host port to reliably enumerate a port
15755 	 * multiplier, the HBA driver should handle that after reset
15756 	 * operation.
15757 	 */
15758 	return (rv);
15759 }
15760 
15761 
15762 /*
15763  * Process ioctl reset all request.
15764  */
15765 static int
15766 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
15767 {
15768 	sata_device_t sata_device;
15769 	int rv = 0;
15770 	int tcport;
15771 
15772 	sata_device.satadev_rev = SATA_DEVICE_REV;
15773 
15774 	/*
15775 	 * There is no protection here for configured devices.
15776 	 */
15777 	/* Sanity check */
15778 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15779 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15780 		    "sata_hba_ioctl: sata_hba_tran missing required "
15781 		    "function sata_tran_reset_dport"));
15782 		return (ENOTSUP);
15783 	}
15784 
15785 	/*
15786 	 * Need to lock all ports, not just one.
15787 	 * If any port is locked by event processing, fail the whole operation.
15788 	 * One port is already locked, but for simplicity lock it again.
15789 	 */
15790 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15791 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15792 		    cport_mutex);
15793 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
15794 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
15795 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15796 			    cport_mutex);
15797 			rv = EBUSY;
15798 			break;
15799 		} else {
15800 			/*
15801 			 * It is enough to lock cport in command-based
15802 			 * switching mode.
15803 			 */
15804 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
15805 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
15806 		}
15807 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15808 		    cport_mutex);
15809 	}
15810 
15811 	if (rv == 0) {
15812 		/*
15813 		 * All cports were successfully locked.
15814 		 * Reset main SATA controller.
15815 		 * Set the device address to port 0, to have a valid device
15816 		 * address.
15817 		 */
15818 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
15819 		sata_device.satadev_addr.cport = 0;
15820 		sata_device.satadev_addr.pmport = 0;
15821 
15822 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15823 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
15824 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15825 			    "sata_hba_ioctl: reset controller failed"));
15826 			return (EIO);
15827 		}
15828 	}
15829 	/*
15830 	 * Unlock all ports
15831 	 */
15832 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15833 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15834 		    cport_mutex);
15835 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
15836 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
15837 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15838 		    cport_mutex);
15839 	}
15840 
15841 	/*
15842 	 * This operation returns EFAULT if either reset
15843 	 * controller failed or a re-probing of any port failed.
15844 	 */
15845 	return (rv);
15846 }
15847 
15848 
15849 /*
15850  * Process ioctl port self test request.
15851  *
15852  * NOTE: Port multiplier code is not completed nor tested.
15853  */
15854 static int
15855 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
15856     sata_device_t *sata_device)
15857 {
15858 	int cport, pmport, qual;
15859 	int rv = 0;
15860 
15861 	/* Sanity check */
15862 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
15863 		return (ENOTSUP);
15864 
15865 	cport = sata_device->satadev_addr.cport;
15866 	pmport = sata_device->satadev_addr.pmport;
15867 	qual = sata_device->satadev_addr.qual;
15868 
15869 	/*
15870 	 * There is no protection here for a configured
15871 	 * device attached to this port.
15872 	 */
15873 
15874 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
15875 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15876 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15877 		    "sata_hba_ioctl: port selftest: "
15878 		    "failed port %d:%d", cport, pmport));
15879 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15880 		    cport_mutex);
15881 		sata_update_port_info(sata_hba_inst, sata_device);
15882 		if (qual == SATA_ADDR_CPORT)
15883 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15884 			    SATA_PSTATE_FAILED;
15885 		else { /* port multiplier device port */
15886 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
15887 			    cport, pmport));
15888 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15889 			    SATA_PSTATE_FAILED;
15890 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
15891 			    cport, pmport));
15892 		}
15893 
15894 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15895 		    cport_mutex);
15896 		return (EIO);
15897 	}
15898 	/*
15899 	 * Beacuse the port was reset in the course of testing, it should be
15900 	 * re-probed and attached device state should be restored. At this
15901 	 * point the port state is unknown - it's state is HBA-specific.
15902 	 * Force port re-probing to get it into a known state.
15903 	 */
15904 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15905 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15906 		rv = EIO;
15907 	return (rv);
15908 }
15909 
15910 
15911 /*
15912  * sata_cfgadm_state:
15913  * Use the sata port state and state of the target node to figure out
15914  * the cfgadm_state.
15915  *
15916  * The port argument is a value with encoded cport,
15917  * pmport and address qualifier, in the same manner as a scsi target number.
15918  * SCSI_TO_SATA_CPORT macro extracts cport number,
15919  * SCSI_TO_SATA_PMPORT extracts pmport number and
15920  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
15921  *
15922  * Port multiplier is supported.
15923  */
15924 
15925 static void
15926 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
15927     devctl_ap_state_t *ap_state)
15928 {
15929 	uint8_t		cport, pmport, qual;
15930 	uint32_t	port_state, pmult_state;
15931 	uint32_t	dev_type;
15932 	sata_drive_info_t *sdinfo;
15933 
15934 	cport = SCSI_TO_SATA_CPORT(port);
15935 	pmport = SCSI_TO_SATA_PMPORT(port);
15936 	qual = SCSI_TO_SATA_ADDR_QUAL(port);
15937 
15938 	/* Check cport state */
15939 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
15940 	if (port_state & SATA_PSTATE_SHUTDOWN ||
15941 	    port_state & SATA_PSTATE_FAILED) {
15942 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15943 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15944 		if (port_state & SATA_PSTATE_FAILED)
15945 			ap_state->ap_condition = AP_COND_FAILED;
15946 		else
15947 			ap_state->ap_condition = AP_COND_UNKNOWN;
15948 
15949 		return;
15950 	}
15951 
15952 	/* cport state is okay. Now check pmport state */
15953 	if (qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) {
15954 		/* Sanity check */
15955 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
15956 		    SATA_DTYPE_PMULT || SATA_PMPORT_INFO(sata_hba_inst,
15957 		    cport, pmport) == NULL)
15958 			return;
15959 		port_state = SATA_PMPORT_STATE(sata_hba_inst, cport, pmport);
15960 		if (port_state & SATA_PSTATE_SHUTDOWN ||
15961 		    port_state & SATA_PSTATE_FAILED) {
15962 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15963 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15964 			if (port_state & SATA_PSTATE_FAILED)
15965 				ap_state->ap_condition = AP_COND_FAILED;
15966 			else
15967 				ap_state->ap_condition = AP_COND_UNKNOWN;
15968 
15969 			return;
15970 		}
15971 	}
15972 
15973 	/* Port is enabled and ready */
15974 	if (qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_CPORT)
15975 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst, cport);
15976 	else
15977 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport, pmport);
15978 
15979 	switch (dev_type) {
15980 	case SATA_DTYPE_NONE:
15981 	{
15982 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15983 		ap_state->ap_condition = AP_COND_OK;
15984 		/* No device attached */
15985 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
15986 		break;
15987 	}
15988 	case SATA_DTYPE_PMULT:
15989 	{
15990 		/* Need to check port multiplier state */
15991 		ASSERT(qual == SATA_ADDR_DCPORT);
15992 		pmult_state = SATA_PMULT_INFO(sata_hba_inst, cport)->
15993 		    pmult_state;
15994 		if (pmult_state & (SATA_PSTATE_SHUTDOWN|SATA_PSTATE_FAILED)) {
15995 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15996 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15997 			if (pmult_state & SATA_PSTATE_FAILED)
15998 				ap_state->ap_condition = AP_COND_FAILED;
15999 			else
16000 				ap_state->ap_condition = AP_COND_UNKNOWN;
16001 
16002 			return;
16003 		}
16004 
16005 		/* Port multiplier is not configurable */
16006 		ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
16007 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
16008 		ap_state->ap_condition = AP_COND_OK;
16009 		break;
16010 	}
16011 
16012 	case SATA_DTYPE_ATADISK:
16013 	case SATA_DTYPE_ATAPICD:
16014 	case SATA_DTYPE_ATAPITAPE:
16015 	case SATA_DTYPE_ATAPIDISK:
16016 	{
16017 		dev_info_t *tdip = NULL;
16018 		dev_info_t *dip = NULL;
16019 		int circ;
16020 
16021 		dip = SATA_DIP(sata_hba_inst);
16022 		tdip = sata_get_target_dip(dip, cport, pmport);
16023 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
16024 		if (tdip != NULL) {
16025 			ndi_devi_enter(dip, &circ);
16026 			mutex_enter(&(DEVI(tdip)->devi_lock));
16027 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
16028 				/*
16029 				 * There could be the case where previously
16030 				 * configured and opened device was removed
16031 				 * and unknown device was plugged.
16032 				 * In such case we want to show a device, and
16033 				 * its configured or unconfigured state but
16034 				 * indicate unusable condition untill the
16035 				 * old target node is released and removed.
16036 				 */
16037 				ap_state->ap_condition = AP_COND_UNUSABLE;
16038 			} else {
16039 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
16040 				    cport));
16041 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
16042 				    cport);
16043 				if (sdinfo != NULL) {
16044 					if ((sdinfo->satadrv_state &
16045 					    SATA_DSTATE_FAILED) != 0)
16046 						ap_state->ap_condition =
16047 						    AP_COND_FAILED;
16048 					else
16049 						ap_state->ap_condition =
16050 						    AP_COND_OK;
16051 				} else {
16052 					ap_state->ap_condition =
16053 					    AP_COND_UNKNOWN;
16054 				}
16055 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
16056 				    cport));
16057 			}
16058 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
16059 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
16060 				ap_state->ap_ostate =
16061 				    AP_OSTATE_UNCONFIGURED;
16062 			} else {
16063 				ap_state->ap_ostate =
16064 				    AP_OSTATE_CONFIGURED;
16065 			}
16066 			mutex_exit(&(DEVI(tdip)->devi_lock));
16067 			ndi_devi_exit(dip, circ);
16068 		} else {
16069 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
16070 			ap_state->ap_condition = AP_COND_UNKNOWN;
16071 		}
16072 		break;
16073 	}
16074 	case SATA_DTYPE_ATAPIPROC:
16075 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
16076 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
16077 		ap_state->ap_condition = AP_COND_OK;
16078 		break;
16079 	default:
16080 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
16081 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
16082 		ap_state->ap_condition = AP_COND_UNKNOWN;
16083 		/*
16084 		 * This is actually internal error condition (non fatal),
16085 		 * because we have already checked all defined device types.
16086 		 */
16087 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16088 		    "sata_cfgadm_state: Internal error: "
16089 		    "unknown device type"));
16090 		break;
16091 	}
16092 }
16093 
16094 
16095 /*
16096  * Process ioctl get device path request.
16097  *
16098  * NOTE: Port multiplier has no target dip. Devices connected to port
16099  * multiplier have target node attached to the HBA node. The only difference
16100  * between them and the directly-attached device node is a target address.
16101  */
16102 static int
16103 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
16104     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
16105 {
16106 	char path[MAXPATHLEN];
16107 	uint32_t size;
16108 	dev_info_t *tdip;
16109 
16110 	(void) strcpy(path, "/devices");
16111 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
16112 	    &sata_device->satadev_addr)) == NULL) {
16113 		/*
16114 		 * No such device. If this is a request for a size, do not
16115 		 * return EINVAL for non-existing target, because cfgadm
16116 		 * will then indicate a meaningless ioctl failure.
16117 		 * If this is a request for a path, indicate invalid
16118 		 * argument.
16119 		 */
16120 		if (ioc->get_size == 0)
16121 			return (EINVAL);
16122 	} else {
16123 		(void) ddi_pathname(tdip, path + strlen(path));
16124 	}
16125 	size = strlen(path) + 1;
16126 
16127 	if (ioc->get_size != 0) {
16128 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
16129 		    mode) != 0)
16130 			return (EFAULT);
16131 	} else {
16132 		if (ioc->bufsiz != size)
16133 			return (EINVAL);
16134 
16135 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
16136 		    mode) != 0)
16137 			return (EFAULT);
16138 	}
16139 	return (0);
16140 }
16141 
16142 /*
16143  * Process ioctl get attachment point type request.
16144  *
16145  * NOTE: Port multiplier is supported.
16146  */
16147 static	int
16148 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
16149     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
16150 {
16151 	uint32_t	type_len;
16152 	const char	*ap_type;
16153 	int		dev_type;
16154 
16155 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
16156 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
16157 		    sata_device->satadev_addr.cport);
16158 	else /* pmport */
16159 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
16160 		    sata_device->satadev_addr.cport,
16161 		    sata_device->satadev_addr.pmport);
16162 
16163 	switch (dev_type) {
16164 	case SATA_DTYPE_NONE:
16165 		ap_type = "port";
16166 		break;
16167 
16168 	case SATA_DTYPE_ATADISK:
16169 	case SATA_DTYPE_ATAPIDISK:
16170 		ap_type = "disk";
16171 		break;
16172 
16173 	case SATA_DTYPE_ATAPICD:
16174 		ap_type = "cd/dvd";
16175 		break;
16176 
16177 	case SATA_DTYPE_ATAPITAPE:
16178 		ap_type = "tape";
16179 		break;
16180 
16181 	case SATA_DTYPE_ATAPIPROC:
16182 		ap_type = "processor";
16183 		break;
16184 
16185 	case SATA_DTYPE_PMULT:
16186 		ap_type = "sata-pmult";
16187 		break;
16188 
16189 	case SATA_DTYPE_UNKNOWN:
16190 		ap_type = "unknown";
16191 		break;
16192 
16193 	default:
16194 		ap_type = "unsupported";
16195 		break;
16196 
16197 	} /* end of dev_type switch */
16198 
16199 	type_len = strlen(ap_type) + 1;
16200 
16201 	if (ioc->get_size) {
16202 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
16203 		    mode) != 0)
16204 			return (EFAULT);
16205 	} else {
16206 		if (ioc->bufsiz != type_len)
16207 			return (EINVAL);
16208 
16209 		if (ddi_copyout((void *)ap_type, ioc->buf,
16210 		    ioc->bufsiz, mode) != 0)
16211 			return (EFAULT);
16212 	}
16213 	return (0);
16214 
16215 }
16216 
16217 /*
16218  * Process ioctl get device model info request.
16219  * This operation should return to cfgadm the device model
16220  * information string
16221  *
16222  * NOTE: Port multiplier is supported.
16223  */
16224 static	int
16225 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
16226     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
16227 {
16228 	sata_drive_info_t *sdinfo;
16229 	uint32_t info_len;
16230 	char ap_info[SATA_ID_MODEL_LEN + 1];
16231 
16232 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
16233 	    sata_device->satadev_addr.cport)->cport_mutex);
16234 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
16235 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
16236 		    sata_device->satadev_addr.cport);
16237 	else /* port multiplier */
16238 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
16239 		    sata_device->satadev_addr.cport,
16240 		    sata_device->satadev_addr.pmport);
16241 	if (sdinfo == NULL) {
16242 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
16243 		    sata_device->satadev_addr.cport)->cport_mutex);
16244 		return (EINVAL);
16245 	}
16246 
16247 #ifdef	_LITTLE_ENDIAN
16248 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
16249 #else	/* _LITTLE_ENDIAN */
16250 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
16251 #endif	/* _LITTLE_ENDIAN */
16252 
16253 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
16254 	    sata_device->satadev_addr.cport)->cport_mutex);
16255 
16256 	ap_info[SATA_ID_MODEL_LEN] = '\0';
16257 
16258 	info_len = strlen(ap_info) + 1;
16259 
16260 	if (ioc->get_size) {
16261 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
16262 		    mode) != 0)
16263 			return (EFAULT);
16264 	} else {
16265 		if (ioc->bufsiz < info_len)
16266 			return (EINVAL);
16267 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
16268 		    mode) != 0)
16269 			return (EFAULT);
16270 	}
16271 	return (0);
16272 }
16273 
16274 
16275 /*
16276  * Process ioctl get device firmware revision info request.
16277  * This operation should return to cfgadm the device firmware revision
16278  * information string
16279  *
16280  * Port multiplier is supported.
16281  */
16282 static	int
16283 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
16284     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
16285 {
16286 	sata_drive_info_t *sdinfo;
16287 	uint32_t info_len;
16288 	char ap_info[SATA_ID_FW_LEN + 1];
16289 
16290 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
16291 	    sata_device->satadev_addr.cport)->cport_mutex);
16292 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
16293 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
16294 		    sata_device->satadev_addr.cport);
16295 	else /* port multiplier */
16296 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
16297 		    sata_device->satadev_addr.cport,
16298 		    sata_device->satadev_addr.pmport);
16299 	if (sdinfo == NULL) {
16300 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
16301 		    sata_device->satadev_addr.cport)->cport_mutex);
16302 		return (EINVAL);
16303 	}
16304 
16305 #ifdef	_LITTLE_ENDIAN
16306 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
16307 #else	/* _LITTLE_ENDIAN */
16308 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
16309 #endif	/* _LITTLE_ENDIAN */
16310 
16311 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
16312 	    sata_device->satadev_addr.cport)->cport_mutex);
16313 
16314 	ap_info[SATA_ID_FW_LEN] = '\0';
16315 
16316 	info_len = strlen(ap_info) + 1;
16317 
16318 	if (ioc->get_size) {
16319 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
16320 		    mode) != 0)
16321 			return (EFAULT);
16322 	} else {
16323 		if (ioc->bufsiz < info_len)
16324 			return (EINVAL);
16325 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
16326 		    mode) != 0)
16327 			return (EFAULT);
16328 	}
16329 	return (0);
16330 }
16331 
16332 
16333 /*
16334  * Process ioctl get device serial number info request.
16335  * This operation should return to cfgadm the device serial number string.
16336  *
16337  * NOTE: Port multiplier is supported.
16338  */
16339 static	int
16340 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
16341     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
16342 {
16343 	sata_drive_info_t *sdinfo;
16344 	uint32_t info_len;
16345 	char ap_info[SATA_ID_SERIAL_LEN + 1];
16346 
16347 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
16348 	    sata_device->satadev_addr.cport)->cport_mutex);
16349 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
16350 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
16351 		    sata_device->satadev_addr.cport);
16352 	else /* port multiplier */
16353 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
16354 		    sata_device->satadev_addr.cport,
16355 		    sata_device->satadev_addr.pmport);
16356 	if (sdinfo == NULL) {
16357 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
16358 		    sata_device->satadev_addr.cport)->cport_mutex);
16359 		return (EINVAL);
16360 	}
16361 
16362 #ifdef	_LITTLE_ENDIAN
16363 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
16364 #else	/* _LITTLE_ENDIAN */
16365 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
16366 #endif	/* _LITTLE_ENDIAN */
16367 
16368 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
16369 	    sata_device->satadev_addr.cport)->cport_mutex);
16370 
16371 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
16372 
16373 	info_len = strlen(ap_info) + 1;
16374 
16375 	if (ioc->get_size) {
16376 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
16377 		    mode) != 0)
16378 			return (EFAULT);
16379 	} else {
16380 		if (ioc->bufsiz < info_len)
16381 			return (EINVAL);
16382 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
16383 		    mode) != 0)
16384 			return (EFAULT);
16385 	}
16386 	return (0);
16387 }
16388 
16389 
16390 /*
16391  * Preset scsi extended sense data (to NO SENSE)
16392  * First 18 bytes of the sense data are preset to current valid sense
16393  * with a key NO SENSE data.
16394  *
16395  * Returns void
16396  */
16397 static void
16398 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
16399 {
16400 	sense->es_valid = 1;		/* Valid sense */
16401 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
16402 	sense->es_key = KEY_NO_SENSE;
16403 	sense->es_info_1 = 0;
16404 	sense->es_info_2 = 0;
16405 	sense->es_info_3 = 0;
16406 	sense->es_info_4 = 0;
16407 	sense->es_add_len = 10;	/* Additional length - replace with a def */
16408 	sense->es_cmd_info[0] = 0;
16409 	sense->es_cmd_info[1] = 0;
16410 	sense->es_cmd_info[2] = 0;
16411 	sense->es_cmd_info[3] = 0;
16412 	sense->es_add_code = 0;
16413 	sense->es_qual_code = 0;
16414 }
16415 
16416 /*
16417  * Register a legacy cmdk-style devid for the target (disk) device.
16418  *
16419  * Note: This function is called only when the HBA devinfo node has the
16420  * property "use-cmdk-devid-format" set. This property indicates that
16421  * devid compatible with old cmdk (target) driver is to be generated
16422  * for any target device attached to this controller. This will take
16423  * precedence over the devid generated by sd (target) driver.
16424  * This function is derived from cmdk_devid_setup() function in cmdk.c.
16425  */
16426 static void
16427 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
16428 {
16429 	char	*hwid;
16430 	int	modlen;
16431 	int	serlen;
16432 	int	rval;
16433 	ddi_devid_t	devid;
16434 
16435 	/*
16436 	 * device ID is a concatanation of model number, "=", serial number.
16437 	 */
16438 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
16439 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
16440 	    sizeof (sdinfo->satadrv_id.ai_model));
16441 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
16442 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
16443 	if (modlen == 0)
16444 		goto err;
16445 	hwid[modlen++] = '=';
16446 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
16447 	    sizeof (sdinfo->satadrv_id.ai_drvser));
16448 	swab(&hwid[modlen], &hwid[modlen],
16449 	    sizeof (sdinfo->satadrv_id.ai_drvser));
16450 	serlen = sata_check_modser(&hwid[modlen],
16451 	    sizeof (sdinfo->satadrv_id.ai_drvser));
16452 	if (serlen == 0)
16453 		goto err;
16454 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
16455 
16456 	/* initialize/register devid */
16457 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
16458 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
16459 		rval = ddi_devid_register(dip, devid);
16460 		/*
16461 		 * Free up the allocated devid buffer.
16462 		 * NOTE: This doesn't mean unregistering devid.
16463 		 */
16464 		ddi_devid_free(devid);
16465 	}
16466 
16467 	if (rval != DDI_SUCCESS)
16468 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
16469 		    " on port %d", sdinfo->satadrv_addr.cport);
16470 err:
16471 	kmem_free(hwid, LEGACY_HWID_LEN);
16472 }
16473 
16474 /*
16475  * valid model/serial string must contain a non-zero non-space characters.
16476  * trim trailing spaces/NULLs.
16477  */
16478 static int
16479 sata_check_modser(char *buf, int buf_len)
16480 {
16481 	boolean_t ret;
16482 	char *s;
16483 	int i;
16484 	int tb;
16485 	char ch;
16486 
16487 	ret = B_FALSE;
16488 	s = buf;
16489 	for (i = 0; i < buf_len; i++) {
16490 		ch = *s++;
16491 		if (ch != ' ' && ch != '\0')
16492 			tb = i + 1;
16493 		if (ch != ' ' && ch != '\0' && ch != '0')
16494 			ret = B_TRUE;
16495 	}
16496 
16497 	if (ret == B_FALSE)
16498 		return (0); /* invalid string */
16499 
16500 	return (tb); /* return length */
16501 }
16502 
16503 /*
16504  * sata_set_drive_features function compares current device features setting
16505  * with the saved device features settings and, if there is a difference,
16506  * it restores device features setting to the previously saved state.
16507  * It also arbitrarily tries to select the highest supported DMA mode.
16508  * Device Identify or Identify Packet Device data has to be current.
16509  * At the moment read ahead and write cache are considered for all devices.
16510  * For atapi devices, Removable Media Status Notification is set in addition
16511  * to common features.
16512  *
16513  * This function cannot be called in the interrupt context (it may sleep).
16514  *
16515  * The input argument sdinfo should point to the drive info structure
16516  * to be updated after features are set. Note, that only
16517  * device (packet) identify data is updated, not the flags indicating the
16518  * supported features.
16519  *
16520  * Returns SATA_SUCCESS if successful or there was nothing to do.
16521  * Device Identify data in the drive info structure pointed to by the sdinfo
16522  * arguments is updated even when no features were set or changed.
16523  *
16524  * Returns SATA_FAILURE if device features could not be set or DMA mode
16525  * for a disk cannot be set and device identify data cannot be fetched.
16526  *
16527  * Returns SATA_RETRY if device features could not be set (other than disk
16528  * DMA mode) but the device identify data was fetched successfully.
16529  *
16530  * Note: This function may fail the port, making it inaccessible.
16531  * In such case the explicit port disconnect/connect or physical device
16532  * detach/attach is required to re-evaluate port state again.
16533  */
16534 
16535 static int
16536 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
16537     sata_drive_info_t *sdinfo, int restore)
16538 {
16539 	int rval = SATA_SUCCESS;
16540 	int rval_set;
16541 	sata_drive_info_t new_sdinfo;
16542 	char *finfo = "sata_set_drive_features: cannot";
16543 	char *finfox;
16544 	int cache_op;
16545 
16546 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
16547 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
16548 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
16549 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
16550 		/*
16551 		 * Cannot get device identification - caller may retry later
16552 		 */
16553 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16554 		    "%s fetch device identify data\n", finfo);
16555 		return (SATA_FAILURE);
16556 	}
16557 	finfox = (restore != 0) ? " restore device features" :
16558 	    " initialize device features\n";
16559 
16560 	switch (sdinfo->satadrv_type) {
16561 	case SATA_DTYPE_ATADISK:
16562 		/* Arbitrarily set UDMA mode */
16563 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
16564 		    SATA_SUCCESS) {
16565 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16566 			    "%s set UDMA mode\n", finfo));
16567 			return (SATA_FAILURE);
16568 		}
16569 		break;
16570 	case SATA_DTYPE_ATAPICD:
16571 	case SATA_DTYPE_ATAPITAPE:
16572 	case SATA_DTYPE_ATAPIDISK:
16573 		/*  Set Removable Media Status Notification, if necessary */
16574 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
16575 		    restore != 0) {
16576 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
16577 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
16578 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
16579 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
16580 				/* Current setting does not match saved one */
16581 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
16582 				    sdinfo->satadrv_settings &
16583 				    SATA_DEV_RMSN) != SATA_SUCCESS)
16584 					rval = SATA_FAILURE;
16585 			}
16586 		}
16587 		/*
16588 		 * We have to set Multiword DMA or UDMA, if it is supported, as
16589 		 * we want to use DMA transfer mode whenever possible.
16590 		 * Some devices require explicit setting of the DMA mode.
16591 		 */
16592 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
16593 			/* Set highest supported DMA mode */
16594 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
16595 			    SATA_SUCCESS) {
16596 				SATA_LOG_D((sata_hba_inst, CE_WARN,
16597 				    "%s set UDMA mode\n", finfo));
16598 				rval = SATA_FAILURE;
16599 			}
16600 		}
16601 		break;
16602 	}
16603 
16604 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
16605 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
16606 		/*
16607 		 * neither READ AHEAD nor WRITE CACHE is supported
16608 		 * - do nothing
16609 		 */
16610 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16611 		    "settable features not supported\n", NULL);
16612 		goto update_sdinfo;
16613 	}
16614 
16615 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
16616 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
16617 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
16618 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
16619 		/*
16620 		 * both READ AHEAD and WRITE CACHE are enabled
16621 		 * - Nothing to do
16622 		 */
16623 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16624 		    "no device features to set\n", NULL);
16625 		goto update_sdinfo;
16626 	}
16627 
16628 	cache_op = 0;
16629 
16630 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
16631 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
16632 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
16633 			/* Enable read ahead / read cache */
16634 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
16635 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16636 			    "enabling read cache\n", NULL);
16637 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
16638 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
16639 			/* Disable read ahead  / read cache */
16640 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
16641 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16642 			    "disabling read cache\n", NULL);
16643 		}
16644 
16645 		if (cache_op != 0) {
16646 			/* Try to set read cache mode */
16647 			rval_set = sata_set_cache_mode(sata_hba_inst,
16648 			    &new_sdinfo, cache_op);
16649 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
16650 				rval = rval_set;
16651 		}
16652 	}
16653 
16654 	cache_op = 0;
16655 
16656 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
16657 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
16658 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
16659 			/* Enable write cache */
16660 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
16661 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16662 			    "enabling write cache\n", NULL);
16663 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
16664 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
16665 			/* Disable write cache */
16666 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
16667 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16668 			    "disabling write cache\n", NULL);
16669 		}
16670 
16671 		if (cache_op != 0) {
16672 			/* Try to set write cache mode */
16673 			rval_set = sata_set_cache_mode(sata_hba_inst,
16674 			    &new_sdinfo, cache_op);
16675 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
16676 				rval = rval_set;
16677 		}
16678 	}
16679 	if (rval != SATA_SUCCESS)
16680 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16681 		    "%s %s", finfo, finfox));
16682 
16683 update_sdinfo:
16684 	/*
16685 	 * We need to fetch Device Identify data again
16686 	 */
16687 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
16688 		/*
16689 		 * Cannot get device identification - retry later
16690 		 */
16691 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16692 		    "%s re-fetch device identify data\n", finfo));
16693 		rval = SATA_FAILURE;
16694 	}
16695 	/* Copy device sata info. */
16696 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
16697 
16698 	return (rval);
16699 }
16700 
16701 
16702 /*
16703  *
16704  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
16705  * unable to determine.
16706  *
16707  * Cannot be called in an interrupt context.
16708  *
16709  * Called by sata_build_lsense_page_2f()
16710  */
16711 
16712 static int
16713 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
16714     sata_drive_info_t *sdinfo)
16715 {
16716 	sata_pkt_t *spkt;
16717 	sata_cmd_t *scmd;
16718 	sata_pkt_txlate_t *spx;
16719 	int rval;
16720 
16721 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16722 	spx->txlt_sata_hba_inst = sata_hba_inst;
16723 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16724 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16725 	if (spkt == NULL) {
16726 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16727 		return (-1);
16728 	}
16729 	/* address is needed now */
16730 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16731 
16732 
16733 	/* Fill sata_pkt */
16734 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16735 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16736 	/* Synchronous mode, no callback */
16737 	spkt->satapkt_comp = NULL;
16738 	/* Timeout 30s */
16739 	spkt->satapkt_time = sata_default_pkt_time;
16740 
16741 	scmd = &spkt->satapkt_cmd;
16742 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
16743 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
16744 
16745 	/* Set up which registers need to be returned */
16746 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
16747 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
16748 
16749 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
16750 	scmd->satacmd_addr_type = 0;		/* N/A */
16751 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16752 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16753 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16754 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16755 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
16756 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16757 	scmd->satacmd_cmd_reg = SATAC_SMART;
16758 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16759 	    sdinfo->satadrv_addr.cport)));
16760 
16761 
16762 	/* Send pkt to SATA HBA driver */
16763 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16764 	    SATA_TRAN_ACCEPTED ||
16765 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16766 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16767 		    sdinfo->satadrv_addr.cport)));
16768 		/*
16769 		 * Whoops, no SMART RETURN STATUS
16770 		 */
16771 		rval = -1;
16772 	} else {
16773 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16774 		    sdinfo->satadrv_addr.cport)));
16775 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
16776 			rval = -1;
16777 			goto fail;
16778 		}
16779 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
16780 			rval = -1;
16781 			goto fail;
16782 		}
16783 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
16784 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
16785 			rval = 0;
16786 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
16787 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
16788 			rval = 1;
16789 		else {
16790 			rval = -1;
16791 			goto fail;
16792 		}
16793 	}
16794 fail:
16795 	/* Free allocated resources */
16796 	sata_pkt_free(spx);
16797 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16798 
16799 	return (rval);
16800 }
16801 
16802 /*
16803  *
16804  * Returns 0 if succeeded, -1 otherwise
16805  *
16806  * Cannot be called in an interrupt context.
16807  *
16808  */
16809 static int
16810 sata_fetch_smart_data(
16811 	sata_hba_inst_t *sata_hba_inst,
16812 	sata_drive_info_t *sdinfo,
16813 	struct smart_data *smart_data)
16814 {
16815 	sata_pkt_t *spkt;
16816 	sata_cmd_t *scmd;
16817 	sata_pkt_txlate_t *spx;
16818 	int rval;
16819 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
16820 
16821 #if ! defined(lint)
16822 	ASSERT(sizeof (struct smart_data) == 512);
16823 #endif
16824 
16825 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16826 	spx->txlt_sata_hba_inst = sata_hba_inst;
16827 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16828 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16829 	if (spkt == NULL) {
16830 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16831 		return (-1);
16832 	}
16833 	/* address is needed now */
16834 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16835 
16836 
16837 	/* Fill sata_pkt */
16838 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16839 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16840 	/* Synchronous mode, no callback */
16841 	spkt->satapkt_comp = NULL;
16842 	/* Timeout 30s */
16843 	spkt->satapkt_time = sata_default_pkt_time;
16844 
16845 	scmd = &spkt->satapkt_cmd;
16846 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16847 
16848 	/*
16849 	 * Allocate buffer for SMART data
16850 	 */
16851 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16852 	    sizeof (struct smart_data));
16853 	if (scmd->satacmd_bp == NULL) {
16854 		sata_pkt_free(spx);
16855 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16856 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16857 		    "sata_fetch_smart_data: "
16858 		    "cannot allocate buffer"));
16859 		return (-1);
16860 	}
16861 
16862 
16863 	/* Build SMART_READ_DATA cmd in the sata_pkt */
16864 	scmd->satacmd_addr_type = 0;		/* N/A */
16865 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16866 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16867 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16868 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16869 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
16870 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16871 	scmd->satacmd_cmd_reg = SATAC_SMART;
16872 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16873 	    sdinfo->satadrv_addr.cport)));
16874 
16875 	/* Send pkt to SATA HBA driver */
16876 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16877 	    SATA_TRAN_ACCEPTED ||
16878 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16879 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16880 		    sdinfo->satadrv_addr.cport)));
16881 		/*
16882 		 * Whoops, no SMART DATA available
16883 		 */
16884 		rval = -1;
16885 		goto fail;
16886 	} else {
16887 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16888 		    sdinfo->satadrv_addr.cport)));
16889 		if (spx->txlt_buf_dma_handle != NULL) {
16890 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16891 			    DDI_DMA_SYNC_FORKERNEL);
16892 			ASSERT(rval == DDI_SUCCESS);
16893 			if (sata_check_for_dma_error(dip, spx)) {
16894 				ddi_fm_service_impact(dip,
16895 				    DDI_SERVICE_UNAFFECTED);
16896 				rval = -1;
16897 				goto fail;
16898 			}
16899 		}
16900 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
16901 		    sizeof (struct smart_data));
16902 	}
16903 
16904 fail:
16905 	/* Free allocated resources */
16906 	sata_free_local_buffer(spx);
16907 	sata_pkt_free(spx);
16908 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16909 
16910 	return (rval);
16911 }
16912 
16913 /*
16914  * Used by LOG SENSE page 0x10
16915  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
16916  * Note: cannot be called in the interrupt context.
16917  *
16918  * return 0 for success, -1 otherwise
16919  *
16920  */
16921 static int
16922 sata_ext_smart_selftest_read_log(
16923 	sata_hba_inst_t *sata_hba_inst,
16924 	sata_drive_info_t *sdinfo,
16925 	struct smart_ext_selftest_log *ext_selftest_log,
16926 	uint16_t block_num)
16927 {
16928 	sata_pkt_txlate_t *spx;
16929 	sata_pkt_t *spkt;
16930 	sata_cmd_t *scmd;
16931 	int rval;
16932 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
16933 
16934 #if ! defined(lint)
16935 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
16936 #endif
16937 
16938 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16939 	spx->txlt_sata_hba_inst = sata_hba_inst;
16940 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16941 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16942 	if (spkt == NULL) {
16943 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16944 		return (-1);
16945 	}
16946 	/* address is needed now */
16947 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16948 
16949 
16950 	/* Fill sata_pkt */
16951 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16952 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16953 	/* Synchronous mode, no callback */
16954 	spkt->satapkt_comp = NULL;
16955 	/* Timeout 30s */
16956 	spkt->satapkt_time = sata_default_pkt_time;
16957 
16958 	scmd = &spkt->satapkt_cmd;
16959 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16960 
16961 	/*
16962 	 * Allocate buffer for SMART extended self-test log
16963 	 */
16964 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16965 	    sizeof (struct smart_ext_selftest_log));
16966 	if (scmd->satacmd_bp == NULL) {
16967 		sata_pkt_free(spx);
16968 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16969 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16970 		    "sata_ext_smart_selftest_log: "
16971 		    "cannot allocate buffer"));
16972 		return (-1);
16973 	}
16974 
16975 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
16976 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16977 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
16978 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
16979 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
16980 	scmd->satacmd_lba_low_msb = 0;
16981 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
16982 	scmd->satacmd_lba_mid_msb = block_num >> 8;
16983 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16984 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16985 
16986 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16987 	    sdinfo->satadrv_addr.cport)));
16988 
16989 	/* Send pkt to SATA HBA driver */
16990 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16991 	    SATA_TRAN_ACCEPTED ||
16992 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16993 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16994 		    sdinfo->satadrv_addr.cport)));
16995 
16996 		/*
16997 		 * Whoops, no SMART selftest log info available
16998 		 */
16999 		rval = -1;
17000 		goto fail;
17001 	} else {
17002 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17003 		    sdinfo->satadrv_addr.cport)));
17004 
17005 		if (spx->txlt_buf_dma_handle != NULL) {
17006 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
17007 			    DDI_DMA_SYNC_FORKERNEL);
17008 			ASSERT(rval == DDI_SUCCESS);
17009 			if (sata_check_for_dma_error(dip, spx)) {
17010 				ddi_fm_service_impact(dip,
17011 				    DDI_SERVICE_UNAFFECTED);
17012 				rval = -1;
17013 				goto fail;
17014 			}
17015 		}
17016 		bcopy(scmd->satacmd_bp->b_un.b_addr,
17017 		    (uint8_t *)ext_selftest_log,
17018 		    sizeof (struct smart_ext_selftest_log));
17019 		rval = 0;
17020 	}
17021 
17022 fail:
17023 	/* Free allocated resources */
17024 	sata_free_local_buffer(spx);
17025 	sata_pkt_free(spx);
17026 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
17027 
17028 	return (rval);
17029 }
17030 
17031 /*
17032  * Returns 0 for success, -1 otherwise
17033  *
17034  * SMART self-test log data is returned in buffer pointed to by selftest_log
17035  */
17036 static int
17037 sata_smart_selftest_log(
17038 	sata_hba_inst_t *sata_hba_inst,
17039 	sata_drive_info_t *sdinfo,
17040 	struct smart_selftest_log *selftest_log)
17041 {
17042 	sata_pkt_t *spkt;
17043 	sata_cmd_t *scmd;
17044 	sata_pkt_txlate_t *spx;
17045 	int rval;
17046 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
17047 
17048 #if ! defined(lint)
17049 	ASSERT(sizeof (struct smart_selftest_log) == 512);
17050 #endif
17051 
17052 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
17053 	spx->txlt_sata_hba_inst = sata_hba_inst;
17054 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
17055 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
17056 	if (spkt == NULL) {
17057 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
17058 		return (-1);
17059 	}
17060 	/* address is needed now */
17061 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
17062 
17063 
17064 	/* Fill sata_pkt */
17065 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
17066 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
17067 	/* Synchronous mode, no callback */
17068 	spkt->satapkt_comp = NULL;
17069 	/* Timeout 30s */
17070 	spkt->satapkt_time = sata_default_pkt_time;
17071 
17072 	scmd = &spkt->satapkt_cmd;
17073 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
17074 
17075 	/*
17076 	 * Allocate buffer for SMART SELFTEST LOG
17077 	 */
17078 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
17079 	    sizeof (struct smart_selftest_log));
17080 	if (scmd->satacmd_bp == NULL) {
17081 		sata_pkt_free(spx);
17082 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
17083 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17084 		    "sata_smart_selftest_log: "
17085 		    "cannot allocate buffer"));
17086 		return (-1);
17087 	}
17088 
17089 	/* Build SMART_READ_LOG cmd in the sata_pkt */
17090 	scmd->satacmd_addr_type = 0;		/* N/A */
17091 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
17092 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
17093 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
17094 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
17095 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
17096 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
17097 	scmd->satacmd_cmd_reg = SATAC_SMART;
17098 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
17099 	    sdinfo->satadrv_addr.cport)));
17100 
17101 	/* Send pkt to SATA HBA driver */
17102 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
17103 	    SATA_TRAN_ACCEPTED ||
17104 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
17105 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17106 		    sdinfo->satadrv_addr.cport)));
17107 		/*
17108 		 * Whoops, no SMART DATA available
17109 		 */
17110 		rval = -1;
17111 		goto fail;
17112 	} else {
17113 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17114 		    sdinfo->satadrv_addr.cport)));
17115 		if (spx->txlt_buf_dma_handle != NULL) {
17116 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
17117 			    DDI_DMA_SYNC_FORKERNEL);
17118 			ASSERT(rval == DDI_SUCCESS);
17119 			if (sata_check_for_dma_error(dip, spx)) {
17120 				ddi_fm_service_impact(dip,
17121 				    DDI_SERVICE_UNAFFECTED);
17122 				rval = -1;
17123 				goto fail;
17124 			}
17125 		}
17126 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
17127 		    sizeof (struct smart_selftest_log));
17128 		rval = 0;
17129 	}
17130 
17131 fail:
17132 	/* Free allocated resources */
17133 	sata_free_local_buffer(spx);
17134 	sata_pkt_free(spx);
17135 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
17136 
17137 	return (rval);
17138 }
17139 
17140 
17141 /*
17142  * Returns 0 for success, -1 otherwise
17143  *
17144  * SMART READ LOG data is returned in buffer pointed to by smart_log
17145  */
17146 static int
17147 sata_smart_read_log(
17148 	sata_hba_inst_t *sata_hba_inst,
17149 	sata_drive_info_t *sdinfo,
17150 	uint8_t *smart_log,		/* where the data should be returned */
17151 	uint8_t which_log,		/* which log should be returned */
17152 	uint8_t log_size)		/* # of 512 bytes in log */
17153 {
17154 	sata_pkt_t *spkt;
17155 	sata_cmd_t *scmd;
17156 	sata_pkt_txlate_t *spx;
17157 	int rval;
17158 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
17159 
17160 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
17161 	spx->txlt_sata_hba_inst = sata_hba_inst;
17162 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
17163 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
17164 	if (spkt == NULL) {
17165 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
17166 		return (-1);
17167 	}
17168 	/* address is needed now */
17169 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
17170 
17171 
17172 	/* Fill sata_pkt */
17173 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
17174 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
17175 	/* Synchronous mode, no callback */
17176 	spkt->satapkt_comp = NULL;
17177 	/* Timeout 30s */
17178 	spkt->satapkt_time = sata_default_pkt_time;
17179 
17180 	scmd = &spkt->satapkt_cmd;
17181 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
17182 
17183 	/*
17184 	 * Allocate buffer for SMART READ LOG
17185 	 */
17186 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
17187 	if (scmd->satacmd_bp == NULL) {
17188 		sata_pkt_free(spx);
17189 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
17190 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17191 		    "sata_smart_read_log: " "cannot allocate buffer"));
17192 		return (-1);
17193 	}
17194 
17195 	/* Build SMART_READ_LOG cmd in the sata_pkt */
17196 	scmd->satacmd_addr_type = 0;		/* N/A */
17197 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
17198 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
17199 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
17200 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
17201 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
17202 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
17203 	scmd->satacmd_cmd_reg = SATAC_SMART;
17204 
17205 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
17206 	    sdinfo->satadrv_addr.cport)));
17207 
17208 	/* Send pkt to SATA HBA driver */
17209 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
17210 	    SATA_TRAN_ACCEPTED ||
17211 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
17212 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17213 		    sdinfo->satadrv_addr.cport)));
17214 
17215 		/*
17216 		 * Whoops, no SMART DATA available
17217 		 */
17218 		rval = -1;
17219 		goto fail;
17220 	} else {
17221 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17222 		    sdinfo->satadrv_addr.cport)));
17223 
17224 		if (spx->txlt_buf_dma_handle != NULL) {
17225 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
17226 			    DDI_DMA_SYNC_FORKERNEL);
17227 			ASSERT(rval == DDI_SUCCESS);
17228 			if (sata_check_for_dma_error(dip, spx)) {
17229 				ddi_fm_service_impact(dip,
17230 				    DDI_SERVICE_UNAFFECTED);
17231 				rval = -1;
17232 				goto fail;
17233 			}
17234 		}
17235 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
17236 		rval = 0;
17237 	}
17238 
17239 fail:
17240 	/* Free allocated resources */
17241 	sata_free_local_buffer(spx);
17242 	sata_pkt_free(spx);
17243 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
17244 
17245 	return (rval);
17246 }
17247 
17248 /*
17249  * Used by LOG SENSE page 0x10
17250  *
17251  * return 0 for success, -1 otherwise
17252  *
17253  */
17254 static int
17255 sata_read_log_ext_directory(
17256 	sata_hba_inst_t *sata_hba_inst,
17257 	sata_drive_info_t *sdinfo,
17258 	struct read_log_ext_directory *logdir)
17259 {
17260 	sata_pkt_txlate_t *spx;
17261 	sata_pkt_t *spkt;
17262 	sata_cmd_t *scmd;
17263 	int rval;
17264 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
17265 
17266 #if ! defined(lint)
17267 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
17268 #endif
17269 
17270 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
17271 	spx->txlt_sata_hba_inst = sata_hba_inst;
17272 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
17273 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
17274 	if (spkt == NULL) {
17275 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
17276 		return (-1);
17277 	}
17278 
17279 	/* Fill sata_pkt */
17280 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
17281 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
17282 	/* Synchronous mode, no callback */
17283 	spkt->satapkt_comp = NULL;
17284 	/* Timeout 30s */
17285 	spkt->satapkt_time = sata_default_pkt_time;
17286 
17287 	scmd = &spkt->satapkt_cmd;
17288 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
17289 
17290 	/*
17291 	 * Allocate buffer for SMART READ LOG EXTENDED command
17292 	 */
17293 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
17294 	    sizeof (struct read_log_ext_directory));
17295 	if (scmd->satacmd_bp == NULL) {
17296 		sata_pkt_free(spx);
17297 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
17298 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17299 		    "sata_read_log_ext_directory: "
17300 		    "cannot allocate buffer"));
17301 		return (-1);
17302 	}
17303 
17304 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
17305 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
17306 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
17307 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
17308 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
17309 	scmd->satacmd_lba_low_msb = 0;
17310 	scmd->satacmd_lba_mid_lsb = 0;
17311 	scmd->satacmd_lba_mid_msb = 0;
17312 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
17313 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
17314 
17315 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
17316 	    sdinfo->satadrv_addr.cport)));
17317 
17318 	/* Send pkt to SATA HBA driver */
17319 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
17320 	    SATA_TRAN_ACCEPTED ||
17321 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
17322 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17323 		    sdinfo->satadrv_addr.cport)));
17324 		/*
17325 		 * Whoops, no SMART selftest log info available
17326 		 */
17327 		rval = -1;
17328 		goto fail;
17329 	} else {
17330 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
17331 		    sdinfo->satadrv_addr.cport)));
17332 		if (spx->txlt_buf_dma_handle != NULL) {
17333 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
17334 			    DDI_DMA_SYNC_FORKERNEL);
17335 			ASSERT(rval == DDI_SUCCESS);
17336 			if (sata_check_for_dma_error(dip, spx)) {
17337 				ddi_fm_service_impact(dip,
17338 				    DDI_SERVICE_UNAFFECTED);
17339 				rval = -1;
17340 				goto fail;
17341 			}
17342 		}
17343 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
17344 		    sizeof (struct read_log_ext_directory));
17345 		rval = 0;
17346 	}
17347 
17348 fail:
17349 	/* Free allocated resources */
17350 	sata_free_local_buffer(spx);
17351 	sata_pkt_free(spx);
17352 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
17353 
17354 	return (rval);
17355 }
17356 
17357 /*
17358  * Set up error retrieval sata command for NCQ command error data
17359  * recovery.
17360  *
17361  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
17362  * returns SATA_FAILURE otherwise.
17363  */
17364 static int
17365 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
17366 {
17367 #ifndef __lock_lint
17368 	_NOTE(ARGUNUSED(sdinfo))
17369 #endif
17370 
17371 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
17372 	sata_cmd_t *scmd;
17373 	struct buf *bp;
17374 
17375 	/* Operation modes are up to the caller */
17376 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
17377 
17378 	/* Synchronous mode, no callback - may be changed by the caller */
17379 	spkt->satapkt_comp = NULL;
17380 	spkt->satapkt_time = sata_default_pkt_time;
17381 
17382 	scmd = &spkt->satapkt_cmd;
17383 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
17384 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
17385 
17386 	/*
17387 	 * Allocate dma_able buffer error data.
17388 	 * Buffer allocation will take care of buffer alignment and other DMA
17389 	 * attributes.
17390 	 */
17391 	bp = sata_alloc_local_buffer(spx,
17392 	    sizeof (struct sata_ncq_error_recovery_page));
17393 	if (bp == NULL)
17394 		return (SATA_FAILURE);
17395 
17396 	bp_mapin(bp); /* make data buffer accessible */
17397 	scmd->satacmd_bp = bp;
17398 
17399 	/*
17400 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
17401 	 * before accessing it. Handle is in usual place in translate struct.
17402 	 */
17403 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
17404 
17405 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
17406 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
17407 
17408 	return (SATA_SUCCESS);
17409 }
17410 
17411 /*
17412  * sata_xlate_errors() is used to translate (S)ATA error
17413  * information to SCSI information returned in the SCSI
17414  * packet.
17415  */
17416 static void
17417 sata_xlate_errors(sata_pkt_txlate_t *spx)
17418 {
17419 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
17420 	struct scsi_extended_sense *sense;
17421 
17422 	scsipkt->pkt_reason = CMD_INCOMPLETE;
17423 	*scsipkt->pkt_scbp = STATUS_CHECK;
17424 	sense = sata_arq_sense(spx);
17425 
17426 	switch (spx->txlt_sata_pkt->satapkt_reason) {
17427 	case SATA_PKT_PORT_ERROR:
17428 		/*
17429 		 * We have no device data. Assume no data transfered.
17430 		 */
17431 		sense->es_key = KEY_HARDWARE_ERROR;
17432 		break;
17433 
17434 	case SATA_PKT_DEV_ERROR:
17435 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
17436 		    SATA_STATUS_ERR) {
17437 			/*
17438 			 * determine dev error reason from error
17439 			 * reg content
17440 			 */
17441 			sata_decode_device_error(spx, sense);
17442 			break;
17443 		}
17444 		/* No extended sense key - no info available */
17445 		break;
17446 
17447 	case SATA_PKT_TIMEOUT:
17448 		scsipkt->pkt_reason = CMD_TIMEOUT;
17449 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
17450 		/* No extended sense key */
17451 		break;
17452 
17453 	case SATA_PKT_ABORTED:
17454 		scsipkt->pkt_reason = CMD_ABORTED;
17455 		scsipkt->pkt_statistics |= STAT_ABORTED;
17456 		/* No extended sense key */
17457 		break;
17458 
17459 	case SATA_PKT_RESET:
17460 		/*
17461 		 * pkt aborted either by an explicit reset request from
17462 		 * a host, or due to error recovery
17463 		 */
17464 		scsipkt->pkt_reason = CMD_RESET;
17465 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
17466 		break;
17467 
17468 	default:
17469 		scsipkt->pkt_reason = CMD_TRAN_ERR;
17470 		break;
17471 	}
17472 }
17473 
17474 
17475 
17476 
17477 /*
17478  * Log sata message
17479  * dev pathname msg line preceeds the logged message.
17480  */
17481 
17482 static	void
17483 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
17484 {
17485 	char pathname[128];
17486 	dev_info_t *dip = NULL;
17487 	va_list ap;
17488 
17489 	mutex_enter(&sata_log_mutex);
17490 
17491 	va_start(ap, fmt);
17492 	(void) vsprintf(sata_log_buf, fmt, ap);
17493 	va_end(ap);
17494 
17495 	if (sata_hba_inst != NULL) {
17496 		dip = SATA_DIP(sata_hba_inst);
17497 		(void) ddi_pathname(dip, pathname);
17498 	} else {
17499 		pathname[0] = 0;
17500 	}
17501 	if (level == CE_CONT) {
17502 		if (sata_debug_flags == 0)
17503 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
17504 		else
17505 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
17506 	} else {
17507 		if (level != CE_NOTE) {
17508 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
17509 		} else if (sata_msg) {
17510 			cmn_err(level, "%s:\n %s", pathname,
17511 			    sata_log_buf);
17512 		}
17513 	}
17514 
17515 	/* sata trace debug */
17516 	sata_trace_debug(dip, sata_log_buf);
17517 
17518 	mutex_exit(&sata_log_mutex);
17519 }
17520 
17521 
17522 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
17523 
17524 /*
17525  * Start or terminate the thread, depending on flag arg and current state
17526  */
17527 static void
17528 sata_event_thread_control(int startstop)
17529 {
17530 	static 	int sata_event_thread_terminating = 0;
17531 	static 	int sata_event_thread_starting = 0;
17532 	int i;
17533 
17534 	mutex_enter(&sata_event_mutex);
17535 
17536 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
17537 	    sata_event_thread_terminating == 1)) {
17538 		mutex_exit(&sata_event_mutex);
17539 		return;
17540 	}
17541 	if (startstop == 1 && sata_event_thread_starting == 1) {
17542 		mutex_exit(&sata_event_mutex);
17543 		return;
17544 	}
17545 	if (startstop == 1 && sata_event_thread_terminating == 1) {
17546 		sata_event_thread_starting = 1;
17547 		/* wait til terminate operation completes */
17548 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
17549 		while (sata_event_thread_terminating == 1) {
17550 			if (i-- <= 0) {
17551 				sata_event_thread_starting = 0;
17552 				mutex_exit(&sata_event_mutex);
17553 #ifdef SATA_DEBUG
17554 				cmn_err(CE_WARN, "sata_event_thread_control: "
17555 				    "timeout waiting for thread to terminate");
17556 #endif
17557 				return;
17558 			}
17559 			mutex_exit(&sata_event_mutex);
17560 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
17561 			mutex_enter(&sata_event_mutex);
17562 		}
17563 	}
17564 	if (startstop == 1) {
17565 		if (sata_event_thread == NULL) {
17566 			sata_event_thread = thread_create(NULL, 0,
17567 			    (void (*)())sata_event_daemon,
17568 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
17569 		}
17570 		sata_event_thread_starting = 0;
17571 		mutex_exit(&sata_event_mutex);
17572 		return;
17573 	}
17574 
17575 	/*
17576 	 * If we got here, thread may need to be terminated
17577 	 */
17578 	if (sata_event_thread != NULL) {
17579 		int i;
17580 		/* Signal event thread to go away */
17581 		sata_event_thread_terminating = 1;
17582 		sata_event_thread_terminate = 1;
17583 		cv_signal(&sata_event_cv);
17584 		/*
17585 		 * Wait til daemon terminates.
17586 		 */
17587 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
17588 		while (sata_event_thread_terminate == 1) {
17589 			mutex_exit(&sata_event_mutex);
17590 			if (i-- <= 0) {
17591 				/* Daemon did not go away !!! */
17592 #ifdef SATA_DEBUG
17593 				cmn_err(CE_WARN, "sata_event_thread_control: "
17594 				    "cannot terminate event daemon thread");
17595 #endif
17596 				mutex_enter(&sata_event_mutex);
17597 				break;
17598 			}
17599 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
17600 			mutex_enter(&sata_event_mutex);
17601 		}
17602 		sata_event_thread_terminating = 0;
17603 	}
17604 	ASSERT(sata_event_thread_terminating == 0);
17605 	ASSERT(sata_event_thread_starting == 0);
17606 	mutex_exit(&sata_event_mutex);
17607 }
17608 
17609 
17610 /*
17611  * SATA HBA event notification function.
17612  * Events reported by SATA HBA drivers per HBA instance relate to a change in
17613  * a port and/or device state or a controller itself.
17614  * Events for different addresses/addr types cannot be combined.
17615  * A warning message is generated for each event type.
17616  * Events are not processed by this function, so only the
17617  * event flag(s)is set for an affected entity and the event thread is
17618  * waken up. Event daemon thread processes all events.
17619  *
17620  * NOTE: Since more than one event may be reported at the same time, one
17621  * cannot determine a sequence of events when opposite event are reported, eg.
17622  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
17623  * is taking precedence over reported events, i.e. may cause ignoring some
17624  * events.
17625  */
17626 #define	SATA_EVENT_MAX_MSG_LENGTH	79
17627 
17628 void
17629 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
17630 {
17631 	sata_hba_inst_t *sata_hba_inst = NULL;
17632 	sata_address_t *saddr;
17633 	sata_pmult_info_t *pmultinfo;
17634 	sata_drive_info_t *sdinfo;
17635 	sata_port_stats_t *pstats;
17636 	sata_cport_info_t *cportinfo;
17637 	sata_pmport_info_t *pmportinfo;
17638 	int cport, pmport;
17639 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
17640 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
17641 	char *lcp;
17642 	static char *err_msg_evnt_1 =
17643 	    "sata_hba_event_notify: invalid port event 0x%x ";
17644 	static char *err_msg_evnt_2 =
17645 	    "sata_hba_event_notify: invalid device event 0x%x ";
17646 	int linkevent;
17647 
17648 	/*
17649 	 * There is a possibility that an event will be generated on HBA
17650 	 * that has not completed attachment or is detaching. We still want
17651 	 * to process events until HBA is detached.
17652 	 */
17653 	mutex_enter(&sata_mutex);
17654 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17655 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17656 		if (SATA_DIP(sata_hba_inst) == dip)
17657 			if (sata_hba_inst->satahba_attached == 1)
17658 				break;
17659 	}
17660 	mutex_exit(&sata_mutex);
17661 	if (sata_hba_inst == NULL)
17662 		/* HBA not attached */
17663 		return;
17664 
17665 	ASSERT(sata_device != NULL);
17666 
17667 	/*
17668 	 * Validate address before - do not proceed with invalid address.
17669 	 */
17670 	saddr = &sata_device->satadev_addr;
17671 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
17672 		return;
17673 
17674 	cport = saddr->cport;
17675 	pmport = saddr->pmport;
17676 
17677 	buf1[0] = buf2[0] = '\0';
17678 
17679 	/*
17680 	 * If event relates to port or device, check port state.
17681 	 * Port has to be initialized, or we cannot accept an event.
17682 	 */
17683 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
17684 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT | SATA_ADDR_PMULT)) != 0) {
17685 		mutex_enter(&sata_hba_inst->satahba_mutex);
17686 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17687 		mutex_exit(&sata_hba_inst->satahba_mutex);
17688 		if (cportinfo == NULL || cportinfo->cport_state == 0)
17689 			return;
17690 	}
17691 
17692 	if ((saddr->qual & (SATA_ADDR_PMULT | SATA_ADDR_PMPORT |
17693 	    SATA_ADDR_DPMPORT)) != 0) {
17694 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
17695 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17696 			    "sata_hba_event_notify: Non-pmult device (0x%x)"
17697 			    "is attached to port %d, ignore pmult/pmport "
17698 			    "event 0x%x", cportinfo->cport_dev_type,
17699 			    cport, event));
17700 			return;
17701 		}
17702 
17703 		mutex_enter(&cportinfo->cport_mutex);
17704 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17705 		mutex_exit(&cportinfo->cport_mutex);
17706 
17707 		/*
17708 		 * The daemon might be processing attachment of port
17709 		 * multiplier, in that case we should ignore events on its
17710 		 * sub-devices.
17711 		 *
17712 		 * NOTE: Only pmult_state is checked in sata_hba_event_notify.
17713 		 * The pmport_state is checked by sata daemon.
17714 		 */
17715 		if (pmultinfo == NULL ||
17716 		    pmultinfo->pmult_state == SATA_STATE_UNKNOWN) {
17717 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17718 			    "sata_hba_event_notify: pmult is not"
17719 			    "available at port %d:%d, ignore event 0x%x",
17720 			    cport, pmport, event));
17721 			return;
17722 		}
17723 	}
17724 
17725 	if ((saddr->qual &
17726 	    (SATA_ADDR_PMPORT | SATA_ADDR_DPMPORT)) != 0) {
17727 
17728 		mutex_enter(&cportinfo->cport_mutex);
17729 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport)) {
17730 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17731 			    "sata_hba_event_notify: invalid/"
17732 			    "un-implemented port %d:%d (%d ports), "
17733 			    "ignore event 0x%x", cport, pmport,
17734 			    SATA_NUM_PMPORTS(sata_hba_inst, cport), event));
17735 			mutex_exit(&cportinfo->cport_mutex);
17736 			return;
17737 		}
17738 		mutex_exit(&cportinfo->cport_mutex);
17739 
17740 		mutex_enter(&sata_hba_inst->satahba_mutex);
17741 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17742 		    cport, pmport);
17743 		mutex_exit(&sata_hba_inst->satahba_mutex);
17744 
17745 		/* pmport is implemented/valid? */
17746 		if (pmportinfo == NULL) {
17747 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17748 			    "sata_hba_event_notify: invalid/"
17749 			    "un-implemented port %d:%d, ignore "
17750 			    "event 0x%x", cport, pmport, event));
17751 			return;
17752 		}
17753 	}
17754 
17755 	/*
17756 	 * Events refer to devices, ports and controllers - each has
17757 	 * unique address. Events for different addresses cannot be combined.
17758 	 */
17759 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
17760 
17761 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17762 
17763 		/* qualify this event(s) */
17764 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
17765 			/* Invalid event for the device port */
17766 			(void) sprintf(buf2, err_msg_evnt_1,
17767 			    event & SATA_EVNT_PORT_EVENTS);
17768 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17769 			goto event_info;
17770 		}
17771 		if (saddr->qual == SATA_ADDR_CPORT) {
17772 			/* Controller's device port event */
17773 
17774 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
17775 			    cport_event_flags |=
17776 			    event & SATA_EVNT_PORT_EVENTS;
17777 			pstats =
17778 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
17779 			    cport_stats;
17780 		} else {
17781 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17782 			mutex_enter(&pmportinfo->pmport_mutex);
17783 			/* Port multiplier's device port event */
17784 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17785 			    pmport_event_flags |=
17786 			    event & SATA_EVNT_PORT_EVENTS;
17787 			pstats =
17788 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17789 			    pmport_stats;
17790 			mutex_exit(&pmportinfo->pmport_mutex);
17791 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17792 		}
17793 
17794 		/*
17795 		 * Add to statistics and log the message. We have to do it
17796 		 * here rather than in the event daemon, because there may be
17797 		 * multiple events occuring before they are processed.
17798 		 */
17799 		linkevent = event &
17800 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
17801 		if (linkevent) {
17802 			if (linkevent == (SATA_EVNT_LINK_LOST |
17803 			    SATA_EVNT_LINK_ESTABLISHED)) {
17804 				/* This is likely event combination */
17805 				(void) strlcat(buf1, "link lost/established, ",
17806 				    SATA_EVENT_MAX_MSG_LENGTH);
17807 
17808 				if (pstats->link_lost < 0xffffffffffffffffULL)
17809 					pstats->link_lost++;
17810 				if (pstats->link_established <
17811 				    0xffffffffffffffffULL)
17812 					pstats->link_established++;
17813 				linkevent = 0;
17814 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
17815 				(void) strlcat(buf1, "link lost, ",
17816 				    SATA_EVENT_MAX_MSG_LENGTH);
17817 
17818 				if (pstats->link_lost < 0xffffffffffffffffULL)
17819 					pstats->link_lost++;
17820 			} else {
17821 				(void) strlcat(buf1, "link established, ",
17822 				    SATA_EVENT_MAX_MSG_LENGTH);
17823 				if (pstats->link_established <
17824 				    0xffffffffffffffffULL)
17825 					pstats->link_established++;
17826 			}
17827 		}
17828 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
17829 			(void) strlcat(buf1, "device attached, ",
17830 			    SATA_EVENT_MAX_MSG_LENGTH);
17831 			if (pstats->device_attached < 0xffffffffffffffffULL)
17832 				pstats->device_attached++;
17833 		}
17834 		if (event & SATA_EVNT_DEVICE_DETACHED) {
17835 			(void) strlcat(buf1, "device detached, ",
17836 			    SATA_EVENT_MAX_MSG_LENGTH);
17837 			if (pstats->device_detached < 0xffffffffffffffffULL)
17838 				pstats->device_detached++;
17839 		}
17840 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
17841 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17842 			    "port %d power level changed", cport);
17843 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
17844 				pstats->port_pwr_changed++;
17845 		}
17846 
17847 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
17848 			/* There should be no other events for this address */
17849 			(void) sprintf(buf2, err_msg_evnt_1,
17850 			    event & ~SATA_EVNT_PORT_EVENTS);
17851 		}
17852 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17853 
17854 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
17855 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17856 
17857 		/* qualify this event */
17858 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
17859 			/* Invalid event for a device */
17860 			(void) sprintf(buf2, err_msg_evnt_2,
17861 			    event & SATA_EVNT_DEVICE_RESET);
17862 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17863 			goto event_info;
17864 		}
17865 		/* drive event */
17866 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
17867 		if (sdinfo != NULL) {
17868 			if (event & SATA_EVNT_DEVICE_RESET) {
17869 				(void) strlcat(buf1, "device reset, ",
17870 				    SATA_EVENT_MAX_MSG_LENGTH);
17871 				if (sdinfo->satadrv_stats.drive_reset <
17872 				    0xffffffffffffffffULL)
17873 					sdinfo->satadrv_stats.drive_reset++;
17874 				sdinfo->satadrv_event_flags |=
17875 				    SATA_EVNT_DEVICE_RESET;
17876 			}
17877 		}
17878 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
17879 			/* Invalid event for a device */
17880 			(void) sprintf(buf2, err_msg_evnt_2,
17881 			    event & ~SATA_EVNT_DRIVE_EVENTS);
17882 		}
17883 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17884 	} else if (saddr->qual == SATA_ADDR_PMULT) {
17885 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17886 
17887 		/* qualify this event */
17888 		if ((event & (SATA_EVNT_DEVICE_RESET |
17889 		    SATA_EVNT_PMULT_LINK_CHANGED)) == 0) {
17890 			/* Invalid event for a port multiplier */
17891 			(void) sprintf(buf2, err_msg_evnt_2,
17892 			    event & SATA_EVNT_DEVICE_RESET);
17893 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17894 			goto event_info;
17895 		}
17896 
17897 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17898 
17899 		if (event & SATA_EVNT_DEVICE_RESET) {
17900 
17901 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17902 			    "[Reset] port-mult on cport %d", cport);
17903 			pmultinfo->pmult_event_flags |=
17904 			    SATA_EVNT_DEVICE_RESET;
17905 			(void) strlcat(buf1, "pmult reset, ",
17906 			    SATA_EVENT_MAX_MSG_LENGTH);
17907 		}
17908 
17909 		if (event & SATA_EVNT_PMULT_LINK_CHANGED) {
17910 
17911 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17912 			    "pmult link changed on cport %d", cport);
17913 			pmultinfo->pmult_event_flags |=
17914 			    SATA_EVNT_PMULT_LINK_CHANGED;
17915 			(void) strlcat(buf1, "pmult link changed, ",
17916 			    SATA_EVENT_MAX_MSG_LENGTH);
17917 		}
17918 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17919 
17920 	} else {
17921 		if (saddr->qual != SATA_ADDR_NULL) {
17922 			/* Wrong address qualifier */
17923 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17924 			    "sata_hba_event_notify: invalid address 0x%x",
17925 			    *(uint32_t *)saddr));
17926 			return;
17927 		}
17928 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
17929 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
17930 			/* Invalid event for the controller */
17931 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17932 			    "sata_hba_event_notify: invalid event 0x%x for "
17933 			    "controller",
17934 			    event & SATA_EVNT_CONTROLLER_EVENTS));
17935 			return;
17936 		}
17937 		buf1[0] = '\0';
17938 		/* This may be a frequent and not interesting event */
17939 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17940 		    "controller power level changed\n", NULL);
17941 
17942 		mutex_enter(&sata_hba_inst->satahba_mutex);
17943 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
17944 		    0xffffffffffffffffULL)
17945 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
17946 
17947 		sata_hba_inst->satahba_event_flags |=
17948 		    SATA_EVNT_PWR_LEVEL_CHANGED;
17949 		mutex_exit(&sata_hba_inst->satahba_mutex);
17950 	}
17951 	/*
17952 	 * If we got here, there is something to do with this HBA
17953 	 * instance.
17954 	 */
17955 	mutex_enter(&sata_hba_inst->satahba_mutex);
17956 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17957 	mutex_exit(&sata_hba_inst->satahba_mutex);
17958 	mutex_enter(&sata_mutex);
17959 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
17960 	mutex_exit(&sata_mutex);
17961 
17962 	/* Tickle event thread */
17963 	mutex_enter(&sata_event_mutex);
17964 	if (sata_event_thread_active == 0)
17965 		cv_signal(&sata_event_cv);
17966 	mutex_exit(&sata_event_mutex);
17967 
17968 event_info:
17969 	if (buf1[0] != '\0') {
17970 		lcp = strrchr(buf1, ',');
17971 		if (lcp != NULL)
17972 			*lcp = '\0';
17973 	}
17974 	if (saddr->qual == SATA_ADDR_CPORT ||
17975 	    saddr->qual == SATA_ADDR_DCPORT) {
17976 		if (buf1[0] != '\0') {
17977 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17978 			    cport, buf1);
17979 		}
17980 		if (buf2[0] != '\0') {
17981 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17982 			    cport, buf2);
17983 		}
17984 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
17985 	    saddr->qual == SATA_ADDR_DPMPORT) {
17986 		if (buf1[0] != '\0') {
17987 			sata_log(sata_hba_inst, CE_NOTE,
17988 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
17989 		}
17990 		if (buf2[0] != '\0') {
17991 			sata_log(sata_hba_inst, CE_NOTE,
17992 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
17993 		}
17994 	}
17995 }
17996 
17997 
17998 /*
17999  * Event processing thread.
18000  * Arg is a pointer to the sata_hba_list pointer.
18001  * It is not really needed, because sata_hba_list is global and static
18002  */
18003 static void
18004 sata_event_daemon(void *arg)
18005 {
18006 #ifndef __lock_lint
18007 	_NOTE(ARGUNUSED(arg))
18008 #endif
18009 	sata_hba_inst_t *sata_hba_inst;
18010 	clock_t delta;
18011 
18012 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
18013 	    "SATA event daemon started\n", NULL);
18014 loop:
18015 	/*
18016 	 * Process events here. Walk through all registered HBAs
18017 	 */
18018 	mutex_enter(&sata_mutex);
18019 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
18020 	    sata_hba_inst = sata_hba_inst->satahba_next) {
18021 		ASSERT(sata_hba_inst != NULL);
18022 		mutex_enter(&sata_hba_inst->satahba_mutex);
18023 		if (sata_hba_inst->satahba_attached == 0 ||
18024 		    (sata_hba_inst->satahba_event_flags &
18025 		    SATA_EVNT_SKIP) != 0) {
18026 			mutex_exit(&sata_hba_inst->satahba_mutex);
18027 			continue;
18028 		}
18029 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
18030 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
18031 			mutex_exit(&sata_hba_inst->satahba_mutex);
18032 			mutex_exit(&sata_mutex);
18033 			/* Got the controller with pending event */
18034 			sata_process_controller_events(sata_hba_inst);
18035 			/*
18036 			 * Since global mutex was released, there is a
18037 			 * possibility that HBA list has changed, so start
18038 			 * over from the top. Just processed controller
18039 			 * will be passed-over because of the SKIP flag.
18040 			 */
18041 			goto loop;
18042 		}
18043 		mutex_exit(&sata_hba_inst->satahba_mutex);
18044 	}
18045 	/* Clear SKIP flag in all controllers */
18046 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
18047 	    sata_hba_inst = sata_hba_inst->satahba_next) {
18048 		mutex_enter(&sata_hba_inst->satahba_mutex);
18049 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
18050 		mutex_exit(&sata_hba_inst->satahba_mutex);
18051 	}
18052 	mutex_exit(&sata_mutex);
18053 
18054 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
18055 	    "SATA EVENT DAEMON suspending itself", NULL);
18056 
18057 #ifdef SATA_DEBUG
18058 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
18059 		sata_log(sata_hba_inst, CE_WARN,
18060 		    "SATA EVENTS PROCESSING DISABLED\n");
18061 		thread_exit(); /* Daemon will not run again */
18062 	}
18063 #endif
18064 	mutex_enter(&sata_event_mutex);
18065 	sata_event_thread_active = 0;
18066 	mutex_exit(&sata_event_mutex);
18067 	/*
18068 	 * Go to sleep/suspend itself and wake up either because new event or
18069 	 * wait timeout. Exit if there is a termination request (driver
18070 	 * unload).
18071 	 */
18072 	delta = drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
18073 	do {
18074 		mutex_enter(&sata_event_mutex);
18075 		(void) cv_reltimedwait(&sata_event_cv, &sata_event_mutex,
18076 		    delta, TR_CLOCK_TICK);
18077 
18078 		if (sata_event_thread_active != 0) {
18079 			mutex_exit(&sata_event_mutex);
18080 			continue;
18081 		}
18082 
18083 		/* Check if it is time to go away */
18084 		if (sata_event_thread_terminate == 1) {
18085 			/*
18086 			 * It is up to the thread setting above flag to make
18087 			 * sure that this thread is not killed prematurely.
18088 			 */
18089 			sata_event_thread_terminate = 0;
18090 			sata_event_thread = NULL;
18091 			mutex_exit(&sata_event_mutex);
18092 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
18093 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
18094 			thread_exit();  { _NOTE(NOT_REACHED) }
18095 		}
18096 		mutex_exit(&sata_event_mutex);
18097 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
18098 
18099 	mutex_enter(&sata_event_mutex);
18100 	sata_event_thread_active = 1;
18101 	mutex_exit(&sata_event_mutex);
18102 
18103 	mutex_enter(&sata_mutex);
18104 	sata_event_pending &= ~SATA_EVNT_MAIN;
18105 	mutex_exit(&sata_mutex);
18106 
18107 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
18108 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
18109 
18110 	goto loop;
18111 }
18112 
18113 /*
18114  * Specific HBA instance event processing.
18115  *
18116  * NOTE: At the moment, device event processing is limited to hard disks
18117  * only.
18118  * Port multiplier is supported now.
18119  */
18120 static void
18121 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
18122 {
18123 	int ncport;
18124 	uint32_t event_flags;
18125 	sata_address_t *saddr;
18126 	sata_cport_info_t *cportinfo;
18127 	sata_pmult_info_t *pmultinfo;
18128 
18129 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
18130 	    "Processing controller %d event(s)",
18131 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
18132 
18133 	mutex_enter(&sata_hba_inst->satahba_mutex);
18134 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
18135 	event_flags = sata_hba_inst->satahba_event_flags;
18136 	mutex_exit(&sata_hba_inst->satahba_mutex);
18137 	/*
18138 	 * Process controller power change first
18139 	 * HERE
18140 	 */
18141 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
18142 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
18143 
18144 	/*
18145 	 * Search through ports/devices to identify affected port/device.
18146 	 * We may have to process events for more than one port/device.
18147 	 */
18148 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
18149 		/*
18150 		 * Not all ports may be processed in attach by the time we
18151 		 * get an event. Check if port info is initialized.
18152 		 */
18153 		mutex_enter(&sata_hba_inst->satahba_mutex);
18154 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
18155 		mutex_exit(&sata_hba_inst->satahba_mutex);
18156 		if (cportinfo == NULL || cportinfo->cport_state == NULL)
18157 			continue;
18158 
18159 		/* We have initialized controller port info */
18160 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
18161 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
18162 		    cport_event_flags;
18163 		/* Check if port was locked by IOCTL processing */
18164 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
18165 			/*
18166 			 * We ignore port events because port is busy
18167 			 * with AP control processing. Set again
18168 			 * controller and main event flag, so that
18169 			 * events may be processed by the next daemon
18170 			 * run.
18171 			 */
18172 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
18173 			mutex_enter(&sata_hba_inst->satahba_mutex);
18174 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18175 			mutex_exit(&sata_hba_inst->satahba_mutex);
18176 			mutex_enter(&sata_mutex);
18177 			sata_event_pending |= SATA_EVNT_MAIN;
18178 			mutex_exit(&sata_mutex);
18179 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
18180 			    "Event processing postponed until "
18181 			    "AP control processing completes",
18182 			    NULL);
18183 			/* Check other ports */
18184 			continue;
18185 		} else {
18186 			/*
18187 			 * Set BSY flag so that AP control would not
18188 			 * interfere with events processing for
18189 			 * this port.
18190 			 */
18191 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
18192 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
18193 		}
18194 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
18195 
18196 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
18197 
18198 		if ((event_flags &
18199 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
18200 			/*
18201 			 * Got port event.
18202 			 * We need some hierarchy of event processing as they
18203 			 * are affecting each other:
18204 			 * 1. port failed
18205 			 * 2. device detached/attached
18206 			 * 3. link events - link events may trigger device
18207 			 *    detached or device attached events in some
18208 			 *    circumstances.
18209 			 * 4. port power level changed
18210 			 */
18211 			if (event_flags & SATA_EVNT_PORT_FAILED) {
18212 				sata_process_port_failed_event(sata_hba_inst,
18213 				    saddr);
18214 			}
18215 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
18216 				sata_process_device_detached(sata_hba_inst,
18217 				    saddr);
18218 			}
18219 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
18220 				sata_process_device_attached(sata_hba_inst,
18221 				    saddr);
18222 			}
18223 			if (event_flags &
18224 			    (SATA_EVNT_LINK_ESTABLISHED |
18225 			    SATA_EVNT_LINK_LOST)) {
18226 				sata_process_port_link_events(sata_hba_inst,
18227 				    saddr);
18228 			}
18229 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
18230 				sata_process_port_pwr_change(sata_hba_inst,
18231 				    saddr);
18232 			}
18233 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
18234 				sata_process_target_node_cleanup(
18235 				    sata_hba_inst, saddr);
18236 			}
18237 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
18238 				sata_process_device_autoonline(
18239 				    sata_hba_inst, saddr);
18240 			}
18241 		}
18242 
18243 
18244 		/*
18245 		 * Scan port multiplier and all its sub-ports event flags.
18246 		 * The events are marked by
18247 		 * (1) sata_pmult_info.pmult_event_flags
18248 		 * (2) sata_pmport_info.pmport_event_flags
18249 		 */
18250 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
18251 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
18252 			/*
18253 			 * There should be another extra check: this
18254 			 * port multiplier still exists?
18255 			 */
18256 			pmultinfo = SATA_PMULT_INFO(sata_hba_inst,
18257 			    ncport);
18258 
18259 			if (pmultinfo != NULL) {
18260 				mutex_exit(&(SATA_CPORT_MUTEX(
18261 				    sata_hba_inst, ncport)));
18262 				sata_process_pmult_events(
18263 				    sata_hba_inst, ncport);
18264 				mutex_enter(&(SATA_CPORT_MUTEX(
18265 				    sata_hba_inst, ncport)));
18266 			} else {
18267 				SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
18268 				    "Port-multiplier is gone. "
18269 				    "Ignore all sub-device events "
18270 				    "at port %d.", ncport);
18271 			}
18272 		}
18273 
18274 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
18275 		    SATA_DTYPE_NONE) &&
18276 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
18277 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
18278 			    satadrv_event_flags &
18279 			    (SATA_EVNT_DEVICE_RESET |
18280 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
18281 				/* Have device event */
18282 				sata_process_device_reset(sata_hba_inst,
18283 				    saddr);
18284 			}
18285 		}
18286 		/* Release PORT_BUSY flag */
18287 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
18288 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
18289 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
18290 
18291 	} /* End of loop through the controller SATA ports */
18292 }
18293 
18294 /*
18295  * Specific port multiplier instance event processing. At the moment, device
18296  * event processing is limited to link/attach event only.
18297  *
18298  * NOTE: power management event is not supported yet.
18299  */
18300 static void
18301 sata_process_pmult_events(sata_hba_inst_t *sata_hba_inst, uint8_t cport)
18302 {
18303 	sata_cport_info_t *cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
18304 	sata_pmult_info_t *pmultinfo;
18305 	sata_pmport_info_t *pmportinfo;
18306 	sata_address_t *saddr;
18307 	sata_device_t sata_device;
18308 	uint32_t event_flags;
18309 	int npmport;
18310 	int rval;
18311 
18312 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
18313 	    "Processing pmult event(s) on cport %d of controller %d",
18314 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
18315 
18316 	/* First process events on port multiplier */
18317 	mutex_enter(&cportinfo->cport_mutex);
18318 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
18319 	event_flags = pmultinfo->pmult_event_flags;
18320 
18321 	/*
18322 	 * Reset event (of port multiplier) has higher priority because the
18323 	 * port multiplier itself might be failed or removed after reset.
18324 	 */
18325 	if (event_flags & SATA_EVNT_DEVICE_RESET) {
18326 		/*
18327 		 * The status of the sub-links are uncertain,
18328 		 * so mark all sub-ports as RESET
18329 		 */
18330 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(
18331 		    sata_hba_inst, cport); npmport ++) {
18332 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
18333 			    cport, npmport);
18334 			if (pmportinfo == NULL) {
18335 				/* That's weird. */
18336 				SATA_LOG_D((sata_hba_inst, CE_WARN,
18337 				    "sata_hba_event_notify: "
18338 				    "invalid/un-implemented "
18339 				    "port %d:%d (%d ports), ",
18340 				    cport, npmport, SATA_NUM_PMPORTS(
18341 				    sata_hba_inst, cport)));
18342 				continue;
18343 			}
18344 
18345 			mutex_enter(&pmportinfo->pmport_mutex);
18346 
18347 			/* Mark all pmport to unknow state. */
18348 			pmportinfo->pmport_state = SATA_STATE_UNKNOWN;
18349 			/* Mark all pmports with link events. */
18350 			pmportinfo->pmport_event_flags =
18351 			    (SATA_EVNT_LINK_ESTABLISHED|SATA_EVNT_LINK_LOST);
18352 			mutex_exit(&pmportinfo->pmport_mutex);
18353 		}
18354 
18355 	} else if (event_flags & SATA_EVNT_PMULT_LINK_CHANGED) {
18356 		/*
18357 		 * We need probe the port multiplier to know what has
18358 		 * happened.
18359 		 */
18360 		bzero(&sata_device, sizeof (sata_device_t));
18361 		sata_device.satadev_rev = SATA_DEVICE_REV;
18362 		sata_device.satadev_addr.cport = cport;
18363 		sata_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
18364 		sata_device.satadev_addr.qual = SATA_ADDR_PMULT;
18365 
18366 		mutex_exit(&cportinfo->cport_mutex);
18367 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18368 		    (SATA_DIP(sata_hba_inst), &sata_device);
18369 		mutex_enter(&cportinfo->cport_mutex);
18370 		if (rval != SATA_SUCCESS) {
18371 			/* Something went wrong? Fail the port */
18372 			cportinfo->cport_state = SATA_PSTATE_FAILED;
18373 			mutex_exit(&cportinfo->cport_mutex);
18374 			SATA_LOG_D((sata_hba_inst, CE_WARN,
18375 			    "SATA port %d probing failed", cport));
18376 
18377 			/* PMult structure must be released.  */
18378 			sata_free_pmult(sata_hba_inst, &sata_device);
18379 			return;
18380 		}
18381 
18382 		sata_update_port_info(sata_hba_inst, &sata_device);
18383 
18384 		/*
18385 		 * Sanity check - Port is active? Is the link active?
18386 		 * The device is still a port multiplier?
18387 		 */
18388 		if ((cportinfo->cport_state &
18389 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
18390 		    ((cportinfo->cport_scr.sstatus &
18391 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) ||
18392 		    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
18393 			mutex_exit(&cportinfo->cport_mutex);
18394 
18395 			/* PMult structure must be released.  */
18396 			sata_free_pmult(sata_hba_inst, &sata_device);
18397 			return;
18398 		}
18399 
18400 		/* Probed succeed, set port ready. */
18401 		cportinfo->cport_state |=
18402 		    SATA_STATE_PROBED | SATA_STATE_READY;
18403 	}
18404 
18405 	/* Release port multiplier event flags. */
18406 	pmultinfo->pmult_event_flags &=
18407 	    ~(SATA_EVNT_DEVICE_RESET|SATA_EVNT_PMULT_LINK_CHANGED);
18408 	mutex_exit(&cportinfo->cport_mutex);
18409 
18410 	/*
18411 	 * Check all sub-links.
18412 	 */
18413 	for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst, cport);
18414 	    npmport ++) {
18415 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
18416 		mutex_enter(&pmportinfo->pmport_mutex);
18417 		event_flags = pmportinfo->pmport_event_flags;
18418 		mutex_exit(&pmportinfo->pmport_mutex);
18419 		saddr = &pmportinfo->pmport_addr;
18420 
18421 		if ((event_flags &
18422 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
18423 			/*
18424 			 * Got port multiplier port event.
18425 			 * We need some hierarchy of event processing as they
18426 			 * are affecting each other:
18427 			 * 1. device detached/attached
18428 			 * 2. link events - link events may trigger device
18429 			 *    detached or device attached events in some
18430 			 *    circumstances.
18431 			 */
18432 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
18433 				sata_process_pmdevice_detached(sata_hba_inst,
18434 				    saddr);
18435 			}
18436 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
18437 				sata_process_pmdevice_attached(sata_hba_inst,
18438 				    saddr);
18439 			}
18440 			if (event_flags & SATA_EVNT_LINK_ESTABLISHED ||
18441 			    event_flags & SATA_EVNT_LINK_LOST) {
18442 				sata_process_pmport_link_events(sata_hba_inst,
18443 				    saddr);
18444 			}
18445 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
18446 				sata_process_target_node_cleanup(
18447 				    sata_hba_inst, saddr);
18448 			}
18449 		}
18450 
18451 		/* Checking drive event(s). */
18452 		mutex_enter(&pmportinfo->pmport_mutex);
18453 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
18454 		    pmportinfo->pmport_sata_drive != NULL) {
18455 			event_flags = pmportinfo->pmport_sata_drive->
18456 			    satadrv_event_flags;
18457 			if (event_flags & (SATA_EVNT_DEVICE_RESET |
18458 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
18459 
18460 				/* Have device event */
18461 				sata_process_pmdevice_reset(sata_hba_inst,
18462 				    saddr);
18463 			}
18464 		}
18465 		mutex_exit(&pmportinfo->pmport_mutex);
18466 
18467 		/* Release PORT_BUSY flag */
18468 		mutex_enter(&cportinfo->cport_mutex);
18469 		cportinfo->cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
18470 		mutex_exit(&cportinfo->cport_mutex);
18471 	}
18472 
18473 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
18474 	    "[DONE] pmult event(s) on cport %d of controller %d",
18475 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
18476 }
18477 
18478 /*
18479  * Process HBA power level change reported by HBA driver.
18480  * Not implemented at this time - event is ignored.
18481  */
18482 static void
18483 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
18484 {
18485 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18486 	    "Processing controller power level change", NULL);
18487 
18488 	/* Ignoring it for now */
18489 	mutex_enter(&sata_hba_inst->satahba_mutex);
18490 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
18491 	mutex_exit(&sata_hba_inst->satahba_mutex);
18492 }
18493 
18494 /*
18495  * Process port power level change reported by HBA driver.
18496  * Not implemented at this time - event is ignored.
18497  */
18498 static void
18499 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
18500     sata_address_t *saddr)
18501 {
18502 	sata_cport_info_t *cportinfo;
18503 
18504 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18505 	    "Processing port power level change", NULL);
18506 
18507 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18508 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18509 	/* Reset event flag */
18510 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
18511 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18512 }
18513 
18514 /*
18515  * Process port failure reported by HBA driver.
18516  * cports support only - no pmports.
18517  */
18518 static void
18519 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
18520     sata_address_t *saddr)
18521 {
18522 	sata_cport_info_t *cportinfo;
18523 
18524 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18525 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18526 	/* Reset event flag first */
18527 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
18528 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
18529 	if ((cportinfo->cport_state &
18530 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
18531 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18532 		    cport_mutex);
18533 		return;
18534 	}
18535 	/* Fail the port */
18536 	cportinfo->cport_state = SATA_PSTATE_FAILED;
18537 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18538 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
18539 }
18540 
18541 /*
18542  * Device Reset Event processing.
18543  * The sequence is managed by 3 stage flags:
18544  * - reset event reported,
18545  * - reset event being processed,
18546  * - request to clear device reset state.
18547  *
18548  * NOTE: This function has to be entered with cport mutex held. It exits with
18549  * mutex held as well, but can release mutex during the processing.
18550  */
18551 static void
18552 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
18553     sata_address_t *saddr)
18554 {
18555 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
18556 	sata_drive_info_t *sdinfo;
18557 	sata_cport_info_t *cportinfo;
18558 	sata_device_t sata_device;
18559 	int rval_probe, rval_set;
18560 
18561 	/* We only care about host sata cport for now */
18562 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18563 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18564 	/*
18565 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
18566 	 * state, ignore reset event.
18567 	 */
18568 	if (((cportinfo->cport_state &
18569 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
18570 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
18571 		sdinfo->satadrv_event_flags &=
18572 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
18573 		return;
18574 	}
18575 
18576 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) ==
18577 	    SATA_DTYPE_PMULT)) {
18578 		/*
18579 		 * Should not happened: this is already handled in
18580 		 * sata_hba_event_notify()
18581 		 */
18582 		mutex_exit(&cportinfo->cport_mutex);
18583 		goto done;
18584 	}
18585 
18586 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
18587 	    SATA_VALID_DEV_TYPE) == 0) {
18588 		/*
18589 		 * This should not happen - coding error.
18590 		 * But we can recover, so do not panic, just clean up
18591 		 * and if in debug mode, log the message.
18592 		 */
18593 #ifdef SATA_DEBUG
18594 		sata_log(sata_hba_inst, CE_WARN,
18595 		    "sata_process_device_reset: "
18596 		    "Invalid device type with sdinfo!", NULL);
18597 #endif
18598 		sdinfo->satadrv_event_flags = 0;
18599 		return;
18600 	}
18601 
18602 #ifdef SATA_DEBUG
18603 	if ((sdinfo->satadrv_event_flags &
18604 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
18605 		/* Nothing to do */
18606 		/* Something is weird - why we are processing dev reset? */
18607 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18608 		    "No device reset event!!!!", NULL);
18609 
18610 		return;
18611 	}
18612 	if ((sdinfo->satadrv_event_flags &
18613 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
18614 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
18615 		/* Something is weird - new device reset event */
18616 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18617 		    "Overlapping device reset events!", NULL);
18618 	}
18619 #endif
18620 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18621 	    "Processing port %d device reset", saddr->cport);
18622 
18623 	/* Clear event flag */
18624 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
18625 
18626 	/* It seems that we always need to check the port state first */
18627 	sata_device.satadev_rev = SATA_DEVICE_REV;
18628 	sata_device.satadev_addr = *saddr;
18629 	/*
18630 	 * We have to exit mutex, because the HBA probe port function may
18631 	 * block on its own mutex.
18632 	 */
18633 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18634 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18635 	    (SATA_DIP(sata_hba_inst), &sata_device);
18636 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18637 	sata_update_port_info(sata_hba_inst, &sata_device);
18638 	if (rval_probe != SATA_SUCCESS) {
18639 		/* Something went wrong? Fail the port */
18640 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18641 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18642 		if (sdinfo != NULL)
18643 			sdinfo->satadrv_event_flags = 0;
18644 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18645 		    cport_mutex);
18646 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18647 		    "SATA port %d probing failed",
18648 		    saddr->cport));
18649 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
18650 		    saddr->cport)->cport_mutex);
18651 		return;
18652 	}
18653 	if ((sata_device.satadev_scr.sstatus  &
18654 	    SATA_PORT_DEVLINK_UP_MASK) !=
18655 	    SATA_PORT_DEVLINK_UP ||
18656 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18657 		/*
18658 		 * No device to process, anymore. Some other event processing
18659 		 * would or have already performed port info cleanup.
18660 		 * To be safe (HBA may need it), request clearing device
18661 		 * reset condition.
18662 		 */
18663 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18664 		if (sdinfo != NULL) {
18665 			sdinfo->satadrv_event_flags &=
18666 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18667 			sdinfo->satadrv_event_flags |=
18668 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18669 		}
18670 		return;
18671 	}
18672 
18673 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18674 	if (sdinfo == NULL) {
18675 		return;
18676 	}
18677 	if ((sdinfo->satadrv_event_flags &
18678 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18679 		/*
18680 		 * Start tracking time for device feature restoration and
18681 		 * identification. Save current time (lbolt value).
18682 		 */
18683 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18684 	}
18685 	/* Mark device reset processing as active */
18686 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18687 
18688 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18689 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18690 
18691 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
18692 
18693 	if (rval_set  != SATA_SUCCESS) {
18694 		/*
18695 		 * Restoring drive setting failed.
18696 		 * Probe the port first, to check if the port state has changed
18697 		 */
18698 		sata_device.satadev_rev = SATA_DEVICE_REV;
18699 		sata_device.satadev_addr = *saddr;
18700 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
18701 		/* probe port */
18702 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18703 		    (SATA_DIP(sata_hba_inst), &sata_device);
18704 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18705 		    cport_mutex);
18706 		if (rval_probe == SATA_SUCCESS &&
18707 		    (sata_device.satadev_state &
18708 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18709 		    (sata_device.satadev_scr.sstatus  &
18710 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18711 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18712 			/*
18713 			 * We may retry this a bit later - in-process reset
18714 			 * condition should be already set.
18715 			 * Track retry time for device identification.
18716 			 */
18717 			if ((cportinfo->cport_dev_type &
18718 			    SATA_VALID_DEV_TYPE) != 0 &&
18719 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
18720 			    sdinfo->satadrv_reset_time != 0) {
18721 				clock_t cur_time = ddi_get_lbolt();
18722 				/*
18723 				 * If the retry time limit was not
18724 				 * exceeded, retry.
18725 				 */
18726 				if ((cur_time - sdinfo->satadrv_reset_time) <
18727 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18728 					mutex_enter(
18729 					    &sata_hba_inst->satahba_mutex);
18730 					sata_hba_inst->satahba_event_flags |=
18731 					    SATA_EVNT_MAIN;
18732 					mutex_exit(
18733 					    &sata_hba_inst->satahba_mutex);
18734 					mutex_enter(&sata_mutex);
18735 					sata_event_pending |= SATA_EVNT_MAIN;
18736 					mutex_exit(&sata_mutex);
18737 					return;
18738 				}
18739 				if (rval_set == SATA_RETRY) {
18740 					/*
18741 					 * Setting drive features failed, but
18742 					 * the drive is still accessible,
18743 					 * so emit a warning message before
18744 					 * return.
18745 					 */
18746 					mutex_exit(&SATA_CPORT_INFO(
18747 					    sata_hba_inst,
18748 					    saddr->cport)->cport_mutex);
18749 					goto done;
18750 				}
18751 			}
18752 			/* Fail the drive */
18753 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18754 
18755 			sata_log(sata_hba_inst, CE_WARN,
18756 			    "SATA device at port %d - device failed",
18757 			    saddr->cport);
18758 
18759 			DTRACE_PROBE(port_failed_f);
18760 		}
18761 		/*
18762 		 * No point of retrying - device failed or some other event
18763 		 * processing or already did or will do port info cleanup.
18764 		 * To be safe (HBA may need it),
18765 		 * request clearing device reset condition.
18766 		 */
18767 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
18768 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18769 		sdinfo->satadrv_reset_time = 0;
18770 		return;
18771 	}
18772 done:
18773 	/*
18774 	 * If setting of drive features failed, but the drive is still
18775 	 * accessible, emit a warning message.
18776 	 */
18777 	if (rval_set == SATA_RETRY) {
18778 		sata_log(sata_hba_inst, CE_WARN,
18779 		    "SATA device at port %d - desired setting could not be "
18780 		    "restored after reset. Device may not operate as expected.",
18781 		    saddr->cport);
18782 	}
18783 	/*
18784 	 * Raise the flag indicating that the next sata command could
18785 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18786 	 * reset is reported.
18787 	 */
18788 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18789 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18790 		sdinfo->satadrv_reset_time = 0;
18791 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
18792 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18793 			sdinfo->satadrv_event_flags &=
18794 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18795 			sdinfo->satadrv_event_flags |=
18796 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18797 		}
18798 	}
18799 }
18800 
18801 
18802 /*
18803  * Port Multiplier Port Device Reset Event processing.
18804  *
18805  * NOTE: This function has to be entered with pmport mutex held. It exits with
18806  * mutex held as well, but can release mutex during the processing.
18807  */
18808 static void
18809 sata_process_pmdevice_reset(sata_hba_inst_t *sata_hba_inst,
18810     sata_address_t *saddr)
18811 {
18812 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
18813 	sata_drive_info_t *sdinfo = NULL;
18814 	sata_cport_info_t *cportinfo = NULL;
18815 	sata_pmport_info_t *pmportinfo = NULL;
18816 	sata_pmult_info_t *pminfo = NULL;
18817 	sata_device_t sata_device;
18818 	uint8_t cport = saddr->cport;
18819 	uint8_t pmport = saddr->pmport;
18820 	int rval;
18821 
18822 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18823 	    "Processing drive reset at port %d:%d", cport, pmport);
18824 
18825 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
18826 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18827 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport);
18828 
18829 	/*
18830 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
18831 	 * state, ignore reset event.
18832 	 */
18833 	if (((cportinfo->cport_state &
18834 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
18835 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
18836 		sdinfo->satadrv_event_flags &=
18837 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
18838 		return;
18839 	}
18840 
18841 	if ((pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
18842 		/*
18843 		 * This should not happen - coding error.
18844 		 * But we can recover, so do not panic, just clean up
18845 		 * and if in debug mode, log the message.
18846 		 */
18847 #ifdef SATA_DEBUG
18848 		sata_log(sata_hba_inst, CE_WARN,
18849 		    "sata_process_pmdevice_reset: "
18850 		    "Invalid device type with sdinfo!", NULL);
18851 #endif
18852 		sdinfo->satadrv_event_flags = 0;
18853 		return;
18854 	}
18855 
18856 #ifdef SATA_DEBUG
18857 	if ((sdinfo->satadrv_event_flags &
18858 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
18859 		/* Nothing to do */
18860 		/* Something is weird - why we are processing dev reset? */
18861 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18862 		    "No device reset event!!!!", NULL);
18863 
18864 		return;
18865 	}
18866 	if ((sdinfo->satadrv_event_flags &
18867 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
18868 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
18869 		/* Something is weird - new device reset event */
18870 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18871 		    "Overlapping device reset events!", NULL);
18872 	}
18873 #endif
18874 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18875 	    "Processing port %d:%d device reset", cport, pmport);
18876 
18877 	/* Clear event flag */
18878 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
18879 
18880 	/* It seems that we always need to check the port state first */
18881 	sata_device.satadev_rev = SATA_DEVICE_REV;
18882 	sata_device.satadev_addr = *saddr;
18883 	/*
18884 	 * We have to exit mutex, because the HBA probe port function may
18885 	 * block on its own mutex.
18886 	 */
18887 	mutex_exit(&pmportinfo->pmport_mutex);
18888 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18889 	    (SATA_DIP(sata_hba_inst), &sata_device);
18890 	mutex_enter(&pmportinfo->pmport_mutex);
18891 
18892 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18893 	if (rval != SATA_SUCCESS) {
18894 		/* Something went wrong? Fail the port */
18895 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18896 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18897 		    saddr->pmport);
18898 		if (sdinfo != NULL)
18899 			sdinfo->satadrv_event_flags = 0;
18900 		mutex_exit(&pmportinfo->pmport_mutex);
18901 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18902 		    "SATA port %d:%d probing failed",
18903 		    saddr->cport, saddr->pmport));
18904 		mutex_enter(&pmportinfo->pmport_mutex);
18905 		return;
18906 	}
18907 	if ((sata_device.satadev_scr.sstatus  &
18908 	    SATA_PORT_DEVLINK_UP_MASK) !=
18909 	    SATA_PORT_DEVLINK_UP ||
18910 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18911 		/*
18912 		 * No device to process, anymore. Some other event processing
18913 		 * would or have already performed port info cleanup.
18914 		 * To be safe (HBA may need it), request clearing device
18915 		 * reset condition.
18916 		 */
18917 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18918 		    saddr->pmport);
18919 		if (sdinfo != NULL) {
18920 			sdinfo->satadrv_event_flags &=
18921 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18922 			/* must clear flags on cport */
18923 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18924 			    saddr->cport);
18925 			pminfo->pmult_event_flags |=
18926 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18927 		}
18928 		return;
18929 	}
18930 
18931 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18932 	    saddr->pmport);
18933 	if (sdinfo == NULL) {
18934 		return;
18935 	}
18936 	if ((sdinfo->satadrv_event_flags &
18937 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18938 		/*
18939 		 * Start tracking time for device feature restoration and
18940 		 * identification. Save current time (lbolt value).
18941 		 */
18942 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18943 	}
18944 	/* Mark device reset processing as active */
18945 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18946 
18947 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18948 	mutex_exit(&pmportinfo->pmport_mutex);
18949 
18950 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
18951 	    SATA_FAILURE) {
18952 		/*
18953 		 * Restoring drive setting failed.
18954 		 * Probe the port first, to check if the port state has changed
18955 		 */
18956 		sata_device.satadev_rev = SATA_DEVICE_REV;
18957 		sata_device.satadev_addr = *saddr;
18958 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
18959 
18960 		/* probe port */
18961 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18962 		    (SATA_DIP(sata_hba_inst), &sata_device);
18963 		mutex_enter(&pmportinfo->pmport_mutex);
18964 		if (rval == SATA_SUCCESS &&
18965 		    (sata_device.satadev_state &
18966 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18967 		    (sata_device.satadev_scr.sstatus  &
18968 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18969 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18970 			/*
18971 			 * We may retry this a bit later - in-process reset
18972 			 * condition should be already set.
18973 			 * Track retry time for device identification.
18974 			 */
18975 			if ((pmportinfo->pmport_dev_type &
18976 			    SATA_VALID_DEV_TYPE) != 0 &&
18977 			    SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL &&
18978 			    sdinfo->satadrv_reset_time != 0) {
18979 				clock_t cur_time = ddi_get_lbolt();
18980 				/*
18981 				 * If the retry time limit was not
18982 				 * exceeded, retry.
18983 				 */
18984 				if ((cur_time - sdinfo->satadrv_reset_time) <
18985 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18986 					mutex_enter(
18987 					    &sata_hba_inst->satahba_mutex);
18988 					sata_hba_inst->satahba_event_flags |=
18989 					    SATA_EVNT_MAIN;
18990 					mutex_exit(
18991 					    &sata_hba_inst->satahba_mutex);
18992 					mutex_enter(&sata_mutex);
18993 					sata_event_pending |= SATA_EVNT_MAIN;
18994 					mutex_exit(&sata_mutex);
18995 					return;
18996 				}
18997 			}
18998 			/* Fail the drive */
18999 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
19000 
19001 			sata_log(sata_hba_inst, CE_WARN,
19002 			    "SATA device at port %d:%d - device failed",
19003 			    saddr->cport, saddr->pmport);
19004 		} else {
19005 			/*
19006 			 * No point of retrying - some other event processing
19007 			 * would or already did port info cleanup.
19008 			 * To be safe (HBA may need it),
19009 			 * request clearing device reset condition.
19010 			 */
19011 			sdinfo->satadrv_event_flags |=
19012 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19013 		}
19014 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
19015 		sdinfo->satadrv_reset_time = 0;
19016 		return;
19017 	}
19018 	/*
19019 	 * Raise the flag indicating that the next sata command could
19020 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
19021 	 * reset is reported.
19022 	 */
19023 	mutex_enter(&pmportinfo->pmport_mutex);
19024 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19025 		sdinfo->satadrv_reset_time = 0;
19026 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
19027 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19028 			sdinfo->satadrv_event_flags &=
19029 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
19030 			/* must clear flags on cport */
19031 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
19032 			    saddr->cport);
19033 			pminfo->pmult_event_flags |=
19034 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19035 		}
19036 	}
19037 }
19038 
19039 /*
19040  * Port Link Events processing.
19041  * Every link established event may involve device reset (due to
19042  * COMRESET signal, equivalent of the hard reset) so arbitrarily
19043  * set device reset event for an attached device (if any).
19044  * If the port is in SHUTDOWN or FAILED state, ignore link events.
19045  *
19046  * The link established event processing varies, depending on the state
19047  * of the target node, HBA hotplugging capabilities, state of the port.
19048  * If the link is not active, the link established event is ignored.
19049  * If HBA cannot detect device attachment and there is no target node,
19050  * the link established event triggers device attach event processing.
19051  * Else, link established event triggers device reset event processing.
19052  *
19053  * The link lost event processing varies, depending on a HBA hotplugging
19054  * capability and the state of the port (link active or not active).
19055  * If the link is active, the lost link event is ignored.
19056  * If HBA cannot detect device removal, the lost link event triggers
19057  * device detached event processing after link lost timeout.
19058  * Else, the event is ignored.
19059  *
19060  * NOTE: Port multiplier ports events are handled by
19061  * sata_process_pmport_link_events();
19062  */
19063 static void
19064 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
19065     sata_address_t *saddr)
19066 {
19067 	sata_device_t sata_device;
19068 	sata_cport_info_t *cportinfo;
19069 	sata_drive_info_t *sdinfo;
19070 	uint32_t event_flags;
19071 	int rval;
19072 
19073 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19074 	    "Processing port %d link event(s)", saddr->cport);
19075 
19076 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19077 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19078 	event_flags = cportinfo->cport_event_flags;
19079 
19080 	/* Reset event flags first */
19081 	cportinfo->cport_event_flags &=
19082 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
19083 
19084 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
19085 	if ((cportinfo->cport_state &
19086 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19087 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19088 		    cport_mutex);
19089 		return;
19090 	}
19091 
19092 	/*
19093 	 * For the sanity sake get current port state.
19094 	 * Set device address only. Other sata_device fields should be
19095 	 * set by HBA driver.
19096 	 */
19097 	sata_device.satadev_rev = SATA_DEVICE_REV;
19098 	sata_device.satadev_addr = *saddr;
19099 	/*
19100 	 * We have to exit mutex, because the HBA probe port function may
19101 	 * block on its own mutex.
19102 	 */
19103 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19104 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19105 	    (SATA_DIP(sata_hba_inst), &sata_device);
19106 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19107 	sata_update_port_info(sata_hba_inst, &sata_device);
19108 	if (rval != SATA_SUCCESS) {
19109 		/* Something went wrong? Fail the port */
19110 		cportinfo->cport_state = SATA_PSTATE_FAILED;
19111 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19112 		    cport_mutex);
19113 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19114 		    "SATA port %d probing failed",
19115 		    saddr->cport));
19116 		/*
19117 		 * We may want to release device info structure, but
19118 		 * it is not necessary.
19119 		 */
19120 		return;
19121 	} else {
19122 		/* port probed successfully */
19123 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
19124 	}
19125 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
19126 
19127 		if ((sata_device.satadev_scr.sstatus &
19128 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
19129 			/* Ignore event */
19130 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19131 			    "Ignoring port %d link established event - "
19132 			    "link down",
19133 			    saddr->cport);
19134 			goto linklost;
19135 		}
19136 
19137 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19138 		    "Processing port %d link established event",
19139 		    saddr->cport);
19140 
19141 		/*
19142 		 * For the sanity sake check if a device is attached - check
19143 		 * return state of a port probing.
19144 		 */
19145 		if (sata_device.satadev_type != SATA_DTYPE_NONE) {
19146 			/*
19147 			 * HBA port probe indicated that there is a device
19148 			 * attached. Check if the framework had device info
19149 			 * structure attached for this device.
19150 			 */
19151 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
19152 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
19153 				    NULL);
19154 
19155 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
19156 				if ((sdinfo->satadrv_type &
19157 				    SATA_VALID_DEV_TYPE) != 0) {
19158 					/*
19159 					 * Dev info structure is present.
19160 					 * If dev_type is set to known type in
19161 					 * the framework's drive info struct
19162 					 * then the device existed before and
19163 					 * the link was probably lost
19164 					 * momentarily - in such case
19165 					 * we may want to check device
19166 					 * identity.
19167 					 * Identity check is not supported now.
19168 					 *
19169 					 * Link established event
19170 					 * triggers device reset event.
19171 					 */
19172 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
19173 					    satadrv_event_flags |=
19174 					    SATA_EVNT_DEVICE_RESET;
19175 				}
19176 			} else if (cportinfo->cport_dev_type ==
19177 			    SATA_DTYPE_NONE) {
19178 				/*
19179 				 * We got new device attached! If HBA does not
19180 				 * generate device attached events, trigger it
19181 				 * here.
19182 				 */
19183 				if (!(SATA_FEATURES(sata_hba_inst) &
19184 				    SATA_CTLF_HOTPLUG)) {
19185 					cportinfo->cport_event_flags |=
19186 					    SATA_EVNT_DEVICE_ATTACHED;
19187 				}
19188 			}
19189 			/* Reset link lost timeout */
19190 			cportinfo->cport_link_lost_time = 0;
19191 		}
19192 	}
19193 linklost:
19194 	if (event_flags & SATA_EVNT_LINK_LOST) {
19195 		if ((sata_device.satadev_scr.sstatus &
19196 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
19197 			/* Ignore event */
19198 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19199 			    "Ignoring port %d link lost event - link is up",
19200 			    saddr->cport);
19201 			goto done;
19202 		}
19203 #ifdef SATA_DEBUG
19204 		if (cportinfo->cport_link_lost_time == 0) {
19205 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19206 			    "Processing port %d link lost event",
19207 			    saddr->cport);
19208 		}
19209 #endif
19210 		/*
19211 		 * When HBA cannot generate device attached/detached events,
19212 		 * we need to track link lost time and eventually generate
19213 		 * device detach event.
19214 		 */
19215 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
19216 			/* We are tracking link lost time */
19217 			if (cportinfo->cport_link_lost_time == 0) {
19218 				/* save current time (lbolt value) */
19219 				cportinfo->cport_link_lost_time =
19220 				    ddi_get_lbolt();
19221 				/* just keep link lost event */
19222 				cportinfo->cport_event_flags |=
19223 				    SATA_EVNT_LINK_LOST;
19224 			} else {
19225 				clock_t cur_time = ddi_get_lbolt();
19226 				if ((cur_time -
19227 				    cportinfo->cport_link_lost_time) >=
19228 				    drv_usectohz(
19229 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
19230 					/* trigger device detach event */
19231 					cportinfo->cport_event_flags |=
19232 					    SATA_EVNT_DEVICE_DETACHED;
19233 					cportinfo->cport_link_lost_time = 0;
19234 					SATADBG1(SATA_DBG_EVENTS,
19235 					    sata_hba_inst,
19236 					    "Triggering port %d "
19237 					    "device detached event",
19238 					    saddr->cport);
19239 				} else {
19240 					/* keep link lost event */
19241 					cportinfo->cport_event_flags |=
19242 					    SATA_EVNT_LINK_LOST;
19243 				}
19244 			}
19245 		}
19246 		/*
19247 		 * We could change port state to disable/delay access to
19248 		 * the attached device until the link is recovered.
19249 		 */
19250 	}
19251 done:
19252 	event_flags = cportinfo->cport_event_flags;
19253 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19254 	if (event_flags != 0) {
19255 		mutex_enter(&sata_hba_inst->satahba_mutex);
19256 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19257 		mutex_exit(&sata_hba_inst->satahba_mutex);
19258 		mutex_enter(&sata_mutex);
19259 		sata_event_pending |= SATA_EVNT_MAIN;
19260 		mutex_exit(&sata_mutex);
19261 	}
19262 }
19263 
19264 /*
19265  * Port Multiplier Port Link Events processing.
19266  */
19267 static void
19268 sata_process_pmport_link_events(sata_hba_inst_t *sata_hba_inst,
19269     sata_address_t *saddr)
19270 {
19271 	sata_device_t sata_device;
19272 	sata_pmport_info_t *pmportinfo = NULL;
19273 	sata_drive_info_t *sdinfo = NULL;
19274 	uint32_t event_flags;
19275 	uint8_t cport = saddr->cport;
19276 	uint8_t pmport = saddr->pmport;
19277 	int rval;
19278 
19279 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19280 	    "Processing port %d:%d link event(s)",
19281 	    cport, pmport);
19282 
19283 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19284 	mutex_enter(&pmportinfo->pmport_mutex);
19285 	event_flags = pmportinfo->pmport_event_flags;
19286 
19287 	/* Reset event flags first */
19288 	pmportinfo->pmport_event_flags &=
19289 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
19290 
19291 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
19292 	if ((pmportinfo->pmport_state &
19293 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19294 		mutex_exit(&pmportinfo->pmport_mutex);
19295 		return;
19296 	}
19297 
19298 	/*
19299 	 * For the sanity sake get current port state.
19300 	 * Set device address only. Other sata_device fields should be
19301 	 * set by HBA driver.
19302 	 */
19303 	sata_device.satadev_rev = SATA_DEVICE_REV;
19304 	sata_device.satadev_addr = *saddr;
19305 	/*
19306 	 * We have to exit mutex, because the HBA probe port function may
19307 	 * block on its own mutex.
19308 	 */
19309 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
19310 	    saddr->pmport));
19311 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19312 	    (SATA_DIP(sata_hba_inst), &sata_device);
19313 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
19314 	    saddr->pmport));
19315 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19316 	if (rval != SATA_SUCCESS) {
19317 		/* Something went wrong? Fail the port */
19318 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19319 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
19320 		    saddr->pmport));
19321 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19322 		    "SATA port %d:%d probing failed",
19323 		    saddr->cport, saddr->pmport));
19324 		/*
19325 		 * We may want to release device info structure, but
19326 		 * it is not necessary.
19327 		 */
19328 		return;
19329 	} else {
19330 		/* port probed successfully */
19331 		pmportinfo->pmport_state |=
19332 		    SATA_STATE_PROBED | SATA_STATE_READY;
19333 	}
19334 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
19335 	    saddr->cport, saddr->pmport));
19336 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
19337 	    saddr->cport, saddr->pmport));
19338 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
19339 
19340 		if ((sata_device.satadev_scr.sstatus &
19341 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
19342 			/* Ignore event */
19343 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19344 			    "Ignoring port %d:%d link established event - "
19345 			    "link down",
19346 			    saddr->cport, saddr->pmport);
19347 			goto linklost;
19348 		}
19349 
19350 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19351 		    "Processing port %d:%d link established event",
19352 		    cport, pmport);
19353 
19354 		/*
19355 		 * For the sanity sake check if a device is attached - check
19356 		 * return state of a port probing.
19357 		 */
19358 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
19359 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
19360 			/*
19361 			 * HBA port probe indicated that there is a device
19362 			 * attached. Check if the framework had device info
19363 			 * structure attached for this device.
19364 			 */
19365 			if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
19366 				ASSERT(SATA_PMPORTINFO_DRV_INFO(pmportinfo) !=
19367 				    NULL);
19368 
19369 				sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19370 				if ((sdinfo->satadrv_type &
19371 				    SATA_VALID_DEV_TYPE) != 0) {
19372 					/*
19373 					 * Dev info structure is present.
19374 					 * If dev_type is set to known type in
19375 					 * the framework's drive info struct
19376 					 * then the device existed before and
19377 					 * the link was probably lost
19378 					 * momentarily - in such case
19379 					 * we may want to check device
19380 					 * identity.
19381 					 * Identity check is not supported now.
19382 					 *
19383 					 * Link established event
19384 					 * triggers device reset event.
19385 					 */
19386 					(SATA_PMPORTINFO_DRV_INFO(pmportinfo))->
19387 					    satadrv_event_flags |=
19388 					    SATA_EVNT_DEVICE_RESET;
19389 				}
19390 			} else if (pmportinfo->pmport_dev_type ==
19391 			    SATA_DTYPE_NONE) {
19392 				/*
19393 				 * We got new device attached! If HBA does not
19394 				 * generate device attached events, trigger it
19395 				 * here.
19396 				 */
19397 				if (!(SATA_FEATURES(sata_hba_inst) &
19398 				    SATA_CTLF_HOTPLUG)) {
19399 					pmportinfo->pmport_event_flags |=
19400 					    SATA_EVNT_DEVICE_ATTACHED;
19401 				}
19402 			}
19403 			/* Reset link lost timeout */
19404 			pmportinfo->pmport_link_lost_time = 0;
19405 		}
19406 	}
19407 linklost:
19408 	if (event_flags & SATA_EVNT_LINK_LOST) {
19409 #ifdef SATA_DEBUG
19410 		if (pmportinfo->pmport_link_lost_time == 0) {
19411 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19412 			    "Processing port %d:%d link lost event",
19413 			    saddr->cport, saddr->pmport);
19414 		}
19415 #endif
19416 		if ((sata_device.satadev_scr.sstatus &
19417 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
19418 			/* Ignore event */
19419 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19420 			    "Ignoring port %d:%d link lost event - link is up",
19421 			    saddr->cport, saddr->pmport);
19422 			goto done;
19423 		}
19424 		/*
19425 		 * When HBA cannot generate device attached/detached events,
19426 		 * we need to track link lost time and eventually generate
19427 		 * device detach event.
19428 		 */
19429 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
19430 			/* We are tracking link lost time */
19431 			if (pmportinfo->pmport_link_lost_time == 0) {
19432 				/* save current time (lbolt value) */
19433 				pmportinfo->pmport_link_lost_time =
19434 				    ddi_get_lbolt();
19435 				/* just keep link lost event */
19436 				pmportinfo->pmport_event_flags |=
19437 				    SATA_EVNT_LINK_LOST;
19438 			} else {
19439 				clock_t cur_time = ddi_get_lbolt();
19440 				if ((cur_time -
19441 				    pmportinfo->pmport_link_lost_time) >=
19442 				    drv_usectohz(
19443 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
19444 					/* trigger device detach event */
19445 					pmportinfo->pmport_event_flags |=
19446 					    SATA_EVNT_DEVICE_DETACHED;
19447 					pmportinfo->pmport_link_lost_time = 0;
19448 					SATADBG2(SATA_DBG_EVENTS,
19449 					    sata_hba_inst,
19450 					    "Triggering port %d:%d "
19451 					    "device detached event",
19452 					    saddr->cport, saddr->pmport);
19453 				} else {
19454 					/* keep link lost event */
19455 					pmportinfo->pmport_event_flags |=
19456 					    SATA_EVNT_LINK_LOST;
19457 				}
19458 			}
19459 		}
19460 		/*
19461 		 * We could change port state to disable/delay access to
19462 		 * the attached device until the link is recovered.
19463 		 */
19464 	}
19465 done:
19466 	event_flags = pmportinfo->pmport_event_flags;
19467 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
19468 	    saddr->pmport));
19469 	if (event_flags != 0) {
19470 		mutex_enter(&sata_hba_inst->satahba_mutex);
19471 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19472 		mutex_exit(&sata_hba_inst->satahba_mutex);
19473 		mutex_enter(&sata_mutex);
19474 		sata_event_pending |= SATA_EVNT_MAIN;
19475 		mutex_exit(&sata_mutex);
19476 	}
19477 }
19478 
19479 /*
19480  * Device Detached Event processing.
19481  * Port is probed to find if a device is really gone. If so,
19482  * the device info structure is detached from the SATA port info structure
19483  * and released.
19484  * Port status is updated.
19485  *
19486  * NOTE: Port multiplier ports events are handled by
19487  * sata_process_pmdevice_detached()
19488  */
19489 static void
19490 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
19491     sata_address_t *saddr)
19492 {
19493 	sata_cport_info_t *cportinfo;
19494 	sata_pmport_info_t *pmportinfo;
19495 	sata_drive_info_t *sdevinfo;
19496 	sata_device_t sata_device;
19497 	sata_address_t pmport_addr;
19498 	char name[16];
19499 	uint8_t cport = saddr->cport;
19500 	int npmport;
19501 	int rval;
19502 
19503 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19504 	    "Processing port %d device detached", saddr->cport);
19505 
19506 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19507 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19508 	/* Clear event flag */
19509 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
19510 
19511 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
19512 	if ((cportinfo->cport_state &
19513 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19514 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19515 		    cport_mutex);
19516 		return;
19517 	}
19518 	/* For sanity, re-probe the port */
19519 	sata_device.satadev_rev = SATA_DEVICE_REV;
19520 	sata_device.satadev_addr = *saddr;
19521 
19522 	/*
19523 	 * We have to exit mutex, because the HBA probe port function may
19524 	 * block on its own mutex.
19525 	 */
19526 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19527 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19528 	    (SATA_DIP(sata_hba_inst), &sata_device);
19529 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19530 	sata_update_port_info(sata_hba_inst, &sata_device);
19531 	if (rval != SATA_SUCCESS) {
19532 		/* Something went wrong? Fail the port */
19533 		cportinfo->cport_state = SATA_PSTATE_FAILED;
19534 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19535 		    cport_mutex);
19536 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19537 		    "SATA port %d probing failed",
19538 		    saddr->cport));
19539 		/*
19540 		 * We may want to release device info structure, but
19541 		 * it is not necessary.
19542 		 */
19543 		return;
19544 	} else {
19545 		/* port probed successfully */
19546 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
19547 	}
19548 	/*
19549 	 * Check if a device is still attached. For sanity, check also
19550 	 * link status - if no link, there is no device.
19551 	 */
19552 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
19553 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
19554 	    SATA_DTYPE_NONE) {
19555 		/*
19556 		 * Device is still attached - ignore detach event.
19557 		 */
19558 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19559 		    cport_mutex);
19560 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19561 		    "Ignoring detach - device still attached to port %d",
19562 		    sata_device.satadev_addr.cport);
19563 		return;
19564 	}
19565 	/*
19566 	 * We need to detach and release device info structure here
19567 	 */
19568 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19569 		/*
19570 		 * A port-multiplier is removed.
19571 		 *
19572 		 * Calling sata_process_pmdevice_detached() does not work
19573 		 * here. The port multiplier is gone, so we cannot probe
19574 		 * sub-port any more and all pmult-related data structure must
19575 		 * be de-allocated immediately. Following structure of every
19576 		 * implemented sub-port behind the pmult are required to
19577 		 * released.
19578 		 *
19579 		 *   - attachment point
19580 		 *   - target node
19581 		 *   - sata_drive_info
19582 		 *   - sata_pmport_info
19583 		 */
19584 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst,
19585 		    cport); npmport ++) {
19586 			SATADBG2(SATA_DBG_PMULT|SATA_DBG_EVENTS_PROC,
19587 			    sata_hba_inst,
19588 			    "Detaching target node at port %d:%d",
19589 			    cport, npmport);
19590 
19591 			mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
19592 
19593 			/* Remove attachment point. */
19594 			name[0] = '\0';
19595 			(void) sprintf(name, "%d.%d", cport, npmport);
19596 			ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
19597 			sata_log(sata_hba_inst, CE_NOTE,
19598 			    "Remove attachment point of port %d:%d",
19599 			    cport, npmport);
19600 
19601 			/* Remove target node */
19602 			pmport_addr.cport = cport;
19603 			pmport_addr.pmport = (uint8_t)npmport;
19604 			pmport_addr.qual = SATA_ADDR_PMPORT;
19605 			sata_remove_target_node(sata_hba_inst, &pmport_addr);
19606 
19607 			mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
19608 
19609 			/* Release sata_pmport_info & sata_drive_info. */
19610 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19611 			    cport, npmport);
19612 			ASSERT(pmportinfo != NULL);
19613 
19614 			sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19615 			if (sdevinfo != NULL) {
19616 				(void) kmem_free((void *) sdevinfo,
19617 				    sizeof (sata_drive_info_t));
19618 			}
19619 
19620 			/* Release sata_pmport_info at last */
19621 			(void) kmem_free((void *) pmportinfo,
19622 			    sizeof (sata_pmport_info_t));
19623 		}
19624 
19625 		/* Finally, release sata_pmult_info */
19626 		(void) kmem_free((void *)
19627 		    SATA_CPORTINFO_PMULT_INFO(cportinfo),
19628 		    sizeof (sata_pmult_info_t));
19629 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
19630 
19631 		sata_log(sata_hba_inst, CE_WARN,
19632 		    "SATA port-multiplier detached at port %d", cport);
19633 
19634 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19635 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19636 		    saddr->cport)->cport_mutex);
19637 	} else {
19638 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19639 			sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
19640 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
19641 			(void) kmem_free((void *)sdevinfo,
19642 			    sizeof (sata_drive_info_t));
19643 		}
19644 		sata_log(sata_hba_inst, CE_WARN,
19645 		    "SATA device detached at port %d", cport);
19646 
19647 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19648 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19649 		    saddr->cport)->cport_mutex);
19650 
19651 		/*
19652 		 * Try to offline a device and remove target node
19653 		 * if it still exists
19654 		 */
19655 		sata_remove_target_node(sata_hba_inst, saddr);
19656 	}
19657 
19658 
19659 	/*
19660 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19661 	 * with the hint: SE_HINT_REMOVE
19662 	 */
19663 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
19664 }
19665 
19666 /*
19667  * Port Multiplier Port Device Deattached Event processing.
19668  *
19669  * NOTE: No Mutex should be hold.
19670  */
19671 static void
19672 sata_process_pmdevice_detached(sata_hba_inst_t *sata_hba_inst,
19673     sata_address_t *saddr)
19674 {
19675 	sata_pmport_info_t *pmportinfo;
19676 	sata_drive_info_t *sdevinfo;
19677 	sata_device_t sata_device;
19678 	int rval;
19679 	uint8_t cport, pmport;
19680 
19681 	cport = saddr->cport;
19682 	pmport = saddr->pmport;
19683 
19684 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19685 	    "Processing port %d:%d device detached",
19686 	    cport, pmport);
19687 
19688 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19689 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19690 
19691 	/* Clear event flag */
19692 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
19693 
19694 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
19695 	if ((pmportinfo->pmport_state &
19696 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19697 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19698 		return;
19699 	}
19700 	/* For sanity, re-probe the port */
19701 	sata_device.satadev_rev = SATA_DEVICE_REV;
19702 	sata_device.satadev_addr = *saddr;
19703 
19704 	/*
19705 	 * We have to exit mutex, because the HBA probe port function may
19706 	 * block on its own mutex.
19707 	 */
19708 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19709 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19710 	    (SATA_DIP(sata_hba_inst), &sata_device);
19711 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19712 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19713 	if (rval != SATA_SUCCESS) {
19714 		/* Something went wrong? Fail the port */
19715 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19716 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19717 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19718 		    "SATA port %d:%d probing failed",
19719 		    saddr->pmport));
19720 		/*
19721 		 * We may want to release device info structure, but
19722 		 * it is not necessary.
19723 		 */
19724 		return;
19725 	} else {
19726 		/* port probed successfully */
19727 		pmportinfo->pmport_state |=
19728 		    SATA_STATE_PROBED | SATA_STATE_READY;
19729 	}
19730 	/*
19731 	 * Check if a device is still attached. For sanity, check also
19732 	 * link status - if no link, there is no device.
19733 	 */
19734 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
19735 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
19736 	    SATA_DTYPE_NONE) {
19737 		/*
19738 		 * Device is still attached - ignore detach event.
19739 		 */
19740 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19741 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19742 		    "Ignoring detach - device still attached to port %d",
19743 		    sata_device.satadev_addr.pmport);
19744 		return;
19745 	}
19746 	/*
19747 	 * We need to detach and release device info structure here
19748 	 */
19749 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19750 		sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19751 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19752 		(void) kmem_free((void *)sdevinfo,
19753 		    sizeof (sata_drive_info_t));
19754 	}
19755 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19756 	/*
19757 	 * Device cannot be reached anymore, even if the target node may be
19758 	 * still present.
19759 	 */
19760 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19761 
19762 	/*
19763 	 * Try to offline a device and remove target node if it still exists
19764 	 */
19765 	sata_remove_target_node(sata_hba_inst, saddr);
19766 
19767 	/*
19768 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19769 	 * with the hint: SE_HINT_REMOVE
19770 	 */
19771 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
19772 }
19773 
19774 
19775 /*
19776  * Device Attached Event processing.
19777  * Port state is checked to verify that a device is really attached. If so,
19778  * the device info structure is created and attached to the SATA port info
19779  * structure.
19780  *
19781  * If attached device cannot be identified or set-up, the retry for the
19782  * attach processing is set-up. Subsequent daemon run would try again to
19783  * identify the device, until the time limit is reached
19784  * (SATA_DEV_IDENTIFY_TIMEOUT).
19785  *
19786  * This function cannot be called in interrupt context (it may sleep).
19787  *
19788  * NOTE: Port multiplier ports events are handled by
19789  * sata_process_pmdevice_attached()
19790  */
19791 static void
19792 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
19793     sata_address_t *saddr)
19794 {
19795 	sata_cport_info_t *cportinfo = NULL;
19796 	sata_drive_info_t *sdevinfo = NULL;
19797 	sata_pmult_info_t *pmultinfo = NULL;
19798 	sata_pmport_info_t *pmportinfo = NULL;
19799 	sata_device_t sata_device;
19800 	dev_info_t *tdip;
19801 	uint32_t event_flags = 0, pmult_event_flags = 0;
19802 	int rval;
19803 	int npmport;
19804 
19805 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19806 	    "Processing port %d device attached", saddr->cport);
19807 
19808 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19809 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19810 
19811 	/* Clear attach event flag first */
19812 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19813 
19814 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19815 	if ((cportinfo->cport_state &
19816 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19817 		cportinfo->cport_dev_attach_time = 0;
19818 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19819 		    cport_mutex);
19820 		return;
19821 	}
19822 
19823 	/*
19824 	 * If the sata_drive_info structure is found attached to the port info,
19825 	 * despite the fact the device was removed and now it is re-attached,
19826 	 * the old drive info structure was not removed.
19827 	 * Arbitrarily release device info structure.
19828 	 */
19829 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19830 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
19831 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
19832 		(void) kmem_free((void *)sdevinfo,
19833 		    sizeof (sata_drive_info_t));
19834 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19835 		    "Arbitrarily detaching old device info.", NULL);
19836 	}
19837 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19838 
19839 	/* For sanity, re-probe the port */
19840 	sata_device.satadev_rev = SATA_DEVICE_REV;
19841 	sata_device.satadev_addr = *saddr;
19842 
19843 	/*
19844 	 * We have to exit mutex, because the HBA probe port function may
19845 	 * block on its own mutex.
19846 	 */
19847 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19848 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19849 	    (SATA_DIP(sata_hba_inst), &sata_device);
19850 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19851 	sata_update_port_info(sata_hba_inst, &sata_device);
19852 	if (rval != SATA_SUCCESS) {
19853 		/* Something went wrong? Fail the port */
19854 		cportinfo->cport_state = SATA_PSTATE_FAILED;
19855 		cportinfo->cport_dev_attach_time = 0;
19856 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19857 		    cport_mutex);
19858 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19859 		    "SATA port %d probing failed",
19860 		    saddr->cport));
19861 		return;
19862 	} else {
19863 		/* port probed successfully */
19864 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
19865 	}
19866 	/*
19867 	 * Check if a device is still attached. For sanity, check also
19868 	 * link status - if no link, there is no device.
19869 	 */
19870 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19871 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19872 	    SATA_DTYPE_NONE) {
19873 		/*
19874 		 * No device - ignore attach event.
19875 		 */
19876 		cportinfo->cport_dev_attach_time = 0;
19877 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19878 		    cport_mutex);
19879 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19880 		    "Ignoring attach - no device connected to port %d",
19881 		    sata_device.satadev_addr.cport);
19882 		return;
19883 	}
19884 
19885 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19886 	/*
19887 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19888 	 * with the hint: SE_HINT_INSERT
19889 	 */
19890 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19891 
19892 	/*
19893 	 * Port reprobing will take care of the creation of the device
19894 	 * info structure and determination of the device type.
19895 	 */
19896 	sata_device.satadev_addr = *saddr;
19897 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19898 	    SATA_DEV_IDENTIFY_NORETRY);
19899 
19900 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19901 	    cport_mutex);
19902 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
19903 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
19904 		/* Some device is attached to the port */
19905 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
19906 			/*
19907 			 * A device was not successfully attached.
19908 			 * Track retry time for device identification.
19909 			 */
19910 			if (cportinfo->cport_dev_attach_time != 0) {
19911 				clock_t cur_time = ddi_get_lbolt();
19912 				/*
19913 				 * If the retry time limit was not exceeded,
19914 				 * reinstate attach event.
19915 				 */
19916 				if ((cur_time -
19917 				    cportinfo->cport_dev_attach_time) <
19918 				    drv_usectohz(
19919 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19920 					/* OK, restore attach event */
19921 					cportinfo->cport_event_flags |=
19922 					    SATA_EVNT_DEVICE_ATTACHED;
19923 				} else {
19924 					/* Timeout - cannot identify device */
19925 					cportinfo->cport_dev_attach_time = 0;
19926 					sata_log(sata_hba_inst,
19927 					    CE_WARN,
19928 					    "Could not identify SATA device "
19929 					    "at port %d",
19930 					    saddr->cport);
19931 				}
19932 			} else {
19933 				/*
19934 				 * Start tracking time for device
19935 				 * identification.
19936 				 * Save current time (lbolt value).
19937 				 */
19938 				cportinfo->cport_dev_attach_time =
19939 				    ddi_get_lbolt();
19940 				/* Restore attach event */
19941 				cportinfo->cport_event_flags |=
19942 				    SATA_EVNT_DEVICE_ATTACHED;
19943 			}
19944 		} else if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19945 			cportinfo->cport_dev_attach_time = 0;
19946 			sata_log(sata_hba_inst, CE_NOTE,
19947 			    "SATA port-multiplier detected at port %d",
19948 			    saddr->cport);
19949 
19950 			if (SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL) {
19951 				/* Log the info of new port multiplier */
19952 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19953 				    saddr->cport)->cport_mutex);
19954 				sata_show_pmult_info(sata_hba_inst,
19955 				    &sata_device);
19956 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19957 				    saddr->cport)->cport_mutex);
19958 			}
19959 
19960 			ASSERT(SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL);
19961 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
19962 			for (npmport = 0; npmport <
19963 			    pmultinfo->pmult_num_dev_ports; npmport++) {
19964 				pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19965 				    saddr->cport, npmport);
19966 				ASSERT(pmportinfo != NULL);
19967 
19968 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19969 				    saddr->cport)->cport_mutex);
19970 				mutex_enter(&pmportinfo->pmport_mutex);
19971 				/* Marked all pmports with link events. */
19972 				pmportinfo->pmport_event_flags =
19973 				    SATA_EVNT_LINK_ESTABLISHED;
19974 				pmult_event_flags |=
19975 				    pmportinfo->pmport_event_flags;
19976 				mutex_exit(&pmportinfo->pmport_mutex);
19977 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19978 				    saddr->cport)->cport_mutex);
19979 			}
19980 			/* Auto-online is not available for PMult now. */
19981 
19982 		} else {
19983 			/*
19984 			 * If device was successfully attached, the subsequent
19985 			 * action depends on a state of the
19986 			 * sata_auto_online variable. If it is set to zero.
19987 			 * an explicit 'configure' command will be needed to
19988 			 * configure it. If its value is non-zero, we will
19989 			 * attempt to online (configure) the device.
19990 			 * First, log the message indicating that a device
19991 			 * was attached.
19992 			 */
19993 			cportinfo->cport_dev_attach_time = 0;
19994 			sata_log(sata_hba_inst, CE_WARN,
19995 			    "SATA device detected at port %d", saddr->cport);
19996 
19997 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19998 				sata_drive_info_t new_sdinfo;
19999 
20000 				/* Log device info data */
20001 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
20002 				    cportinfo));
20003 				sata_show_drive_info(sata_hba_inst,
20004 				    &new_sdinfo);
20005 			}
20006 
20007 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20008 			    saddr->cport)->cport_mutex);
20009 
20010 			/*
20011 			 * Make sure that there is no target node for that
20012 			 * device. If so, release it. It should not happen,
20013 			 * unless we had problem removing the node when
20014 			 * device was detached.
20015 			 */
20016 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
20017 			    saddr->cport, saddr->pmport);
20018 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20019 			    saddr->cport)->cport_mutex);
20020 			if (tdip != NULL) {
20021 
20022 #ifdef SATA_DEBUG
20023 				if ((cportinfo->cport_event_flags &
20024 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
20025 					sata_log(sata_hba_inst, CE_WARN,
20026 					    "sata_process_device_attached: "
20027 					    "old device target node exists!");
20028 #endif
20029 				/*
20030 				 * target node exists - try to unconfigure
20031 				 * device and remove the node.
20032 				 */
20033 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20034 				    saddr->cport)->cport_mutex);
20035 				rval = ndi_devi_offline(tdip,
20036 				    NDI_DEVI_REMOVE);
20037 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20038 				    saddr->cport)->cport_mutex);
20039 
20040 				if (rval == NDI_SUCCESS) {
20041 					cportinfo->cport_event_flags &=
20042 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
20043 					cportinfo->cport_tgtnode_clean = B_TRUE;
20044 				} else {
20045 					/*
20046 					 * PROBLEM - the target node remained
20047 					 * and it belongs to a previously
20048 					 * attached device.
20049 					 * This happens when the file was open
20050 					 * or the node was waiting for
20051 					 * resources at the time the
20052 					 * associated device was removed.
20053 					 * Instruct event daemon to retry the
20054 					 * cleanup later.
20055 					 */
20056 					sata_log(sata_hba_inst,
20057 					    CE_WARN,
20058 					    "Application(s) accessing "
20059 					    "previously attached SATA "
20060 					    "device have to release "
20061 					    "it before newly inserted "
20062 					    "device can be made accessible.",
20063 					    saddr->cport);
20064 					cportinfo->cport_event_flags |=
20065 					    SATA_EVNT_TARGET_NODE_CLEANUP;
20066 					cportinfo->cport_tgtnode_clean =
20067 					    B_FALSE;
20068 				}
20069 			}
20070 			if (sata_auto_online != 0) {
20071 				cportinfo->cport_event_flags |=
20072 				    SATA_EVNT_AUTOONLINE_DEVICE;
20073 			}
20074 
20075 		}
20076 	} else {
20077 		cportinfo->cport_dev_attach_time = 0;
20078 	}
20079 
20080 	event_flags = cportinfo->cport_event_flags;
20081 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
20082 	if (event_flags != 0 || pmult_event_flags != 0) {
20083 		mutex_enter(&sata_hba_inst->satahba_mutex);
20084 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20085 		mutex_exit(&sata_hba_inst->satahba_mutex);
20086 		mutex_enter(&sata_mutex);
20087 		sata_event_pending |= SATA_EVNT_MAIN;
20088 		mutex_exit(&sata_mutex);
20089 	}
20090 }
20091 
20092 /*
20093  * Port Multiplier Port Device Attached Event processing.
20094  *
20095  * NOTE: No Mutex should be hold.
20096  */
20097 static void
20098 sata_process_pmdevice_attached(sata_hba_inst_t *sata_hba_inst,
20099     sata_address_t *saddr)
20100 {
20101 	sata_pmport_info_t *pmportinfo;
20102 	sata_drive_info_t *sdinfo;
20103 	sata_device_t sata_device;
20104 	dev_info_t *tdip;
20105 	uint32_t event_flags;
20106 	uint8_t cport = saddr->cport;
20107 	uint8_t pmport = saddr->pmport;
20108 	int rval;
20109 
20110 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20111 	    "Processing port %d:%d device attached", cport, pmport);
20112 
20113 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
20114 
20115 	mutex_enter(&pmportinfo->pmport_mutex);
20116 
20117 	/* Clear attach event flag first */
20118 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
20119 
20120 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
20121 	if ((pmportinfo->pmport_state &
20122 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
20123 		pmportinfo->pmport_dev_attach_time = 0;
20124 		mutex_exit(&pmportinfo->pmport_mutex);
20125 		return;
20126 	}
20127 
20128 	/*
20129 	 * If the sata_drive_info structure is found attached to the port info,
20130 	 * despite the fact the device was removed and now it is re-attached,
20131 	 * the old drive info structure was not removed.
20132 	 * Arbitrarily release device info structure.
20133 	 */
20134 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
20135 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
20136 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
20137 		(void) kmem_free((void *)sdinfo,
20138 		    sizeof (sata_drive_info_t));
20139 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20140 		    "Arbitrarily detaching old device info.", NULL);
20141 	}
20142 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
20143 
20144 	/* For sanity, re-probe the port */
20145 	sata_device.satadev_rev = SATA_DEVICE_REV;
20146 	sata_device.satadev_addr = *saddr;
20147 
20148 	/*
20149 	 * We have to exit mutex, because the HBA probe port function may
20150 	 * block on its own mutex.
20151 	 */
20152 	mutex_exit(&pmportinfo->pmport_mutex);
20153 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
20154 	    (SATA_DIP(sata_hba_inst), &sata_device);
20155 	mutex_enter(&pmportinfo->pmport_mutex);
20156 
20157 	sata_update_pmport_info(sata_hba_inst, &sata_device);
20158 	if (rval != SATA_SUCCESS) {
20159 		/* Something went wrong? Fail the port */
20160 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
20161 		pmportinfo->pmport_dev_attach_time = 0;
20162 		mutex_exit(&pmportinfo->pmport_mutex);
20163 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20164 		    "SATA port %d:%d probing failed", cport, pmport));
20165 		return;
20166 	} else {
20167 		/* pmport probed successfully */
20168 		pmportinfo->pmport_state |=
20169 		    SATA_STATE_PROBED | SATA_STATE_READY;
20170 	}
20171 	/*
20172 	 * Check if a device is still attached. For sanity, check also
20173 	 * link status - if no link, there is no device.
20174 	 */
20175 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
20176 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
20177 	    SATA_DTYPE_NONE) {
20178 		/*
20179 		 * No device - ignore attach event.
20180 		 */
20181 		pmportinfo->pmport_dev_attach_time = 0;
20182 		mutex_exit(&pmportinfo->pmport_mutex);
20183 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20184 		    "Ignoring attach - no device connected to port %d:%d",
20185 		    cport, pmport);
20186 		return;
20187 	}
20188 
20189 	mutex_exit(&pmportinfo->pmport_mutex);
20190 	/*
20191 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
20192 	 * with the hint: SE_HINT_INSERT
20193 	 */
20194 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
20195 
20196 	/*
20197 	 * Port reprobing will take care of the creation of the device
20198 	 * info structure and determination of the device type.
20199 	 */
20200 	sata_device.satadev_addr = *saddr;
20201 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
20202 	    SATA_DEV_IDENTIFY_NORETRY);
20203 
20204 	mutex_enter(&pmportinfo->pmport_mutex);
20205 	if ((pmportinfo->pmport_state & SATA_STATE_READY) &&
20206 	    (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE)) {
20207 		/* Some device is attached to the port */
20208 		if (pmportinfo->pmport_dev_type == SATA_DTYPE_UNKNOWN) {
20209 			/*
20210 			 * A device was not successfully attached.
20211 			 * Track retry time for device identification.
20212 			 */
20213 			if (pmportinfo->pmport_dev_attach_time != 0) {
20214 				clock_t cur_time = ddi_get_lbolt();
20215 				/*
20216 				 * If the retry time limit was not exceeded,
20217 				 * reinstate attach event.
20218 				 */
20219 				if ((cur_time -
20220 				    pmportinfo->pmport_dev_attach_time) <
20221 				    drv_usectohz(
20222 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
20223 					/* OK, restore attach event */
20224 					pmportinfo->pmport_event_flags |=
20225 					    SATA_EVNT_DEVICE_ATTACHED;
20226 				} else {
20227 					/* Timeout - cannot identify device */
20228 					pmportinfo->pmport_dev_attach_time = 0;
20229 					sata_log(sata_hba_inst, CE_WARN,
20230 					    "Could not identify SATA device "
20231 					    "at port %d:%d",
20232 					    cport, pmport);
20233 				}
20234 			} else {
20235 				/*
20236 				 * Start tracking time for device
20237 				 * identification.
20238 				 * Save current time (lbolt value).
20239 				 */
20240 				pmportinfo->pmport_dev_attach_time =
20241 				    ddi_get_lbolt();
20242 				/* Restore attach event */
20243 				pmportinfo->pmport_event_flags |=
20244 				    SATA_EVNT_DEVICE_ATTACHED;
20245 			}
20246 		} else {
20247 			/*
20248 			 * If device was successfully attached, the subsequent
20249 			 * action depends on a state of the
20250 			 * sata_auto_online variable. If it is set to zero.
20251 			 * an explicit 'configure' command will be needed to
20252 			 * configure it. If its value is non-zero, we will
20253 			 * attempt to online (configure) the device.
20254 			 * First, log the message indicating that a device
20255 			 * was attached.
20256 			 */
20257 			pmportinfo->pmport_dev_attach_time = 0;
20258 			sata_log(sata_hba_inst, CE_WARN,
20259 			    "SATA device detected at port %d:%d",
20260 			    cport, pmport);
20261 
20262 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
20263 				sata_drive_info_t new_sdinfo;
20264 
20265 				/* Log device info data */
20266 				new_sdinfo = *(SATA_PMPORTINFO_DRV_INFO(
20267 				    pmportinfo));
20268 				sata_show_drive_info(sata_hba_inst,
20269 				    &new_sdinfo);
20270 			}
20271 
20272 			mutex_exit(&pmportinfo->pmport_mutex);
20273 
20274 			/*
20275 			 * Make sure that there is no target node for that
20276 			 * device. If so, release it. It should not happen,
20277 			 * unless we had problem removing the node when
20278 			 * device was detached.
20279 			 */
20280 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
20281 			    saddr->cport, saddr->pmport);
20282 			mutex_enter(&pmportinfo->pmport_mutex);
20283 			if (tdip != NULL) {
20284 
20285 #ifdef SATA_DEBUG
20286 				if ((pmportinfo->pmport_event_flags &
20287 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
20288 					sata_log(sata_hba_inst, CE_WARN,
20289 					    "sata_process_device_attached: "
20290 					    "old device target node exists!");
20291 #endif
20292 				/*
20293 				 * target node exists - try to unconfigure
20294 				 * device and remove the node.
20295 				 */
20296 				mutex_exit(&pmportinfo->pmport_mutex);
20297 				rval = ndi_devi_offline(tdip,
20298 				    NDI_DEVI_REMOVE);
20299 				mutex_enter(&pmportinfo->pmport_mutex);
20300 
20301 				if (rval == NDI_SUCCESS) {
20302 					pmportinfo->pmport_event_flags &=
20303 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
20304 					pmportinfo->pmport_tgtnode_clean =
20305 					    B_TRUE;
20306 				} else {
20307 					/*
20308 					 * PROBLEM - the target node remained
20309 					 * and it belongs to a previously
20310 					 * attached device.
20311 					 * This happens when the file was open
20312 					 * or the node was waiting for
20313 					 * resources at the time the
20314 					 * associated device was removed.
20315 					 * Instruct event daemon to retry the
20316 					 * cleanup later.
20317 					 */
20318 					sata_log(sata_hba_inst,
20319 					    CE_WARN,
20320 					    "Application(s) accessing "
20321 					    "previously attached SATA "
20322 					    "device have to release "
20323 					    "it before newly inserted "
20324 					    "device can be made accessible."
20325 					    "at port %d:%d",
20326 					    cport, pmport);
20327 					pmportinfo->pmport_event_flags |=
20328 					    SATA_EVNT_TARGET_NODE_CLEANUP;
20329 					pmportinfo->pmport_tgtnode_clean =
20330 					    B_FALSE;
20331 				}
20332 			}
20333 			if (sata_auto_online != 0) {
20334 				pmportinfo->pmport_event_flags |=
20335 				    SATA_EVNT_AUTOONLINE_DEVICE;
20336 			}
20337 
20338 		}
20339 	} else {
20340 		pmportinfo->pmport_dev_attach_time = 0;
20341 	}
20342 
20343 	event_flags = pmportinfo->pmport_event_flags;
20344 	mutex_exit(&pmportinfo->pmport_mutex);
20345 	if (event_flags != 0) {
20346 		mutex_enter(&sata_hba_inst->satahba_mutex);
20347 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20348 		mutex_exit(&sata_hba_inst->satahba_mutex);
20349 		mutex_enter(&sata_mutex);
20350 		sata_event_pending |= SATA_EVNT_MAIN;
20351 		mutex_exit(&sata_mutex);
20352 	}
20353 
20354 	/* clear the reset_in_progress events */
20355 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
20356 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
20357 			/* must clear flags on cport */
20358 			sata_pmult_info_t *pminfo =
20359 			    SATA_PMULT_INFO(sata_hba_inst,
20360 			    saddr->cport);
20361 			pminfo->pmult_event_flags |=
20362 			    SATA_EVNT_CLEAR_DEVICE_RESET;
20363 		}
20364 	}
20365 }
20366 
20367 /*
20368  * Device Target Node Cleanup Event processing.
20369  * If the target node associated with a sata port device is in
20370  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
20371  * If the target node cannot be removed, the event flag is left intact,
20372  * so that event daemon may re-run this function later.
20373  *
20374  * This function cannot be called in interrupt context (it may sleep).
20375  *
20376  * NOTE: Processes cport events only, not port multiplier ports.
20377  */
20378 static void
20379 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
20380     sata_address_t *saddr)
20381 {
20382 	sata_cport_info_t *cportinfo;
20383 	dev_info_t *tdip;
20384 
20385 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20386 	    "Processing port %d device target node cleanup", saddr->cport);
20387 
20388 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
20389 
20390 	/*
20391 	 * Check if there is target node for that device and it is in the
20392 	 * DEVI_DEVICE_REMOVED state. If so, release it.
20393 	 */
20394 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
20395 	    saddr->pmport);
20396 	if (tdip != NULL) {
20397 		/*
20398 		 * target node exists - check if it is target node of
20399 		 * a removed device.
20400 		 */
20401 		if (sata_check_device_removed(tdip) == B_TRUE) {
20402 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20403 			    "sata_process_target_node_cleanup: "
20404 			    "old device target node exists!", NULL);
20405 			/*
20406 			 * Unconfigure and remove the target node
20407 			 */
20408 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
20409 			    NDI_SUCCESS) {
20410 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20411 				    saddr->cport)->cport_mutex);
20412 				cportinfo->cport_event_flags &=
20413 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
20414 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20415 				    saddr->cport)->cport_mutex);
20416 				return;
20417 			}
20418 			/*
20419 			 * Event daemon will retry the cleanup later.
20420 			 */
20421 			mutex_enter(&sata_hba_inst->satahba_mutex);
20422 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20423 			mutex_exit(&sata_hba_inst->satahba_mutex);
20424 			mutex_enter(&sata_mutex);
20425 			sata_event_pending |= SATA_EVNT_MAIN;
20426 			mutex_exit(&sata_mutex);
20427 		}
20428 	} else {
20429 		if (saddr->qual == SATA_ADDR_CPORT ||
20430 		    saddr->qual == SATA_ADDR_DCPORT) {
20431 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20432 			    saddr->cport)->cport_mutex);
20433 			cportinfo->cport_event_flags &=
20434 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
20435 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20436 			    saddr->cport)->cport_mutex);
20437 		} else {
20438 			/* sanity check */
20439 			if (SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) !=
20440 			    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
20441 			    saddr->cport) == NULL)
20442 				return;
20443 			if (SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
20444 			    saddr->pmport) == NULL)
20445 				return;
20446 
20447 			mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
20448 			    saddr->cport, saddr->pmport)->pmport_mutex);
20449 			SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
20450 			    saddr->pmport)->pmport_event_flags &=
20451 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
20452 			mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
20453 			    saddr->cport, saddr->pmport)->pmport_mutex);
20454 		}
20455 	}
20456 }
20457 
20458 /*
20459  * Device AutoOnline Event processing.
20460  * If attached device is to be onlined, an attempt is made to online this
20461  * device, but only if there is no lingering (old) target node present.
20462  * If the device cannot be onlined, the event flag is left intact,
20463  * so that event daemon may re-run this function later.
20464  *
20465  * This function cannot be called in interrupt context (it may sleep).
20466  *
20467  * NOTE: Processes cport events only, not port multiplier ports.
20468  */
20469 static void
20470 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
20471     sata_address_t *saddr)
20472 {
20473 	sata_cport_info_t *cportinfo;
20474 	sata_drive_info_t *sdinfo;
20475 	sata_device_t sata_device;
20476 	dev_info_t *tdip;
20477 
20478 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20479 	    "Processing port %d attached device auto-onlining", saddr->cport);
20480 
20481 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
20482 
20483 	/*
20484 	 * Check if device is present and recognized. If not, reset event.
20485 	 */
20486 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
20487 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
20488 		/* Nothing to online */
20489 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
20490 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20491 		    saddr->cport)->cport_mutex);
20492 		return;
20493 	}
20494 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
20495 
20496 	/*
20497 	 * Check if there is target node for this device and if it is in the
20498 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
20499 	 * the event for later processing.
20500 	 */
20501 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
20502 	    saddr->pmport);
20503 	if (tdip != NULL) {
20504 		/*
20505 		 * target node exists - check if it is target node of
20506 		 * a removed device.
20507 		 */
20508 		if (sata_check_device_removed(tdip) == B_TRUE) {
20509 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
20510 			    "sata_process_device_autoonline: "
20511 			    "old device target node exists!", NULL);
20512 			/*
20513 			 * Event daemon will retry device onlining later.
20514 			 */
20515 			mutex_enter(&sata_hba_inst->satahba_mutex);
20516 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20517 			mutex_exit(&sata_hba_inst->satahba_mutex);
20518 			mutex_enter(&sata_mutex);
20519 			sata_event_pending |= SATA_EVNT_MAIN;
20520 			mutex_exit(&sata_mutex);
20521 			return;
20522 		}
20523 		/*
20524 		 * If the target node is not in the 'removed" state, assume
20525 		 * that it belongs to this device. There is nothing more to do,
20526 		 * but reset the event.
20527 		 */
20528 	} else {
20529 
20530 		/*
20531 		 * Try to online the device
20532 		 * If there is any reset-related event, remove it. We are
20533 		 * configuring the device and no state restoring is needed.
20534 		 */
20535 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20536 		    saddr->cport)->cport_mutex);
20537 		sata_device.satadev_addr = *saddr;
20538 		if (saddr->qual == SATA_ADDR_CPORT)
20539 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
20540 		else
20541 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
20542 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
20543 		if (sdinfo != NULL) {
20544 			if (sdinfo->satadrv_event_flags &
20545 			    (SATA_EVNT_DEVICE_RESET |
20546 			    SATA_EVNT_INPROC_DEVICE_RESET))
20547 				sdinfo->satadrv_event_flags = 0;
20548 			sdinfo->satadrv_event_flags |=
20549 			    SATA_EVNT_CLEAR_DEVICE_RESET;
20550 
20551 			/* Need to create a new target node. */
20552 			cportinfo->cport_tgtnode_clean = B_TRUE;
20553 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20554 			    saddr->cport)->cport_mutex);
20555 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
20556 			    sata_hba_inst, &sata_device.satadev_addr);
20557 			if (tdip == NULL) {
20558 				/*
20559 				 * Configure (onlining) failed.
20560 				 * We will NOT retry
20561 				 */
20562 				SATA_LOG_D((sata_hba_inst, CE_WARN,
20563 				    "sata_process_device_autoonline: "
20564 				    "configuring SATA device at port %d failed",
20565 				    saddr->cport));
20566 			}
20567 		} else {
20568 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20569 			    saddr->cport)->cport_mutex);
20570 		}
20571 
20572 	}
20573 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
20574 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
20575 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20576 	    saddr->cport)->cport_mutex);
20577 }
20578 
20579 
20580 static void
20581 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
20582     int hint)
20583 {
20584 	char ap[MAXPATHLEN];
20585 	nvlist_t *ev_attr_list = NULL;
20586 	int err;
20587 
20588 	/* Allocate and build sysevent attribute list */
20589 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
20590 	if (err != 0) {
20591 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20592 		    "sata_gen_sysevent: "
20593 		    "cannot allocate memory for sysevent attributes\n"));
20594 		return;
20595 	}
20596 	/* Add hint attribute */
20597 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
20598 	if (err != 0) {
20599 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20600 		    "sata_gen_sysevent: "
20601 		    "failed to add DR_HINT attr for sysevent"));
20602 		nvlist_free(ev_attr_list);
20603 		return;
20604 	}
20605 	/*
20606 	 * Add AP attribute.
20607 	 * Get controller pathname and convert it into AP pathname by adding
20608 	 * a target number.
20609 	 */
20610 	(void) snprintf(ap, MAXPATHLEN, "/devices");
20611 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
20612 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
20613 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
20614 
20615 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
20616 	if (err != 0) {
20617 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20618 		    "sata_gen_sysevent: "
20619 		    "failed to add DR_AP_ID attr for sysevent"));
20620 		nvlist_free(ev_attr_list);
20621 		return;
20622 	}
20623 
20624 	/* Generate/log sysevent */
20625 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
20626 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
20627 	if (err != DDI_SUCCESS) {
20628 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20629 		    "sata_gen_sysevent: "
20630 		    "cannot log sysevent, err code %x\n", err));
20631 	}
20632 
20633 	nvlist_free(ev_attr_list);
20634 }
20635 
20636 
20637 
20638 
20639 /*
20640  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
20641  */
20642 static void
20643 sata_set_device_removed(dev_info_t *tdip)
20644 {
20645 	int circ;
20646 
20647 	ASSERT(tdip != NULL);
20648 
20649 	ndi_devi_enter(tdip, &circ);
20650 	mutex_enter(&DEVI(tdip)->devi_lock);
20651 	DEVI_SET_DEVICE_REMOVED(tdip);
20652 	mutex_exit(&DEVI(tdip)->devi_lock);
20653 	ndi_devi_exit(tdip, circ);
20654 }
20655 
20656 
20657 /*
20658  * Set internal event instructing event daemon to try
20659  * to perform the target node cleanup.
20660  */
20661 static void
20662 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
20663     sata_address_t *saddr)
20664 {
20665 	if (saddr->qual == SATA_ADDR_CPORT ||
20666 	    saddr->qual == SATA_ADDR_DCPORT) {
20667 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20668 		    saddr->cport)->cport_mutex);
20669 		SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
20670 		    SATA_EVNT_TARGET_NODE_CLEANUP;
20671 		SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
20672 		    cport_tgtnode_clean = B_FALSE;
20673 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20674 		    saddr->cport)->cport_mutex);
20675 	} else {
20676 		mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
20677 		    saddr->cport, saddr->pmport)->pmport_mutex);
20678 		SATA_PMPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport,
20679 		    saddr->pmport) |= SATA_EVNT_TARGET_NODE_CLEANUP;
20680 		SATA_PMPORT_INFO(sata_hba_inst, saddr->cport, saddr->pmport)->
20681 		    pmport_tgtnode_clean = B_FALSE;
20682 		mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
20683 		    saddr->cport, saddr->pmport)->pmport_mutex);
20684 	}
20685 	mutex_enter(&sata_hba_inst->satahba_mutex);
20686 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20687 	mutex_exit(&sata_hba_inst->satahba_mutex);
20688 	mutex_enter(&sata_mutex);
20689 	sata_event_pending |= SATA_EVNT_MAIN;
20690 	mutex_exit(&sata_mutex);
20691 }
20692 
20693 
20694 /*
20695  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
20696  * i.e. check if the target node state indicates that it belongs to a removed
20697  * device.
20698  *
20699  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
20700  * B_FALSE otherwise.
20701  */
20702 static boolean_t
20703 sata_check_device_removed(dev_info_t *tdip)
20704 {
20705 	ASSERT(tdip != NULL);
20706 
20707 	if (DEVI_IS_DEVICE_REMOVED(tdip))
20708 		return (B_TRUE);
20709 	else
20710 		return (B_FALSE);
20711 }
20712 
20713 
20714 /*
20715  * Check for DMA error. Return B_TRUE if error, B_FALSE otherwise.
20716  */
20717 static boolean_t
20718 sata_check_for_dma_error(dev_info_t *dip, sata_pkt_txlate_t *spx)
20719 {
20720 	int fm_capability = ddi_fm_capable(dip);
20721 	ddi_fm_error_t de;
20722 
20723 	if (fm_capability & DDI_FM_DMACHK_CAPABLE) {
20724 		if (spx->txlt_buf_dma_handle != NULL) {
20725 			ddi_fm_dma_err_get(spx->txlt_buf_dma_handle, &de,
20726 			    DDI_FME_VERSION);
20727 			if (de.fme_status != DDI_SUCCESS)
20728 				return (B_TRUE);
20729 		}
20730 	}
20731 	return (B_FALSE);
20732 }
20733 
20734 
20735 /* ************************ FAULT INJECTTION **************************** */
20736 
20737 #ifdef SATA_INJECT_FAULTS
20738 
20739 static	uint32_t sata_fault_count = 0;
20740 static	uint32_t sata_fault_suspend_count = 0;
20741 
20742 /*
20743  * Inject sata pkt fault
20744  * It modifies returned values of the sata packet.
20745  * It returns immediately if:
20746  * pkt fault injection is not enabled (via sata_inject_fault,
20747  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
20748  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
20749  * pkt is not directed to specified fault controller/device
20750  * (sata_fault_ctrl_dev and sata_fault_device).
20751  * If fault controller is not specified, fault injection applies to all
20752  * controllers and devices.
20753  *
20754  * First argument is the pointer to the executed sata packet.
20755  * Second argument is a pointer to a value returned by the HBA tran_start
20756  * function.
20757  * Third argument specifies injected error. Injected sata packet faults
20758  * are the satapkt_reason values.
20759  * SATA_PKT_BUSY		-1	Not completed, busy
20760  * SATA_PKT_DEV_ERROR		1	Device reported error
20761  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
20762  * SATA_PKT_PORT_ERROR		3	Not completed, port error
20763  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
20764  * SATA_PKT_ABORTED		5	Aborted by request
20765  * SATA_PKT_TIMEOUT		6	Operation timeut
20766  * SATA_PKT_RESET		7	Aborted by reset request
20767  *
20768  * Additional global variables affecting the execution:
20769  *
20770  * sata_inject_fault_count variable specifies number of times in row the
20771  * error is injected. Value of -1 specifies permanent fault, ie. every time
20772  * the fault injection point is reached, the fault is injected and a pause
20773  * between fault injection specified by sata_inject_fault_pause_count is
20774  * ignored). Fault injection routine decrements sata_inject_fault_count
20775  * (if greater than zero) until it reaches 0. No fault is injected when
20776  * sata_inject_fault_count is 0 (zero).
20777  *
20778  * sata_inject_fault_pause_count variable specifies number of times a fault
20779  * injection is bypassed (pause between fault injections).
20780  * If set to 0, a fault is injected only a number of times specified by
20781  * sata_inject_fault_count.
20782  *
20783  * The fault counts are static, so for periodic errors they have to be manually
20784  * reset to start repetition sequence from scratch.
20785  * If the original value returned by the HBA tran_start function is not
20786  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
20787  * is injected (to avoid masking real problems);
20788  *
20789  * NOTE: In its current incarnation, this function should be invoked only for
20790  * commands executed in SYNCHRONOUS mode.
20791  */
20792 
20793 
20794 static void
20795 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
20796 {
20797 
20798 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
20799 		return;
20800 
20801 	if (sata_inject_fault_count == 0)
20802 		return;
20803 
20804 	if (fault == 0)
20805 		return;
20806 
20807 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
20808 		return;
20809 
20810 	if (sata_fault_ctrl != NULL) {
20811 		sata_pkt_txlate_t *spx =
20812 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
20813 
20814 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
20815 		    spx->txlt_sata_hba_inst->satahba_dip)
20816 			return;
20817 
20818 		if (sata_fault_device.satadev_addr.cport !=
20819 		    spkt->satapkt_device.satadev_addr.cport ||
20820 		    sata_fault_device.satadev_addr.pmport !=
20821 		    spkt->satapkt_device.satadev_addr.pmport ||
20822 		    sata_fault_device.satadev_addr.qual !=
20823 		    spkt->satapkt_device.satadev_addr.qual)
20824 			return;
20825 	}
20826 
20827 	/* Modify pkt return parameters */
20828 	if (*rval != SATA_TRAN_ACCEPTED ||
20829 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
20830 		sata_fault_count = 0;
20831 		sata_fault_suspend_count = 0;
20832 		return;
20833 	}
20834 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
20835 		/* Pause in the injection */
20836 		sata_fault_suspend_count -= 1;
20837 		return;
20838 	}
20839 
20840 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
20841 		/*
20842 		 * Init inject fault cycle. If fault count is set to -1,
20843 		 * it is a permanent fault.
20844 		 */
20845 		if (sata_inject_fault_count != -1) {
20846 			sata_fault_count = sata_inject_fault_count;
20847 			sata_fault_suspend_count =
20848 			    sata_inject_fault_pause_count;
20849 			if (sata_fault_suspend_count == 0)
20850 				sata_inject_fault_count = 0;
20851 		}
20852 	}
20853 
20854 	if (sata_fault_count != 0)
20855 		sata_fault_count -= 1;
20856 
20857 	switch (fault) {
20858 	case SATA_PKT_BUSY:
20859 		*rval = SATA_TRAN_BUSY;
20860 		spkt->satapkt_reason = SATA_PKT_BUSY;
20861 		break;
20862 
20863 	case SATA_PKT_QUEUE_FULL:
20864 		*rval = SATA_TRAN_QUEUE_FULL;
20865 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
20866 		break;
20867 
20868 	case SATA_PKT_CMD_UNSUPPORTED:
20869 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
20870 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
20871 		break;
20872 
20873 	case SATA_PKT_PORT_ERROR:
20874 		/* This is "rejected" command */
20875 		*rval = SATA_TRAN_PORT_ERROR;
20876 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
20877 		/* Additional error setup could be done here - port state */
20878 		break;
20879 
20880 	case SATA_PKT_DEV_ERROR:
20881 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
20882 		/*
20883 		 * Additional error setup could be done here
20884 		 */
20885 		break;
20886 
20887 	case SATA_PKT_ABORTED:
20888 		spkt->satapkt_reason = SATA_PKT_ABORTED;
20889 		break;
20890 
20891 	case SATA_PKT_TIMEOUT:
20892 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
20893 		/* Additional error setup could be done here */
20894 		break;
20895 
20896 	case SATA_PKT_RESET:
20897 		spkt->satapkt_reason = SATA_PKT_RESET;
20898 		/*
20899 		 * Additional error setup could be done here - device reset
20900 		 */
20901 		break;
20902 
20903 	default:
20904 		break;
20905 	}
20906 }
20907 
20908 #endif
20909 
20910 /*
20911  * SATA Trace Ring Buffer
20912  * ----------------------
20913  *
20914  * Overview
20915  *
20916  * The SATA trace ring buffer is a ring buffer created and managed by
20917  * the SATA framework module that can be used by any module or driver
20918  * within the SATA framework to store debug messages.
20919  *
20920  * Ring Buffer Interfaces:
20921  *
20922  *	sata_vtrace_debug()	<-- Adds debug message to ring buffer
20923  *	sata_trace_debug()	<-- Wraps varargs into sata_vtrace_debug()
20924  *
20925  *	Note that the sata_trace_debug() interface was created to give
20926  *	consumers the flexibilty of sending debug messages to ring buffer
20927  *	as variable arguments.  Consumers can send type va_list debug
20928  *	messages directly to sata_vtrace_debug(). The sata_trace_debug()
20929  *	and sata_vtrace_debug() relationship is similar to that of
20930  *	cmn_err(9F) and vcmn_err(9F).
20931  *
20932  * Below is a diagram of the SATA trace ring buffer interfaces and
20933  * sample consumers:
20934  *
20935  * +---------------------------------+
20936  * |    o  o  SATA Framework Module  |
20937  * | o  SATA  o     +------------------+      +------------------+
20938  * |o   Trace  o <--|sata_vtrace_debug/|<-----|SATA HBA Driver #1|
20939  * |o   R-Buf  o    |sata_trace_debug  |<--+  +------------------+
20940  * | o        o     +------------------+   |  +------------------+
20941  * |    o  o                ^        |     +--|SATA HBA Driver #2|
20942  * |                        |        |        +------------------+
20943  * |           +------------------+  |
20944  * |           |SATA Debug Message|  |
20945  * |           +------------------+  |
20946  * +---------------------------------+
20947  *
20948  * Supporting Routines:
20949  *
20950  *	sata_trace_rbuf_alloc()	<-- Initializes ring buffer
20951  *	sata_trace_rbuf_free()	<-- Destroys ring buffer
20952  *	sata_trace_dmsg_alloc() <-- Creates or reuses buffer in ring buffer
20953  *	sata_trace_dmsg_free()	<-- Destroys content of ring buffer
20954  *
20955  * The default SATA trace ring buffer size is defined by DMSG_RING_SIZE.
20956  * The ring buffer size can be adjusted by setting dmsg_ring_size in
20957  * /etc/system to desired size in unit of bytes.
20958  *
20959  * The individual debug message size in the ring buffer is restricted
20960  * to DMSG_BUF_SIZE.
20961  */
20962 void
20963 sata_vtrace_debug(dev_info_t *dip, const char *fmt, va_list ap)
20964 {
20965 	sata_trace_dmsg_t *dmsg;
20966 
20967 	if (sata_debug_rbuf == NULL) {
20968 		return;
20969 	}
20970 
20971 	/*
20972 	 * If max size of ring buffer is smaller than size
20973 	 * required for one debug message then just return
20974 	 * since we have no room for the debug message.
20975 	 */
20976 	if (sata_debug_rbuf->maxsize < (sizeof (sata_trace_dmsg_t))) {
20977 		return;
20978 	}
20979 
20980 	mutex_enter(&sata_debug_rbuf->lock);
20981 
20982 	/* alloc or reuse on ring buffer */
20983 	dmsg = sata_trace_dmsg_alloc();
20984 
20985 	if (dmsg == NULL) {
20986 		/* resource allocation failed */
20987 		mutex_exit(&sata_debug_rbuf->lock);
20988 		return;
20989 	}
20990 
20991 	dmsg->dip = dip;
20992 	gethrestime(&dmsg->timestamp);
20993 
20994 	(void) vsnprintf(dmsg->buf, sizeof (dmsg->buf), fmt, ap);
20995 
20996 	mutex_exit(&sata_debug_rbuf->lock);
20997 }
20998 
20999 void
21000 sata_trace_debug(dev_info_t *dip, const char *fmt, ...)
21001 {
21002 	va_list ap;
21003 
21004 	va_start(ap, fmt);
21005 	sata_vtrace_debug(dip, fmt, ap);
21006 	va_end(ap);
21007 }
21008 
21009 /*
21010  * This routine is used to manage debug messages
21011  * on ring buffer.
21012  */
21013 static sata_trace_dmsg_t *
21014 sata_trace_dmsg_alloc(void)
21015 {
21016 	sata_trace_dmsg_t *dmsg_alloc, *dmsg = sata_debug_rbuf->dmsgp;
21017 
21018 	if (sata_debug_rbuf->looped == TRUE) {
21019 		sata_debug_rbuf->dmsgp = dmsg->next;
21020 		return (sata_debug_rbuf->dmsgp);
21021 	}
21022 
21023 	/*
21024 	 * If we're looping for the first time,
21025 	 * connect the ring.
21026 	 */
21027 	if (((sata_debug_rbuf->size + (sizeof (sata_trace_dmsg_t))) >
21028 	    sata_debug_rbuf->maxsize) && (sata_debug_rbuf->dmsgh != NULL)) {
21029 		dmsg->next = sata_debug_rbuf->dmsgh;
21030 		sata_debug_rbuf->dmsgp = sata_debug_rbuf->dmsgh;
21031 		sata_debug_rbuf->looped = TRUE;
21032 		return (sata_debug_rbuf->dmsgp);
21033 	}
21034 
21035 	/* If we've gotten this far then memory allocation is needed */
21036 	dmsg_alloc = kmem_zalloc(sizeof (sata_trace_dmsg_t), KM_NOSLEEP);
21037 	if (dmsg_alloc == NULL) {
21038 		sata_debug_rbuf->allocfailed++;
21039 		return (dmsg_alloc);
21040 	} else {
21041 		sata_debug_rbuf->size += sizeof (sata_trace_dmsg_t);
21042 	}
21043 
21044 	if (sata_debug_rbuf->dmsgp != NULL) {
21045 		dmsg->next = dmsg_alloc;
21046 		sata_debug_rbuf->dmsgp = dmsg->next;
21047 		return (sata_debug_rbuf->dmsgp);
21048 	} else {
21049 		/*
21050 		 * We should only be here if we're initializing
21051 		 * the ring buffer.
21052 		 */
21053 		if (sata_debug_rbuf->dmsgh == NULL) {
21054 			sata_debug_rbuf->dmsgh = dmsg_alloc;
21055 		} else {
21056 			/* Something is wrong */
21057 			kmem_free(dmsg_alloc, sizeof (sata_trace_dmsg_t));
21058 			return (NULL);
21059 		}
21060 
21061 		sata_debug_rbuf->dmsgp = dmsg_alloc;
21062 		return (sata_debug_rbuf->dmsgp);
21063 	}
21064 }
21065 
21066 
21067 /*
21068  * Free all messages on debug ring buffer.
21069  */
21070 static void
21071 sata_trace_dmsg_free(void)
21072 {
21073 	sata_trace_dmsg_t *dmsg_next, *dmsg = sata_debug_rbuf->dmsgh;
21074 
21075 	while (dmsg != NULL) {
21076 		dmsg_next = dmsg->next;
21077 		kmem_free(dmsg, sizeof (sata_trace_dmsg_t));
21078 
21079 		/*
21080 		 * If we've looped around the ring than we're done.
21081 		 */
21082 		if (dmsg_next == sata_debug_rbuf->dmsgh) {
21083 			break;
21084 		} else {
21085 			dmsg = dmsg_next;
21086 		}
21087 	}
21088 }
21089 
21090 
21091 /*
21092  * This function can block
21093  */
21094 static void
21095 sata_trace_rbuf_alloc(void)
21096 {
21097 	sata_debug_rbuf = kmem_zalloc(sizeof (sata_trace_rbuf_t), KM_SLEEP);
21098 
21099 	mutex_init(&sata_debug_rbuf->lock, NULL, MUTEX_DRIVER, NULL);
21100 
21101 	if (dmsg_ring_size > 0) {
21102 		sata_debug_rbuf->maxsize = (size_t)dmsg_ring_size;
21103 	}
21104 }
21105 
21106 
21107 static void
21108 sata_trace_rbuf_free(void)
21109 {
21110 	sata_trace_dmsg_free();
21111 	mutex_destroy(&sata_debug_rbuf->lock);
21112 	kmem_free(sata_debug_rbuf, sizeof (sata_trace_rbuf_t));
21113 }
21114 
21115 /*
21116  * If SATA_DEBUG is not defined then this routine is called instead
21117  * of sata_log() via the SATA_LOG_D macro.
21118  */
21119 static void
21120 sata_trace_log(sata_hba_inst_t *sata_hba_inst, uint_t level,
21121     const char *fmt, ...)
21122 {
21123 #ifndef __lock_lint
21124 	_NOTE(ARGUNUSED(level))
21125 #endif
21126 
21127 	dev_info_t *dip = NULL;
21128 	va_list ap;
21129 
21130 	if (sata_hba_inst != NULL) {
21131 		dip = SATA_DIP(sata_hba_inst);
21132 	}
21133 
21134 	va_start(ap, fmt);
21135 	sata_vtrace_debug(dip, fmt, ap);
21136 	va_end(ap);
21137 }
21138