xref: /titanic_44/usr/src/uts/common/io/sata/impl/sata.c (revision bd28a477274db2b836577dfd6f223c696ad00720)
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 2010 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 
28 /*
29  * SATA Framework
30  * Generic SATA Host Adapter Implementation
31  */
32 
33 #include <sys/conf.h>
34 #include <sys/file.h>
35 #include <sys/ddi.h>
36 #include <sys/sunddi.h>
37 #include <sys/modctl.h>
38 #include <sys/cmn_err.h>
39 #include <sys/errno.h>
40 #include <sys/thread.h>
41 #include <sys/kstat.h>
42 #include <sys/note.h>
43 #include <sys/sysevent.h>
44 #include <sys/sysevent/eventdefs.h>
45 #include <sys/sysevent/dr.h>
46 #include <sys/taskq.h>
47 #include <sys/disp.h>
48 
49 #include <sys/sata/impl/sata.h>
50 #include <sys/sata/sata_hba.h>
51 #include <sys/sata/sata_defs.h>
52 #include <sys/sata/sata_cfgadm.h>
53 #include <sys/sata/sata_blacklist.h>
54 #include <sys/sata/sata_satl.h>
55 
56 #include <sys/scsi/impl/spc3_types.h>
57 
58 /* Debug flags - defined in sata.h */
59 int	sata_debug_flags = 0;
60 int	sata_msg = 0;
61 
62 /*
63  * Flags enabling selected SATA HBA framework functionality
64  */
65 #define	SATA_ENABLE_QUEUING		1
66 #define	SATA_ENABLE_NCQ			2
67 #define	SATA_ENABLE_PROCESS_EVENTS	4
68 #define	SATA_ENABLE_PMULT_FBS		8 /* FIS-Based Switching */
69 int sata_func_enable =
70 	SATA_ENABLE_PROCESS_EVENTS | SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ;
71 
72 /*
73  * Global variable setting default maximum queue depth (NCQ or TCQ)
74  * Note:minimum queue depth is 1
75  */
76 int sata_max_queue_depth = SATA_MAX_QUEUE_DEPTH; /* max NCQ/TCQ queue depth */
77 
78 /*
79  * Currently used default NCQ/TCQ queue depth. It is set-up during the driver
80  * initialization, using value from sata_max_queue_depth
81  * It is adjusted to minimum supported by the controller and by the device,
82  * if queueing is enabled.
83  */
84 static	int sata_current_max_qdepth;
85 
86 /*
87  * Global variable determining the default behavior after device hotpluggin.
88  * If non-zero, the hotplugged device is onlined (if possible) without explicit
89  * IOCTL request (AP_CONFIGURE).
90  * If zero, hotplugged device is identified, but not onlined.
91  * Enabling (AP_CONNECT) device port with an attached device does not result
92  * in device onlining regardless of the flag setting
93  */
94 int sata_auto_online = 0;
95 
96 #ifdef SATA_DEBUG
97 
98 #define	SATA_LOG_D(args)	sata_log args
99 uint64_t mbuf_count = 0;
100 uint64_t mbuffail_count = 0;
101 
102 sata_atapi_cmd_t sata_atapi_trace[64];
103 uint32_t sata_atapi_trace_index = 0;
104 int sata_atapi_trace_save = 1;
105 static	void sata_save_atapi_trace(sata_pkt_txlate_t *, int);
106 #define	SATAATAPITRACE(spx, count)	if (sata_atapi_trace_save) \
107     sata_save_atapi_trace(spx, count);
108 
109 #else
110 #define	SATA_LOG_D(args)	sata_trace_log args
111 #define	SATAATAPITRACE(spx, count)
112 #endif
113 
114 #if 0
115 static void
116 sata_test_atapi_packet_command(sata_hba_inst_t *, int);
117 #endif
118 
119 #ifdef SATA_INJECT_FAULTS
120 
121 #define		SATA_INJECT_PKT_FAULT	1
122 uint32_t	sata_inject_fault = 0;
123 
124 uint32_t	sata_inject_fault_count = 0;
125 uint32_t	sata_inject_fault_pause_count = 0;
126 uint32_t	sata_fault_type = 0;
127 uint32_t	sata_fault_cmd = 0;
128 dev_info_t	*sata_fault_ctrl = NULL;
129 sata_device_t	sata_fault_device;
130 
131 static	void sata_inject_pkt_fault(sata_pkt_t *, int *, int);
132 
133 #endif
134 
135 #define	LEGACY_HWID_LEN	64	/* Model (40) + Serial (20) + pad */
136 
137 static char sata_rev_tag[] = {"1.46"};
138 
139 /*
140  * SATA cb_ops functions
141  */
142 static 	int sata_hba_open(dev_t *, int, int, cred_t *);
143 static 	int sata_hba_close(dev_t, int, int, cred_t *);
144 static 	int sata_hba_ioctl(dev_t, int, intptr_t, int, cred_t *,	int *);
145 
146 /*
147  * SCSA required entry points
148  */
149 static	int sata_scsi_tgt_init(dev_info_t *, dev_info_t *,
150     scsi_hba_tran_t *, struct scsi_device *);
151 static	int sata_scsi_tgt_probe(struct scsi_device *,
152     int (*callback)(void));
153 static void sata_scsi_tgt_free(dev_info_t *, dev_info_t *,
154     scsi_hba_tran_t *, struct scsi_device *);
155 static 	int sata_scsi_start(struct scsi_address *, struct scsi_pkt *);
156 static 	int sata_scsi_abort(struct scsi_address *, struct scsi_pkt *);
157 static 	int sata_scsi_reset(struct scsi_address *, int);
158 static 	int sata_scsi_getcap(struct scsi_address *, char *, int);
159 static 	int sata_scsi_setcap(struct scsi_address *, char *, int, int);
160 static 	struct scsi_pkt *sata_scsi_init_pkt(struct scsi_address *,
161     struct scsi_pkt *, struct buf *, int, int, int, int, int (*)(caddr_t),
162     caddr_t);
163 static 	void sata_scsi_destroy_pkt(struct scsi_address *, struct scsi_pkt *);
164 static 	void sata_scsi_dmafree(struct scsi_address *, struct scsi_pkt *);
165 static 	void sata_scsi_sync_pkt(struct scsi_address *, struct scsi_pkt *);
166 
167 /*
168  * SATA HBA interface functions are defined in sata_hba.h header file
169  */
170 
171 /* Event processing functions */
172 static	void sata_event_daemon(void *);
173 static	void sata_event_thread_control(int);
174 static	void sata_process_controller_events(sata_hba_inst_t *sata_hba_inst);
175 static	void sata_process_pmult_events(sata_hba_inst_t *, uint8_t);
176 static	void sata_process_device_reset(sata_hba_inst_t *, sata_address_t *);
177 static	void sata_process_pmdevice_reset(sata_hba_inst_t *, sata_address_t *);
178 static	void sata_process_port_failed_event(sata_hba_inst_t *,
179     sata_address_t *);
180 static	void sata_process_port_link_events(sata_hba_inst_t *,
181     sata_address_t *);
182 static	void sata_process_pmport_link_events(sata_hba_inst_t *,
183     sata_address_t *);
184 static	void sata_process_device_detached(sata_hba_inst_t *, sata_address_t *);
185 static	void sata_process_pmdevice_detached(sata_hba_inst_t *,
186     sata_address_t *);
187 static	void sata_process_device_attached(sata_hba_inst_t *, sata_address_t *);
188 static	void sata_process_pmdevice_attached(sata_hba_inst_t *,
189     sata_address_t *);
190 static	void sata_process_port_pwr_change(sata_hba_inst_t *, sata_address_t *);
191 static	void sata_process_cntrl_pwr_level_change(sata_hba_inst_t *);
192 static	void sata_process_target_node_cleanup(sata_hba_inst_t *,
193     sata_address_t *);
194 static	void sata_process_device_autoonline(sata_hba_inst_t *,
195     sata_address_t *saddr);
196 
197 /*
198  * Local translation functions
199  */
200 static	int sata_txlt_inquiry(sata_pkt_txlate_t *);
201 static	int sata_txlt_test_unit_ready(sata_pkt_txlate_t *);
202 static	int sata_txlt_start_stop_unit(sata_pkt_txlate_t *);
203 static	int sata_txlt_read_capacity(sata_pkt_txlate_t *);
204 static	int sata_txlt_read_capacity16(sata_pkt_txlate_t *);
205 static	int sata_txlt_request_sense(sata_pkt_txlate_t *);
206 static	int sata_txlt_read(sata_pkt_txlate_t *);
207 static	int sata_txlt_write(sata_pkt_txlate_t *);
208 static	int sata_txlt_log_sense(sata_pkt_txlate_t *);
209 static	int sata_txlt_log_select(sata_pkt_txlate_t *);
210 static	int sata_txlt_mode_sense(sata_pkt_txlate_t *);
211 static	int sata_txlt_mode_select(sata_pkt_txlate_t *);
212 static	int sata_txlt_ata_pass_thru(sata_pkt_txlate_t *);
213 static	int sata_txlt_synchronize_cache(sata_pkt_txlate_t *);
214 static	int sata_txlt_write_buffer(sata_pkt_txlate_t *);
215 static	int sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *);
216 
217 static	int sata_hba_start(sata_pkt_txlate_t *, int *);
218 static	int sata_txlt_invalid_command(sata_pkt_txlate_t *);
219 static	int sata_txlt_check_condition(sata_pkt_txlate_t *, uchar_t, uchar_t);
220 static	int sata_txlt_lba_out_of_range(sata_pkt_txlate_t *);
221 static	int sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *);
222 static	void sata_txlt_rw_completion(sata_pkt_t *);
223 static	void sata_txlt_nodata_cmd_completion(sata_pkt_t *);
224 static	void sata_txlt_apt_completion(sata_pkt_t *sata_pkt);
225 static	void sata_txlt_download_mcode_cmd_completion(sata_pkt_t *);
226 static	int sata_emul_rw_completion(sata_pkt_txlate_t *);
227 static	void sata_fill_ata_return_desc(sata_pkt_t *, uint8_t, uint8_t,
228     uint8_t);
229 static	struct scsi_extended_sense *sata_immediate_error_response(
230     sata_pkt_txlate_t *, int);
231 static	struct scsi_extended_sense *sata_arq_sense(sata_pkt_txlate_t *);
232 
233 static	int sata_txlt_atapi(sata_pkt_txlate_t *);
234 static	void sata_txlt_atapi_completion(sata_pkt_t *);
235 
236 /*
237  * Local functions for ioctl
238  */
239 static	int32_t sata_get_port_num(sata_hba_inst_t *,  struct devctl_iocdata *);
240 static	void sata_cfgadm_state(sata_hba_inst_t *, int32_t,
241     devctl_ap_state_t *);
242 static	dev_info_t *sata_get_target_dip(dev_info_t *, uint8_t, uint8_t);
243 static	dev_info_t *sata_get_scsi_target_dip(dev_info_t *, sata_address_t *);
244 static	dev_info_t *sata_devt_to_devinfo(dev_t);
245 static	int sata_ioctl_connect(sata_hba_inst_t *, sata_device_t *);
246 static	int sata_ioctl_disconnect(sata_hba_inst_t *, sata_device_t *);
247 static	int sata_ioctl_configure(sata_hba_inst_t *, sata_device_t *);
248 static	int sata_ioctl_unconfigure(sata_hba_inst_t *, sata_device_t *);
249 static	int sata_ioctl_activate(sata_hba_inst_t *, sata_device_t *);
250 static	int sata_ioctl_deactivate(sata_hba_inst_t *, sata_device_t *);
251 static	int sata_ioctl_reset_port(sata_hba_inst_t *, sata_device_t *);
252 static	int sata_ioctl_reset_device(sata_hba_inst_t *, sata_device_t *);
253 static	int sata_ioctl_reset_all(sata_hba_inst_t *);
254 static	int sata_ioctl_port_self_test(sata_hba_inst_t *, sata_device_t *);
255 static	int sata_ioctl_get_device_path(sata_hba_inst_t *, sata_device_t *,
256     sata_ioctl_data_t *, int mode);
257 static	int sata_ioctl_get_ap_type(sata_hba_inst_t *, sata_device_t *,
258     sata_ioctl_data_t *, int mode);
259 static	int sata_ioctl_get_model_info(sata_hba_inst_t *, sata_device_t *,
260     sata_ioctl_data_t *, int mode);
261 static	int sata_ioctl_get_revfirmware_info(sata_hba_inst_t *, sata_device_t *,
262     sata_ioctl_data_t *, int mode);
263 static	int sata_ioctl_get_serialnumber_info(sata_hba_inst_t *,
264     sata_device_t *, sata_ioctl_data_t *, int mode);
265 
266 /*
267  * Local functions
268  */
269 static 	void sata_remove_hba_instance(dev_info_t *);
270 static 	int sata_validate_sata_hba_tran(dev_info_t *, sata_hba_tran_t *);
271 static 	void sata_probe_ports(sata_hba_inst_t *);
272 static	void sata_probe_pmports(sata_hba_inst_t *, uint8_t);
273 static 	int sata_reprobe_port(sata_hba_inst_t *, sata_device_t *, int);
274 static 	int sata_reprobe_pmult(sata_hba_inst_t *, sata_device_t *, int);
275 static 	int sata_reprobe_pmport(sata_hba_inst_t *, sata_device_t *, int);
276 static	int sata_alloc_pmult(sata_hba_inst_t *, sata_device_t *);
277 static	void sata_free_pmult(sata_hba_inst_t *, sata_device_t *);
278 static 	int sata_add_device(dev_info_t *, sata_hba_inst_t *, sata_device_t *);
279 static	int sata_offline_device(sata_hba_inst_t *, sata_device_t *,
280     sata_drive_info_t *);
281 static 	dev_info_t *sata_create_target_node(dev_info_t *, sata_hba_inst_t *,
282     sata_address_t *);
283 static 	void sata_remove_target_node(sata_hba_inst_t *,
284     sata_address_t *);
285 static 	int sata_validate_scsi_address(sata_hba_inst_t *,
286     struct scsi_address *, sata_device_t *);
287 static 	int sata_validate_sata_address(sata_hba_inst_t *, int, int, int);
288 static	sata_pkt_t *sata_pkt_alloc(sata_pkt_txlate_t *, int (*)(caddr_t));
289 static	void sata_pkt_free(sata_pkt_txlate_t *);
290 static	int sata_dma_buf_setup(sata_pkt_txlate_t *, int, int (*)(caddr_t),
291     caddr_t, ddi_dma_attr_t *);
292 static	void sata_common_free_dma_rsrcs(sata_pkt_txlate_t *);
293 static	int sata_probe_device(sata_hba_inst_t *, sata_device_t *);
294 static	sata_drive_info_t *sata_get_device_info(sata_hba_inst_t *,
295     sata_device_t *);
296 static 	int sata_identify_device(sata_hba_inst_t *, sata_drive_info_t *);
297 static	void sata_reidentify_device(sata_pkt_txlate_t *);
298 static	struct buf *sata_alloc_local_buffer(sata_pkt_txlate_t *, int);
299 static 	void sata_free_local_buffer(sata_pkt_txlate_t *);
300 static 	uint64_t sata_check_capacity(sata_drive_info_t *);
301 void 	sata_adjust_dma_attr(sata_drive_info_t *, ddi_dma_attr_t *,
302     ddi_dma_attr_t *);
303 static 	int sata_fetch_device_identify_data(sata_hba_inst_t *,
304     sata_drive_info_t *);
305 static	void sata_update_port_info(sata_hba_inst_t *, sata_device_t *);
306 static	void sata_update_pmport_info(sata_hba_inst_t *, sata_device_t *);
307 static	void sata_update_port_scr(sata_port_scr_t *, sata_device_t *);
308 static	int sata_set_dma_mode(sata_hba_inst_t *, sata_drive_info_t *);
309 static	int sata_set_cache_mode(sata_hba_inst_t *, sata_drive_info_t *, int);
310 static	int sata_set_rmsn(sata_hba_inst_t *, sata_drive_info_t *, int);
311 static	int sata_set_drive_features(sata_hba_inst_t *,
312     sata_drive_info_t *, int flag);
313 static	void sata_init_write_cache_mode(sata_drive_info_t *sdinfo);
314 static	int sata_initialize_device(sata_hba_inst_t *, sata_drive_info_t *);
315 static	void sata_identdev_to_inquiry(sata_hba_inst_t *, sata_drive_info_t *,
316     uint8_t *);
317 static	int sata_get_atapi_inquiry_data(sata_hba_inst_t *, sata_address_t *,
318     struct scsi_inquiry *);
319 static	int sata_build_msense_page_1(sata_drive_info_t *, int, uint8_t *);
320 static	int sata_build_msense_page_8(sata_drive_info_t *, int, uint8_t *);
321 static	int sata_build_msense_page_1a(sata_drive_info_t *, int, uint8_t *);
322 static	int sata_build_msense_page_1c(sata_drive_info_t *, int, uint8_t *);
323 static	int sata_build_msense_page_30(sata_drive_info_t *, int, uint8_t *);
324 static	int sata_mode_select_page_8(sata_pkt_txlate_t *,
325     struct mode_cache_scsi3 *, int, int *, int *, int *);
326 static	int sata_mode_select_page_1a(sata_pkt_txlate_t *,
327     struct mode_info_power_cond *, int, int *, int *, int *);
328 static	int sata_mode_select_page_1c(sata_pkt_txlate_t *,
329     struct mode_info_excpt_page *, int, int *, int *, int *);
330 static	int sata_mode_select_page_30(sata_pkt_txlate_t *,
331     struct mode_acoustic_management *, int, int *, int *, int *);
332 
333 static	int sata_build_lsense_page_0(sata_drive_info_t *, uint8_t *);
334 static	int sata_build_lsense_page_10(sata_drive_info_t *, uint8_t *,
335     sata_hba_inst_t *);
336 static	int sata_build_lsense_page_2f(sata_drive_info_t *, uint8_t *,
337     sata_hba_inst_t *);
338 static	int sata_build_lsense_page_30(sata_drive_info_t *, uint8_t *,
339     sata_hba_inst_t *);
340 static	int sata_build_lsense_page_0e(sata_drive_info_t *, uint8_t *,
341     sata_pkt_txlate_t *);
342 
343 static	void sata_set_arq_data(sata_pkt_t *);
344 static	void sata_build_read_verify_cmd(sata_cmd_t *, uint16_t, uint64_t);
345 static	void sata_build_generic_cmd(sata_cmd_t *, uint8_t);
346 static	uint8_t sata_get_standby_timer(uint8_t *timer);
347 
348 static	void sata_save_drive_settings(sata_drive_info_t *);
349 static	void sata_show_drive_info(sata_hba_inst_t *, sata_drive_info_t *);
350 static	void sata_show_pmult_info(sata_hba_inst_t *, sata_device_t *);
351 static	void sata_log(sata_hba_inst_t *, uint_t, char *fmt, ...);
352 static	void sata_trace_log(sata_hba_inst_t *, uint_t, const char *fmt, ...);
353 static	int sata_fetch_smart_return_status(sata_hba_inst_t *,
354     sata_drive_info_t *);
355 static	int sata_fetch_smart_data(sata_hba_inst_t *, sata_drive_info_t *,
356     struct smart_data *);
357 static	int sata_smart_selftest_log(sata_hba_inst_t *,
358     sata_drive_info_t *,
359     struct smart_selftest_log *);
360 static	int sata_ext_smart_selftest_read_log(sata_hba_inst_t *,
361     sata_drive_info_t *, struct smart_ext_selftest_log *, uint16_t);
362 static	int sata_smart_read_log(sata_hba_inst_t *, sata_drive_info_t *,
363     uint8_t *, uint8_t, uint8_t);
364 static	int sata_read_log_ext_directory(sata_hba_inst_t *, sata_drive_info_t *,
365     struct read_log_ext_directory *);
366 static	void sata_gen_sysevent(sata_hba_inst_t *, sata_address_t *, int);
367 static	void sata_xlate_errors(sata_pkt_txlate_t *);
368 static	void sata_decode_device_error(sata_pkt_txlate_t *,
369     struct scsi_extended_sense *);
370 static	void sata_set_device_removed(dev_info_t *);
371 static	boolean_t sata_check_device_removed(dev_info_t *);
372 static	void sata_set_target_node_cleanup(sata_hba_inst_t *, sata_address_t *);
373 static	int sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *,
374     sata_drive_info_t *);
375 static	int sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *,
376     sata_drive_info_t *);
377 static	void sata_atapi_packet_cmd_setup(sata_cmd_t *, sata_drive_info_t *);
378 static	void sata_fixed_sense_data_preset(struct scsi_extended_sense *);
379 static  void sata_target_devid_register(dev_info_t *, sata_drive_info_t *);
380 static  int sata_check_modser(char *, int);
381 
382 
383 
384 /*
385  * SATA Framework will ignore SATA HBA driver cb_ops structure and
386  * register following one with SCSA framework.
387  * Open & close are provided, so scsi framework will not use its own
388  */
389 static struct cb_ops sata_cb_ops = {
390 	sata_hba_open,			/* open */
391 	sata_hba_close,			/* close */
392 	nodev,				/* strategy */
393 	nodev,				/* print */
394 	nodev,				/* dump */
395 	nodev,				/* read */
396 	nodev,				/* write */
397 	sata_hba_ioctl,			/* ioctl */
398 	nodev,				/* devmap */
399 	nodev,				/* mmap */
400 	nodev,				/* segmap */
401 	nochpoll,			/* chpoll */
402 	ddi_prop_op,			/* cb_prop_op */
403 	0,				/* streamtab */
404 	D_NEW | D_MP,			/* cb_flag */
405 	CB_REV,				/* rev */
406 	nodev,				/* aread */
407 	nodev				/* awrite */
408 };
409 
410 
411 extern struct mod_ops mod_miscops;
412 extern uchar_t	scsi_cdb_size[];
413 
414 static struct modlmisc modlmisc = {
415 	&mod_miscops,			/* Type of module */
416 	"SATA Module"			/* module name */
417 };
418 
419 
420 static struct modlinkage modlinkage = {
421 	MODREV_1,
422 	(void *)&modlmisc,
423 	NULL
424 };
425 
426 /*
427  * Default sata pkt timeout. Used when a target driver scsi_pkt time is zero,
428  * i.e. when scsi_pkt has not timeout specified.
429  */
430 static int sata_default_pkt_time = 60;	/* 60 seconds */
431 
432 /*
433  * Intermediate buffer device access attributes - they are required,
434  * but not necessarily used.
435  */
436 static ddi_device_acc_attr_t sata_acc_attr = {
437 	DDI_DEVICE_ATTR_V0,
438 	DDI_STRUCTURE_LE_ACC,
439 	DDI_STRICTORDER_ACC
440 };
441 
442 
443 /*
444  * Mutexes protecting structures in multithreaded operations.
445  * Because events are relatively rare, a single global mutex protecting
446  * data structures should be sufficient. To increase performance, add
447  * separate mutex per each sata port and use global mutex only to protect
448  * common data structures.
449  */
450 static	kmutex_t sata_mutex;		/* protects sata_hba_list */
451 static	kmutex_t sata_log_mutex;	/* protects log */
452 
453 static 	char sata_log_buf[256];
454 
455 /*
456  * sata trace debug
457  */
458 static	sata_trace_rbuf_t *sata_debug_rbuf;
459 static	sata_trace_dmsg_t *sata_trace_dmsg_alloc(void);
460 static	void sata_trace_dmsg_free(void);
461 static	void sata_trace_rbuf_alloc(void);
462 static	void sata_trace_rbuf_free(void);
463 
464 int	dmsg_ring_size = DMSG_RING_SIZE;
465 
466 /* Default write cache setting for SATA hard disks */
467 int	sata_write_cache = 1;		/* enabled */
468 
469 /* Default write cache setting for SATA ATAPI CD/DVD */
470 int	sata_atapicdvd_write_cache = 1; /* enabled */
471 
472 /* Default write cache setting for SATA ATAPI tape */
473 int	sata_atapitape_write_cache = 1; /* enabled */
474 
475 /* Default write cache setting for SATA ATAPI disk */
476 int	sata_atapidisk_write_cache = 1;	/* enabled */
477 
478 /*
479  * Linked list of HBA instances
480  */
481 static 	sata_hba_inst_t *sata_hba_list = NULL;
482 static 	sata_hba_inst_t *sata_hba_list_tail = NULL;
483 /*
484  * Pointer to per-instance SATA HBA soft structure is stored in sata_hba_tran
485  * structure and in sata soft state.
486  */
487 
488 /*
489  * Event daemon related variables
490  */
491 static 	kmutex_t sata_event_mutex;
492 static 	kcondvar_t sata_event_cv;
493 static 	kthread_t *sata_event_thread = NULL;
494 static 	int sata_event_thread_terminate = 0;
495 static 	int sata_event_pending = 0;
496 static 	int sata_event_thread_active = 0;
497 extern 	pri_t minclsyspri;
498 
499 /*
500  * NCQ error recovery command
501  */
502 static const sata_cmd_t sata_rle_cmd = {
503 	SATA_CMD_REV,
504 	NULL,
505 	{
506 		SATA_DIR_READ
507 	},
508 	ATA_ADDR_LBA48,
509 	0,
510 	0,
511 	0,
512 	0,
513 	0,
514 	1,
515 	READ_LOG_EXT_NCQ_ERROR_RECOVERY,
516 	0,
517 	0,
518 	0,
519 	SATAC_READ_LOG_EXT,
520 	0,
521 	0,
522 	0,
523 };
524 
525 /*
526  * ATAPI error recovery CDB
527  */
528 static const uint8_t sata_rqsense_cdb[SATA_ATAPI_RQSENSE_CDB_LEN] = {
529 	SCMD_REQUEST_SENSE,
530 	0,			/* Only fixed RQ format is supported */
531 	0,
532 	0,
533 	SATA_ATAPI_MIN_RQSENSE_LEN, /* Less data may be returned */
534 	0
535 };
536 
537 
538 /* Warlock directives */
539 
540 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran))
541 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_device))
542 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_ops))
543 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_extended_sense))
544 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_arq_status))
545 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_attr))
546 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_cookie_t))
547 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", devctl_ap_state))
548 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_info::devi_state))
549 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_list))
550 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_list))
551 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_next))
552 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_prev))
553 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", \
554     sata_hba_inst::satahba_scsi_tran))
555 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_tran))
556 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_dip))
557 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_hba_inst::satahba_attached))
558 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_inst::satahba_dev_port))
559 _NOTE(MUTEX_PROTECTS_DATA(sata_hba_inst::satahba_mutex,
560     sata_hba_inst::satahba_event_flags))
561 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
562     sata_cport_info::cport_devp))
563 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_devp))
564 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_cport_info::cport_addr))
565 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
566     sata_cport_info::cport_dev_type))
567 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_dev_type))
568 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
569     sata_cport_info::cport_state))
570 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_state))
571 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
572     sata_pmport_info::pmport_state))
573 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_state))
574 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
575     sata_pmport_info::pmport_dev_type))
576 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_dev_type))
577 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
578     sata_pmport_info::pmport_sata_drive))
579 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
580     sata_pmport_info::pmport_tgtnode_clean))
581 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
582     sata_pmport_info::pmport_event_flags))
583 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_sata_drive))
584 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_dev_port))
585 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_num_dev_ports))
586 #ifdef SATA_DEBUG
587 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuf_count))
588 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuffail_count))
589 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace))
590 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace_index))
591 #endif
592 
593 /* End of warlock directives */
594 
595 /* ************** loadable module configuration functions ************** */
596 
597 int
598 _init()
599 {
600 	int rval;
601 
602 	mutex_init(&sata_mutex, NULL, MUTEX_DRIVER, NULL);
603 	mutex_init(&sata_event_mutex, NULL, MUTEX_DRIVER, NULL);
604 	mutex_init(&sata_log_mutex, NULL, MUTEX_DRIVER, NULL);
605 	cv_init(&sata_event_cv, NULL, CV_DRIVER, NULL);
606 	sata_trace_rbuf_alloc();
607 	if ((rval = mod_install(&modlinkage)) != 0) {
608 #ifdef SATA_DEBUG
609 		cmn_err(CE_WARN, "sata: _init: mod_install failed\n");
610 #endif
611 		sata_trace_rbuf_free();
612 		mutex_destroy(&sata_log_mutex);
613 		cv_destroy(&sata_event_cv);
614 		mutex_destroy(&sata_event_mutex);
615 		mutex_destroy(&sata_mutex);
616 	}
617 	return (rval);
618 }
619 
620 int
621 _fini()
622 {
623 	int rval;
624 
625 	if ((rval = mod_remove(&modlinkage)) != 0)
626 		return (rval);
627 
628 	sata_trace_rbuf_free();
629 	mutex_destroy(&sata_log_mutex);
630 	cv_destroy(&sata_event_cv);
631 	mutex_destroy(&sata_event_mutex);
632 	mutex_destroy(&sata_mutex);
633 	return (rval);
634 }
635 
636 int
637 _info(struct modinfo *modinfop)
638 {
639 	return (mod_info(&modlinkage, modinfop));
640 }
641 
642 
643 
644 /* ********************* SATA HBA entry points ********************* */
645 
646 
647 /*
648  * Called by SATA HBA from _init().
649  * Registers HBA driver instance/sata framework pair with scsi framework, by
650  * calling scsi_hba_init().
651  *
652  * SATA HBA driver cb_ops are ignored - SATA HBA framework cb_ops are used
653  * instead. SATA HBA framework cb_ops pointer overwrites SATA HBA driver
654  * cb_ops pointer in SATA HBA driver dev_ops structure.
655  * SATA HBA framework cb_ops supplies cb_open cb_close and cb_ioctl vectors.
656  *
657  * Return status of the scsi_hba_init() is returned to a calling SATA HBA
658  * driver.
659  */
660 int
661 sata_hba_init(struct modlinkage *modlp)
662 {
663 	int rval;
664 	struct dev_ops *hba_ops;
665 
666 	SATADBG1(SATA_DBG_HBA_IF, NULL,
667 	    "sata_hba_init: name %s \n",
668 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
669 	/*
670 	 * Fill-up cb_ops and dev_ops when necessary
671 	 */
672 	hba_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
673 	/*
674 	 * Provide pointer to SATA dev_ops
675 	 */
676 	hba_ops->devo_cb_ops = &sata_cb_ops;
677 
678 	/*
679 	 * Register SATA HBA with SCSI framework
680 	 */
681 	if ((rval = scsi_hba_init(modlp)) != 0) {
682 		SATADBG1(SATA_DBG_HBA_IF, NULL,
683 		    "sata_hba_init: scsi hba init failed\n", NULL);
684 		return (rval);
685 	}
686 
687 	return (0);
688 }
689 
690 
691 /* HBA attach stages */
692 #define	HBA_ATTACH_STAGE_SATA_HBA_INST	1
693 #define	HBA_ATTACH_STAGE_SCSI_ATTACHED	2
694 #define	HBA_ATTACH_STAGE_SETUP		4
695 #define	HBA_ATTACH_STAGE_LINKED		8
696 
697 
698 /*
699  *
700  * Called from SATA HBA driver's attach routine to attach an instance of
701  * the HBA.
702  *
703  * For DDI_ATTACH command:
704  * sata_hba_inst structure is allocated here and initialized with pointers to
705  * SATA framework implementation of required scsi tran functions.
706  * The scsi_tran's tran_hba_private field is used by SATA Framework to point
707  * to the soft structure (sata_hba_inst) allocated by SATA framework for
708  * SATA HBA instance related data.
709  * The scsi_tran's tran_hba_private field is used by SATA framework to
710  * store a pointer to per-HBA-instance of sata_hba_inst structure.
711  * The sata_hba_inst structure is cross-linked to scsi tran structure.
712  * Among other info, a pointer to sata_hba_tran structure is stored in
713  * sata_hba_inst. The sata_hba_inst structures for different HBA instances are
714  * linked together into the list, pointed to by sata_hba_list.
715  * On the first HBA instance attach the sata event thread is initialized.
716  * Attachment points are created for all SATA ports of the HBA being attached.
717  * All HBA instance's SATA ports are probed and type of plugged devices is
718  * determined. For each device of a supported type, a target node is created.
719  *
720  * DDI_SUCCESS is returned when attachment process is successful,
721  * DDI_FAILURE is returned otherwise.
722  *
723  * For DDI_RESUME command:
724  * Not implemented at this time (postponed until phase 2 of the development).
725  */
726 int
727 sata_hba_attach(dev_info_t *dip, sata_hba_tran_t *sata_tran,
728     ddi_attach_cmd_t cmd)
729 {
730 	sata_hba_inst_t	*sata_hba_inst;
731 	scsi_hba_tran_t *scsi_tran = NULL;
732 	int hba_attach_state = 0;
733 	char taskq_name[MAXPATHLEN];
734 
735 	SATADBG3(SATA_DBG_HBA_IF, NULL,
736 	    "sata_hba_attach: node %s (%s%d)\n",
737 	    ddi_node_name(dip), ddi_driver_name(dip),
738 	    ddi_get_instance(dip));
739 
740 	if (cmd == DDI_RESUME) {
741 		/*
742 		 * Postponed until phase 2 of the development
743 		 */
744 		return (DDI_FAILURE);
745 	}
746 
747 	if (cmd != DDI_ATTACH) {
748 		return (DDI_FAILURE);
749 	}
750 
751 	/* cmd == DDI_ATTACH */
752 
753 	if (sata_validate_sata_hba_tran(dip, sata_tran) != SATA_SUCCESS) {
754 		SATA_LOG_D((NULL, CE_WARN,
755 		    "sata_hba_attach: invalid sata_hba_tran"));
756 		return (DDI_FAILURE);
757 	}
758 	/*
759 	 * Allocate and initialize SCSI tran structure.
760 	 * SATA copy of tran_bus_config is provided to create port nodes.
761 	 */
762 	scsi_tran = scsi_hba_tran_alloc(dip, SCSI_HBA_CANSLEEP);
763 	if (scsi_tran == NULL)
764 		return (DDI_FAILURE);
765 	/*
766 	 * Allocate soft structure for SATA HBA instance.
767 	 * There is a separate softstate for each HBA instance.
768 	 */
769 	sata_hba_inst = kmem_zalloc(sizeof (struct sata_hba_inst), KM_SLEEP);
770 	ASSERT(sata_hba_inst != NULL); /* this should not fail */
771 	mutex_init(&sata_hba_inst->satahba_mutex, NULL, MUTEX_DRIVER, NULL);
772 	hba_attach_state |= HBA_ATTACH_STAGE_SATA_HBA_INST;
773 
774 	/*
775 	 * scsi_trans's tran_hba_private is used by SATA Framework to point to
776 	 * soft structure allocated by SATA framework for
777 	 * SATA HBA instance related data.
778 	 */
779 	scsi_tran->tran_hba_private	= sata_hba_inst;
780 	scsi_tran->tran_tgt_private	= NULL;
781 
782 	scsi_tran->tran_tgt_init	= sata_scsi_tgt_init;
783 	scsi_tran->tran_tgt_probe	= sata_scsi_tgt_probe;
784 	scsi_tran->tran_tgt_free	= sata_scsi_tgt_free;
785 
786 	scsi_tran->tran_start		= sata_scsi_start;
787 	scsi_tran->tran_reset		= sata_scsi_reset;
788 	scsi_tran->tran_abort		= sata_scsi_abort;
789 	scsi_tran->tran_getcap		= sata_scsi_getcap;
790 	scsi_tran->tran_setcap		= sata_scsi_setcap;
791 	scsi_tran->tran_init_pkt	= sata_scsi_init_pkt;
792 	scsi_tran->tran_destroy_pkt	= sata_scsi_destroy_pkt;
793 
794 	scsi_tran->tran_dmafree		= sata_scsi_dmafree;
795 	scsi_tran->tran_sync_pkt	= sata_scsi_sync_pkt;
796 
797 	scsi_tran->tran_reset_notify	= NULL;
798 	scsi_tran->tran_get_bus_addr	= NULL;
799 	scsi_tran->tran_quiesce		= NULL;
800 	scsi_tran->tran_unquiesce	= NULL;
801 	scsi_tran->tran_bus_reset	= NULL;
802 
803 	if (scsi_hba_attach_setup(dip, sata_tran->sata_tran_hba_dma_attr,
804 	    scsi_tran, 0) != DDI_SUCCESS) {
805 #ifdef SATA_DEBUG
806 		cmn_err(CE_WARN, "?SATA: %s%d hba scsi attach failed",
807 		    ddi_driver_name(dip), ddi_get_instance(dip));
808 #endif
809 		goto fail;
810 	}
811 	hba_attach_state |= HBA_ATTACH_STAGE_SCSI_ATTACHED;
812 
813 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "sata")) {
814 		if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
815 		    "sata", 1) != DDI_PROP_SUCCESS) {
816 			SATA_LOG_D((NULL, CE_WARN, "sata_hba_attach: "
817 			    "failed to create hba sata prop"));
818 			goto fail;
819 		}
820 	}
821 
822 	/*
823 	 * Save pointers in hba instance soft state.
824 	 */
825 	sata_hba_inst->satahba_scsi_tran = scsi_tran;
826 	sata_hba_inst->satahba_tran = sata_tran;
827 	sata_hba_inst->satahba_dip = dip;
828 
829 	/*
830 	 * Create a task queue to handle emulated commands completion
831 	 * Use node name, dash, instance number as the queue name.
832 	 */
833 	taskq_name[0] = '\0';
834 	(void) strlcat(taskq_name, DEVI(dip)->devi_node_name,
835 	    sizeof (taskq_name));
836 	(void) snprintf(taskq_name + strlen(taskq_name),
837 	    sizeof (taskq_name) - strlen(taskq_name),
838 	    "-%d", DEVI(dip)->devi_instance);
839 	sata_hba_inst->satahba_taskq = taskq_create(taskq_name, 1,
840 	    minclsyspri, 1, sata_tran->sata_tran_hba_num_cports * 4,
841 	    TASKQ_DYNAMIC);
842 
843 	hba_attach_state |= HBA_ATTACH_STAGE_SETUP;
844 
845 	/*
846 	 * Create events thread if not created yet.
847 	 */
848 	sata_event_thread_control(1);
849 
850 	/*
851 	 * Link this hba instance into the list.
852 	 */
853 	mutex_enter(&sata_mutex);
854 
855 	if (sata_hba_list == NULL) {
856 		/*
857 		 * The first instance of HBA is attached.
858 		 * Set current/active default maximum NCQ/TCQ queue depth for
859 		 * all SATA devices. It is done here and now, to eliminate the
860 		 * possibility of the dynamic, programatic modification of the
861 		 * queue depth via global (and public) sata_max_queue_depth
862 		 * variable (this would require special handling in HBA drivers)
863 		 */
864 		sata_current_max_qdepth = sata_max_queue_depth;
865 		if (sata_current_max_qdepth > 32)
866 			sata_current_max_qdepth = 32;
867 		else if (sata_current_max_qdepth < 1)
868 			sata_current_max_qdepth = 1;
869 	}
870 
871 	sata_hba_inst->satahba_next = NULL;
872 	sata_hba_inst->satahba_prev = sata_hba_list_tail;
873 	if (sata_hba_list == NULL) {
874 		sata_hba_list = sata_hba_inst;
875 	}
876 	if (sata_hba_list_tail != NULL) {
877 		sata_hba_list_tail->satahba_next = sata_hba_inst;
878 	}
879 	sata_hba_list_tail = sata_hba_inst;
880 	mutex_exit(&sata_mutex);
881 	hba_attach_state |= HBA_ATTACH_STAGE_LINKED;
882 
883 	/*
884 	 * Create SATA HBA devctl minor node for sata_hba_open, close, ioctl
885 	 * SATA HBA driver should not use its own open/close entry points.
886 	 *
887 	 * Make sure that instance number doesn't overflow
888 	 * when forming minor numbers.
889 	 */
890 	ASSERT(ddi_get_instance(dip) <= (L_MAXMIN >> INST_MINOR_SHIFT));
891 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
892 	    INST2DEVCTL(ddi_get_instance(dip)),
893 	    DDI_NT_SATA_NEXUS, 0) != DDI_SUCCESS) {
894 #ifdef SATA_DEBUG
895 		cmn_err(CE_WARN, "sata_hba_attach: "
896 		    "cannot create devctl minor node");
897 #endif
898 		goto fail;
899 	}
900 
901 
902 	/*
903 	 * Set-up kstats here, if necessary.
904 	 * (postponed until future phase of the development).
905 	 */
906 
907 	/*
908 	 * Indicate that HBA is attached. This will enable events processing
909 	 * for this HBA.
910 	 */
911 	sata_hba_inst->satahba_attached = 1;
912 	/*
913 	 * Probe controller ports. This operation will describe a current
914 	 * controller/port/multipliers/device configuration and will create
915 	 * attachment points.
916 	 * We may end-up with just a controller with no devices attached.
917 	 * For the ports with a supported device attached, device target nodes
918 	 * are created and devices are initialized.
919 	 */
920 	sata_probe_ports(sata_hba_inst);
921 
922 	return (DDI_SUCCESS);
923 
924 fail:
925 	if (hba_attach_state & HBA_ATTACH_STAGE_LINKED) {
926 		(void) sata_remove_hba_instance(dip);
927 		if (sata_hba_list == NULL)
928 			sata_event_thread_control(0);
929 	}
930 
931 	if (hba_attach_state & HBA_ATTACH_STAGE_SETUP) {
932 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
933 		taskq_destroy(sata_hba_inst->satahba_taskq);
934 	}
935 
936 	if (hba_attach_state & HBA_ATTACH_STAGE_SCSI_ATTACHED)
937 		(void) scsi_hba_detach(dip);
938 
939 	if (hba_attach_state & HBA_ATTACH_STAGE_SATA_HBA_INST) {
940 		mutex_destroy(&sata_hba_inst->satahba_mutex);
941 		kmem_free((void *)sata_hba_inst,
942 		    sizeof (struct sata_hba_inst));
943 		scsi_hba_tran_free(scsi_tran);
944 	}
945 
946 	sata_log(NULL, CE_WARN, "?SATA: %s%d hba attach failed",
947 	    ddi_driver_name(dip), ddi_get_instance(dip));
948 
949 	return (DDI_FAILURE);
950 }
951 
952 
953 /*
954  * Called by SATA HBA from to detach an instance of the driver.
955  *
956  * For DDI_DETACH command:
957  * Free local structures allocated for SATA HBA instance during
958  * sata_hba_attach processing.
959  *
960  * Returns DDI_SUCCESS when HBA was detached, DDI_FAILURE otherwise.
961  *
962  * For DDI_SUSPEND command:
963  * Not implemented at this time (postponed until phase 2 of the development)
964  * Returnd DDI_SUCCESS.
965  *
966  * When the last HBA instance is detached, the event daemon is terminated.
967  *
968  * NOTE: Port multiplier is supported.
969  */
970 int
971 sata_hba_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
972 {
973 	dev_info_t	*tdip;
974 	sata_hba_inst_t	*sata_hba_inst;
975 	scsi_hba_tran_t *scsi_hba_tran;
976 	sata_cport_info_t *cportinfo;
977 	sata_pmult_info_t *pminfo;
978 	sata_drive_info_t *sdinfo;
979 	sata_device_t	sdevice;
980 	int ncport, npmport;
981 
982 	SATADBG3(SATA_DBG_HBA_IF, NULL, "sata_hba_detach: node %s (%s%d)\n",
983 	    ddi_node_name(dip), ddi_driver_name(dip), ddi_get_instance(dip));
984 
985 	switch (cmd) {
986 	case DDI_DETACH:
987 
988 		if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
989 			return (DDI_FAILURE);
990 
991 		sata_hba_inst = scsi_hba_tran->tran_hba_private;
992 		if (sata_hba_inst == NULL)
993 			return (DDI_FAILURE);
994 
995 		if (scsi_hba_detach(dip) == DDI_FAILURE) {
996 			sata_hba_inst->satahba_attached = 1;
997 			return (DDI_FAILURE);
998 		}
999 
1000 		/*
1001 		 * Free all target nodes - at this point
1002 		 * devices should be at least offlined
1003 		 * otherwise scsi_hba_detach() should not be called.
1004 		 */
1005 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
1006 		    ncport++) {
1007 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
1008 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1009 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
1010 				if (sdinfo != NULL) {
1011 					tdip = sata_get_target_dip(dip,
1012 					    ncport, 0);
1013 					if (tdip != NULL) {
1014 						if (ndi_devi_offline(tdip,
1015 						    NDI_DEVI_REMOVE) !=
1016 						    NDI_SUCCESS) {
1017 							SATA_LOG_D((
1018 							    sata_hba_inst,
1019 							    CE_WARN,
1020 							    "sata_hba_detach: "
1021 							    "Target node not "
1022 							    "removed !"));
1023 							return (DDI_FAILURE);
1024 						}
1025 					}
1026 				}
1027 			} else { /* SATA_DTYPE_PMULT */
1028 				mutex_enter(&cportinfo->cport_mutex);
1029 				pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
1030 
1031 				if (pminfo == NULL) {
1032 					SATA_LOG_D((sata_hba_inst, CE_WARN,
1033 					    "sata_hba_detach: Port multiplier "
1034 					    "not ready yet!"));
1035 					mutex_exit(&cportinfo->cport_mutex);
1036 					return (DDI_FAILURE);
1037 				}
1038 
1039 				/*
1040 				 * Detach would fail if removal of any of the
1041 				 * target nodes is failed - albeit in that
1042 				 * case some of them may have been removed.
1043 				 */
1044 				for (npmport = 0; npmport < SATA_NUM_PMPORTS(
1045 				    sata_hba_inst, ncport); npmport++) {
1046 					tdip = sata_get_target_dip(dip, ncport,
1047 					    npmport);
1048 					if (tdip != NULL) {
1049 						if (ndi_devi_offline(tdip,
1050 						    NDI_DEVI_REMOVE) !=
1051 						    NDI_SUCCESS) {
1052 							SATA_LOG_D((
1053 							    sata_hba_inst,
1054 							    CE_WARN,
1055 							    "sata_hba_detach: "
1056 							    "Target node not "
1057 							    "removed !"));
1058 							mutex_exit(&cportinfo->
1059 							    cport_mutex);
1060 							return (DDI_FAILURE);
1061 						}
1062 					}
1063 				}
1064 				mutex_exit(&cportinfo->cport_mutex);
1065 			}
1066 		}
1067 		/*
1068 		 * Disable sata event daemon processing for this HBA
1069 		 */
1070 		sata_hba_inst->satahba_attached = 0;
1071 
1072 		/*
1073 		 * Remove event daemon thread, if it is last HBA instance.
1074 		 */
1075 
1076 		mutex_enter(&sata_mutex);
1077 		if (sata_hba_list->satahba_next == NULL) {
1078 			mutex_exit(&sata_mutex);
1079 			sata_event_thread_control(0);
1080 			mutex_enter(&sata_mutex);
1081 		}
1082 		mutex_exit(&sata_mutex);
1083 
1084 		/* Remove this HBA instance from the HBA list */
1085 		sata_remove_hba_instance(dip);
1086 
1087 		/*
1088 		 * At this point there should be no target nodes attached.
1089 		 * Detach and destroy device and port info structures.
1090 		 */
1091 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
1092 		    ncport++) {
1093 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
1094 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1095 				sdinfo =
1096 				    cportinfo->cport_devp.cport_sata_drive;
1097 				if (sdinfo != NULL) {
1098 					/* Release device structure */
1099 					kmem_free(sdinfo,
1100 					    sizeof (sata_drive_info_t));
1101 				}
1102 				/* Release cport info */
1103 				mutex_destroy(&cportinfo->cport_mutex);
1104 				kmem_free(cportinfo,
1105 				    sizeof (sata_cport_info_t));
1106 			} else { /* SATA_DTYPE_PMULT */
1107 				sdevice.satadev_addr.cport = (uint8_t)ncport;
1108 				sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
1109 				sata_free_pmult(sata_hba_inst, &sdevice);
1110 			}
1111 		}
1112 
1113 		scsi_hba_tran_free(sata_hba_inst->satahba_scsi_tran);
1114 
1115 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
1116 
1117 		taskq_destroy(sata_hba_inst->satahba_taskq);
1118 
1119 		mutex_destroy(&sata_hba_inst->satahba_mutex);
1120 		kmem_free((void *)sata_hba_inst,
1121 		    sizeof (struct sata_hba_inst));
1122 
1123 		return (DDI_SUCCESS);
1124 
1125 	case DDI_SUSPEND:
1126 		/*
1127 		 * Postponed until phase 2
1128 		 */
1129 		return (DDI_FAILURE);
1130 
1131 	default:
1132 		return (DDI_FAILURE);
1133 	}
1134 }
1135 
1136 
1137 /*
1138  * Called by an HBA drive from _fini() routine.
1139  * Unregisters SATA HBA instance/SATA framework pair from the scsi framework.
1140  */
1141 void
1142 sata_hba_fini(struct modlinkage *modlp)
1143 {
1144 	SATADBG1(SATA_DBG_HBA_IF, NULL,
1145 	    "sata_hba_fini: name %s\n",
1146 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
1147 
1148 	scsi_hba_fini(modlp);
1149 }
1150 
1151 
1152 /*
1153  * Default open and close routine for sata_hba framework.
1154  *
1155  */
1156 /*
1157  * Open devctl node.
1158  *
1159  * Returns:
1160  * 0 if node was open successfully, error code otherwise.
1161  *
1162  *
1163  */
1164 
1165 static int
1166 sata_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
1167 {
1168 #ifndef __lock_lint
1169 	_NOTE(ARGUNUSED(credp))
1170 #endif
1171 	int rv = 0;
1172 	dev_info_t *dip;
1173 	scsi_hba_tran_t *scsi_hba_tran;
1174 	sata_hba_inst_t	*sata_hba_inst;
1175 
1176 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_open: entered", NULL);
1177 
1178 	if (otyp != OTYP_CHR)
1179 		return (EINVAL);
1180 
1181 	dip = sata_devt_to_devinfo(*devp);
1182 	if (dip == NULL)
1183 		return (ENXIO);
1184 
1185 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1186 		return (ENXIO);
1187 
1188 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1189 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1190 		return (ENXIO);
1191 
1192 	mutex_enter(&sata_mutex);
1193 	if (flags & FEXCL) {
1194 		if (sata_hba_inst->satahba_open_flag != 0) {
1195 			rv = EBUSY;
1196 		} else {
1197 			sata_hba_inst->satahba_open_flag =
1198 			    SATA_DEVCTL_EXOPENED;
1199 		}
1200 	} else {
1201 		if (sata_hba_inst->satahba_open_flag == SATA_DEVCTL_EXOPENED) {
1202 			rv = EBUSY;
1203 		} else {
1204 			sata_hba_inst->satahba_open_flag =
1205 			    SATA_DEVCTL_SOPENED;
1206 		}
1207 	}
1208 	mutex_exit(&sata_mutex);
1209 
1210 	return (rv);
1211 }
1212 
1213 
1214 /*
1215  * Close devctl node.
1216  * Returns:
1217  * 0 if node was closed successfully, error code otherwise.
1218  *
1219  */
1220 
1221 static int
1222 sata_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
1223 {
1224 #ifndef __lock_lint
1225 	_NOTE(ARGUNUSED(credp))
1226 	_NOTE(ARGUNUSED(flag))
1227 #endif
1228 	dev_info_t *dip;
1229 	scsi_hba_tran_t *scsi_hba_tran;
1230 	sata_hba_inst_t	*sata_hba_inst;
1231 
1232 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_close: entered", NULL);
1233 
1234 	if (otyp != OTYP_CHR)
1235 		return (EINVAL);
1236 
1237 	dip = sata_devt_to_devinfo(dev);
1238 	if (dip == NULL)
1239 		return (ENXIO);
1240 
1241 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1242 		return (ENXIO);
1243 
1244 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1245 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1246 		return (ENXIO);
1247 
1248 	mutex_enter(&sata_mutex);
1249 	sata_hba_inst->satahba_open_flag = 0;
1250 	mutex_exit(&sata_mutex);
1251 	return (0);
1252 }
1253 
1254 
1255 
1256 /*
1257  * Standard IOCTL commands for SATA hotplugging.
1258  * Implemented DEVCTL_AP commands:
1259  * DEVCTL_AP_CONNECT
1260  * DEVCTL_AP_DISCONNECT
1261  * DEVCTL_AP_CONFIGURE
1262  * DEVCTL_UNCONFIGURE
1263  * DEVCTL_AP_CONTROL
1264  *
1265  * Commands passed to default ndi ioctl handler:
1266  * DEVCTL_DEVICE_GETSTATE
1267  * DEVCTL_DEVICE_ONLINE
1268  * DEVCTL_DEVICE_OFFLINE
1269  * DEVCTL_DEVICE_REMOVE
1270  * DEVCTL_DEVICE_INSERT
1271  * DEVCTL_BUS_GETSTATE
1272  *
1273  * All other cmds are passed to HBA if it provide ioctl handler, or failed
1274  * if not.
1275  *
1276  * Returns:
1277  * 0 if successful,
1278  * error code if operation failed.
1279  *
1280  * Port Multiplier support is supported now.
1281  *
1282  * NOTE: qual should be SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT
1283  */
1284 
1285 static int
1286 sata_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
1287     int *rvalp)
1288 {
1289 #ifndef __lock_lint
1290 	_NOTE(ARGUNUSED(credp))
1291 	_NOTE(ARGUNUSED(rvalp))
1292 #endif
1293 	int rv = 0;
1294 	int32_t	comp_port = -1;
1295 	dev_info_t *dip;
1296 	devctl_ap_state_t ap_state;
1297 	struct devctl_iocdata *dcp = NULL;
1298 	scsi_hba_tran_t *scsi_hba_tran;
1299 	sata_hba_inst_t *sata_hba_inst;
1300 	sata_device_t sata_device;
1301 	sata_cport_info_t *cportinfo;
1302 	int cport, pmport, qual;
1303 	int rval = SATA_SUCCESS;
1304 
1305 	dip = sata_devt_to_devinfo(dev);
1306 	if (dip == NULL)
1307 		return (ENXIO);
1308 
1309 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1310 		return (ENXIO);
1311 
1312 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1313 	if (sata_hba_inst == NULL)
1314 		return (ENXIO);
1315 
1316 	if (sata_hba_inst->satahba_tran == NULL)
1317 		return (ENXIO);
1318 
1319 	switch (cmd) {
1320 
1321 	case DEVCTL_DEVICE_GETSTATE:
1322 	case DEVCTL_DEVICE_ONLINE:
1323 	case DEVCTL_DEVICE_OFFLINE:
1324 	case DEVCTL_DEVICE_REMOVE:
1325 	case DEVCTL_BUS_GETSTATE:
1326 		/*
1327 		 * There may be more cases that we want to pass to default
1328 		 * handler rather than fail them.
1329 		 */
1330 		return (ndi_devctl_ioctl(dip, cmd, arg, mode, 0));
1331 	}
1332 
1333 	/* read devctl ioctl data */
1334 	if (cmd != DEVCTL_AP_CONTROL) {
1335 		if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS)
1336 			return (EFAULT);
1337 
1338 		if ((comp_port = sata_get_port_num(sata_hba_inst, dcp)) ==
1339 		    -1) {
1340 			if (dcp)
1341 				ndi_dc_freehdl(dcp);
1342 			return (EINVAL);
1343 		}
1344 
1345 		/*
1346 		 * According to SCSI_TO_SATA_ADDR_QUAL, qual should be either
1347 		 * SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT.
1348 		 */
1349 		cport = SCSI_TO_SATA_CPORT(comp_port);
1350 		pmport = SCSI_TO_SATA_PMPORT(comp_port);
1351 		qual = SCSI_TO_SATA_ADDR_QUAL(comp_port);
1352 
1353 		if (sata_validate_sata_address(sata_hba_inst, cport, pmport,
1354 		    qual) != 0) {
1355 			ndi_dc_freehdl(dcp);
1356 			return (EINVAL);
1357 		}
1358 
1359 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1360 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1361 		    cport_mutex);
1362 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1363 			/*
1364 			 * Cannot process ioctl request now. Come back later.
1365 			 */
1366 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1367 			    cport_mutex);
1368 			ndi_dc_freehdl(dcp);
1369 			return (EBUSY);
1370 		}
1371 		/* Block event processing for this port */
1372 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1373 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1374 
1375 		sata_device.satadev_addr.cport = cport;
1376 		sata_device.satadev_addr.pmport = pmport;
1377 		sata_device.satadev_addr.qual = qual;
1378 		sata_device.satadev_rev = SATA_DEVICE_REV;
1379 	}
1380 
1381 	switch (cmd) {
1382 
1383 	case DEVCTL_AP_DISCONNECT:
1384 
1385 		/*
1386 		 * Normally, cfgadm sata plugin will try to offline
1387 		 * (unconfigure) device before this request. Nevertheless,
1388 		 * if a device is still configured, we need to
1389 		 * attempt to offline and unconfigure device first, and we will
1390 		 * deactivate the port regardless of the unconfigure
1391 		 * operation results.
1392 		 *
1393 		 */
1394 		rv = sata_ioctl_disconnect(sata_hba_inst, &sata_device);
1395 
1396 		break;
1397 
1398 	case DEVCTL_AP_UNCONFIGURE:
1399 
1400 		/*
1401 		 * The unconfigure operation uses generic nexus operation to
1402 		 * offline a device. It leaves a target device node attached.
1403 		 * and obviously sata_drive_info attached as well, because
1404 		 * from the hardware point of view nothing has changed.
1405 		 */
1406 		rv = sata_ioctl_unconfigure(sata_hba_inst, &sata_device);
1407 		break;
1408 
1409 	case DEVCTL_AP_CONNECT:
1410 	{
1411 		/*
1412 		 * The sata cfgadm pluging will invoke this operation only if
1413 		 * port was found in the disconnect state (failed state
1414 		 * is also treated as the disconnected state).
1415 		 * If port activation is successful and a device is found
1416 		 * attached to the port, the initialization sequence is
1417 		 * executed to probe the port and attach
1418 		 * a device structure to a port structure. The device is not
1419 		 * set in configured state (system-wise) by this operation.
1420 		 */
1421 
1422 		rv = sata_ioctl_connect(sata_hba_inst, &sata_device);
1423 
1424 		break;
1425 	}
1426 
1427 	case DEVCTL_AP_CONFIGURE:
1428 	{
1429 		/*
1430 		 * A port may be in an active or shutdown state.
1431 		 * If port is in a failed state, operation is aborted.
1432 		 * If a port is in a shutdown state, sata_tran_port_activate()
1433 		 * is invoked prior to any other operation.
1434 		 *
1435 		 * Onlining the device involves creating a new target node.
1436 		 * If there is an old target node present (belonging to
1437 		 * previously removed device), the operation is aborted - the
1438 		 * old node has to be released and removed before configure
1439 		 * operation is attempted.
1440 		 */
1441 
1442 		rv = sata_ioctl_configure(sata_hba_inst, &sata_device);
1443 
1444 		break;
1445 	}
1446 
1447 	case DEVCTL_AP_GETSTATE:
1448 
1449 		sata_cfgadm_state(sata_hba_inst, comp_port, &ap_state);
1450 
1451 		ap_state.ap_last_change = (time_t)-1;
1452 		ap_state.ap_error_code = 0;
1453 		ap_state.ap_in_transition = 0;
1454 
1455 		/* Copy the return AP-state information to the user space */
1456 		if (ndi_dc_return_ap_state(&ap_state, dcp) != NDI_SUCCESS) {
1457 			rv = EFAULT;
1458 		}
1459 		break;
1460 
1461 	case DEVCTL_AP_CONTROL:
1462 	{
1463 		/*
1464 		 * Generic devctl for hardware specific functionality
1465 		 */
1466 		sata_ioctl_data_t	ioc;
1467 
1468 		ASSERT(dcp == NULL);
1469 
1470 		/* Copy in user ioctl data first */
1471 #ifdef _MULTI_DATAMODEL
1472 		if (ddi_model_convert_from(mode & FMODELS) ==
1473 		    DDI_MODEL_ILP32) {
1474 
1475 			sata_ioctl_data_32_t	ioc32;
1476 
1477 			if (ddi_copyin((void *)arg, (void *)&ioc32,
1478 			    sizeof (ioc32), mode) != 0) {
1479 				rv = EFAULT;
1480 				break;
1481 			}
1482 			ioc.cmd 	= (uint_t)ioc32.cmd;
1483 			ioc.port	= (uint_t)ioc32.port;
1484 			ioc.get_size	= (uint_t)ioc32.get_size;
1485 			ioc.buf		= (caddr_t)(uintptr_t)ioc32.buf;
1486 			ioc.bufsiz	= (uint_t)ioc32.bufsiz;
1487 			ioc.misc_arg	= (uint_t)ioc32.misc_arg;
1488 		} else
1489 #endif /* _MULTI_DATAMODEL */
1490 		if (ddi_copyin((void *)arg, (void *)&ioc, sizeof (ioc),
1491 		    mode) != 0) {
1492 			return (EFAULT);
1493 		}
1494 
1495 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
1496 		    "sata_hba_ioctl: DEVCTL_AP_CONTROL "
1497 		    "cmd 0x%x, port 0x%x", ioc.cmd, ioc.port);
1498 
1499 		/*
1500 		 * To avoid BE/LE and 32/64 issues, a get_size always returns
1501 		 * a 32-bit number.
1502 		 */
1503 		if (ioc.get_size != 0 && ioc.bufsiz != (sizeof (uint32_t))) {
1504 			return (EINVAL);
1505 		}
1506 		/* validate address */
1507 		cport = SCSI_TO_SATA_CPORT(ioc.port);
1508 		pmport = SCSI_TO_SATA_PMPORT(ioc.port);
1509 		qual = SCSI_TO_SATA_ADDR_QUAL(ioc.port);
1510 
1511 		SATADBG3(SATA_DBG_IOCTL_IF, sata_hba_inst,
1512 		    "sata_hba_ioctl: target port is %d:%d (%d)",
1513 		    cport, pmport, qual);
1514 
1515 		if (sata_validate_sata_address(sata_hba_inst, cport,
1516 		    pmport, qual) != 0)
1517 			return (EINVAL);
1518 
1519 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1520 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1521 		    cport_mutex);
1522 		/* Is the port locked by event processing daemon ? */
1523 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1524 			/*
1525 			 * Cannot process ioctl request now. Come back later
1526 			 */
1527 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1528 			    cport_mutex);
1529 			return (EBUSY);
1530 		}
1531 		/* Block event processing for this port */
1532 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1533 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1534 
1535 
1536 		sata_device.satadev_addr.cport = cport;
1537 		sata_device.satadev_addr.pmport = pmport;
1538 		sata_device.satadev_addr.qual = qual;
1539 		sata_device.satadev_rev = SATA_DEVICE_REV;
1540 
1541 		switch (ioc.cmd) {
1542 
1543 		case SATA_CFGA_RESET_PORT:
1544 			/*
1545 			 * There is no protection for configured device.
1546 			 */
1547 			rv = sata_ioctl_reset_port(sata_hba_inst, &sata_device);
1548 			break;
1549 
1550 		case SATA_CFGA_RESET_DEVICE:
1551 			/*
1552 			 * There is no protection for configured device.
1553 			 */
1554 			rv = sata_ioctl_reset_device(sata_hba_inst,
1555 			    &sata_device);
1556 			break;
1557 
1558 		case SATA_CFGA_RESET_ALL:
1559 			/*
1560 			 * There is no protection for configured devices.
1561 			 */
1562 			rv = sata_ioctl_reset_all(sata_hba_inst);
1563 			/*
1564 			 * We return here, because common return is for
1565 			 * a single port operation - we have already unlocked
1566 			 * all ports and no dc handle was allocated.
1567 			 */
1568 			return (rv);
1569 
1570 		case SATA_CFGA_PORT_DEACTIVATE:
1571 			/*
1572 			 * Arbitrarily unconfigure attached device, if any.
1573 			 * Even if the unconfigure fails, proceed with the
1574 			 * port deactivation.
1575 			 */
1576 			rv = sata_ioctl_deactivate(sata_hba_inst, &sata_device);
1577 
1578 			break;
1579 
1580 		case SATA_CFGA_PORT_ACTIVATE:
1581 
1582 			rv = sata_ioctl_activate(sata_hba_inst, &sata_device);
1583 			break;
1584 
1585 		case SATA_CFGA_PORT_SELF_TEST:
1586 
1587 			rv = sata_ioctl_port_self_test(sata_hba_inst,
1588 			    &sata_device);
1589 			break;
1590 
1591 		case SATA_CFGA_GET_DEVICE_PATH:
1592 
1593 			rv = sata_ioctl_get_device_path(sata_hba_inst,
1594 			    &sata_device, &ioc, mode);
1595 			break;
1596 
1597 		case SATA_CFGA_GET_AP_TYPE:
1598 
1599 			rv = sata_ioctl_get_ap_type(sata_hba_inst,
1600 			    &sata_device, &ioc, mode);
1601 			break;
1602 
1603 		case SATA_CFGA_GET_MODEL_INFO:
1604 
1605 			rv = sata_ioctl_get_model_info(sata_hba_inst,
1606 			    &sata_device, &ioc, mode);
1607 			break;
1608 
1609 		case SATA_CFGA_GET_REVFIRMWARE_INFO:
1610 
1611 			rv = sata_ioctl_get_revfirmware_info(sata_hba_inst,
1612 			    &sata_device, &ioc, mode);
1613 			break;
1614 
1615 		case SATA_CFGA_GET_SERIALNUMBER_INFO:
1616 
1617 			rv = sata_ioctl_get_serialnumber_info(sata_hba_inst,
1618 			    &sata_device, &ioc, mode);
1619 			break;
1620 
1621 		default:
1622 			rv = EINVAL;
1623 			break;
1624 
1625 		} /* End of DEVCTL_AP_CONTROL cmd switch */
1626 
1627 		break;
1628 	}
1629 
1630 	default:
1631 	{
1632 		/*
1633 		 * If we got here, we got an IOCTL that SATA HBA Framework
1634 		 * does not recognize. Pass ioctl to HBA driver, in case
1635 		 * it could process it.
1636 		 */
1637 		sata_hba_tran_t *sata_tran = sata_hba_inst->satahba_tran;
1638 		dev_info_t	*mydip = SATA_DIP(sata_hba_inst);
1639 
1640 		SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1641 		    "IOCTL 0x%2x not supported in SATA framework, "
1642 		    "passthrough to HBA", cmd);
1643 
1644 		if (sata_tran->sata_tran_ioctl == NULL) {
1645 			rv = EINVAL;
1646 			break;
1647 		}
1648 		rval = (*sata_tran->sata_tran_ioctl)(mydip, cmd, arg);
1649 		if (rval != 0) {
1650 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1651 			    "IOCTL 0x%2x failed in HBA", cmd);
1652 			rv = rval;
1653 		}
1654 		break;
1655 	}
1656 
1657 	} /* End of main IOCTL switch */
1658 
1659 	if (dcp) {
1660 		ndi_dc_freehdl(dcp);
1661 	}
1662 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1663 	cportinfo->cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
1664 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1665 
1666 	return (rv);
1667 }
1668 
1669 
1670 /*
1671  * Create error retrieval sata packet
1672  *
1673  * A sata packet is allocated and set-up to contain specified error retrieval
1674  * command and appropriate dma-able data buffer.
1675  * No association with any scsi packet is made and no callback routine is
1676  * specified.
1677  *
1678  * Returns a pointer to sata packet upon successfull packet creation.
1679  * Returns NULL, if packet cannot be created.
1680  */
1681 sata_pkt_t *
1682 sata_get_error_retrieval_pkt(dev_info_t *dip, sata_device_t *sata_device,
1683     int pkt_type)
1684 {
1685 	sata_hba_inst_t	*sata_hba_inst;
1686 	sata_pkt_txlate_t *spx;
1687 	sata_pkt_t *spkt;
1688 	sata_drive_info_t *sdinfo;
1689 
1690 	mutex_enter(&sata_mutex);
1691 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1692 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1693 		if (SATA_DIP(sata_hba_inst) == dip)
1694 			break;
1695 	}
1696 	mutex_exit(&sata_mutex);
1697 	ASSERT(sata_hba_inst != NULL);
1698 
1699 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
1700 	if (sdinfo == NULL) {
1701 		sata_log(sata_hba_inst, CE_WARN,
1702 		    "sata: error recovery request for non-attached device at "
1703 		    "cport %d", sata_device->satadev_addr.cport);
1704 		return (NULL);
1705 	}
1706 
1707 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1708 	spx->txlt_sata_hba_inst = sata_hba_inst;
1709 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
1710 	spkt = sata_pkt_alloc(spx, NULL);
1711 	if (spkt == NULL) {
1712 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1713 		return (NULL);
1714 	}
1715 	/* address is needed now */
1716 	spkt->satapkt_device.satadev_addr = sata_device->satadev_addr;
1717 
1718 	switch (pkt_type) {
1719 	case SATA_ERR_RETR_PKT_TYPE_NCQ:
1720 		if (sata_ncq_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1721 			return (spkt);
1722 		break;
1723 
1724 	case SATA_ERR_RETR_PKT_TYPE_ATAPI:
1725 		if (sata_atapi_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1726 			return (spkt);
1727 		break;
1728 
1729 	default:
1730 		break;
1731 	}
1732 
1733 	sata_pkt_free(spx);
1734 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1735 	return (NULL);
1736 
1737 }
1738 
1739 
1740 /*
1741  * Free error retrieval sata packet
1742  *
1743  * Free sata packet and any associated resources allocated previously by
1744  * sata_get_error_retrieval_pkt().
1745  *
1746  * Void return.
1747  */
1748 void
1749 sata_free_error_retrieval_pkt(sata_pkt_t *sata_pkt)
1750 {
1751 	sata_pkt_txlate_t *spx =
1752 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1753 
1754 	ASSERT(sata_pkt != NULL);
1755 
1756 	sata_free_local_buffer(spx);
1757 	sata_pkt_free(spx);
1758 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1759 
1760 }
1761 
1762 /*
1763  * Create READ PORT MULTIPLIER and WRITE PORT MULTIPLIER sata packet
1764  *
1765  * No association with any scsi packet is made and no callback routine is
1766  * specified.
1767  *
1768  * Returns a pointer to sata packet upon successfull packet creation.
1769  * Returns NULL, if packet cannot be created.
1770  *
1771  * NOTE: Input/Output value includes 64 bits accoring to SATA Spec 2.6,
1772  * only lower 32 bits are available currently.
1773  */
1774 sata_pkt_t *
1775 sata_get_rdwr_pmult_pkt(dev_info_t *dip, sata_device_t *sd,
1776     uint8_t regn, uint32_t regv, uint32_t type)
1777 {
1778 	sata_hba_inst_t	*sata_hba_inst;
1779 	sata_pkt_txlate_t *spx;
1780 	sata_pkt_t *spkt;
1781 	sata_cmd_t *scmd;
1782 
1783 	/* Only READ/WRITE commands are accepted. */
1784 	ASSERT(type == SATA_RDWR_PMULT_PKT_TYPE_READ ||
1785 	    type == SATA_RDWR_PMULT_PKT_TYPE_WRITE);
1786 
1787 	mutex_enter(&sata_mutex);
1788 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1789 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1790 		if (SATA_DIP(sata_hba_inst) == dip)
1791 			break;
1792 	}
1793 	mutex_exit(&sata_mutex);
1794 	ASSERT(sata_hba_inst != NULL);
1795 
1796 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1797 	spx->txlt_sata_hba_inst = sata_hba_inst;
1798 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
1799 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
1800 	if (spkt == NULL) {
1801 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1802 		return (NULL);
1803 	}
1804 
1805 	/*
1806 	 * NOTE: We need to send this command to the port multiplier,
1807 	 * that means send to SATA_PMULT_HOSTPORT(0xf) pmport
1808 	 *
1809 	 * sata_device contains the address of actual target device, and the
1810 	 * pmport number in the command comes from the sata_device structure.
1811 	 */
1812 	spkt->satapkt_device.satadev_addr = sd->satadev_addr;
1813 	spkt->satapkt_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
1814 	spkt->satapkt_device.satadev_addr.qual = SATA_ADDR_PMULT;
1815 
1816 	/* Fill sata_pkt */
1817 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_POLLING;
1818 	spkt->satapkt_comp = NULL; /* Synchronous mode, no callback */
1819 	spkt->satapkt_time = 10; /* Timeout 10s */
1820 
1821 	/* Build READ PORT MULTIPLIER cmd in the sata_pkt */
1822 	scmd = &spkt->satapkt_cmd;
1823 	scmd->satacmd_features_reg = regn & 0xff;
1824 	scmd->satacmd_features_reg_ext = (regn >> 8) & 0xff;
1825 	scmd->satacmd_device_reg = sd->satadev_addr.pmport;
1826 	scmd->satacmd_addr_type = 0;		/* N/A */
1827 
1828 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
1829 
1830 	if (type == SATA_RDWR_PMULT_PKT_TYPE_READ) {
1831 		scmd->satacmd_cmd_reg = SATAC_READ_PORTMULT;
1832 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
1833 		scmd->satacmd_flags.sata_special_regs = 1;
1834 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
1835 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
1836 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
1837 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
1838 	} else if (type == SATA_RDWR_PMULT_PKT_TYPE_WRITE) {
1839 		scmd->satacmd_cmd_reg = SATAC_WRITE_PORTMULT;
1840 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
1841 		scmd->satacmd_sec_count_lsb = regv & 0xff;
1842 		scmd->satacmd_lba_low_lsb = regv >> 8 & 0xff;
1843 		scmd->satacmd_lba_mid_lsb = regv >> 16 & 0xff;
1844 		scmd->satacmd_lba_high_lsb = regv >> 24 & 0xff;
1845 	}
1846 
1847 	return (spkt);
1848 }
1849 
1850 /*
1851  * Free sata packet and any associated resources allocated previously by
1852  * sata_get_rdwr_pmult_pkt().
1853  *
1854  * Void return.
1855  */
1856 void
1857 sata_free_rdwr_pmult_pkt(sata_pkt_t *sata_pkt)
1858 {
1859 	sata_pkt_txlate_t *spx =
1860 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1861 
1862 	/* Free allocated resources */
1863 	sata_pkt_free(spx);
1864 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1865 }
1866 
1867 /*
1868  * Register a port multiplier to framework.
1869  * 1) Store the GSCR values in the previous allocated pmult_info strctures.
1870  * 2) Search in the blacklist and update the number of the device ports of the
1871  * port multiplier.
1872  *
1873  * Void return.
1874  */
1875 void
1876 sata_register_pmult(dev_info_t *dip, sata_device_t *sd, sata_pmult_gscr_t *sg)
1877 {
1878 	sata_hba_inst_t *sata_hba_inst = NULL;
1879 	sata_pmult_info_t *pmultinfo;
1880 	sata_pmult_bl_t *blp;
1881 	int cport = sd->satadev_addr.cport;
1882 
1883 	mutex_enter(&sata_mutex);
1884 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1885 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1886 		if (SATA_DIP(sata_hba_inst) == dip)
1887 			if (sata_hba_inst->satahba_attached == 1)
1888 				break;
1889 	}
1890 	mutex_exit(&sata_mutex);
1891 	/* HBA not attached? */
1892 	if (sata_hba_inst == NULL)
1893 		return;
1894 
1895 	/* Number of pmports */
1896 	sd->satadev_add_info = sg->gscr2 & SATA_PMULT_PORTNUM_MASK;
1897 
1898 	/* Check the blacklist */
1899 	for (blp = sata_pmult_blacklist; blp->bl_gscr0; blp++) {
1900 		if (sg->gscr0 != blp->bl_gscr0 && blp->bl_gscr0)
1901 			continue;
1902 		if (sg->gscr1 != blp->bl_gscr1 && blp->bl_gscr1)
1903 			continue;
1904 		if (sg->gscr2 != blp->bl_gscr2 && blp->bl_gscr2)
1905 			continue;
1906 
1907 		cmn_err(CE_WARN, "!Port multiplier is on the blacklist.");
1908 		sd->satadev_add_info = blp->bl_flags;
1909 		break;
1910 	}
1911 
1912 	/* Register the port multiplier GSCR */
1913 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
1914 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
1915 	if (pmultinfo != NULL) {
1916 		pmultinfo->pmult_gscr = *sg;
1917 		pmultinfo->pmult_num_dev_ports =
1918 		    sd->satadev_add_info & SATA_PMULT_PORTNUM_MASK;
1919 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
1920 		    "Port multiplier registered at port %d", cport);
1921 	}
1922 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
1923 }
1924 
1925 /*
1926  * sata_name_child is for composing the name of the node
1927  * the format of the name is "target,0".
1928  */
1929 static int
1930 sata_name_child(dev_info_t *dip, char *name, int namelen)
1931 {
1932 	int target;
1933 
1934 	target = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1935 	    DDI_PROP_DONTPASS, "target", -1);
1936 	if (target == -1)
1937 		return (DDI_FAILURE);
1938 	(void) snprintf(name, namelen, "%x,0", target);
1939 	return (DDI_SUCCESS);
1940 }
1941 
1942 
1943 
1944 /* ****************** SCSA required entry points *********************** */
1945 
1946 /*
1947  * Implementation of scsi tran_tgt_init.
1948  * sata_scsi_tgt_init() initializes scsi_device structure
1949  *
1950  * If successful, DDI_SUCCESS is returned.
1951  * DDI_FAILURE is returned if addressed device does not exist
1952  */
1953 
1954 static int
1955 sata_scsi_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
1956     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
1957 {
1958 #ifndef __lock_lint
1959 	_NOTE(ARGUNUSED(hba_dip))
1960 	_NOTE(ARGUNUSED(tgt_dip))
1961 #endif
1962 	sata_device_t		sata_device;
1963 	sata_drive_info_t	*sdinfo;
1964 	struct sata_id		*sid;
1965 	sata_hba_inst_t		*sata_hba_inst;
1966 	char			model[SATA_ID_MODEL_LEN + 1];
1967 	char			fw[SATA_ID_FW_LEN + 1];
1968 	char			*vid, *pid;
1969 	int			i;
1970 
1971 	/*
1972 	 * Fail tran_tgt_init for .conf stub node
1973 	 */
1974 	if (ndi_dev_is_persistent_node(tgt_dip) == 0) {
1975 		(void) ndi_merge_node(tgt_dip, sata_name_child);
1976 		ddi_set_name_addr(tgt_dip, NULL);
1977 		return (DDI_FAILURE);
1978 	}
1979 
1980 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
1981 
1982 	/* Validate scsi device address */
1983 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
1984 	    &sata_device) != 0)
1985 		return (DDI_FAILURE);
1986 
1987 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1988 	    sata_device.satadev_addr.cport)));
1989 
1990 	/* sata_device now contains a valid sata address */
1991 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
1992 	if (sdinfo == NULL) {
1993 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1994 		    sata_device.satadev_addr.cport)));
1995 		return (DDI_FAILURE);
1996 	}
1997 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1998 	    sata_device.satadev_addr.cport)));
1999 
2000 	/*
2001 	 * Check if we need to create a legacy devid (i.e cmdk style) for
2002 	 * the target disks.
2003 	 *
2004 	 * HBA devinfo node will have the property "use-cmdk-devid-format"
2005 	 * if we need to create cmdk-style devid for all the disk devices
2006 	 * attached to this controller. This property may have been set
2007 	 * from HBA driver's .conf file or by the HBA driver in its
2008 	 * attach(9F) function.
2009 	 */
2010 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
2011 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
2012 	    "use-cmdk-devid-format", 0) == 1)) {
2013 		/* register a legacy devid for this target node */
2014 		sata_target_devid_register(tgt_dip, sdinfo);
2015 	}
2016 
2017 
2018 	/*
2019 	 * 'Identify Device Data' does not always fit in standard SCSI
2020 	 * INQUIRY data, so establish INQUIRY_* properties with full-form
2021 	 * of information.
2022 	 */
2023 	sid = &sdinfo->satadrv_id;
2024 #ifdef	_LITTLE_ENDIAN
2025 	swab(sid->ai_model, model, SATA_ID_MODEL_LEN);
2026 	swab(sid->ai_fw, fw, SATA_ID_FW_LEN);
2027 #else	/* _LITTLE_ENDIAN */
2028 	bcopy(sid->ai_model, model, SATA_ID_MODEL_LEN);
2029 	bcopy(sid->ai_fw, fw, SATA_ID_FW_LEN);
2030 #endif	/* _LITTLE_ENDIAN */
2031 	model[SATA_ID_MODEL_LEN] = 0;
2032 	fw[SATA_ID_FW_LEN] = 0;
2033 
2034 	/* split model into into vid/pid */
2035 	for (i = 0, pid = model; i < SATA_ID_MODEL_LEN; i++, pid++)
2036 		if ((*pid == ' ') || (*pid == '\t'))
2037 			break;
2038 	if (i < SATA_ID_MODEL_LEN) {
2039 		vid = model;
2040 		*pid++ = 0;		/* terminate vid, establish pid */
2041 	} else {
2042 		vid = NULL;		/* vid will stay "ATA     " */
2043 		pid = model;		/* model is all pid */
2044 	}
2045 
2046 	if (vid)
2047 		(void) scsi_device_prop_update_inqstring(sd, INQUIRY_VENDOR_ID,
2048 		    vid, strlen(vid));
2049 	if (pid)
2050 		(void) scsi_device_prop_update_inqstring(sd, INQUIRY_PRODUCT_ID,
2051 		    pid, strlen(pid));
2052 	(void) scsi_device_prop_update_inqstring(sd, INQUIRY_REVISION_ID,
2053 	    fw, strlen(fw));
2054 
2055 	return (DDI_SUCCESS);
2056 }
2057 
2058 /*
2059  * Implementation of scsi tran_tgt_probe.
2060  * Probe target, by calling default scsi routine scsi_hba_probe()
2061  */
2062 static int
2063 sata_scsi_tgt_probe(struct scsi_device *sd, int (*callback)(void))
2064 {
2065 	sata_hba_inst_t *sata_hba_inst =
2066 	    (sata_hba_inst_t *)(sd->sd_address.a_hba_tran->tran_hba_private);
2067 	int rval;
2068 	uint32_t pm_cap;
2069 
2070 	rval = scsi_hba_probe(sd, callback);
2071 	pm_cap = SATA_CAP_POWER_CONDITON | SATA_CAP_SMART_PAGE |
2072 	    SATA_CAP_LOG_SENSE;
2073 
2074 	if (rval == SCSIPROBE_EXISTS) {
2075 		/*
2076 		 * Set property "pm-capable" on the target device node, so that
2077 		 * the target driver will not try to fetch scsi cycle counters
2078 		 * before enabling device power-management.
2079 		 */
2080 		if ((ddi_prop_update_int(DDI_DEV_T_NONE, sd->sd_dev,
2081 		    "pm-capable", pm_cap)) != DDI_PROP_SUCCESS) {
2082 			sata_log(sata_hba_inst, CE_WARN,
2083 			    "SATA device at port %d: "
2084 			    "will not be power-managed ",
2085 			    SCSI_TO_SATA_CPORT(sd->sd_address.a_target));
2086 			SATA_LOG_D((sata_hba_inst, CE_WARN,
2087 			    "failure updating pm-capable property"));
2088 		}
2089 	}
2090 	return (rval);
2091 }
2092 
2093 /*
2094  * Implementation of scsi tran_tgt_free.
2095  * Release all resources allocated for scsi_device
2096  */
2097 static void
2098 sata_scsi_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
2099     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
2100 {
2101 #ifndef __lock_lint
2102 	_NOTE(ARGUNUSED(hba_dip))
2103 #endif
2104 	sata_device_t		sata_device;
2105 	sata_drive_info_t	*sdinfo;
2106 	sata_hba_inst_t		*sata_hba_inst;
2107 	ddi_devid_t		devid;
2108 
2109 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
2110 
2111 	/* Validate scsi device address */
2112 	/*
2113 	 * Note: tgt_free relates to the SCSA view of a device. If called, there
2114 	 * was a device at this address, so even if the sata framework internal
2115 	 * resources were alredy released because a device was detached,
2116 	 * this function should be executed as long as its actions do
2117 	 * not require the internal sata view of a device and the address
2118 	 * refers to a valid sata address.
2119 	 * Validating the address here means that we do not trust SCSA...
2120 	 */
2121 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
2122 	    &sata_device) == -1)
2123 		return;
2124 
2125 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2126 	    sata_device.satadev_addr.cport)));
2127 
2128 	/* sata_device now should contain a valid sata address */
2129 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
2130 	if (sdinfo == NULL) {
2131 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2132 		    sata_device.satadev_addr.cport)));
2133 		return;
2134 	}
2135 	/*
2136 	 * We did not allocate any resources in sata_scsi_tgt_init()
2137 	 * other than few properties.
2138 	 * Free them.
2139 	 */
2140 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2141 	    sata_device.satadev_addr.cport)));
2142 	(void) ndi_prop_remove(DDI_DEV_T_NONE, tgt_dip, "pm-capable");
2143 
2144 	/*
2145 	 * If devid was previously created but not freed up from
2146 	 * sd(7D) driver (i.e during detach(9F)) then do it here.
2147 	 */
2148 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
2149 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
2150 	    "use-cmdk-devid-format", 0) == 1) &&
2151 	    (ddi_devid_get(tgt_dip, &devid) == DDI_SUCCESS)) {
2152 		ddi_devid_unregister(tgt_dip);
2153 		ddi_devid_free(devid);
2154 	}
2155 }
2156 
2157 /*
2158  * Implementation of scsi tran_init_pkt
2159  * Upon successful return, scsi pkt buffer has DMA resources allocated.
2160  *
2161  * It seems that we should always allocate pkt, even if the address is
2162  * for non-existing device - just use some default for dma_attr.
2163  * The reason is that there is no way to communicate this to a caller here.
2164  * Subsequent call to sata_scsi_start may fail appropriately.
2165  * Simply returning NULL does not seem to discourage a target driver...
2166  *
2167  * Returns a pointer to initialized scsi_pkt, or NULL otherwise.
2168  */
2169 static struct scsi_pkt *
2170 sata_scsi_init_pkt(struct scsi_address *ap, struct scsi_pkt *pkt,
2171     struct buf *bp, int cmdlen, int statuslen, int tgtlen, int flags,
2172     int (*callback)(caddr_t), caddr_t arg)
2173 {
2174 	sata_hba_inst_t *sata_hba_inst =
2175 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2176 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
2177 	sata_device_t sata_device;
2178 	sata_drive_info_t *sdinfo;
2179 	sata_pkt_txlate_t *spx;
2180 	ddi_dma_attr_t cur_dma_attr;
2181 	int rval;
2182 	boolean_t new_pkt = TRUE;
2183 
2184 	ASSERT(ap->a_hba_tran->tran_hba_dip == dip);
2185 
2186 	/*
2187 	 * We need to translate the address, even if it could be
2188 	 * a bogus one, for a non-existing device
2189 	 */
2190 	sata_device.satadev_addr.qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
2191 	sata_device.satadev_addr.cport = SCSI_TO_SATA_CPORT(ap->a_target);
2192 	sata_device.satadev_addr.pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2193 	sata_device.satadev_rev = SATA_DEVICE_REV;
2194 
2195 	if (pkt == NULL) {
2196 		/*
2197 		 * Have to allocate a brand new scsi packet.
2198 		 * We need to operate with auto request sense enabled.
2199 		 */
2200 		pkt = scsi_hba_pkt_alloc(dip, ap, cmdlen,
2201 		    MAX(statuslen, SATA_MAX_SENSE_LEN),
2202 		    tgtlen, sizeof (sata_pkt_txlate_t), callback, arg);
2203 
2204 		if (pkt == NULL)
2205 			return (NULL);
2206 
2207 		/* Fill scsi packet structure */
2208 		pkt->pkt_comp		= (void (*)())NULL;
2209 		pkt->pkt_time		= 0;
2210 		pkt->pkt_resid		= 0;
2211 		pkt->pkt_statistics	= 0;
2212 		pkt->pkt_reason		= 0;
2213 
2214 		/*
2215 		 * pkt_hba_private will point to sata pkt txlate structure
2216 		 */
2217 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2218 		bzero(spx, sizeof (sata_pkt_txlate_t));
2219 
2220 		spx->txlt_scsi_pkt = pkt;
2221 		spx->txlt_sata_hba_inst = sata_hba_inst;
2222 
2223 		/* Allocate sata_pkt */
2224 		spx->txlt_sata_pkt = sata_pkt_alloc(spx, callback);
2225 		if (spx->txlt_sata_pkt == NULL) {
2226 			/* Could not allocate sata pkt */
2227 			scsi_hba_pkt_free(ap, pkt);
2228 			return (NULL);
2229 		}
2230 		/* Set sata address */
2231 		spx->txlt_sata_pkt->satapkt_device.satadev_addr =
2232 		    sata_device.satadev_addr;
2233 		spx->txlt_sata_pkt->satapkt_device.satadev_rev =
2234 		    sata_device.satadev_rev;
2235 
2236 		if ((bp == NULL) || (bp->b_bcount == 0))
2237 			return (pkt);
2238 
2239 		spx->txlt_total_residue = bp->b_bcount;
2240 	} else {
2241 		new_pkt = FALSE;
2242 		/*
2243 		 * Packet was preallocated/initialized by previous call
2244 		 */
2245 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2246 
2247 		if ((bp == NULL) || (bp->b_bcount == 0)) {
2248 			return (pkt);
2249 		}
2250 
2251 		/* Pkt is available already: spx->txlt_scsi_pkt == pkt; */
2252 	}
2253 
2254 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
2255 
2256 	/*
2257 	 * We use an adjusted version of the dma_attr, to account
2258 	 * for device addressing limitations.
2259 	 * sata_adjust_dma_attr() will handle sdinfo == NULL which may
2260 	 * happen when a device is not yet configured.
2261 	 */
2262 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2263 	    sata_device.satadev_addr.cport)));
2264 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
2265 	    &spx->txlt_sata_pkt->satapkt_device);
2266 	/* NULL sdinfo may be passsed to sata_adjust_dma_attr() */
2267 	sata_adjust_dma_attr(sdinfo,
2268 	    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
2269 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2270 	    sata_device.satadev_addr.cport)));
2271 	/*
2272 	 * Allocate necessary DMA resources for the packet's data buffer
2273 	 * NOTE:
2274 	 * In case of read/write commands, DMA resource allocation here is
2275 	 * based on the premise that the transfer length specified in
2276 	 * the read/write scsi cdb will match exactly DMA resources -
2277 	 * returning correct packet residue is crucial.
2278 	 */
2279 	if ((rval = sata_dma_buf_setup(spx, flags, callback, arg,
2280 	    &cur_dma_attr)) != DDI_SUCCESS) {
2281 		/*
2282 		 * If a DMA allocation request fails with
2283 		 * DDI_DMA_NOMAPPING, indicate the error by calling
2284 		 * bioerror(9F) with bp and an error code of EFAULT.
2285 		 * If a DMA allocation request fails with
2286 		 * DDI_DMA_TOOBIG, indicate the error by calling
2287 		 * bioerror(9F) with bp and an error code of EINVAL.
2288 		 * For DDI_DMA_NORESOURCES, we may have some of them allocated.
2289 		 * Request may be repeated later - there is no real error.
2290 		 */
2291 		switch (rval) {
2292 		case DDI_DMA_NORESOURCES:
2293 			bioerror(bp, 0);
2294 			break;
2295 		case DDI_DMA_NOMAPPING:
2296 		case DDI_DMA_BADATTR:
2297 			bioerror(bp, EFAULT);
2298 			break;
2299 		case DDI_DMA_TOOBIG:
2300 		default:
2301 			bioerror(bp, EINVAL);
2302 			break;
2303 		}
2304 		if (new_pkt == TRUE) {
2305 			/*
2306 			 * Since this is a new packet, we can clean-up
2307 			 * everything
2308 			 */
2309 			sata_scsi_destroy_pkt(ap, pkt);
2310 		} else {
2311 			/*
2312 			 * This is a re-used packet. It will be target driver's
2313 			 * responsibility to eventually destroy it (which
2314 			 * will free allocated resources).
2315 			 * Here, we just "complete" the request, leaving
2316 			 * allocated resources intact, so the request may
2317 			 * be retried.
2318 			 */
2319 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2320 			sata_pkt_free(spx);
2321 		}
2322 		return (NULL);
2323 	}
2324 	/* Set number of bytes that are not yet accounted for */
2325 	pkt->pkt_resid = spx->txlt_total_residue;
2326 	ASSERT(pkt->pkt_resid >= 0);
2327 
2328 	return (pkt);
2329 }
2330 
2331 /*
2332  * Implementation of scsi tran_start.
2333  * Translate scsi cmd into sata operation and return status.
2334  * ATAPI CDBs are passed to ATAPI devices - the device determines what commands
2335  * are supported.
2336  * For SATA hard disks, supported scsi commands:
2337  * SCMD_INQUIRY
2338  * SCMD_TEST_UNIT_READY
2339  * SCMD_START_STOP
2340  * SCMD_READ_CAPACITY
2341  * SCMD_SVC_ACTION_IN_G4 (READ CAPACITY (16))
2342  * SCMD_REQUEST_SENSE
2343  * SCMD_LOG_SENSE_G1
2344  * SCMD_LOG_SELECT_G1
2345  * SCMD_MODE_SENSE	(specific pages)
2346  * SCMD_MODE_SENSE_G1	(specific pages)
2347  * SCMD_MODE_SELECT	(specific pages)
2348  * SCMD_MODE_SELECT_G1	(specific pages)
2349  * SCMD_SYNCHRONIZE_CACHE
2350  * SCMD_SYNCHRONIZE_CACHE_G1
2351  * SCMD_READ
2352  * SCMD_READ_G1
2353  * SCMD_READ_G4
2354  * SCMD_READ_G5
2355  * SCMD_WRITE
2356  * SCMD_WRITE_BUFFER
2357  * SCMD_WRITE_G1
2358  * SCMD_WRITE_G4
2359  * SCMD_WRITE_G5
2360  * SCMD_SEEK		(noop)
2361  * SCMD_SDIAG
2362  *
2363  * All other commands are rejected as unsupported.
2364  *
2365  * Returns:
2366  * TRAN_ACCEPT if command was executed successfully or accepted by HBA driver
2367  * for execution. TRAN_ACCEPT may be returned also if device was removed but
2368  * a callback could be scheduled.
2369  * TRAN_BADPKT if cmd was directed to invalid address.
2370  * TRAN_FATAL_ERROR is command was rejected due to hardware error, including
2371  * some unspecified error. TRAN_FATAL_ERROR may be also returned if a device
2372  * was removed and there was no callback specified in scsi pkt.
2373  * TRAN_BUSY if command could not be executed becasue HBA driver or SATA
2374  * framework was busy performing some other operation(s).
2375  *
2376  */
2377 static int
2378 sata_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
2379 {
2380 	sata_hba_inst_t *sata_hba_inst =
2381 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2382 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2383 	sata_device_t *sdevice = &spx->txlt_sata_pkt->satapkt_device;
2384 	sata_drive_info_t *sdinfo;
2385 	struct buf *bp;
2386 	uint8_t cport, pmport;
2387 	boolean_t dev_gone = B_FALSE;
2388 	int rval;
2389 
2390 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2391 	    "sata_scsi_start: cmd 0x%02x\n", pkt->pkt_cdbp[0]);
2392 
2393 	ASSERT(spx != NULL &&
2394 	    spx->txlt_scsi_pkt == pkt && spx->txlt_sata_pkt != NULL);
2395 
2396 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
2397 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2398 
2399 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2400 
2401 	if (sdevice->satadev_addr.qual == SATA_ADDR_DCPORT) {
2402 		sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2403 		if (sdinfo == NULL ||
2404 		    SATA_CPORT_INFO(sata_hba_inst, cport)->
2405 		    cport_tgtnode_clean == B_FALSE ||
2406 		    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2407 			dev_gone = B_TRUE;
2408 		}
2409 	} else if (sdevice->satadev_addr.qual == SATA_ADDR_DPMPORT) {
2410 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
2411 		    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
2412 		    cport) == NULL) {
2413 			dev_gone = B_TRUE;
2414 		} else if (SATA_PMPORT_INFO(sata_hba_inst, cport,
2415 		    pmport) == NULL) {
2416 			dev_gone = B_TRUE;
2417 		} else {
2418 			mutex_enter(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2419 			    cport, pmport)));
2420 			sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2421 			if (sdinfo == NULL ||
2422 			    SATA_PMPORT_INFO(sata_hba_inst, cport, pmport)->
2423 			    pmport_tgtnode_clean == B_FALSE ||
2424 			    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2425 				dev_gone = B_TRUE;
2426 			}
2427 			mutex_exit(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2428 			    cport, pmport)));
2429 		}
2430 	}
2431 
2432 	if (dev_gone == B_TRUE) {
2433 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2434 		pkt->pkt_reason = CMD_DEV_GONE;
2435 		/*
2436 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
2437 		 * only in callback function (for normal requests) and
2438 		 * in the dump code path.
2439 		 * So, if the callback is available, we need to do
2440 		 * the callback rather than returning TRAN_FATAL_ERROR here.
2441 		 */
2442 		if (pkt->pkt_comp != NULL) {
2443 			/* scsi callback required */
2444 			if (servicing_interrupt()) {
2445 				if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2446 				    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2447 				    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
2448 				    NULL) {
2449 					return (TRAN_BUSY);
2450 				}
2451 			} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2452 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
2453 			    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
2454 				/* Scheduling the callback failed */
2455 				return (TRAN_BUSY);
2456 			}
2457 			return (TRAN_ACCEPT);
2458 		}
2459 		/* No callback available */
2460 		return (TRAN_FATAL_ERROR);
2461 	}
2462 
2463 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
2464 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2465 		rval = sata_txlt_atapi(spx);
2466 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2467 		    "sata_scsi_start atapi: rval %d\n", rval);
2468 		return (rval);
2469 	}
2470 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2471 
2472 	/*
2473 	 * Checking for power state, if it was on
2474 	 * STOPPED state, then the drive is not capable
2475 	 * of processing media access command.  And
2476 	 * TEST_UNIT_READY, REQUEST_SENSE has special handling
2477 	 * in the function for different power state.
2478 	 */
2479 	if (((sdinfo->satadrv_power_level == SATA_POWER_STANDBY) ||
2480 	    (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)) &&
2481 	    (SATA_IS_MEDIUM_ACCESS_CMD(pkt->pkt_cdbp[0]))) {
2482 		return (sata_txlt_check_condition(spx, KEY_NOT_READY,
2483 		    SD_SCSI_ASC_LU_NOT_READY));
2484 	}
2485 
2486 	/* ATA Disk commands processing starts here */
2487 
2488 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2489 
2490 	switch (pkt->pkt_cdbp[0]) {
2491 
2492 	case SCMD_INQUIRY:
2493 		/* Mapped to identify device */
2494 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2495 			bp_mapin(bp);
2496 		rval = sata_txlt_inquiry(spx);
2497 		break;
2498 
2499 	case SCMD_TEST_UNIT_READY:
2500 		/*
2501 		 * SAT "SATA to ATA Translation" doc specifies translation
2502 		 * to ATA CHECK POWER MODE.
2503 		 */
2504 		rval = sata_txlt_test_unit_ready(spx);
2505 		break;
2506 
2507 	case SCMD_START_STOP:
2508 		/* Mapping depends on the command */
2509 		rval = sata_txlt_start_stop_unit(spx);
2510 		break;
2511 
2512 	case SCMD_READ_CAPACITY:
2513 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2514 			bp_mapin(bp);
2515 		rval = sata_txlt_read_capacity(spx);
2516 		break;
2517 
2518 	case SCMD_SVC_ACTION_IN_G4:		/* READ CAPACITY (16) */
2519 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2520 			bp_mapin(bp);
2521 		rval = sata_txlt_read_capacity16(spx);
2522 		break;
2523 
2524 	case SCMD_REQUEST_SENSE:
2525 		/*
2526 		 * Always No Sense, since we force ARQ
2527 		 */
2528 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2529 			bp_mapin(bp);
2530 		rval = sata_txlt_request_sense(spx);
2531 		break;
2532 
2533 	case SCMD_LOG_SENSE_G1:
2534 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2535 			bp_mapin(bp);
2536 		rval = sata_txlt_log_sense(spx);
2537 		break;
2538 
2539 	case SCMD_LOG_SELECT_G1:
2540 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2541 			bp_mapin(bp);
2542 		rval = sata_txlt_log_select(spx);
2543 		break;
2544 
2545 	case SCMD_MODE_SENSE:
2546 	case SCMD_MODE_SENSE_G1:
2547 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2548 			bp_mapin(bp);
2549 		rval = sata_txlt_mode_sense(spx);
2550 		break;
2551 
2552 
2553 	case SCMD_MODE_SELECT:
2554 	case SCMD_MODE_SELECT_G1:
2555 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2556 			bp_mapin(bp);
2557 		rval = sata_txlt_mode_select(spx);
2558 		break;
2559 
2560 	case SCMD_SYNCHRONIZE_CACHE:
2561 	case SCMD_SYNCHRONIZE_CACHE_G1:
2562 		rval = sata_txlt_synchronize_cache(spx);
2563 		break;
2564 
2565 	case SCMD_READ:
2566 	case SCMD_READ_G1:
2567 	case SCMD_READ_G4:
2568 	case SCMD_READ_G5:
2569 		rval = sata_txlt_read(spx);
2570 		break;
2571 	case SCMD_WRITE_BUFFER:
2572 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2573 			bp_mapin(bp);
2574 		rval = sata_txlt_write_buffer(spx);
2575 		break;
2576 
2577 	case SCMD_WRITE:
2578 	case SCMD_WRITE_G1:
2579 	case SCMD_WRITE_G4:
2580 	case SCMD_WRITE_G5:
2581 		rval = sata_txlt_write(spx);
2582 		break;
2583 
2584 	case SCMD_SEEK:
2585 		rval = sata_txlt_nodata_cmd_immediate(spx);
2586 		break;
2587 
2588 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
2589 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
2590 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2591 			bp_mapin(bp);
2592 		rval = sata_txlt_ata_pass_thru(spx);
2593 		break;
2594 
2595 		/* Other cases will be filed later */
2596 		/* postponed until phase 2 of the development */
2597 	default:
2598 		rval = sata_txlt_invalid_command(spx);
2599 		break;
2600 	}
2601 
2602 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2603 	    "sata_scsi_start: rval %d\n", rval);
2604 
2605 	return (rval);
2606 }
2607 
2608 /*
2609  * Implementation of scsi tran_abort.
2610  * Abort specific pkt or all packets.
2611  *
2612  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2613  *
2614  * May be called from an interrupt level.
2615  */
2616 static int
2617 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2618 {
2619 	sata_hba_inst_t *sata_hba_inst =
2620 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2621 	sata_device_t	sata_device;
2622 	sata_pkt_t	*sata_pkt;
2623 
2624 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2625 	    "sata_scsi_abort: %s at target: 0x%x\n",
2626 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2627 
2628 	/* Validate address */
2629 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2630 		/* Invalid address */
2631 		return (0);
2632 
2633 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2634 	    sata_device.satadev_addr.cport)));
2635 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2636 		/* invalid address */
2637 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2638 		    sata_device.satadev_addr.cport)));
2639 		return (0);
2640 	}
2641 	if (scsi_pkt == NULL) {
2642 		/*
2643 		 * Abort all packets.
2644 		 * Although we do not have specific packet, we still need
2645 		 * dummy packet structure to pass device address to HBA.
2646 		 * Allocate one, without sleeping. Fail if pkt cannot be
2647 		 * allocated.
2648 		 */
2649 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2650 		if (sata_pkt == NULL) {
2651 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2652 			    sata_device.satadev_addr.cport)));
2653 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2654 			    "could not allocate sata_pkt"));
2655 			return (0);
2656 		}
2657 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2658 		sata_pkt->satapkt_device = sata_device;
2659 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2660 	} else {
2661 		if (scsi_pkt->pkt_ha_private == NULL) {
2662 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2663 			    sata_device.satadev_addr.cport)));
2664 			return (0); /* Bad scsi pkt */
2665 		}
2666 		/* extract pointer to sata pkt */
2667 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2668 		    txlt_sata_pkt;
2669 	}
2670 
2671 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2672 	    sata_device.satadev_addr.cport)));
2673 	/* Send abort request to HBA */
2674 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2675 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2676 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2677 	    SATA_SUCCESS) {
2678 		if (scsi_pkt == NULL)
2679 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2680 		/* Success */
2681 		return (1);
2682 	}
2683 	/* Else, something did not go right */
2684 	if (scsi_pkt == NULL)
2685 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
2686 	/* Failure */
2687 	return (0);
2688 }
2689 
2690 
2691 /*
2692  * Implementation of scsi tran_reset.
2693  * RESET_ALL request is translated into port reset.
2694  * RESET_TARGET requests is translated into a device reset,
2695  * RESET_LUN request is accepted only for LUN 0 and translated into
2696  * device reset.
2697  * The target reset should cause all HBA active and queued packets to
2698  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
2699  * the return. HBA should report reset event for the device.
2700  *
2701  * Returns 1 upon success, 0 upon failure.
2702  */
2703 static int
2704 sata_scsi_reset(struct scsi_address *ap, int level)
2705 {
2706 	sata_hba_inst_t	*sata_hba_inst =
2707 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2708 	sata_device_t	sata_device;
2709 	int		val;
2710 
2711 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2712 	    "sata_scsi_reset: level %d target: 0x%x\n",
2713 	    level, ap->a_target);
2714 
2715 	/* Validate address */
2716 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
2717 	if (val == -1)
2718 		/* Invalid address */
2719 		return (0);
2720 
2721 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2722 	    sata_device.satadev_addr.cport)));
2723 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2724 		/* invalid address */
2725 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2726 		    sata_device.satadev_addr.cport)));
2727 		return (0);
2728 	}
2729 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2730 	    sata_device.satadev_addr.cport)));
2731 	if (level == RESET_ALL) {
2732 		/* port reset */
2733 		if (sata_device.satadev_addr.qual == SATA_ADDR_DCPORT)
2734 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2735 		else
2736 			sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
2737 
2738 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2739 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2740 			return (1);
2741 		else
2742 			return (0);
2743 
2744 	} else if (val == 0 &&
2745 	    (level == RESET_TARGET || level == RESET_LUN)) {
2746 		/* reset device (device attached) */
2747 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2748 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2749 			return (1);
2750 		else
2751 			return (0);
2752 	}
2753 	return (0);
2754 }
2755 
2756 
2757 /*
2758  * Implementation of scsi tran_getcap (get transport/device capabilities).
2759  * Supported capabilities for SATA hard disks:
2760  * auto-rqsense		(always supported)
2761  * tagged-qing		(supported if HBA supports it)
2762  * untagged-qing	(could be supported if disk supports it, but because
2763  *			 caching behavior allowing untagged queuing actually
2764  *			 results in reduced performance.  sd tries to throttle
2765  *			 back to only 3 outstanding commands, which may
2766  *			 work for real SCSI disks, but with read ahead
2767  *			 caching, having more than 1 outstanding command
2768  *			 results in cache thrashing.)
2769  * sector_size
2770  * dma_max
2771  * interconnect-type	(INTERCONNECT_SATA)
2772  *
2773  * Supported capabilities for ATAPI CD/DVD devices:
2774  * auto-rqsense		(always supported)
2775  * sector_size
2776  * dma_max
2777  * max-cdb-length
2778  * interconnect-type	(INTERCONNECT_SATA)
2779  *
2780  * Supported capabilities for ATAPI TAPE devices:
2781  * auto-rqsense		(always supported)
2782  * dma_max
2783  * max-cdb-length
2784  *
2785  * Supported capabilities for SATA ATAPI hard disks:
2786  * auto-rqsense		(always supported)
2787  * interconnect-type	(INTERCONNECT_SATA)
2788  * max-cdb-length
2789  *
2790  * Request for other capabilities is rejected as unsupported.
2791  *
2792  * Returns supported capability value, or -1 if capability is unsuppported or
2793  * the address is invalid - no device.
2794  */
2795 
2796 static int
2797 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
2798 {
2799 
2800 	sata_hba_inst_t 	*sata_hba_inst =
2801 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2802 	sata_device_t		sata_device;
2803 	sata_drive_info_t	*sdinfo;
2804 	ddi_dma_attr_t		adj_dma_attr;
2805 	int 			rval;
2806 
2807 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2808 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
2809 	    ap->a_target, cap);
2810 
2811 	/*
2812 	 * We want to process the capabilities on per port granularity.
2813 	 * So, we are specifically restricting ourselves to whom != 0
2814 	 * to exclude the controller wide handling.
2815 	 */
2816 	if (cap == NULL || whom == 0)
2817 		return (-1);
2818 
2819 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2820 		/* Invalid address */
2821 		return (-1);
2822 	}
2823 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2824 	    sata_device.satadev_addr.cport)));
2825 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
2826 	    NULL) {
2827 		/* invalid address */
2828 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2829 		    sata_device.satadev_addr.cport)));
2830 		return (-1);
2831 	}
2832 
2833 	switch (scsi_hba_lookup_capstr(cap)) {
2834 	case SCSI_CAP_ARQ:
2835 		rval = 1;		/* ARQ supported, turned on */
2836 		break;
2837 
2838 	case SCSI_CAP_SECTOR_SIZE:
2839 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
2840 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
2841 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
2842 			rval = SATA_ATAPI_SECTOR_SIZE;
2843 		else rval = -1;
2844 		break;
2845 
2846 	/*
2847 	 * untagged queuing cause a performance inversion because of
2848 	 * the way sd operates.  Because of this reason we do not
2849 	 * use it when available.
2850 	 */
2851 	case SCSI_CAP_UNTAGGED_QING:
2852 		if (sdinfo->satadrv_features_enabled &
2853 		    SATA_DEV_F_E_UNTAGGED_QING)
2854 			rval = 1;	/* Untagged queuing available */
2855 		else
2856 			rval = -1;	/* Untagged queuing not available */
2857 		break;
2858 
2859 	case SCSI_CAP_TAGGED_QING:
2860 		if ((sdinfo->satadrv_features_enabled &
2861 		    SATA_DEV_F_E_TAGGED_QING) &&
2862 		    (sdinfo->satadrv_max_queue_depth > 1))
2863 			rval = 1;	/* Tagged queuing available */
2864 		else
2865 			rval = -1;	/* Tagged queuing not available */
2866 		break;
2867 
2868 	case SCSI_CAP_DMA_MAX:
2869 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
2870 		    &adj_dma_attr);
2871 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
2872 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
2873 		break;
2874 
2875 	case SCSI_CAP_INTERCONNECT_TYPE:
2876 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
2877 		break;
2878 
2879 	case SCSI_CAP_CDB_LEN:
2880 		if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI)
2881 			rval = sdinfo->satadrv_atapi_cdb_len;
2882 		else
2883 			rval = -1;
2884 		break;
2885 
2886 	default:
2887 		rval = -1;
2888 		break;
2889 	}
2890 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2891 	    sata_device.satadev_addr.cport)));
2892 	return (rval);
2893 }
2894 
2895 /*
2896  * Implementation of scsi tran_setcap
2897  *
2898  * Only SCSI_CAP_UNTAGGED_QING and  SCSI_CAP_TAGGED_QING are changeable.
2899  *
2900  */
2901 static int
2902 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
2903 {
2904 	sata_hba_inst_t	*sata_hba_inst =
2905 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2906 	sata_device_t	sata_device;
2907 	sata_drive_info_t	*sdinfo;
2908 	int		rval;
2909 
2910 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2911 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
2912 
2913 	/*
2914 	 * We want to process the capabilities on per port granularity.
2915 	 * So, we are specifically restricting ourselves to whom != 0
2916 	 * to exclude the controller wide handling.
2917 	 */
2918 	if (cap == NULL || whom == 0) {
2919 		return (-1);
2920 	}
2921 
2922 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2923 		/* Invalid address */
2924 		return (-1);
2925 	}
2926 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2927 	    sata_device.satadev_addr.cport)));
2928 	if ((sdinfo = sata_get_device_info(sata_hba_inst,
2929 	    &sata_device)) == NULL) {
2930 		/* invalid address */
2931 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2932 		    sata_device.satadev_addr.cport)));
2933 		return (-1);
2934 	}
2935 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2936 	    sata_device.satadev_addr.cport)));
2937 
2938 	switch (scsi_hba_lookup_capstr(cap)) {
2939 	case SCSI_CAP_ARQ:
2940 	case SCSI_CAP_SECTOR_SIZE:
2941 	case SCSI_CAP_DMA_MAX:
2942 	case SCSI_CAP_INTERCONNECT_TYPE:
2943 		rval = 0;
2944 		break;
2945 	case SCSI_CAP_UNTAGGED_QING:
2946 		if (SATA_QDEPTH(sata_hba_inst) > 1) {
2947 			rval = 1;
2948 			if (value == 1) {
2949 				sdinfo->satadrv_features_enabled |=
2950 				    SATA_DEV_F_E_UNTAGGED_QING;
2951 			} else if (value == 0) {
2952 				sdinfo->satadrv_features_enabled &=
2953 				    ~SATA_DEV_F_E_UNTAGGED_QING;
2954 			} else {
2955 				rval = -1;
2956 			}
2957 		} else {
2958 			rval = 0;
2959 		}
2960 		break;
2961 	case SCSI_CAP_TAGGED_QING:
2962 		/* This can TCQ or NCQ */
2963 		if (sata_func_enable & SATA_ENABLE_QUEUING &&
2964 		    ((sdinfo->satadrv_features_support & SATA_DEV_F_TCQ &&
2965 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_QCMD) ||
2966 		    (sata_func_enable & SATA_ENABLE_NCQ &&
2967 		    sdinfo->satadrv_features_support & SATA_DEV_F_NCQ &&
2968 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_NCQ)) &&
2969 		    (sdinfo->satadrv_max_queue_depth > 1)) {
2970 			rval = 1;
2971 			if (value == 1) {
2972 				sdinfo->satadrv_features_enabled |=
2973 				    SATA_DEV_F_E_TAGGED_QING;
2974 			} else if (value == 0) {
2975 				sdinfo->satadrv_features_enabled &=
2976 				    ~SATA_DEV_F_E_TAGGED_QING;
2977 			} else {
2978 				rval = -1;
2979 			}
2980 		} else {
2981 			rval = 0;
2982 		}
2983 		break;
2984 	default:
2985 		rval = -1;
2986 		break;
2987 	}
2988 	return (rval);
2989 }
2990 
2991 /*
2992  * Implementations of scsi tran_destroy_pkt.
2993  * Free resources allocated by sata_scsi_init_pkt()
2994  */
2995 static void
2996 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2997 {
2998 	sata_pkt_txlate_t *spx;
2999 
3000 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3001 
3002 	sata_common_free_dma_rsrcs(spx);
3003 
3004 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
3005 	sata_pkt_free(spx);
3006 
3007 	scsi_hba_pkt_free(ap, pkt);
3008 }
3009 
3010 /*
3011  * Implementation of scsi tran_dmafree.
3012  * Free DMA resources allocated by sata_scsi_init_pkt()
3013  */
3014 
3015 static void
3016 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
3017 {
3018 #ifndef __lock_lint
3019 	_NOTE(ARGUNUSED(ap))
3020 #endif
3021 	sata_pkt_txlate_t *spx;
3022 
3023 	ASSERT(pkt != NULL);
3024 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3025 
3026 	sata_common_free_dma_rsrcs(spx);
3027 }
3028 
3029 /*
3030  * Implementation of scsi tran_sync_pkt.
3031  *
3032  * The assumption below is that pkt is unique - there is no need to check ap
3033  *
3034  * Synchronize DMA buffer and, if the intermediate buffer is used, copy data
3035  * into/from the real buffer.
3036  */
3037 static void
3038 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3039 {
3040 #ifndef __lock_lint
3041 	_NOTE(ARGUNUSED(ap))
3042 #endif
3043 	int rval;
3044 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3045 	struct buf *bp;
3046 	int direction;
3047 
3048 	ASSERT(spx != NULL);
3049 	if (spx->txlt_buf_dma_handle != NULL) {
3050 		direction = spx->txlt_sata_pkt->
3051 		    satapkt_cmd.satacmd_flags.sata_data_direction;
3052 		if (spx->txlt_sata_pkt != NULL &&
3053 		    direction != SATA_DIR_NODATA_XFER) {
3054 			if (spx->txlt_tmp_buf != NULL) {
3055 				/* Intermediate DMA buffer used */
3056 				bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3057 
3058 				if (direction & SATA_DIR_WRITE) {
3059 					bcopy(bp->b_un.b_addr,
3060 					    spx->txlt_tmp_buf, bp->b_bcount);
3061 				}
3062 			}
3063 			/* Sync the buffer for device or for CPU */
3064 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle,   0, 0,
3065 			    (direction & SATA_DIR_WRITE) ?
3066 			    DDI_DMA_SYNC_FORDEV :  DDI_DMA_SYNC_FORCPU);
3067 			ASSERT(rval == DDI_SUCCESS);
3068 			if (spx->txlt_tmp_buf != NULL &&
3069 			    !(direction & SATA_DIR_WRITE)) {
3070 				/* Intermediate DMA buffer used for read */
3071 				bcopy(spx->txlt_tmp_buf,
3072 				    bp->b_un.b_addr, bp->b_bcount);
3073 			}
3074 
3075 		}
3076 	}
3077 }
3078 
3079 
3080 
3081 /* *******************  SATA - SCSI Translation functions **************** */
3082 /*
3083  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
3084  * translation.
3085  */
3086 
3087 /*
3088  * Checks if a device exists and can be access and translates common
3089  * scsi_pkt data to sata_pkt data.
3090  *
3091  * Flag argument indicates that a non-read/write ATA command may be sent
3092  * to HBA in arbitrary SYNC mode to execute this packet.
3093  *
3094  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_CMPLT if device exists and
3095  * sata_pkt was set-up.
3096  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_DEV_GONE if device does not
3097  * exist and pkt_comp callback was scheduled.
3098  * Returns other TRAN_XXXXX values when error occured and command should be
3099  * rejected with the returned TRAN_XXXXX value.
3100  *
3101  * This function should be called with port mutex held.
3102  */
3103 static int
3104 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx, int *reason, int flag)
3105 {
3106 	sata_drive_info_t *sdinfo;
3107 	sata_device_t sata_device;
3108 	const struct sata_cmd_flags sata_initial_cmd_flags = {
3109 		SATA_DIR_NODATA_XFER,
3110 		/* all other values to 0/FALSE */
3111 	};
3112 	/*
3113 	 * Pkt_reason has to be set if the pkt_comp callback is invoked,
3114 	 * and that implies TRAN_ACCEPT return value. Any other returned value
3115 	 * indicates that the scsi packet was not accepted (the reason will not
3116 	 * be checked by the scsi target driver).
3117 	 * To make debugging easier, we set pkt_reason to know value here.
3118 	 * It may be changed later when different completion reason is
3119 	 * determined.
3120 	 */
3121 	spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
3122 	*reason = CMD_TRAN_ERR;
3123 
3124 	/* Validate address */
3125 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
3126 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
3127 
3128 	case -1:
3129 		/* Invalid address or invalid device type */
3130 		return (TRAN_BADPKT);
3131 	case 2:
3132 		/*
3133 		 * Valid address but device type is unknown - Chack if it is
3134 		 * in the reset state and therefore in an indeterminate state.
3135 		 */
3136 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3137 		    &spx->txlt_sata_pkt->satapkt_device);
3138 		if (sdinfo != NULL && (sdinfo->satadrv_event_flags &
3139 		    (SATA_EVNT_DEVICE_RESET |
3140 		    SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3141 			if (!ddi_in_panic()) {
3142 				spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3143 				*reason = CMD_INCOMPLETE;
3144 				SATADBG1(SATA_DBG_SCSI_IF,
3145 				    spx->txlt_sata_hba_inst,
3146 				    "sata_scsi_start: rejecting command "
3147 				    "because of device reset state\n", NULL);
3148 				return (TRAN_BUSY);
3149 			}
3150 		}
3151 		/* FALLTHROUGH */
3152 	case 1:
3153 		/* valid address but no valid device - it has disappeared */
3154 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
3155 		*reason = CMD_DEV_GONE;
3156 		/*
3157 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
3158 		 * only in callback function (for normal requests) and
3159 		 * in the dump code path.
3160 		 * So, if the callback is available, we need to do
3161 		 * the callback rather than returning TRAN_FATAL_ERROR here.
3162 		 */
3163 		if (spx->txlt_scsi_pkt->pkt_comp != NULL) {
3164 			/* scsi callback required */
3165 			if (servicing_interrupt()) {
3166 				if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3167 				    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3168 				    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) ==
3169 				    NULL) {
3170 					return (TRAN_BUSY);
3171 				}
3172 			} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3173 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3174 			    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3175 				/* Scheduling the callback failed */
3176 				return (TRAN_BUSY);
3177 			}
3178 
3179 			return (TRAN_ACCEPT);
3180 		}
3181 		return (TRAN_FATAL_ERROR);
3182 	default:
3183 		/* all OK; pkt reason will be overwritten later */
3184 		break;
3185 	}
3186 	/*
3187 	 * If pkt is to be executed in polling mode and a command will not be
3188 	 * emulated in SATA module (requires sending a non-read/write ATA
3189 	 * command to HBA driver in arbitrary SYNC mode) and we are in the
3190 	 * interrupt context and not in the panic dump, then reject the packet
3191 	 * to avoid a possible interrupt stack overrun or hang caused by
3192 	 * a potentially blocked interrupt.
3193 	 */
3194 	if (((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0 || flag != 0) &&
3195 	    servicing_interrupt() && !ddi_in_panic()) {
3196 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
3197 		    "sata_scsi_start: rejecting synchronous command because "
3198 		    "of interrupt context\n", NULL);
3199 		return (TRAN_BUSY);
3200 	}
3201 
3202 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3203 	    &spx->txlt_sata_pkt->satapkt_device);
3204 
3205 	/*
3206 	 * If device is in reset condition, reject the packet with
3207 	 * TRAN_BUSY, unless:
3208 	 * 1. system is panicking (dumping)
3209 	 * In such case only one thread is running and there is no way to
3210 	 * process reset.
3211 	 * 2. cfgadm operation is is progress (internal APCTL lock is set)
3212 	 * Some cfgadm operations involve drive commands, so reset condition
3213 	 * needs to be ignored for IOCTL operations.
3214 	 */
3215 	if ((sdinfo->satadrv_event_flags &
3216 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3217 
3218 		if (!ddi_in_panic() &&
3219 		    ((SATA_CPORT_EVENT_FLAGS(spx->txlt_sata_hba_inst,
3220 		    sata_device.satadev_addr.cport) &
3221 		    SATA_APCTL_LOCK_PORT_BUSY) == 0)) {
3222 			spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3223 			*reason = CMD_INCOMPLETE;
3224 			SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3225 			    "sata_scsi_start: rejecting command because "
3226 			    "of device reset state\n", NULL);
3227 			return (TRAN_BUSY);
3228 		}
3229 	}
3230 
3231 	/*
3232 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
3233 	 * sata_scsi_pkt_init() because pkt init had to work also with
3234 	 * non-existing devices.
3235 	 * Now we know that the packet was set-up for a real device, so its
3236 	 * type is known.
3237 	 */
3238 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
3239 
3240 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
3241 	if ((SATA_CPORT_INFO(spx->txlt_sata_hba_inst,
3242 	    sata_device.satadev_addr.cport)->cport_event_flags &
3243 	    SATA_APCTL_LOCK_PORT_BUSY) != 0) {
3244 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3245 		    sata_ignore_dev_reset = B_TRUE;
3246 	}
3247 	/*
3248 	 * At this point the generic translation routine determined that the
3249 	 * scsi packet should be accepted. Packet completion reason may be
3250 	 * changed later when a different completion reason is determined.
3251 	 */
3252 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3253 	*reason = CMD_CMPLT;
3254 
3255 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3256 		/* Synchronous execution */
3257 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
3258 		    SATA_OPMODE_POLLING;
3259 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3260 		    sata_ignore_dev_reset = ddi_in_panic();
3261 	} else {
3262 		/* Asynchronous execution */
3263 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
3264 		    SATA_OPMODE_INTERRUPTS;
3265 	}
3266 	/* Convert queuing information */
3267 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
3268 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
3269 		    B_TRUE;
3270 	else if (spx->txlt_scsi_pkt->pkt_flags &
3271 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
3272 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
3273 		    B_TRUE;
3274 
3275 	/* Always limit pkt time */
3276 	if (spx->txlt_scsi_pkt->pkt_time == 0)
3277 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
3278 	else
3279 		/* Pass on scsi_pkt time */
3280 		spx->txlt_sata_pkt->satapkt_time =
3281 		    spx->txlt_scsi_pkt->pkt_time;
3282 
3283 	return (TRAN_ACCEPT);
3284 }
3285 
3286 
3287 /*
3288  * Translate ATA Identify Device data to SCSI Inquiry data.
3289  * This function may be called only for ATA devices.
3290  * This function should not be called for ATAPI devices - they
3291  * respond directly to SCSI Inquiry command.
3292  *
3293  * SATA Identify Device data has to be valid in sata_drive_info.
3294  * Buffer has to accomodate the inquiry length (36 bytes).
3295  *
3296  * This function should be called with a port mutex held.
3297  */
3298 static	void
3299 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
3300     sata_drive_info_t *sdinfo, uint8_t *buf)
3301 {
3302 
3303 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
3304 	struct sata_id *sid = &sdinfo->satadrv_id;
3305 
3306 	/* Start with a nice clean slate */
3307 	bzero((void *)inq, sizeof (struct scsi_inquiry));
3308 
3309 	/*
3310 	 * Rely on the dev_type for setting paripheral qualifier.
3311 	 * Assume that  DTYPE_RODIRECT applies to CD/DVD R/W devices.
3312 	 * It could be that DTYPE_OPTICAL could also qualify in the future.
3313 	 * ATAPI Inquiry may provide more data to the target driver.
3314 	 */
3315 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3316 	    DTYPE_DIRECT : DTYPE_RODIRECT; /* DTYPE_UNKNOWN; */
3317 
3318 	/* CFA type device is not a removable media device */
3319 	inq->inq_rmb = ((sid->ai_config != SATA_CFA_TYPE) &&
3320 	    (sid->ai_config & SATA_REM_MEDIA)) ? 1 : 0;
3321 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
3322 	inq->inq_iso = 0;	/* ISO version */
3323 	inq->inq_ecma = 0;	/* ECMA version */
3324 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
3325 	inq->inq_aenc = 0;	/* Async event notification cap. */
3326 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg - NO */
3327 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
3328 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
3329 	inq->inq_len = 31;	/* Additional length */
3330 	inq->inq_dualp = 0;	/* dual port device - NO */
3331 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
3332 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
3333 	inq->inq_linked = 0;	/* Supports linked commands - NO */
3334 				/*
3335 				 * Queuing support - controller has to
3336 				 * support some sort of command queuing.
3337 				 */
3338 	if (SATA_QDEPTH(sata_hba_inst) > 1)
3339 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
3340 	else
3341 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
3342 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
3343 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
3344 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
3345 
3346 #ifdef	_LITTLE_ENDIAN
3347 	/* Swap text fields to match SCSI format */
3348 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3349 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3350 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3351 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
3352 	else
3353 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
3354 #else	/* _LITTLE_ENDIAN */
3355 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3356 	bcopy(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3357 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3358 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
3359 	else
3360 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
3361 #endif	/* _LITTLE_ENDIAN */
3362 }
3363 
3364 
3365 /*
3366  * Scsi response set up for invalid command (command not supported)
3367  *
3368  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3369  */
3370 static int
3371 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
3372 {
3373 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3374 	struct scsi_extended_sense *sense;
3375 
3376 	scsipkt->pkt_reason = CMD_CMPLT;
3377 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3378 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3379 
3380 	*scsipkt->pkt_scbp = STATUS_CHECK;
3381 
3382 	sense = sata_arq_sense(spx);
3383 	sense->es_key = KEY_ILLEGAL_REQUEST;
3384 	sense->es_add_code = SD_SCSI_ASC_INVALID_COMMAND_CODE;
3385 
3386 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3387 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3388 
3389 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3390 	    scsipkt->pkt_comp != NULL) {
3391 		/* scsi callback required */
3392 		if (servicing_interrupt()) {
3393 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3394 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3395 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3396 				return (TRAN_BUSY);
3397 			}
3398 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3399 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3400 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3401 			/* Scheduling the callback failed */
3402 			return (TRAN_BUSY);
3403 		}
3404 	}
3405 	return (TRAN_ACCEPT);
3406 }
3407 
3408 /*
3409  * Scsi response set up for check condition with special sense key
3410  * and additional sense code.
3411  *
3412  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3413  */
3414 static int
3415 sata_txlt_check_condition(sata_pkt_txlate_t *spx, uchar_t key, uchar_t code)
3416 {
3417 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3418 	int cport = SATA_TXLT_CPORT(spx);
3419 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3420 	struct scsi_extended_sense *sense;
3421 
3422 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3423 	scsipkt->pkt_reason = CMD_CMPLT;
3424 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3425 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3426 
3427 	*scsipkt->pkt_scbp = STATUS_CHECK;
3428 
3429 	sense = sata_arq_sense(spx);
3430 	sense->es_key = key;
3431 	sense->es_add_code = code;
3432 
3433 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3434 
3435 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3436 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3437 
3438 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3439 	    scsipkt->pkt_comp != NULL) {
3440 		/* scsi callback required */
3441 		if (servicing_interrupt()) {
3442 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3443 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3444 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3445 				return (TRAN_BUSY);
3446 			}
3447 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3448 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3449 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3450 			/* Scheduling the callback failed */
3451 			return (TRAN_BUSY);
3452 		}
3453 	}
3454 	return (TRAN_ACCEPT);
3455 }
3456 
3457 /*
3458  * Scsi response setup for
3459  * emulated non-data command that requires no action/return data
3460  *
3461  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3462  */
3463 static	int
3464 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3465 {
3466 	int rval;
3467 	int reason;
3468 
3469 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3470 
3471 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3472 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3473 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3474 		return (rval);
3475 	}
3476 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3477 
3478 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3479 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3480 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3481 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3482 
3483 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3484 	    "Scsi_pkt completion reason %x\n",
3485 	    spx->txlt_scsi_pkt->pkt_reason);
3486 
3487 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3488 	    spx->txlt_scsi_pkt->pkt_comp != NULL) {
3489 		/* scsi callback required */
3490 		if (servicing_interrupt()) {
3491 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3492 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3493 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3494 				return (TRAN_BUSY);
3495 			}
3496 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3497 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3498 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3499 			/* Scheduling the callback failed */
3500 			return (TRAN_BUSY);
3501 		}
3502 	}
3503 	return (TRAN_ACCEPT);
3504 }
3505 
3506 
3507 /*
3508  * SATA translate command: Inquiry / Identify Device
3509  * Use cached Identify Device data for now, rather than issuing actual
3510  * Device Identify cmd request. If device is detached and re-attached,
3511  * asynchronous event processing should fetch and refresh Identify Device
3512  * data.
3513  * Two VPD pages are supported now:
3514  * Vital Product Data page
3515  * Unit Serial Number page
3516  *
3517  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3518  */
3519 
3520 #define	EVPD			1	/* Extended Vital Product Data flag */
3521 #define	CMDDT			2	/* Command Support Data - Obsolete */
3522 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VPD Pages Page Code */
3523 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3524 #define	INQUIRY_BDC_PAGE	0xB1	/* Block Device Characteristics Page */
3525 					/* Code */
3526 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3527 
3528 static int
3529 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3530 {
3531 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3532 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3533 	sata_drive_info_t *sdinfo;
3534 	struct scsi_extended_sense *sense;
3535 	int count;
3536 	uint8_t *p;
3537 	int i, j;
3538 	uint8_t page_buf[0xff]; /* Max length */
3539 	int rval, reason;
3540 	ushort_t rate;
3541 
3542 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3543 
3544 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3545 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3546 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3547 		return (rval);
3548 	}
3549 
3550 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3551 	    &spx->txlt_sata_pkt->satapkt_device);
3552 
3553 	ASSERT(sdinfo != NULL);
3554 
3555 	scsipkt->pkt_reason = CMD_CMPLT;
3556 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3557 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3558 
3559 	/* Reject not supported request */
3560 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3561 		*scsipkt->pkt_scbp = STATUS_CHECK;
3562 		sense = sata_arq_sense(spx);
3563 		sense->es_key = KEY_ILLEGAL_REQUEST;
3564 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3565 		goto done;
3566 	}
3567 
3568 	/* Valid Inquiry request */
3569 	*scsipkt->pkt_scbp = STATUS_GOOD;
3570 
3571 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3572 
3573 		/*
3574 		 * Because it is fully emulated command storing data
3575 		 * programatically in the specified buffer, release
3576 		 * preallocated DMA resources before storing data in the buffer,
3577 		 * so no unwanted DMA sync would take place.
3578 		 */
3579 		sata_scsi_dmafree(NULL, scsipkt);
3580 
3581 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3582 			/* Standard Inquiry Data request */
3583 			struct scsi_inquiry inq;
3584 			unsigned int bufsize;
3585 
3586 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3587 			    sdinfo, (uint8_t *)&inq);
3588 			/* Copy no more than requested */
3589 			count = MIN(bp->b_bcount,
3590 			    sizeof (struct scsi_inquiry));
3591 			bufsize = scsipkt->pkt_cdbp[4];
3592 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3593 			count = MIN(count, bufsize);
3594 			bcopy(&inq, bp->b_un.b_addr, count);
3595 
3596 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3597 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3598 			    bufsize - count : 0;
3599 		} else {
3600 			/*
3601 			 * peripheral_qualifier = 0;
3602 			 *
3603 			 * We are dealing only with HD and will be
3604 			 * dealing with CD/DVD devices soon
3605 			 */
3606 			uint8_t peripheral_device_type =
3607 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3608 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3609 
3610 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3611 			case INQUIRY_SUP_VPD_PAGE:
3612 				/*
3613 				 * Request for suported Vital Product Data
3614 				 * pages - assuming only 2 page codes
3615 				 * supported.
3616 				 */
3617 				page_buf[0] = peripheral_device_type;
3618 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3619 				page_buf[2] = 0;
3620 				page_buf[3] = 3; /* page length */
3621 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3622 				page_buf[5] = INQUIRY_USN_PAGE;
3623 				page_buf[6] = INQUIRY_BDC_PAGE;
3624 				/* Copy no more than requested */
3625 				count = MIN(bp->b_bcount, 7);
3626 				bcopy(page_buf, bp->b_un.b_addr, count);
3627 				break;
3628 
3629 			case INQUIRY_USN_PAGE:
3630 				/*
3631 				 * Request for Unit Serial Number page.
3632 				 * Set-up the page.
3633 				 */
3634 				page_buf[0] = peripheral_device_type;
3635 				page_buf[1] = INQUIRY_USN_PAGE;
3636 				page_buf[2] = 0;
3637 				/* remaining page length */
3638 				page_buf[3] = SATA_ID_SERIAL_LEN;
3639 
3640 				/*
3641 				 * Copy serial number from Identify Device data
3642 				 * words into the inquiry page and swap bytes
3643 				 * when necessary.
3644 				 */
3645 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3646 #ifdef	_LITTLE_ENDIAN
3647 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3648 #else
3649 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3650 #endif
3651 				/*
3652 				 * Least significant character of the serial
3653 				 * number shall appear as the last byte,
3654 				 * according to SBC-3 spec.
3655 				 * Count trailing spaces to determine the
3656 				 * necessary shift length.
3657 				 */
3658 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3659 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3660 					if (*(p - j) != '\0' &&
3661 					    *(p - j) != '\040')
3662 						break;
3663 				}
3664 
3665 				/*
3666 				 * Shift SN string right, so that the last
3667 				 * non-blank character would appear in last
3668 				 * byte of SN field in the page.
3669 				 * 'j' is the shift length.
3670 				 */
3671 				for (i = 0;
3672 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3673 				    i++, p--)
3674 					*p = *(p - j);
3675 
3676 				/*
3677 				 * Add leading spaces - same number as the
3678 				 * shift size
3679 				 */
3680 				for (; j > 0; j--)
3681 					page_buf[4 + j - 1] = '\040';
3682 
3683 				count = MIN(bp->b_bcount,
3684 				    SATA_ID_SERIAL_LEN + 4);
3685 				bcopy(page_buf, bp->b_un.b_addr, count);
3686 				break;
3687 
3688 			case INQUIRY_BDC_PAGE:
3689 				/*
3690 				 * Request for Block Device Characteristics
3691 				 * page.  Set-up the page.
3692 				 */
3693 				page_buf[0] = peripheral_device_type;
3694 				page_buf[1] = INQUIRY_BDC_PAGE;
3695 				page_buf[2] = 0;
3696 				/* remaining page length */
3697 				page_buf[3] = SATA_ID_BDC_LEN;
3698 
3699 				rate = sdinfo->satadrv_id.ai_medrotrate;
3700 				page_buf[4] = (rate >> 8) & 0xff;
3701 				page_buf[5] = rate & 0xff;
3702 				page_buf[6] = 0;
3703 				page_buf[7] = sdinfo->satadrv_id.
3704 				    ai_nomformfactor & 0xf;
3705 
3706 				count = MIN(bp->b_bcount,
3707 				    SATA_ID_BDC_LEN + 4);
3708 				bcopy(page_buf, bp->b_un.b_addr, count);
3709 				break;
3710 
3711 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3712 				/*
3713 				 * We may want to implement this page, when
3714 				 * identifiers are common for SATA devices
3715 				 * But not now.
3716 				 */
3717 				/*FALLTHROUGH*/
3718 
3719 			default:
3720 				/* Request for unsupported VPD page */
3721 				*scsipkt->pkt_scbp = STATUS_CHECK;
3722 				sense = sata_arq_sense(spx);
3723 				sense->es_key = KEY_ILLEGAL_REQUEST;
3724 				sense->es_add_code =
3725 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3726 				goto done;
3727 			}
3728 		}
3729 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3730 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3731 		    scsipkt->pkt_cdbp[4] - count : 0;
3732 	}
3733 done:
3734 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3735 
3736 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3737 	    "Scsi_pkt completion reason %x\n",
3738 	    scsipkt->pkt_reason);
3739 
3740 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3741 	    scsipkt->pkt_comp != NULL) {
3742 		/* scsi callback required */
3743 		if (servicing_interrupt()) {
3744 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3745 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3746 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3747 				return (TRAN_BUSY);
3748 			}
3749 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3750 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3751 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3752 			/* Scheduling the callback failed */
3753 			return (TRAN_BUSY);
3754 		}
3755 	}
3756 	return (TRAN_ACCEPT);
3757 }
3758 
3759 /*
3760  * SATA translate command: Request Sense.
3761  *
3762  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3763  * At the moment this is an emulated command (ATA version for SATA hard disks).
3764  * May be translated into Check Power Mode command in the future.
3765  *
3766  * Note: There is a mismatch between already implemented Informational
3767  * Exception Mode Select page 0x1C and this function.
3768  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3769  * NO SENSE and set additional sense code to the exception code - this is not
3770  * implemented here.
3771  */
3772 static int
3773 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3774 {
3775 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3776 	struct scsi_extended_sense sense;
3777 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3778 	sata_drive_info_t *sdinfo;
3779 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3780 	int rval, reason, power_state = 0;
3781 
3782 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3783 
3784 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3785 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3786 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3787 		return (rval);
3788 	}
3789 
3790 	scsipkt->pkt_reason = CMD_CMPLT;
3791 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3792 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3793 	*scsipkt->pkt_scbp = STATUS_GOOD;
3794 
3795 	/*
3796 	 * when CONTROL field's NACA bit == 1
3797 	 * return ILLEGAL_REQUEST
3798 	 */
3799 	if (scsipkt->pkt_cdbp[5] & CTL_BYTE_NACA_MASK) {
3800 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3801 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3802 		    SD_SCSI_ASC_CMD_SEQUENCE_ERR));
3803 	}
3804 
3805 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3806 	    &spx->txlt_sata_pkt->satapkt_device);
3807 	ASSERT(sdinfo != NULL);
3808 
3809 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3810 
3811 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3812 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3813 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3814 	if (sata_hba_start(spx, &rval) != 0) {
3815 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3816 		return (rval);
3817 	} else {
3818 		if (scmd->satacmd_error_reg != 0) {
3819 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3820 			return (sata_txlt_check_condition(spx, KEY_NO_SENSE,
3821 			    SD_SCSI_ASC_NO_ADD_SENSE));
3822 		}
3823 	}
3824 
3825 	switch (scmd->satacmd_sec_count_lsb) {
3826 	case SATA_PWRMODE_STANDBY: /* device in standby mode */
3827 		if (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)
3828 			power_state = SATA_POWER_STOPPED;
3829 		else {
3830 			power_state = SATA_POWER_STANDBY;
3831 			sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
3832 		}
3833 		break;
3834 	case SATA_PWRMODE_IDLE: /* device in idle mode */
3835 		power_state = SATA_POWER_IDLE;
3836 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
3837 		break;
3838 	case SATA_PWRMODE_ACTIVE: /* device in active or idle mode */
3839 	default:		  /* 0x40, 0x41 active mode */
3840 		if (sdinfo->satadrv_power_level == SATA_POWER_IDLE)
3841 			power_state = SATA_POWER_IDLE;
3842 		else {
3843 			power_state = SATA_POWER_ACTIVE;
3844 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3845 		}
3846 		break;
3847 	}
3848 
3849 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3850 
3851 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3852 		/*
3853 		 * Because it is fully emulated command storing data
3854 		 * programatically in the specified buffer, release
3855 		 * preallocated DMA resources before storing data in the buffer,
3856 		 * so no unwanted DMA sync would take place.
3857 		 */
3858 		int count = MIN(bp->b_bcount,
3859 		    sizeof (struct scsi_extended_sense));
3860 		sata_scsi_dmafree(NULL, scsipkt);
3861 		bzero(&sense, sizeof (struct scsi_extended_sense));
3862 		sense.es_valid = 0;	/* Valid LBA */
3863 		sense.es_class = 7;	/* Response code 0x70 - current err */
3864 		sense.es_key = KEY_NO_SENSE;
3865 		sense.es_add_len = 6;	/* Additional length */
3866 		/* Copy no more than requested */
3867 		bcopy(&sense, bp->b_un.b_addr, count);
3868 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3869 		scsipkt->pkt_resid = 0;
3870 		switch (power_state) {
3871 		case SATA_POWER_IDLE:
3872 		case SATA_POWER_STANDBY:
3873 			sense.es_add_code =
3874 			    SD_SCSI_ASC_LOW_POWER_CONDITION_ON;
3875 			break;
3876 		case SATA_POWER_STOPPED:
3877 			sense.es_add_code = SD_SCSI_ASC_NO_ADD_SENSE;
3878 			break;
3879 		case SATA_POWER_ACTIVE:
3880 		default:
3881 			break;
3882 		}
3883 	}
3884 
3885 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3886 	    "Scsi_pkt completion reason %x\n",
3887 	    scsipkt->pkt_reason);
3888 
3889 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3890 	    scsipkt->pkt_comp != NULL) {
3891 		/* scsi callback required */
3892 		if (servicing_interrupt()) {
3893 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3894 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3895 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3896 				return (TRAN_BUSY);
3897 			}
3898 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3899 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3900 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3901 			/* Scheduling the callback failed */
3902 			return (TRAN_BUSY);
3903 		}
3904 	}
3905 	return (TRAN_ACCEPT);
3906 }
3907 
3908 /*
3909  * SATA translate command: Test Unit Ready
3910  * (ATA version for SATA hard disks).
3911  * It is translated into the Check Power Mode command.
3912  *
3913  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3914  */
3915 static int
3916 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3917 {
3918 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3919 	struct scsi_extended_sense *sense;
3920 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3921 	sata_drive_info_t *sdinfo;
3922 	int power_state;
3923 	int rval, reason;
3924 
3925 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3926 
3927 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3928 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3929 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3930 		return (rval);
3931 	}
3932 
3933 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3934 	    &spx->txlt_sata_pkt->satapkt_device);
3935 	ASSERT(sdinfo != NULL);
3936 
3937 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3938 
3939 	/* send CHECK POWER MODE command */
3940 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3941 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3942 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3943 	if (sata_hba_start(spx, &rval) != 0) {
3944 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3945 		return (rval);
3946 	} else {
3947 		if (scmd->satacmd_error_reg != 0) {
3948 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3949 			return (sata_txlt_check_condition(spx, KEY_NOT_READY,
3950 			    SD_SCSI_ASC_LU_NOT_RESPONSE));
3951 		}
3952 	}
3953 
3954 	power_state = scmd->satacmd_sec_count_lsb;
3955 
3956 	/*
3957 	 * return NOT READY when device in STOPPED mode
3958 	 */
3959 	if (power_state == SATA_PWRMODE_STANDBY &&
3960 	    sdinfo->satadrv_power_level == SATA_POWER_STOPPED) {
3961 		*scsipkt->pkt_scbp = STATUS_CHECK;
3962 		sense = sata_arq_sense(spx);
3963 		sense->es_key = KEY_NOT_READY;
3964 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
3965 	} else {
3966 		/*
3967 		 * For other power mode, return GOOD status
3968 		 */
3969 		*scsipkt->pkt_scbp = STATUS_GOOD;
3970 	}
3971 
3972 	scsipkt->pkt_reason = CMD_CMPLT;
3973 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3974 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3975 
3976 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3977 
3978 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3979 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3980 
3981 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3982 	    scsipkt->pkt_comp != NULL) {
3983 		/* scsi callback required */
3984 		if (servicing_interrupt()) {
3985 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3986 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3987 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
3988 				return (TRAN_BUSY);
3989 			}
3990 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3991 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3992 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
3993 			/* Scheduling the callback failed */
3994 			return (TRAN_BUSY);
3995 		}
3996 	}
3997 
3998 	return (TRAN_ACCEPT);
3999 }
4000 
4001 /*
4002  * SATA translate command: Start Stop Unit
4003  * Translation depends on a command:
4004  *
4005  * Power condition bits will be supported
4006  * and the power level should be maintained by SATL,
4007  * When SATL received a command, it will check the
4008  * power level firstly, and return the status according
4009  * to SAT2 v2.6 and SAT-2 Standby Modifications
4010  *
4011  * SPC-4/SBC-3      SATL    ATA power condition  SATL      SPC/SBC
4012  * -----------------------------------------------------------------------
4013  * SSU_PC1 Active   <==>     ATA  Active         <==>     SSU:start_bit =1
4014  * SSU_PC2 Idle     <==>     ATA  Idle           <==>     N/A
4015  * SSU_PC3 Standby  <==>     ATA  Standby        <==>     N/A
4016  * SSU_PC4 Stopped  <==>     ATA  Standby        <==>     SSU:start_bit = 0
4017  *
4018  *	Unload Media / NOT SUPPORTED YET
4019  *	Load Media / NOT SUPPROTED YET
4020  *	Immediate bit / NOT SUPPORTED YET (deferred error)
4021  *
4022  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
4023  * appropriate values in scsi_pkt fields.
4024  */
4025 static int
4026 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
4027 {
4028 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4029 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4030 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
4031 	int cport = SATA_TXLT_CPORT(spx);
4032 	int rval, reason;
4033 	sata_drive_info_t *sdinfo;
4034 	sata_id_t *sata_id;
4035 
4036 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4037 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
4038 
4039 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
4040 
4041 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4042 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4043 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4044 		return (rval);
4045 	}
4046 
4047 	if (scsipkt->pkt_cdbp[1] & START_STOP_IMMED_MASK) {
4048 		/* IMMED bit - not supported */
4049 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4050 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4051 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4052 	}
4053 
4054 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
4055 	spx->txlt_sata_pkt->satapkt_comp = NULL;
4056 
4057 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4058 	    &spx->txlt_sata_pkt->satapkt_device);
4059 	ASSERT(sdinfo != NULL);
4060 	sata_id = &sdinfo->satadrv_id;
4061 
4062 	switch ((scsipkt->pkt_cdbp[4] & START_STOP_POWER_COND_MASK) >> 4) {
4063 	case 0:
4064 		if (scsipkt->pkt_cdbp[4] & START_STOP_LOEJ_MASK) {
4065 			/* Load/Unload Media - invalid request */
4066 			goto err_out;
4067 		}
4068 		if (scsipkt->pkt_cdbp[4] & START_STOP_START_MASK) {
4069 			/* Start Unit */
4070 			sata_build_read_verify_cmd(scmd, 1, 5);
4071 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4072 			/* Transfer command to HBA */
4073 			if (sata_hba_start(spx, &rval) != 0) {
4074 				/* Pkt not accepted for execution */
4075 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4076 				return (rval);
4077 			} else {
4078 				if (scmd->satacmd_error_reg != 0) {
4079 					goto err_out;
4080 				}
4081 			}
4082 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4083 		} else {
4084 			/* Stop Unit */
4085 			sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4086 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4087 			if (sata_hba_start(spx, &rval) != 0) {
4088 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4089 				return (rval);
4090 			} else {
4091 				if (scmd->satacmd_error_reg != 0) {
4092 					goto err_out;
4093 				}
4094 			}
4095 			/* ata standby immediate command */
4096 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4097 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4098 			if (sata_hba_start(spx, &rval) != 0) {
4099 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4100 				return (rval);
4101 			} else {
4102 				if (scmd->satacmd_error_reg != 0) {
4103 					goto err_out;
4104 				}
4105 			}
4106 			sdinfo->satadrv_power_level = SATA_POWER_STOPPED;
4107 		}
4108 		break;
4109 	case 0x1:
4110 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4111 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4112 		if (sata_hba_start(spx, &rval) != 0) {
4113 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4114 			return (rval);
4115 		} else {
4116 			if (scmd->satacmd_error_reg != 0) {
4117 				goto err_out;
4118 			}
4119 		}
4120 		sata_build_read_verify_cmd(scmd, 1, 5);
4121 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4122 		/* Transfer command to HBA */
4123 		if (sata_hba_start(spx, &rval) != 0) {
4124 			/* Pkt not accepted for execution */
4125 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4126 			return (rval);
4127 		} else {
4128 			if (scmd->satacmd_error_reg != 0) {
4129 				goto err_out;
4130 			}
4131 		}
4132 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4133 		break;
4134 	case 0x2:
4135 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4136 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4137 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4138 			if (sata_hba_start(spx, &rval) != 0) {
4139 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4140 				return (rval);
4141 			} else {
4142 				if (scmd->satacmd_error_reg != 0) {
4143 					goto err_out;
4144 				}
4145 			}
4146 		}
4147 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4148 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4149 		if (sata_hba_start(spx, &rval) != 0) {
4150 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4151 			return (rval);
4152 		} else {
4153 			if (scmd->satacmd_error_reg != 0) {
4154 				goto err_out;
4155 			}
4156 		}
4157 		if ((scsipkt->pkt_cdbp[3] & START_STOP_MODIFIER_MASK)) {
4158 			/*
4159 			 *  POWER CONDITION MODIFIER bit set
4160 			 *  to 0x1 or larger it will be handled
4161 			 *  on the same way as bit = 0x1
4162 			 */
4163 			if (!(sata_id->ai_cmdset84 &
4164 			    SATA_IDLE_UNLOAD_SUPPORTED)) {
4165 				sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4166 				break;
4167 			}
4168 			sata_build_generic_cmd(scmd, SATAC_IDLE_IM);
4169 			scmd->satacmd_features_reg = 0x44;
4170 			scmd->satacmd_lba_low_lsb = 0x4c;
4171 			scmd->satacmd_lba_mid_lsb = 0x4e;
4172 			scmd->satacmd_lba_high_lsb = 0x55;
4173 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4174 			if (sata_hba_start(spx, &rval) != 0) {
4175 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4176 				return (rval);
4177 			} else {
4178 				if (scmd->satacmd_error_reg != 0) {
4179 					goto err_out;
4180 				}
4181 			}
4182 		}
4183 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4184 		break;
4185 	case 0x3:
4186 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4187 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4188 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4189 			if (sata_hba_start(spx, &rval) != 0) {
4190 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4191 				return (rval);
4192 			} else {
4193 				if (scmd->satacmd_error_reg != 0) {
4194 					goto err_out;
4195 				}
4196 			}
4197 		}
4198 		sata_build_generic_cmd(scmd, SATAC_STANDBY);
4199 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4200 		if (sata_hba_start(spx, &rval) != 0) {
4201 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4202 			return (rval);
4203 		} else {
4204 			if (scmd->satacmd_error_reg != 0) {
4205 				goto err_out;
4206 			}
4207 		}
4208 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4209 		break;
4210 	case 0x7:
4211 		sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4212 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4213 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4214 		if (sata_hba_start(spx, &rval) != 0) {
4215 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4216 			return (rval);
4217 		} else {
4218 			if (scmd->satacmd_error_reg != 0) {
4219 				goto err_out;
4220 			}
4221 		}
4222 		switch (scmd->satacmd_sec_count_lsb) {
4223 		case SATA_PWRMODE_STANDBY:
4224 			sata_build_generic_cmd(scmd, SATAC_STANDBY);
4225 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4226 			    sdinfo->satadrv_standby_timer);
4227 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4228 			if (sata_hba_start(spx, &rval) != 0) {
4229 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4230 				return (rval);
4231 			} else {
4232 				if (scmd->satacmd_error_reg != 0) {
4233 					goto err_out;
4234 				}
4235 			}
4236 			break;
4237 		case SATA_PWRMODE_IDLE:
4238 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4239 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4240 			    sdinfo->satadrv_standby_timer);
4241 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4242 			if (sata_hba_start(spx, &rval) != 0) {
4243 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4244 				return (rval);
4245 			} else {
4246 				if (scmd->satacmd_error_reg != 0) {
4247 					goto err_out;
4248 				}
4249 			}
4250 			break;
4251 		case SATA_PWRMODE_ACTIVE_SPINDOWN:
4252 		case SATA_PWRMODE_ACTIVE_SPINUP:
4253 		case SATA_PWRMODE_ACTIVE:
4254 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4255 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4256 			    sdinfo->satadrv_standby_timer);
4257 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4258 			if (sata_hba_start(spx, &rval) != 0) {
4259 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4260 				return (rval);
4261 			} else {
4262 				if (scmd->satacmd_error_reg != 0) {
4263 					goto err_out;
4264 				}
4265 			}
4266 			sata_build_read_verify_cmd(scmd, 1, 5);
4267 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4268 			if (sata_hba_start(spx, &rval) != 0) {
4269 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4270 				return (rval);
4271 			} else {
4272 				if (scmd->satacmd_error_reg != 0) {
4273 					goto err_out;
4274 				}
4275 			}
4276 			break;
4277 		default:
4278 			goto err_out;
4279 		}
4280 		break;
4281 	case 0xb:
4282 		if ((sata_get_standby_timer(sdinfo->satadrv_standby_timer) ==
4283 		    0) || (!(sata_id->ai_cap & SATA_STANDBYTIMER))) {
4284 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4285 			return (sata_txlt_check_condition(spx,
4286 			    KEY_ILLEGAL_REQUEST,
4287 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4288 		}
4289 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4290 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4291 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4292 			if (sata_hba_start(spx, &rval) != 0) {
4293 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4294 				return (rval);
4295 			} else {
4296 				if (scmd->satacmd_error_reg != 0) {
4297 					goto err_out;
4298 				}
4299 			}
4300 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4301 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4302 			if (sata_hba_start(spx, &rval) != 0) {
4303 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4304 				return (rval);
4305 			} else {
4306 				if (scmd->satacmd_error_reg != 0) {
4307 					goto err_out;
4308 				}
4309 			}
4310 		}
4311 		bzero(sdinfo->satadrv_standby_timer, sizeof (uchar_t) * 4);
4312 		break;
4313 	default:
4314 err_out:
4315 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4316 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4317 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4318 	}
4319 
4320 	/*
4321 	 * Since it was a synchronous command,
4322 	 * a callback function will be called directly.
4323 	 */
4324 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4325 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4326 	    "synchronous execution status %x\n",
4327 	    spx->txlt_sata_pkt->satapkt_reason);
4328 
4329 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4330 	    scsipkt->pkt_comp != NULL) {
4331 		sata_set_arq_data(spx->txlt_sata_pkt);
4332 		if (servicing_interrupt()) {
4333 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4334 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4335 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4336 				return (TRAN_BUSY);
4337 			}
4338 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4339 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4340 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4341 			/* Scheduling the callback failed */
4342 			return (TRAN_BUSY);
4343 		}
4344 	}
4345 	else
4346 
4347 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
4348 
4349 	return (TRAN_ACCEPT);
4350 
4351 }
4352 
4353 /*
4354  * SATA translate command:  Read Capacity.
4355  * Emulated command for SATA disks.
4356  * Capacity is retrieved from cached Idenifty Device data.
4357  * Identify Device data shows effective disk capacity, not the native
4358  * capacity, which may be limitted by Set Max Address command.
4359  * This is ATA version for SATA hard disks.
4360  *
4361  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4362  */
4363 static int
4364 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
4365 {
4366 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4367 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4368 	sata_drive_info_t *sdinfo;
4369 	uint64_t val;
4370 	uchar_t *rbuf;
4371 	int rval, reason;
4372 
4373 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4374 	    "sata_txlt_read_capacity: ", NULL);
4375 
4376 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4377 
4378 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4379 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4380 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4381 		return (rval);
4382 	}
4383 
4384 	scsipkt->pkt_reason = CMD_CMPLT;
4385 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4386 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4387 	*scsipkt->pkt_scbp = STATUS_GOOD;
4388 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4389 		/*
4390 		 * Because it is fully emulated command storing data
4391 		 * programatically in the specified buffer, release
4392 		 * preallocated DMA resources before storing data in the buffer,
4393 		 * so no unwanted DMA sync would take place.
4394 		 */
4395 		sata_scsi_dmafree(NULL, scsipkt);
4396 
4397 		sdinfo = sata_get_device_info(
4398 		    spx->txlt_sata_hba_inst,
4399 		    &spx->txlt_sata_pkt->satapkt_device);
4400 
4401 		/*
4402 		 * As per SBC-3, the "returned LBA" is either the highest
4403 		 * addressable LBA or 0xffffffff, whichever is smaller.
4404 		 */
4405 		val = MIN(sdinfo->satadrv_capacity - 1, UINT32_MAX);
4406 
4407 		rbuf = (uchar_t *)bp->b_un.b_addr;
4408 		/* Need to swap endians to match scsi format */
4409 		rbuf[0] = (val >> 24) & 0xff;
4410 		rbuf[1] = (val >> 16) & 0xff;
4411 		rbuf[2] = (val >> 8) & 0xff;
4412 		rbuf[3] = val & 0xff;
4413 		/* block size - always 512 bytes, for now */
4414 		rbuf[4] = 0;
4415 		rbuf[5] = 0;
4416 		rbuf[6] = 0x02;
4417 		rbuf[7] = 0;
4418 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4419 		scsipkt->pkt_resid = 0;
4420 
4421 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
4422 		    sdinfo->satadrv_capacity -1);
4423 	}
4424 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4425 	/*
4426 	 * If a callback was requested, do it now.
4427 	 */
4428 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4429 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4430 
4431 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4432 	    scsipkt->pkt_comp != NULL) {
4433 		/* scsi callback required */
4434 		if (servicing_interrupt()) {
4435 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4436 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4437 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4438 				return (TRAN_BUSY);
4439 			}
4440 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4441 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4442 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4443 			/* Scheduling the callback failed */
4444 			return (TRAN_BUSY);
4445 		}
4446 	}
4447 
4448 	return (TRAN_ACCEPT);
4449 }
4450 
4451 /*
4452  * SATA translate command:  Read Capacity (16).
4453  * Emulated command for SATA disks.
4454  * Info is retrieved from cached Identify Device data.
4455  * Implemented to SBC-3 (draft 21) and SAT-2 (final) specifications.
4456  *
4457  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4458  */
4459 static int
4460 sata_txlt_read_capacity16(sata_pkt_txlate_t *spx)
4461 {
4462 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4463 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4464 	sata_drive_info_t *sdinfo;
4465 	uint64_t val;
4466 	uint16_t l2p_exp;
4467 	uchar_t *rbuf;
4468 	int rval, reason;
4469 
4470 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4471 	    "sata_txlt_read_capacity: ", NULL);
4472 
4473 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4474 
4475 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4476 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4477 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4478 		return (rval);
4479 	}
4480 
4481 	scsipkt->pkt_reason = CMD_CMPLT;
4482 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4483 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4484 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4485 		/*
4486 		 * Because it is fully emulated command storing data
4487 		 * programatically in the specified buffer, release
4488 		 * preallocated DMA resources before storing data in the buffer,
4489 		 * so no unwanted DMA sync would take place.
4490 		 */
4491 		sata_scsi_dmafree(NULL, scsipkt);
4492 
4493 		/* Check SERVICE ACTION field */
4494 		if ((scsipkt->pkt_cdbp[1] & 0x1f) !=
4495 		    SSVC_ACTION_READ_CAPACITY_G4) {
4496 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4497 			return (sata_txlt_check_condition(spx,
4498 			    KEY_ILLEGAL_REQUEST,
4499 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4500 		}
4501 
4502 		/* Check LBA field */
4503 		if ((scsipkt->pkt_cdbp[2] != 0) ||
4504 		    (scsipkt->pkt_cdbp[3] != 0) ||
4505 		    (scsipkt->pkt_cdbp[4] != 0) ||
4506 		    (scsipkt->pkt_cdbp[5] != 0) ||
4507 		    (scsipkt->pkt_cdbp[6] != 0) ||
4508 		    (scsipkt->pkt_cdbp[7] != 0) ||
4509 		    (scsipkt->pkt_cdbp[8] != 0) ||
4510 		    (scsipkt->pkt_cdbp[9] != 0)) {
4511 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4512 			return (sata_txlt_check_condition(spx,
4513 			    KEY_ILLEGAL_REQUEST,
4514 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4515 		}
4516 
4517 		/* Check PMI bit */
4518 		if (scsipkt->pkt_cdbp[14] & 0x1) {
4519 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4520 			return (sata_txlt_check_condition(spx,
4521 			    KEY_ILLEGAL_REQUEST,
4522 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4523 		}
4524 
4525 		*scsipkt->pkt_scbp = STATUS_GOOD;
4526 
4527 		sdinfo = sata_get_device_info(
4528 		    spx->txlt_sata_hba_inst,
4529 		    &spx->txlt_sata_pkt->satapkt_device);
4530 
4531 		/* last logical block address */
4532 		val = MIN(sdinfo->satadrv_capacity - 1,
4533 		    SCSI_READ_CAPACITY16_MAX_LBA);
4534 
4535 		/* logical to physical block size exponent */
4536 		l2p_exp = 0;
4537 		if (sdinfo->satadrv_id.ai_phys_sect_sz & SATA_L2PS_CHECK_BIT) {
4538 			/* physical/logical sector size word is valid */
4539 
4540 			if (sdinfo->satadrv_id.ai_phys_sect_sz &
4541 			    SATA_L2PS_HAS_MULT) {
4542 				/* multiple logical sectors per phys sectors */
4543 				l2p_exp =
4544 				    sdinfo->satadrv_id.ai_phys_sect_sz &
4545 				    SATA_L2PS_EXP_MASK;
4546 			}
4547 		}
4548 
4549 		rbuf = (uchar_t *)bp->b_un.b_addr;
4550 		bzero(rbuf, bp->b_bcount);
4551 
4552 		/* returned logical block address */
4553 		rbuf[0] = (val >> 56) & 0xff;
4554 		rbuf[1] = (val >> 48) & 0xff;
4555 		rbuf[2] = (val >> 40) & 0xff;
4556 		rbuf[3] = (val >> 32) & 0xff;
4557 		rbuf[4] = (val >> 24) & 0xff;
4558 		rbuf[5] = (val >> 16) & 0xff;
4559 		rbuf[6] = (val >> 8) & 0xff;
4560 		rbuf[7] = val & 0xff;
4561 
4562 		/* logical block length in bytes = 512 (for now) */
4563 		/* rbuf[8] = 0; */
4564 		/* rbuf[9] = 0; */
4565 		rbuf[10] = 0x02;
4566 		/* rbuf[11] = 0; */
4567 
4568 		/* p_type, prot_en, unspecified by SAT-2 */
4569 		/* rbuf[12] = 0; */
4570 
4571 		/* p_i_exponent, undefined by SAT-2 */
4572 		/* logical blocks per physical block exponent */
4573 		rbuf[13] = l2p_exp;
4574 
4575 		/* tpe, tprz, undefined by SAT-2 */
4576 		/* lowest aligned logical block address = 0 (for now) */
4577 		/* rbuf[14] = 0; */
4578 		/* rbuf[15] = 0; */
4579 
4580 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4581 		scsipkt->pkt_resid = 0;
4582 
4583 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%llu\n",
4584 		    sdinfo->satadrv_capacity -1);
4585 	}
4586 
4587 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4588 
4589 	/*
4590 	 * If a callback was requested, do it now.
4591 	 */
4592 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4593 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4594 
4595 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4596 	    scsipkt->pkt_comp != NULL) {
4597 		/* scsi callback required */
4598 		if (servicing_interrupt()) {
4599 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4600 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4601 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4602 				return (TRAN_BUSY);
4603 			}
4604 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4605 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4606 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4607 			/* Scheduling the callback failed */
4608 			return (TRAN_BUSY);
4609 		}
4610 	}
4611 
4612 	return (TRAN_ACCEPT);
4613 }
4614 
4615 /*
4616  * SATA translate command: Mode Sense.
4617  * Translated into appropriate SATA command or emulated.
4618  * Saved Values Page Control (03) are not supported.
4619  *
4620  * NOTE: only caching mode sense page is currently implemented.
4621  *
4622  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4623  */
4624 
4625 #define	LLBAA	0x10	/* Long LBA Accepted */
4626 
4627 static int
4628 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4629 {
4630 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4631 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4632 	sata_drive_info_t *sdinfo;
4633 	sata_id_t *sata_id;
4634 	struct scsi_extended_sense *sense;
4635 	int 		len, bdlen, count, alc_len;
4636 	int		pc;	/* Page Control code */
4637 	uint8_t		*buf;	/* mode sense buffer */
4638 	int		rval, reason;
4639 
4640 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4641 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
4642 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4643 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4644 
4645 	if (servicing_interrupt()) {
4646 		buf = kmem_zalloc(1024, KM_NOSLEEP);
4647 		if (buf == NULL) {
4648 			return (TRAN_BUSY);
4649 		}
4650 	} else {
4651 		buf = kmem_zalloc(1024, KM_SLEEP);
4652 	}
4653 
4654 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4655 
4656 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4657 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4658 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4659 		kmem_free(buf, 1024);
4660 		return (rval);
4661 	}
4662 
4663 	scsipkt->pkt_reason = CMD_CMPLT;
4664 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4665 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4666 
4667 	pc = scsipkt->pkt_cdbp[2] >> 6;
4668 
4669 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4670 		/*
4671 		 * Because it is fully emulated command storing data
4672 		 * programatically in the specified buffer, release
4673 		 * preallocated DMA resources before storing data in the buffer,
4674 		 * so no unwanted DMA sync would take place.
4675 		 */
4676 		sata_scsi_dmafree(NULL, scsipkt);
4677 
4678 		len = 0;
4679 		bdlen = 0;
4680 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
4681 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
4682 			    (scsipkt->pkt_cdbp[1] & LLBAA))
4683 				bdlen = 16;
4684 			else
4685 				bdlen = 8;
4686 		}
4687 		/* Build mode parameter header */
4688 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4689 			/* 4-byte mode parameter header */
4690 			buf[len++] = 0;		/* mode data length */
4691 			buf[len++] = 0;		/* medium type */
4692 			buf[len++] = 0;		/* dev-specific param */
4693 			buf[len++] = bdlen;	/* Block Descriptor length */
4694 		} else {
4695 			/* 8-byte mode parameter header */
4696 			buf[len++] = 0;		/* mode data length */
4697 			buf[len++] = 0;
4698 			buf[len++] = 0;		/* medium type */
4699 			buf[len++] = 0;		/* dev-specific param */
4700 			if (bdlen == 16)
4701 				buf[len++] = 1;	/* long lba descriptor */
4702 			else
4703 				buf[len++] = 0;
4704 			buf[len++] = 0;
4705 			buf[len++] = 0;		/* Block Descriptor length */
4706 			buf[len++] = bdlen;
4707 		}
4708 
4709 		sdinfo = sata_get_device_info(
4710 		    spx->txlt_sata_hba_inst,
4711 		    &spx->txlt_sata_pkt->satapkt_device);
4712 
4713 		/* Build block descriptor only if not disabled (DBD) */
4714 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
4715 			/* Block descriptor - direct-access device format */
4716 			if (bdlen == 8) {
4717 				/* build regular block descriptor */
4718 				buf[len++] =
4719 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4720 				buf[len++] =
4721 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4722 				buf[len++] =
4723 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4724 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4725 				buf[len++] = 0; /* density code */
4726 				buf[len++] = 0;
4727 				if (sdinfo->satadrv_type ==
4728 				    SATA_DTYPE_ATADISK)
4729 					buf[len++] = 2;
4730 				else
4731 					/* ATAPI */
4732 					buf[len++] = 8;
4733 				buf[len++] = 0;
4734 			} else if (bdlen == 16) {
4735 				/* Long LBA Accepted */
4736 				/* build long lba block descriptor */
4737 #ifndef __lock_lint
4738 				buf[len++] =
4739 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
4740 				buf[len++] =
4741 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
4742 				buf[len++] =
4743 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
4744 				buf[len++] =
4745 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
4746 #endif
4747 				buf[len++] =
4748 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4749 				buf[len++] =
4750 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4751 				buf[len++] =
4752 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4753 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4754 				buf[len++] = 0;
4755 				buf[len++] = 0; /* density code */
4756 				buf[len++] = 0;
4757 				buf[len++] = 0;
4758 				if (sdinfo->satadrv_type ==
4759 				    SATA_DTYPE_ATADISK)
4760 					buf[len++] = 2;
4761 				else
4762 					/* ATAPI */
4763 					buf[len++] = 8;
4764 				buf[len++] = 0;
4765 			}
4766 		}
4767 
4768 		sata_id = &sdinfo->satadrv_id;
4769 
4770 		/*
4771 		 * Add requested pages.
4772 		 * Page 3 and 4 are obsolete and we are not supporting them.
4773 		 * We deal now with:
4774 		 * caching (read/write cache control).
4775 		 * We should eventually deal with following mode pages:
4776 		 * error recovery  (0x01),
4777 		 * power condition (0x1a),
4778 		 * exception control page (enables SMART) (0x1c),
4779 		 * enclosure management (ses),
4780 		 * protocol-specific port mode (port control).
4781 		 */
4782 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
4783 		case MODEPAGE_RW_ERRRECOV:
4784 			/* DAD_MODE_ERR_RECOV */
4785 			/* R/W recovery */
4786 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4787 			break;
4788 		case MODEPAGE_CACHING:
4789 			/* DAD_MODE_CACHE */
4790 			/* Reject not supported request for saved parameters */
4791 			if (pc == 3) {
4792 				*scsipkt->pkt_scbp = STATUS_CHECK;
4793 				sense = sata_arq_sense(spx);
4794 				sense->es_key = KEY_ILLEGAL_REQUEST;
4795 				sense->es_add_code =
4796 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
4797 				goto done;
4798 			}
4799 
4800 			/* caching */
4801 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4802 			break;
4803 		case MODEPAGE_INFO_EXCPT:
4804 			/* exception cntrl */
4805 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4806 				len += sata_build_msense_page_1c(sdinfo, pc,
4807 				    buf+len);
4808 			}
4809 			else
4810 				goto err;
4811 			break;
4812 		case MODEPAGE_POWER_COND:
4813 			/* DAD_MODE_POWER_COND */
4814 			/* power condition */
4815 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4816 			break;
4817 
4818 		case MODEPAGE_ACOUSTIC_MANAG:
4819 			/* acoustic management */
4820 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4821 			break;
4822 		case MODEPAGE_ALLPAGES:
4823 			/* all pages */
4824 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4825 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4826 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4827 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4828 				len += sata_build_msense_page_1c(sdinfo, pc,
4829 				    buf+len);
4830 			}
4831 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4832 			break;
4833 		default:
4834 		err:
4835 			/* Invalid request */
4836 			*scsipkt->pkt_scbp = STATUS_CHECK;
4837 			sense = sata_arq_sense(spx);
4838 			sense->es_key = KEY_ILLEGAL_REQUEST;
4839 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4840 			goto done;
4841 		}
4842 
4843 		/* fix total mode data length */
4844 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4845 			/* 4-byte mode parameter header */
4846 			buf[0] = len - 1;	/* mode data length */
4847 		} else {
4848 			buf[0] = (len -2) >> 8;
4849 			buf[1] = (len -2) & 0xff;
4850 		}
4851 
4852 
4853 		/* Check allocation length */
4854 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4855 			alc_len = scsipkt->pkt_cdbp[4];
4856 		} else {
4857 			alc_len = scsipkt->pkt_cdbp[7];
4858 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4859 		}
4860 		/*
4861 		 * We do not check for possible parameters truncation
4862 		 * (alc_len < len) assuming that the target driver works
4863 		 * correctly. Just avoiding overrun.
4864 		 * Copy no more than requested and possible, buffer-wise.
4865 		 */
4866 		count = MIN(alc_len, len);
4867 		count = MIN(bp->b_bcount, count);
4868 		bcopy(buf, bp->b_un.b_addr, count);
4869 
4870 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4871 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4872 	}
4873 	*scsipkt->pkt_scbp = STATUS_GOOD;
4874 done:
4875 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4876 	(void) kmem_free(buf, 1024);
4877 
4878 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4879 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4880 
4881 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4882 	    scsipkt->pkt_comp != NULL) {
4883 		/* scsi callback required */
4884 		if (servicing_interrupt()) {
4885 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4886 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4887 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
4888 				return (TRAN_BUSY);
4889 			}
4890 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4891 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
4892 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
4893 			/* Scheduling the callback failed */
4894 			return (TRAN_BUSY);
4895 		}
4896 	}
4897 
4898 	return (TRAN_ACCEPT);
4899 }
4900 
4901 
4902 /*
4903  * SATA translate command: Mode Select.
4904  * Translated into appropriate SATA command or emulated.
4905  * Saving parameters is not supported.
4906  * Changing device capacity is not supported (although theoretically
4907  * possible by executing SET FEATURES/SET MAX ADDRESS)
4908  *
4909  * Assumption is that the target driver is working correctly.
4910  *
4911  * More than one SATA command may be executed to perform operations specified
4912  * by mode select pages. The first error terminates further execution.
4913  * Operations performed successully are not backed-up in such case.
4914  *
4915  * NOTE: Implemented pages:
4916  * - caching page
4917  * - informational exception page
4918  * - acoustic management page
4919  * - power condition page
4920  * Caching setup is remembered so it could be re-stored in case of
4921  * an unexpected device reset.
4922  *
4923  * Returns TRAN_XXXX.
4924  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
4925  */
4926 
4927 static int
4928 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
4929 {
4930 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4931 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4932 	struct scsi_extended_sense *sense;
4933 	int len, pagelen, count, pllen;
4934 	uint8_t *buf;	/* mode select buffer */
4935 	int rval, stat, reason;
4936 	uint_t nointr_flag;
4937 	int dmod = 0;
4938 
4939 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4940 	    "sata_txlt_mode_select, pc %x page code 0x%02x\n",
4941 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4942 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4943 
4944 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4945 
4946 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4947 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4948 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4949 		return (rval);
4950 	}
4951 
4952 	rval = TRAN_ACCEPT;
4953 
4954 	scsipkt->pkt_reason = CMD_CMPLT;
4955 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4956 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4957 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
4958 
4959 	/* Reject not supported request */
4960 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
4961 		*scsipkt->pkt_scbp = STATUS_CHECK;
4962 		sense = sata_arq_sense(spx);
4963 		sense->es_key = KEY_ILLEGAL_REQUEST;
4964 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4965 		goto done;
4966 	}
4967 
4968 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4969 		pllen = scsipkt->pkt_cdbp[4];
4970 	} else {
4971 		pllen = scsipkt->pkt_cdbp[7];
4972 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
4973 	}
4974 
4975 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
4976 
4977 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
4978 		buf = (uint8_t *)bp->b_un.b_addr;
4979 		count = MIN(bp->b_bcount, pllen);
4980 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4981 		scsipkt->pkt_resid = 0;
4982 		pllen = count;
4983 
4984 		/*
4985 		 * Check the header to skip the block descriptor(s) - we
4986 		 * do not support setting device capacity.
4987 		 * Existing macros do not recognize long LBA dscriptor,
4988 		 * hence manual calculation.
4989 		 */
4990 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4991 			/* 6-bytes CMD, 4 bytes header */
4992 			if (count <= 4)
4993 				goto done;		/* header only */
4994 			len = buf[3] + 4;
4995 		} else {
4996 			/* 10-bytes CMD, 8 bytes header */
4997 			if (count <= 8)
4998 				goto done;		/* header only */
4999 			len = buf[6];
5000 			len = (len << 8) + buf[7] + 8;
5001 		}
5002 		if (len >= count)
5003 			goto done;	/* header + descriptor(s) only */
5004 
5005 		pllen -= len;		/* remaining data length */
5006 
5007 		/*
5008 		 * We may be executing SATA command and want to execute it
5009 		 * in SYNCH mode, regardless of scsi_pkt setting.
5010 		 * Save scsi_pkt setting and indicate SYNCH mode
5011 		 */
5012 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5013 		    scsipkt->pkt_comp != NULL) {
5014 			scsipkt->pkt_flags |= FLAG_NOINTR;
5015 		}
5016 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
5017 
5018 		/*
5019 		 * len is now the offset to a first mode select page
5020 		 * Process all pages
5021 		 */
5022 		while (pllen > 0) {
5023 			switch ((int)buf[len]) {
5024 			case MODEPAGE_CACHING:
5025 				/* No support for SP (saving) */
5026 				if (scsipkt->pkt_cdbp[1] & 0x01) {
5027 					*scsipkt->pkt_scbp = STATUS_CHECK;
5028 					sense = sata_arq_sense(spx);
5029 					sense->es_key = KEY_ILLEGAL_REQUEST;
5030 					sense->es_add_code =
5031 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5032 					goto done;
5033 				}
5034 				stat = sata_mode_select_page_8(spx,
5035 				    (struct mode_cache_scsi3 *)&buf[len],
5036 				    pllen, &pagelen, &rval, &dmod);
5037 				/*
5038 				 * The pagelen value indicates the number of
5039 				 * parameter bytes already processed.
5040 				 * The rval is the return value from
5041 				 * sata_tran_start().
5042 				 * The stat indicates the overall status of
5043 				 * the operation(s).
5044 				 */
5045 				if (stat != SATA_SUCCESS)
5046 					/*
5047 					 * Page processing did not succeed -
5048 					 * all error info is already set-up,
5049 					 * just return
5050 					 */
5051 					pllen = 0; /* this breaks the loop */
5052 				else {
5053 					len += pagelen;
5054 					pllen -= pagelen;
5055 				}
5056 				break;
5057 
5058 			case MODEPAGE_INFO_EXCPT:
5059 				stat = sata_mode_select_page_1c(spx,
5060 				    (struct mode_info_excpt_page *)&buf[len],
5061 				    pllen, &pagelen, &rval, &dmod);
5062 				/*
5063 				 * The pagelen value indicates the number of
5064 				 * parameter bytes already processed.
5065 				 * The rval is the return value from
5066 				 * sata_tran_start().
5067 				 * The stat indicates the overall status of
5068 				 * the operation(s).
5069 				 */
5070 				if (stat != SATA_SUCCESS)
5071 					/*
5072 					 * Page processing did not succeed -
5073 					 * all error info is already set-up,
5074 					 * just return
5075 					 */
5076 					pllen = 0; /* this breaks the loop */
5077 				else {
5078 					len += pagelen;
5079 					pllen -= pagelen;
5080 				}
5081 				break;
5082 
5083 			case MODEPAGE_ACOUSTIC_MANAG:
5084 				stat = sata_mode_select_page_30(spx,
5085 				    (struct mode_acoustic_management *)
5086 				    &buf[len], pllen, &pagelen, &rval, &dmod);
5087 				/*
5088 				 * The pagelen value indicates the number of
5089 				 * parameter bytes already processed.
5090 				 * The rval is the return value from
5091 				 * sata_tran_start().
5092 				 * The stat indicates the overall status of
5093 				 * the operation(s).
5094 				 */
5095 				if (stat != SATA_SUCCESS)
5096 					/*
5097 					 * Page processing did not succeed -
5098 					 * all error info is already set-up,
5099 					 * just return
5100 					 */
5101 					pllen = 0; /* this breaks the loop */
5102 				else {
5103 					len += pagelen;
5104 					pllen -= pagelen;
5105 				}
5106 
5107 				break;
5108 			case MODEPAGE_POWER_COND:
5109 				stat = sata_mode_select_page_1a(spx,
5110 				    (struct mode_info_power_cond *)&buf[len],
5111 				    pllen, &pagelen, &rval, &dmod);
5112 				/*
5113 				 * The pagelen value indicates the number of
5114 				 * parameter bytes already processed.
5115 				 * The rval is the return value from
5116 				 * sata_tran_start().
5117 				 * The stat indicates the overall status of
5118 				 * the operation(s).
5119 				 */
5120 				if (stat != SATA_SUCCESS)
5121 					/*
5122 					 * Page processing did not succeed -
5123 					 * all error info is already set-up,
5124 					 * just return
5125 					 */
5126 					pllen = 0; /* this breaks the loop */
5127 				else {
5128 					len += pagelen;
5129 					pllen -= pagelen;
5130 				}
5131 				break;
5132 			default:
5133 				*scsipkt->pkt_scbp = STATUS_CHECK;
5134 				sense = sata_arq_sense(spx);
5135 				sense->es_key = KEY_ILLEGAL_REQUEST;
5136 				sense->es_add_code =
5137 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
5138 				goto done;
5139 			}
5140 		}
5141 	}
5142 done:
5143 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5144 	/*
5145 	 * If device parameters were modified, fetch and store the new
5146 	 * Identify Device data. Since port mutex could have been released
5147 	 * for accessing HBA driver, we need to re-check device existence.
5148 	 */
5149 	if (dmod != 0) {
5150 		sata_drive_info_t new_sdinfo, *sdinfo;
5151 		int rv = 0;
5152 
5153 		/*
5154 		 * Following statement has to be changed if this function is
5155 		 * used for devices other than SATA hard disks.
5156 		 */
5157 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
5158 
5159 		new_sdinfo.satadrv_addr =
5160 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
5161 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
5162 		    &new_sdinfo);
5163 
5164 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5165 		/*
5166 		 * Since port mutex could have been released when
5167 		 * accessing HBA driver, we need to re-check that the
5168 		 * framework still holds the device info structure.
5169 		 */
5170 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5171 		    &spx->txlt_sata_pkt->satapkt_device);
5172 		if (sdinfo != NULL) {
5173 			/*
5174 			 * Device still has info structure in the
5175 			 * sata framework. Copy newly fetched info
5176 			 */
5177 			if (rv == 0) {
5178 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
5179 				sata_save_drive_settings(sdinfo);
5180 			} else {
5181 				/*
5182 				 * Could not fetch new data - invalidate
5183 				 * sata_drive_info. That makes device
5184 				 * unusable.
5185 				 */
5186 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
5187 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
5188 			}
5189 		}
5190 		if (rv != 0 || sdinfo == NULL) {
5191 			/*
5192 			 * This changes the overall mode select completion
5193 			 * reason to a failed one !!!!!
5194 			 */
5195 			*scsipkt->pkt_scbp = STATUS_CHECK;
5196 			sense = sata_arq_sense(spx);
5197 			scsipkt->pkt_reason = CMD_INCOMPLETE;
5198 			rval = TRAN_ACCEPT;
5199 		}
5200 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5201 	}
5202 	/* Restore the scsi pkt flags */
5203 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
5204 	scsipkt->pkt_flags |= nointr_flag;
5205 
5206 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5207 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5208 
5209 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5210 	    scsipkt->pkt_comp != NULL) {
5211 		/* scsi callback required */
5212 		if (servicing_interrupt()) {
5213 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5214 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5215 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
5216 				return (TRAN_BUSY);
5217 			}
5218 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5219 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5220 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
5221 			/* Scheduling the callback failed */
5222 			return (TRAN_BUSY);
5223 		}
5224 	}
5225 
5226 	return (rval);
5227 }
5228 
5229 /*
5230  * Translate command: ATA Pass Through
5231  * Incomplete implementation.  Only supports No-Data, PIO Data-In, and
5232  * PIO Data-Out protocols.  Also supports CK_COND bit.
5233  *
5234  * Mapping of the incoming CDB bytes to the outgoing satacmd bytes is
5235  * described in Table 111 of SAT-2 (Draft 9).
5236  */
5237 static  int
5238 sata_txlt_ata_pass_thru(sata_pkt_txlate_t *spx)
5239 {
5240 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5241 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5242 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5243 	int extend;
5244 	uint64_t lba;
5245 	uint16_t feature, sec_count;
5246 	int t_len, synch;
5247 	int rval, reason;
5248 
5249 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5250 
5251 	rval = sata_txlt_generic_pkt_info(spx, &reason, 1);
5252 	if ((rval != TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5253 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5254 		return (rval);
5255 	}
5256 
5257 	/* T_DIR bit */
5258 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_T_DIR)
5259 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5260 	else
5261 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5262 
5263 	/* MULTIPLE_COUNT field.  If non-zero, invalid command (for now). */
5264 	if (((scsipkt->pkt_cdbp[1] >> 5) & 0x7) != 0) {
5265 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5266 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5267 	}
5268 
5269 	/* OFFLINE field. If non-zero, invalid command (for now). */
5270 	if (((scsipkt->pkt_cdbp[2] >> 6) & 0x3) != 0) {
5271 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5272 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5273 	}
5274 
5275 	/* PROTOCOL field */
5276 	switch ((scsipkt->pkt_cdbp[1] >> 1) & 0xf) {
5277 	case SATL_APT_P_HW_RESET:
5278 	case SATL_APT_P_SRST:
5279 	case SATL_APT_P_DMA:
5280 	case SATL_APT_P_DMA_QUEUED:
5281 	case SATL_APT_P_DEV_DIAG:
5282 	case SATL_APT_P_DEV_RESET:
5283 	case SATL_APT_P_UDMA_IN:
5284 	case SATL_APT_P_UDMA_OUT:
5285 	case SATL_APT_P_FPDMA:
5286 	case SATL_APT_P_RET_RESP:
5287 		/* Not yet implemented */
5288 	default:
5289 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5290 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5291 
5292 	case SATL_APT_P_NON_DATA:
5293 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
5294 		break;
5295 
5296 	case SATL_APT_P_PIO_DATA_IN:
5297 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5298 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_WRITE) {
5299 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5300 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5301 		}
5302 
5303 		/* if there is a buffer, release its DMA resources */
5304 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5305 			sata_scsi_dmafree(NULL, scsipkt);
5306 		} else {
5307 			/* if there is no buffer, how do you PIO in? */
5308 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5309 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5310 		}
5311 
5312 		break;
5313 
5314 	case SATL_APT_P_PIO_DATA_OUT:
5315 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5316 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_READ) {
5317 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5318 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5319 		}
5320 
5321 		/* if there is a buffer, release its DMA resources */
5322 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5323 			sata_scsi_dmafree(NULL, scsipkt);
5324 		} else {
5325 			/* if there is no buffer, how do you PIO out? */
5326 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5327 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5328 		}
5329 
5330 		break;
5331 	}
5332 
5333 	/* Parse the ATA cmd fields, transfer some straight to the satacmd */
5334 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5335 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
5336 		feature = scsipkt->pkt_cdbp[3];
5337 
5338 		sec_count = scsipkt->pkt_cdbp[4];
5339 
5340 		lba = scsipkt->pkt_cdbp[8] & 0xf;
5341 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5342 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5343 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5344 
5345 		scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] & 0xf0;
5346 		scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[9];
5347 
5348 		break;
5349 
5350 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
5351 		if (scsipkt->pkt_cdbp[1] & SATL_APT_BM_EXTEND) {
5352 			extend = 1;
5353 
5354 			feature = scsipkt->pkt_cdbp[3];
5355 			feature = (feature << 8) | scsipkt->pkt_cdbp[4];
5356 
5357 			sec_count = scsipkt->pkt_cdbp[5];
5358 			sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[6];
5359 
5360 			lba = scsipkt->pkt_cdbp[11];
5361 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5362 			lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5363 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5364 			lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5365 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5366 
5367 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13];
5368 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5369 		} else {
5370 			feature = scsipkt->pkt_cdbp[3];
5371 
5372 			sec_count = scsipkt->pkt_cdbp[5];
5373 
5374 			lba = scsipkt->pkt_cdbp[13] & 0xf;
5375 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5376 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5377 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5378 
5379 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] &
5380 			    0xf0;
5381 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5382 		}
5383 
5384 		break;
5385 	}
5386 
5387 	/* CK_COND bit */
5388 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
5389 		if (extend) {
5390 			scmd->satacmd_flags.sata_copy_out_sec_count_msb = 1;
5391 			scmd->satacmd_flags.sata_copy_out_lba_low_msb = 1;
5392 			scmd->satacmd_flags.sata_copy_out_lba_mid_msb = 1;
5393 			scmd->satacmd_flags.sata_copy_out_lba_high_msb = 1;
5394 		}
5395 
5396 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
5397 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
5398 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
5399 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
5400 		scmd->satacmd_flags.sata_copy_out_device_reg = 1;
5401 		scmd->satacmd_flags.sata_copy_out_error_reg = 1;
5402 	}
5403 
5404 	/* Transfer remaining parsed ATA cmd values to the satacmd */
5405 	if (extend) {
5406 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5407 
5408 		scmd->satacmd_features_reg_ext = (feature >> 8) & 0xff;
5409 		scmd->satacmd_sec_count_msb = (sec_count >> 8) & 0xff;
5410 		scmd->satacmd_lba_low_msb = (lba >> 8) & 0xff;
5411 		scmd->satacmd_lba_mid_msb = (lba >> 8) & 0xff;
5412 		scmd->satacmd_lba_high_msb = lba >> 40;
5413 	} else {
5414 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5415 
5416 		scmd->satacmd_features_reg_ext = 0;
5417 		scmd->satacmd_sec_count_msb = 0;
5418 		scmd->satacmd_lba_low_msb = 0;
5419 		scmd->satacmd_lba_mid_msb = 0;
5420 		scmd->satacmd_lba_high_msb = 0;
5421 	}
5422 
5423 	scmd->satacmd_features_reg = feature & 0xff;
5424 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5425 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5426 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5427 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5428 
5429 	/* Determine transfer length */
5430 	switch (scsipkt->pkt_cdbp[2] & 0x3) {		/* T_LENGTH field */
5431 	case 1:
5432 		t_len = feature;
5433 		break;
5434 	case 2:
5435 		t_len = sec_count;
5436 		break;
5437 	default:
5438 		t_len = 0;
5439 		break;
5440 	}
5441 
5442 	/* Adjust transfer length for the Byte Block bit */
5443 	if ((scsipkt->pkt_cdbp[2] >> 2) & 1)
5444 		t_len *= SATA_DISK_SECTOR_SIZE;
5445 
5446 	/* Start processing command */
5447 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5448 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_apt_completion;
5449 		synch = FALSE;
5450 	} else {
5451 		synch = TRUE;
5452 	}
5453 
5454 	if (sata_hba_start(spx, &rval) != 0) {
5455 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5456 		return (rval);
5457 	}
5458 
5459 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5460 
5461 	if (synch) {
5462 		sata_txlt_apt_completion(spx->txlt_sata_pkt);
5463 	}
5464 
5465 	return (TRAN_ACCEPT);
5466 }
5467 
5468 /*
5469  * Translate command: Log Sense
5470  */
5471 static 	int
5472 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
5473 {
5474 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
5475 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5476 	sata_drive_info_t *sdinfo;
5477 	struct scsi_extended_sense *sense;
5478 	int 		len, count, alc_len;
5479 	int		pc;	/* Page Control code */
5480 	int		page_code;	/* Page code */
5481 	uint8_t		*buf;	/* log sense buffer */
5482 	int		rval, reason;
5483 #define	MAX_LOG_SENSE_PAGE_SIZE	512
5484 
5485 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5486 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
5487 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5488 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5489 
5490 	if (servicing_interrupt()) {
5491 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_NOSLEEP);
5492 		if (buf == NULL) {
5493 			return (TRAN_BUSY);
5494 		}
5495 	} else {
5496 		buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
5497 	}
5498 
5499 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5500 
5501 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5502 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5503 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5504 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5505 		return (rval);
5506 	}
5507 
5508 	scsipkt->pkt_reason = CMD_CMPLT;
5509 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5510 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5511 
5512 	pc = scsipkt->pkt_cdbp[2] >> 6;
5513 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
5514 
5515 	/* Reject not supported request for all but cumulative values */
5516 	switch (pc) {
5517 	case PC_CUMULATIVE_VALUES:
5518 		break;
5519 	default:
5520 		*scsipkt->pkt_scbp = STATUS_CHECK;
5521 		sense = sata_arq_sense(spx);
5522 		sense->es_key = KEY_ILLEGAL_REQUEST;
5523 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5524 		goto done;
5525 	}
5526 
5527 	switch (page_code) {
5528 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5529 	case PAGE_CODE_SELF_TEST_RESULTS:
5530 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
5531 	case PAGE_CODE_SMART_READ_DATA:
5532 	case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5533 		break;
5534 	default:
5535 		*scsipkt->pkt_scbp = STATUS_CHECK;
5536 		sense = sata_arq_sense(spx);
5537 		sense->es_key = KEY_ILLEGAL_REQUEST;
5538 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5539 		goto done;
5540 	}
5541 
5542 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
5543 		/*
5544 		 * Because log sense uses local buffers for data retrieval from
5545 		 * the devices and sets the data programatically in the
5546 		 * original specified buffer, release preallocated DMA
5547 		 * resources before storing data in the original buffer,
5548 		 * so no unwanted DMA sync would take place.
5549 		 */
5550 		sata_id_t *sata_id;
5551 
5552 		sata_scsi_dmafree(NULL, scsipkt);
5553 
5554 		len = 0;
5555 
5556 		/* Build log parameter header */
5557 		buf[len++] = page_code;	/* page code as in the CDB */
5558 		buf[len++] = 0;		/* reserved */
5559 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
5560 		buf[len++] = 0;		/* (LSB) */
5561 
5562 		sdinfo = sata_get_device_info(
5563 		    spx->txlt_sata_hba_inst,
5564 		    &spx->txlt_sata_pkt->satapkt_device);
5565 
5566 		/*
5567 		 * Add requested pages.
5568 		 */
5569 		switch (page_code) {
5570 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5571 			len = sata_build_lsense_page_0(sdinfo, buf + len);
5572 			break;
5573 		case PAGE_CODE_SELF_TEST_RESULTS:
5574 			sata_id = &sdinfo->satadrv_id;
5575 			if ((! (sata_id->ai_cmdset84 &
5576 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
5577 			    (! (sata_id->ai_features87 &
5578 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
5579 				*scsipkt->pkt_scbp = STATUS_CHECK;
5580 				sense = sata_arq_sense(spx);
5581 				sense->es_key = KEY_ILLEGAL_REQUEST;
5582 				sense->es_add_code =
5583 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5584 
5585 				goto done;
5586 			}
5587 			len = sata_build_lsense_page_10(sdinfo, buf + len,
5588 			    spx->txlt_sata_hba_inst);
5589 			break;
5590 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
5591 			sata_id = &sdinfo->satadrv_id;
5592 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5593 				*scsipkt->pkt_scbp = STATUS_CHECK;
5594 				sense = sata_arq_sense(spx);
5595 				sense->es_key = KEY_ILLEGAL_REQUEST;
5596 				sense->es_add_code =
5597 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5598 
5599 				goto done;
5600 			}
5601 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5602 				*scsipkt->pkt_scbp = STATUS_CHECK;
5603 				sense = sata_arq_sense(spx);
5604 				sense->es_key = KEY_ABORTED_COMMAND;
5605 				sense->es_add_code =
5606 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5607 				sense->es_qual_code =
5608 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5609 
5610 				goto done;
5611 			}
5612 
5613 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
5614 			    spx->txlt_sata_hba_inst);
5615 			break;
5616 		case PAGE_CODE_SMART_READ_DATA:
5617 			sata_id = &sdinfo->satadrv_id;
5618 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5619 				*scsipkt->pkt_scbp = STATUS_CHECK;
5620 				sense = sata_arq_sense(spx);
5621 				sense->es_key = KEY_ILLEGAL_REQUEST;
5622 				sense->es_add_code =
5623 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5624 
5625 				goto done;
5626 			}
5627 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5628 				*scsipkt->pkt_scbp = STATUS_CHECK;
5629 				sense = sata_arq_sense(spx);
5630 				sense->es_key = KEY_ABORTED_COMMAND;
5631 				sense->es_add_code =
5632 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5633 				sense->es_qual_code =
5634 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5635 
5636 				goto done;
5637 			}
5638 
5639 			/* This page doesn't include a page header */
5640 			len = sata_build_lsense_page_30(sdinfo, buf,
5641 			    spx->txlt_sata_hba_inst);
5642 			goto no_header;
5643 		case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5644 			sata_id = &sdinfo->satadrv_id;
5645 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5646 				*scsipkt->pkt_scbp = STATUS_CHECK;
5647 				sense = sata_arq_sense(spx);
5648 				sense->es_key = KEY_ILLEGAL_REQUEST;
5649 				sense->es_add_code =
5650 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5651 
5652 				goto done;
5653 			}
5654 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5655 				*scsipkt->pkt_scbp = STATUS_CHECK;
5656 				sense = sata_arq_sense(spx);
5657 				sense->es_key = KEY_ABORTED_COMMAND;
5658 				sense->es_add_code =
5659 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5660 				sense->es_qual_code =
5661 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5662 
5663 				goto done;
5664 			}
5665 			len = sata_build_lsense_page_0e(sdinfo, buf, spx);
5666 			goto no_header;
5667 		default:
5668 			/* Invalid request */
5669 			*scsipkt->pkt_scbp = STATUS_CHECK;
5670 			sense = sata_arq_sense(spx);
5671 			sense->es_key = KEY_ILLEGAL_REQUEST;
5672 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5673 			goto done;
5674 		}
5675 
5676 		/* set parameter log sense data length */
5677 		buf[2] = len >> 8;	/* log sense length (MSB) */
5678 		buf[3] = len & 0xff;	/* log sense length (LSB) */
5679 
5680 		len += SCSI_LOG_PAGE_HDR_LEN;
5681 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
5682 
5683 no_header:
5684 		/* Check allocation length */
5685 		alc_len = scsipkt->pkt_cdbp[7];
5686 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
5687 
5688 		/*
5689 		 * We do not check for possible parameters truncation
5690 		 * (alc_len < len) assuming that the target driver works
5691 		 * correctly. Just avoiding overrun.
5692 		 * Copy no more than requested and possible, buffer-wise.
5693 		 */
5694 		count = MIN(alc_len, len);
5695 		count = MIN(bp->b_bcount, count);
5696 		bcopy(buf, bp->b_un.b_addr, count);
5697 
5698 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5699 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
5700 	}
5701 	*scsipkt->pkt_scbp = STATUS_GOOD;
5702 done:
5703 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5704 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5705 
5706 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5707 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5708 
5709 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5710 	    scsipkt->pkt_comp != NULL) {
5711 		/* scsi callback required */
5712 		if (servicing_interrupt()) {
5713 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5714 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5715 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
5716 				return (TRAN_BUSY);
5717 			}
5718 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5719 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
5720 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
5721 			/* Scheduling the callback failed */
5722 			return (TRAN_BUSY);
5723 		}
5724 	}
5725 
5726 	return (TRAN_ACCEPT);
5727 }
5728 
5729 /*
5730  * Translate command: Log Select
5731  * Not implemented at this time - returns invalid command response.
5732  */
5733 static	int
5734 sata_txlt_log_select(sata_pkt_txlate_t *spx)
5735 {
5736 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5737 	    "sata_txlt_log_select\n", NULL);
5738 
5739 	return (sata_txlt_invalid_command(spx));
5740 }
5741 
5742 
5743 /*
5744  * Translate command: Read (various types).
5745  * Translated into appropriate type of ATA READ command
5746  * for SATA hard disks.
5747  * Both the device capabilities and requested operation mode are
5748  * considered.
5749  *
5750  * Following scsi cdb fields are ignored:
5751  * rdprotect, dpo, fua, fua_nv, group_number.
5752  *
5753  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5754  * enable variable sata_func_enable), the capability of the controller and
5755  * capability of a device are checked and if both support queueing, read
5756  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
5757  * command rather than plain READ_XXX command.
5758  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5759  * both the controller and device suport such functionality, the read
5760  * request will be translated to READ_FPDMA_QUEUED command.
5761  * In both cases the maximum queue depth is derived as minimum of:
5762  * HBA capability,device capability and sata_max_queue_depth variable setting.
5763  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5764  * used to pass max queue depth value, and the maximum possible queue depth
5765  * is 32.
5766  *
5767  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5768  * appropriate values in scsi_pkt fields.
5769  */
5770 static int
5771 sata_txlt_read(sata_pkt_txlate_t *spx)
5772 {
5773 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5774 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5775 	sata_drive_info_t *sdinfo;
5776 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5777 	int cport = SATA_TXLT_CPORT(spx);
5778 	uint16_t sec_count;
5779 	uint64_t lba;
5780 	int rval, reason;
5781 	int synch;
5782 
5783 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5784 
5785 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
5786 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5787 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5788 		return (rval);
5789 	}
5790 
5791 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5792 	    &spx->txlt_sata_pkt->satapkt_device);
5793 
5794 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5795 	/*
5796 	 * Extract LBA and sector count from scsi CDB.
5797 	 */
5798 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5799 	case SCMD_READ:
5800 		/* 6-byte scsi read cmd : 0x08 */
5801 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5802 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5803 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5804 		sec_count = scsipkt->pkt_cdbp[4];
5805 		/* sec_count 0 will be interpreted as 256 by a device */
5806 		break;
5807 	case SCMD_READ_G1:
5808 		/* 10-bytes scsi read command : 0x28 */
5809 		lba = scsipkt->pkt_cdbp[2];
5810 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5811 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5812 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5813 		sec_count = scsipkt->pkt_cdbp[7];
5814 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5815 		break;
5816 	case SCMD_READ_G5:
5817 		/* 12-bytes scsi read command : 0xA8 */
5818 		lba = scsipkt->pkt_cdbp[2];
5819 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5820 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5821 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5822 		sec_count = scsipkt->pkt_cdbp[6];
5823 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5824 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5825 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5826 		break;
5827 	case SCMD_READ_G4:
5828 		/* 16-bytes scsi read command : 0x88 */
5829 		lba = scsipkt->pkt_cdbp[2];
5830 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5831 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5832 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5833 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5834 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5835 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5836 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5837 		sec_count = scsipkt->pkt_cdbp[10];
5838 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5839 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5840 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5841 		break;
5842 	default:
5843 		/* Unsupported command */
5844 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5845 		return (sata_txlt_invalid_command(spx));
5846 	}
5847 
5848 	/*
5849 	 * Check if specified address exceeds device capacity
5850 	 */
5851 	if ((lba >= sdinfo->satadrv_capacity) ||
5852 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5853 		/* LBA out of range */
5854 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5855 		return (sata_txlt_lba_out_of_range(spx));
5856 	}
5857 
5858 	/*
5859 	 * For zero-length transfer, emulate good completion of the command
5860 	 * (reasons for rejecting the command were already checked).
5861 	 * No DMA resources were allocated.
5862 	 */
5863 	if (spx->txlt_dma_cookie_list == NULL) {
5864 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5865 		return (sata_emul_rw_completion(spx));
5866 	}
5867 
5868 	/*
5869 	 * Build cmd block depending on the device capability and
5870 	 * requested operation mode.
5871 	 * Do not bother with non-dma mode - we are working only with
5872 	 * devices supporting DMA.
5873 	 */
5874 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5875 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5876 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
5877 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5878 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5879 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
5880 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5881 #ifndef __lock_lint
5882 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5883 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5884 		scmd->satacmd_lba_high_msb = lba >> 40;
5885 #endif
5886 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5887 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5888 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5889 	}
5890 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5891 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5892 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5893 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5894 	scmd->satacmd_features_reg = 0;
5895 	scmd->satacmd_status_reg = 0;
5896 	scmd->satacmd_error_reg = 0;
5897 
5898 	/*
5899 	 * Check if queueing commands should be used and switch
5900 	 * to appropriate command if possible
5901 	 */
5902 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5903 		boolean_t using_queuing;
5904 
5905 		/* Queuing supported by controller and device? */
5906 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5907 		    (sdinfo->satadrv_features_support &
5908 		    SATA_DEV_F_NCQ) &&
5909 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5910 		    SATA_CTLF_NCQ)) {
5911 			using_queuing = B_TRUE;
5912 
5913 			/* NCQ supported - use FPDMA READ */
5914 			scmd->satacmd_cmd_reg =
5915 			    SATAC_READ_FPDMA_QUEUED;
5916 			scmd->satacmd_features_reg_ext =
5917 			    scmd->satacmd_sec_count_msb;
5918 			scmd->satacmd_sec_count_msb = 0;
5919 		} else if ((sdinfo->satadrv_features_support &
5920 		    SATA_DEV_F_TCQ) &&
5921 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5922 		    SATA_CTLF_QCMD)) {
5923 			using_queuing = B_TRUE;
5924 
5925 			/* Legacy queueing */
5926 			if (sdinfo->satadrv_features_support &
5927 			    SATA_DEV_F_LBA48) {
5928 				scmd->satacmd_cmd_reg =
5929 				    SATAC_READ_DMA_QUEUED_EXT;
5930 				scmd->satacmd_features_reg_ext =
5931 				    scmd->satacmd_sec_count_msb;
5932 				scmd->satacmd_sec_count_msb = 0;
5933 			} else {
5934 				scmd->satacmd_cmd_reg =
5935 				    SATAC_READ_DMA_QUEUED;
5936 			}
5937 		} else	/* NCQ nor legacy queuing not supported */
5938 			using_queuing = B_FALSE;
5939 
5940 		/*
5941 		 * If queuing, the sector count goes in the features register
5942 		 * and the secount count will contain the tag.
5943 		 */
5944 		if (using_queuing) {
5945 			scmd->satacmd_features_reg =
5946 			    scmd->satacmd_sec_count_lsb;
5947 			scmd->satacmd_sec_count_lsb = 0;
5948 			scmd->satacmd_flags.sata_queued = B_TRUE;
5949 
5950 			/* Set-up maximum queue depth */
5951 			scmd->satacmd_flags.sata_max_queue_depth =
5952 			    sdinfo->satadrv_max_queue_depth - 1;
5953 		} else if (sdinfo->satadrv_features_enabled &
5954 		    SATA_DEV_F_E_UNTAGGED_QING) {
5955 			/*
5956 			 * Although NCQ/TCQ is not enabled, untagged queuing
5957 			 * may be still used.
5958 			 * Set-up the maximum untagged queue depth.
5959 			 * Use controller's queue depth from sata_hba_tran.
5960 			 * SATA HBA drivers may ignore this value and rely on
5961 			 * the internal limits.For drivers that do not
5962 			 * ignore untaged queue depth, limit the value to
5963 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5964 			 * largest value that can be passed via
5965 			 * satacmd_flags.sata_max_queue_depth.
5966 			 */
5967 			scmd->satacmd_flags.sata_max_queue_depth =
5968 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5969 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5970 
5971 		} else {
5972 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5973 		}
5974 	} else
5975 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5976 
5977 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
5978 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
5979 	    scmd->satacmd_cmd_reg, lba, sec_count);
5980 
5981 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5982 		/* Need callback function */
5983 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5984 		synch = FALSE;
5985 	} else
5986 		synch = TRUE;
5987 
5988 	/* Transfer command to HBA */
5989 	if (sata_hba_start(spx, &rval) != 0) {
5990 		/* Pkt not accepted for execution */
5991 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5992 		return (rval);
5993 	}
5994 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5995 	/*
5996 	 * If execution is non-synchronous,
5997 	 * a callback function will handle potential errors, translate
5998 	 * the response and will do a callback to a target driver.
5999 	 * If it was synchronous, check execution status using the same
6000 	 * framework callback.
6001 	 */
6002 	if (synch) {
6003 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6004 		    "synchronous execution status %x\n",
6005 		    spx->txlt_sata_pkt->satapkt_reason);
6006 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
6007 	}
6008 	return (TRAN_ACCEPT);
6009 }
6010 
6011 
6012 /*
6013  * SATA translate command: Write (various types)
6014  * Translated into appropriate type of ATA WRITE command
6015  * for SATA hard disks.
6016  * Both the device capabilities and requested operation mode are
6017  * considered.
6018  *
6019  * Following scsi cdb fields are ignored:
6020  * rwprotect, dpo, fua, fua_nv, group_number.
6021  *
6022  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
6023  * enable variable sata_func_enable), the capability of the controller and
6024  * capability of a device are checked and if both support queueing, write
6025  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
6026  * command rather than plain WRITE_XXX command.
6027  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
6028  * both the controller and device suport such functionality, the write
6029  * request will be translated to WRITE_FPDMA_QUEUED command.
6030  * In both cases the maximum queue depth is derived as minimum of:
6031  * HBA capability,device capability and sata_max_queue_depth variable setting.
6032  * The value passed to HBA driver is decremented by 1, because only 5 bits are
6033  * used to pass max queue depth value, and the maximum possible queue depth
6034  * is 32.
6035  *
6036  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6037  * appropriate values in scsi_pkt fields.
6038  */
6039 static int
6040 sata_txlt_write(sata_pkt_txlate_t *spx)
6041 {
6042 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6043 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6044 	sata_drive_info_t *sdinfo;
6045 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6046 	int cport = SATA_TXLT_CPORT(spx);
6047 	uint16_t sec_count;
6048 	uint64_t lba;
6049 	int rval, reason;
6050 	int synch;
6051 
6052 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6053 
6054 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
6055 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6056 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6057 		return (rval);
6058 	}
6059 
6060 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
6061 	    &spx->txlt_sata_pkt->satapkt_device);
6062 
6063 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
6064 	/*
6065 	 * Extract LBA and sector count from scsi CDB
6066 	 */
6067 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
6068 	case SCMD_WRITE:
6069 		/* 6-byte scsi read cmd : 0x0A */
6070 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
6071 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
6072 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6073 		sec_count = scsipkt->pkt_cdbp[4];
6074 		/* sec_count 0 will be interpreted as 256 by a device */
6075 		break;
6076 	case SCMD_WRITE_G1:
6077 		/* 10-bytes scsi write command : 0x2A */
6078 		lba = scsipkt->pkt_cdbp[2];
6079 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6080 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6081 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6082 		sec_count = scsipkt->pkt_cdbp[7];
6083 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
6084 		break;
6085 	case SCMD_WRITE_G5:
6086 		/* 12-bytes scsi read command : 0xAA */
6087 		lba = scsipkt->pkt_cdbp[2];
6088 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6089 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6090 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6091 		sec_count = scsipkt->pkt_cdbp[6];
6092 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
6093 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
6094 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
6095 		break;
6096 	case SCMD_WRITE_G4:
6097 		/* 16-bytes scsi write command : 0x8A */
6098 		lba = scsipkt->pkt_cdbp[2];
6099 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
6100 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
6101 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
6102 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
6103 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
6104 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
6105 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
6106 		sec_count = scsipkt->pkt_cdbp[10];
6107 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
6108 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
6109 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
6110 		break;
6111 	default:
6112 		/* Unsupported command */
6113 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6114 		return (sata_txlt_invalid_command(spx));
6115 	}
6116 
6117 	/*
6118 	 * Check if specified address and length exceeds device capacity
6119 	 */
6120 	if ((lba >= sdinfo->satadrv_capacity) ||
6121 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
6122 		/* LBA out of range */
6123 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6124 		return (sata_txlt_lba_out_of_range(spx));
6125 	}
6126 
6127 	/*
6128 	 * For zero-length transfer, emulate good completion of the command
6129 	 * (reasons for rejecting the command were already checked).
6130 	 * No DMA resources were allocated.
6131 	 */
6132 	if (spx->txlt_dma_cookie_list == NULL) {
6133 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6134 		return (sata_emul_rw_completion(spx));
6135 	}
6136 
6137 	/*
6138 	 * Build cmd block depending on the device capability and
6139 	 * requested operation mode.
6140 	 * Do not bother with non-dma mode- we are working only with
6141 	 * devices supporting DMA.
6142 	 */
6143 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
6144 	scmd->satacmd_device_reg = SATA_ADH_LBA;
6145 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
6146 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
6147 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
6148 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
6149 		scmd->satacmd_sec_count_msb = sec_count >> 8;
6150 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
6151 #ifndef __lock_lint
6152 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
6153 		scmd->satacmd_lba_high_msb = lba >> 40;
6154 #endif
6155 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
6156 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
6157 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
6158 	}
6159 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
6160 	scmd->satacmd_lba_low_lsb = lba & 0xff;
6161 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
6162 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
6163 	scmd->satacmd_features_reg = 0;
6164 	scmd->satacmd_status_reg = 0;
6165 	scmd->satacmd_error_reg = 0;
6166 
6167 	/*
6168 	 * Check if queueing commands should be used and switch
6169 	 * to appropriate command if possible
6170 	 */
6171 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
6172 		boolean_t using_queuing;
6173 
6174 		/* Queuing supported by controller and device? */
6175 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
6176 		    (sdinfo->satadrv_features_support &
6177 		    SATA_DEV_F_NCQ) &&
6178 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6179 		    SATA_CTLF_NCQ)) {
6180 			using_queuing = B_TRUE;
6181 
6182 			/* NCQ supported - use FPDMA WRITE */
6183 			scmd->satacmd_cmd_reg =
6184 			    SATAC_WRITE_FPDMA_QUEUED;
6185 			scmd->satacmd_features_reg_ext =
6186 			    scmd->satacmd_sec_count_msb;
6187 			scmd->satacmd_sec_count_msb = 0;
6188 		} else if ((sdinfo->satadrv_features_support &
6189 		    SATA_DEV_F_TCQ) &&
6190 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
6191 		    SATA_CTLF_QCMD)) {
6192 			using_queuing = B_TRUE;
6193 
6194 			/* Legacy queueing */
6195 			if (sdinfo->satadrv_features_support &
6196 			    SATA_DEV_F_LBA48) {
6197 				scmd->satacmd_cmd_reg =
6198 				    SATAC_WRITE_DMA_QUEUED_EXT;
6199 				scmd->satacmd_features_reg_ext =
6200 				    scmd->satacmd_sec_count_msb;
6201 				scmd->satacmd_sec_count_msb = 0;
6202 			} else {
6203 				scmd->satacmd_cmd_reg =
6204 				    SATAC_WRITE_DMA_QUEUED;
6205 			}
6206 		} else	/*  NCQ nor legacy queuing not supported */
6207 			using_queuing = B_FALSE;
6208 
6209 		if (using_queuing) {
6210 			scmd->satacmd_features_reg =
6211 			    scmd->satacmd_sec_count_lsb;
6212 			scmd->satacmd_sec_count_lsb = 0;
6213 			scmd->satacmd_flags.sata_queued = B_TRUE;
6214 			/* Set-up maximum queue depth */
6215 			scmd->satacmd_flags.sata_max_queue_depth =
6216 			    sdinfo->satadrv_max_queue_depth - 1;
6217 		} else if (sdinfo->satadrv_features_enabled &
6218 		    SATA_DEV_F_E_UNTAGGED_QING) {
6219 			/*
6220 			 * Although NCQ/TCQ is not enabled, untagged queuing
6221 			 * may be still used.
6222 			 * Set-up the maximum untagged queue depth.
6223 			 * Use controller's queue depth from sata_hba_tran.
6224 			 * SATA HBA drivers may ignore this value and rely on
6225 			 * the internal limits. For drivera that do not
6226 			 * ignore untaged queue depth, limit the value to
6227 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
6228 			 * largest value that can be passed via
6229 			 * satacmd_flags.sata_max_queue_depth.
6230 			 */
6231 			scmd->satacmd_flags.sata_max_queue_depth =
6232 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
6233 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
6234 
6235 		} else {
6236 			scmd->satacmd_flags.sata_max_queue_depth = 0;
6237 		}
6238 	} else
6239 		scmd->satacmd_flags.sata_max_queue_depth = 0;
6240 
6241 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6242 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
6243 	    scmd->satacmd_cmd_reg, lba, sec_count);
6244 
6245 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6246 		/* Need callback function */
6247 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
6248 		synch = FALSE;
6249 	} else
6250 		synch = TRUE;
6251 
6252 	/* Transfer command to HBA */
6253 	if (sata_hba_start(spx, &rval) != 0) {
6254 		/* Pkt not accepted for execution */
6255 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6256 		return (rval);
6257 	}
6258 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6259 
6260 	/*
6261 	 * If execution is non-synchronous,
6262 	 * a callback function will handle potential errors, translate
6263 	 * the response and will do a callback to a target driver.
6264 	 * If it was synchronous, check execution status using the same
6265 	 * framework callback.
6266 	 */
6267 	if (synch) {
6268 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6269 		    "synchronous execution status %x\n",
6270 		    spx->txlt_sata_pkt->satapkt_reason);
6271 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
6272 	}
6273 	return (TRAN_ACCEPT);
6274 }
6275 
6276 
6277 /*
6278  * Implements SCSI SBC WRITE BUFFER command download microcode option
6279  */
6280 static int
6281 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
6282 {
6283 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
6284 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
6285 
6286 	sata_hba_inst_t *sata_hba_inst = SATA_TXLT_HBA_INST(spx);
6287 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6288 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
6289 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6290 
6291 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6292 	struct scsi_extended_sense *sense;
6293 	int rval, mode, sector_count, reason;
6294 	int cport = SATA_TXLT_CPORT(spx);
6295 
6296 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
6297 
6298 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6299 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
6300 
6301 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6302 
6303 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6304 	    TRAN_ACCEPT) {
6305 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6306 		return (rval);
6307 	}
6308 
6309 	/* Use synchronous mode */
6310 	spx->txlt_sata_pkt->satapkt_op_mode
6311 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
6312 
6313 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
6314 
6315 	scsipkt->pkt_reason = CMD_CMPLT;
6316 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6317 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6318 
6319 	/*
6320 	 * The SCSI to ATA translation specification only calls
6321 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
6322 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
6323 	 * ATA 8 (draft) got rid of download microcode for temp
6324 	 * and it is even optional for ATA 7, so it may be aborted.
6325 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
6326 	 * it is not specified and the buffer offset for SCSI is a 16-bit
6327 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
6328 	 * sectors.  Thus the offset really doesn't buy us anything.
6329 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
6330 	 * is revised, this can be revisisted.
6331 	 */
6332 	/* Reject not supported request */
6333 	switch (mode) {
6334 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
6335 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
6336 		break;
6337 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
6338 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
6339 		break;
6340 	default:
6341 		goto bad_param;
6342 	}
6343 
6344 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
6345 
6346 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
6347 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
6348 		goto bad_param;
6349 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
6350 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
6351 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
6352 	scmd->satacmd_lba_mid_lsb = 0;
6353 	scmd->satacmd_lba_high_lsb = 0;
6354 	scmd->satacmd_device_reg = 0;
6355 	spx->txlt_sata_pkt->satapkt_comp = NULL;
6356 	scmd->satacmd_addr_type = 0;
6357 
6358 	/* Transfer command to HBA */
6359 	if (sata_hba_start(spx, &rval) != 0) {
6360 		/* Pkt not accepted for execution */
6361 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6362 		return (rval);
6363 	}
6364 
6365 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6366 
6367 	/* Then we need synchronous check the status of the disk */
6368 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6369 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6370 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6371 		scsipkt->pkt_reason = CMD_CMPLT;
6372 
6373 		/* Download commmand succeed, so probe and identify device */
6374 		sata_reidentify_device(spx);
6375 	} else {
6376 		/* Something went wrong, microcode download command failed */
6377 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6378 		*scsipkt->pkt_scbp = STATUS_CHECK;
6379 		sense = sata_arq_sense(spx);
6380 		switch (sata_pkt->satapkt_reason) {
6381 		case SATA_PKT_PORT_ERROR:
6382 			/*
6383 			 * We have no device data. Assume no data transfered.
6384 			 */
6385 			sense->es_key = KEY_HARDWARE_ERROR;
6386 			break;
6387 
6388 		case SATA_PKT_DEV_ERROR:
6389 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6390 			    SATA_STATUS_ERR) {
6391 				/*
6392 				 * determine dev error reason from error
6393 				 * reg content
6394 				 */
6395 				sata_decode_device_error(spx, sense);
6396 				break;
6397 			}
6398 			/* No extended sense key - no info available */
6399 			break;
6400 
6401 		case SATA_PKT_TIMEOUT:
6402 			scsipkt->pkt_reason = CMD_TIMEOUT;
6403 			scsipkt->pkt_statistics |=
6404 			    STAT_TIMEOUT | STAT_DEV_RESET;
6405 			/* No extended sense key ? */
6406 			break;
6407 
6408 		case SATA_PKT_ABORTED:
6409 			scsipkt->pkt_reason = CMD_ABORTED;
6410 			scsipkt->pkt_statistics |= STAT_ABORTED;
6411 			/* No extended sense key ? */
6412 			break;
6413 
6414 		case SATA_PKT_RESET:
6415 			/* pkt aborted by an explicit reset from a host */
6416 			scsipkt->pkt_reason = CMD_RESET;
6417 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6418 			break;
6419 
6420 		default:
6421 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6422 			    "sata_txlt_nodata_cmd_completion: "
6423 			    "invalid packet completion reason %d",
6424 			    sata_pkt->satapkt_reason));
6425 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6426 			break;
6427 		}
6428 
6429 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6430 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6431 
6432 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6433 			/* scsi callback required */
6434 			scsi_hba_pkt_comp(scsipkt);
6435 	}
6436 	return (TRAN_ACCEPT);
6437 
6438 bad_param:
6439 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6440 	*scsipkt->pkt_scbp = STATUS_CHECK;
6441 	sense = sata_arq_sense(spx);
6442 	sense->es_key = KEY_ILLEGAL_REQUEST;
6443 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6444 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6445 	    scsipkt->pkt_comp != NULL) {
6446 		/* scsi callback required */
6447 		if (servicing_interrupt()) {
6448 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6449 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6450 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6451 				return (TRAN_BUSY);
6452 			}
6453 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6454 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6455 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6456 			/* Scheduling the callback failed */
6457 			return (TRAN_BUSY);
6458 		}
6459 	}
6460 	return (rval);
6461 }
6462 
6463 /*
6464  * Re-identify device after doing a firmware download.
6465  */
6466 static void
6467 sata_reidentify_device(sata_pkt_txlate_t *spx)
6468 {
6469 #define	DOWNLOAD_WAIT_TIME_SECS	60
6470 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
6471 	int rval;
6472 	int retry_cnt;
6473 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6474 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6475 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
6476 	sata_drive_info_t *sdinfo;
6477 
6478 	/*
6479 	 * Before returning good status, probe device.
6480 	 * Device probing will get IDENTIFY DEVICE data, if possible.
6481 	 * The assumption is that the new microcode is applied by the
6482 	 * device. It is a caller responsibility to verify this.
6483 	 */
6484 	for (retry_cnt = 0;
6485 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
6486 	    retry_cnt++) {
6487 		rval = sata_probe_device(sata_hba_inst, &sata_device);
6488 
6489 		if (rval == SATA_SUCCESS) { /* Set default features */
6490 			sdinfo = sata_get_device_info(sata_hba_inst,
6491 			    &sata_device);
6492 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
6493 			    SATA_SUCCESS) {
6494 				/* retry */
6495 				rval = sata_initialize_device(sata_hba_inst,
6496 				    sdinfo);
6497 				if (rval == SATA_RETRY)
6498 					sata_log(sata_hba_inst, CE_WARN,
6499 					    "SATA device at port %d pmport %d -"
6500 					    " default device features could not"
6501 					    " be set. Device may not operate "
6502 					    "as expected.",
6503 					    sata_device.satadev_addr.cport,
6504 					    sata_device.satadev_addr.pmport);
6505 			}
6506 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6507 				scsi_hba_pkt_comp(scsipkt);
6508 			return;
6509 		} else if (rval == SATA_RETRY) {
6510 			delay(drv_usectohz(1000000 *
6511 			    DOWNLOAD_WAIT_INTERVAL_SECS));
6512 			continue;
6513 		} else	/* failed - no reason to retry */
6514 			break;
6515 	}
6516 
6517 	/*
6518 	 * Something went wrong, device probing failed.
6519 	 */
6520 	SATA_LOG_D((sata_hba_inst, CE_WARN,
6521 	    "Cannot probe device after downloading microcode\n"));
6522 
6523 	/* Reset device to force retrying the probe. */
6524 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
6525 	    (SATA_DIP(sata_hba_inst), &sata_device);
6526 
6527 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6528 		scsi_hba_pkt_comp(scsipkt);
6529 }
6530 
6531 
6532 /*
6533  * Translate command: Synchronize Cache.
6534  * Translates into Flush Cache command for SATA hard disks.
6535  *
6536  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6537  * appropriate values in scsi_pkt fields.
6538  */
6539 static 	int
6540 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
6541 {
6542 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6543 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6544 	int cport = SATA_TXLT_CPORT(spx);
6545 	int rval, reason;
6546 	int synch;
6547 
6548 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6549 
6550 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6551 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6552 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6553 		return (rval);
6554 	}
6555 
6556 	scmd->satacmd_addr_type = 0;
6557 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
6558 	scmd->satacmd_device_reg = 0;
6559 	scmd->satacmd_sec_count_lsb = 0;
6560 	scmd->satacmd_lba_low_lsb = 0;
6561 	scmd->satacmd_lba_mid_lsb = 0;
6562 	scmd->satacmd_lba_high_lsb = 0;
6563 	scmd->satacmd_features_reg = 0;
6564 	scmd->satacmd_status_reg = 0;
6565 	scmd->satacmd_error_reg = 0;
6566 
6567 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6568 	    "sata_txlt_synchronize_cache\n", NULL);
6569 
6570 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6571 		/* Need to set-up a callback function */
6572 		spx->txlt_sata_pkt->satapkt_comp =
6573 		    sata_txlt_nodata_cmd_completion;
6574 		synch = FALSE;
6575 	} else
6576 		synch = TRUE;
6577 
6578 	/* Transfer command to HBA */
6579 	if (sata_hba_start(spx, &rval) != 0) {
6580 		/* Pkt not accepted for execution */
6581 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6582 		return (rval);
6583 	}
6584 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6585 
6586 	/*
6587 	 * If execution non-synchronous, it had to be completed
6588 	 * a callback function will handle potential errors, translate
6589 	 * the response and will do a callback to a target driver.
6590 	 * If it was synchronous, check status, using the same
6591 	 * framework callback.
6592 	 */
6593 	if (synch) {
6594 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6595 		    "synchronous execution status %x\n",
6596 		    spx->txlt_sata_pkt->satapkt_reason);
6597 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
6598 	}
6599 	return (TRAN_ACCEPT);
6600 }
6601 
6602 
6603 /*
6604  * Send pkt to SATA HBA driver
6605  *
6606  * This function may be called only if the operation is requested by scsi_pkt,
6607  * i.e. scsi_pkt is not NULL.
6608  *
6609  * This function has to be called with cport mutex held. It does release
6610  * the mutex when it calls HBA driver sata_tran_start function and
6611  * re-acquires it afterwards.
6612  *
6613  * If return value is 0, pkt was accepted, -1 otherwise
6614  * rval is set to appropriate sata_scsi_start return value.
6615  *
6616  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
6617  * have called the sata_pkt callback function for this packet.
6618  *
6619  * The scsi callback has to be performed by the caller of this routine.
6620  */
6621 static int
6622 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
6623 {
6624 	int stat;
6625 	uint8_t cport = SATA_TXLT_CPORT(spx);
6626 	uint8_t pmport = SATA_TXLT_PMPORT(spx);
6627 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6628 	sata_drive_info_t *sdinfo;
6629 	sata_pmult_info_t *pminfo;
6630 	sata_pmport_info_t *pmportinfo = NULL;
6631 	sata_device_t *sata_device = NULL;
6632 	uint8_t cmd;
6633 	struct sata_cmd_flags cmd_flags;
6634 
6635 	ASSERT(spx->txlt_sata_pkt != NULL);
6636 
6637 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6638 
6639 	sdinfo = sata_get_device_info(sata_hba_inst,
6640 	    &spx->txlt_sata_pkt->satapkt_device);
6641 	ASSERT(sdinfo != NULL);
6642 
6643 	/* Clear device reset state? */
6644 	/* qual should be XXX_DPMPORT, but add XXX_PMPORT in case */
6645 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT ||
6646 	    sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT) {
6647 
6648 		/*
6649 		 * Get the pmult_info of the its parent port multiplier, all
6650 		 * sub-devices share a common device reset flags on in
6651 		 * pmult_info.
6652 		 */
6653 		pminfo = SATA_PMULT_INFO(sata_hba_inst, cport);
6654 		pmportinfo = pminfo->pmult_dev_port[pmport];
6655 		ASSERT(pminfo != NULL);
6656 		if (pminfo->pmult_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
6657 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6658 			    sata_clear_dev_reset = B_TRUE;
6659 			pminfo->pmult_event_flags &=
6660 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6661 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6662 			    "sata_hba_start: clearing device reset state"
6663 			    "on pmult.\n", NULL);
6664 		}
6665 	} else {
6666 		if (sdinfo->satadrv_event_flags &
6667 		    SATA_EVNT_CLEAR_DEVICE_RESET) {
6668 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6669 			    sata_clear_dev_reset = B_TRUE;
6670 			sdinfo->satadrv_event_flags &=
6671 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6672 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6673 			    "sata_hba_start: clearing device reset state\n",
6674 			    NULL);
6675 		}
6676 	}
6677 
6678 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
6679 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
6680 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
6681 
6682 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6683 
6684 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6685 	    "Sata cmd 0x%2x\n", cmd);
6686 
6687 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
6688 	    spx->txlt_sata_pkt);
6689 
6690 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6691 	/*
6692 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
6693 	 * with the sata callback, the sata_pkt could be already destroyed
6694 	 * by the time we check ther return status from the hba_start()
6695 	 * function, because sata_scsi_destroy_pkt() could have been already
6696 	 * called (perhaps in the interrupt context). So, in such case, there
6697 	 * should be no references to it. In other cases, sata_pkt still
6698 	 * exists.
6699 	 */
6700 	if (stat == SATA_TRAN_ACCEPTED) {
6701 		/*
6702 		 * pkt accepted for execution.
6703 		 * If it was executed synchronously, it is already completed
6704 		 * and pkt completion_reason indicates completion status.
6705 		 */
6706 		*rval = TRAN_ACCEPT;
6707 		return (0);
6708 	}
6709 
6710 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6711 	switch (stat) {
6712 	case SATA_TRAN_QUEUE_FULL:
6713 		/*
6714 		 * Controller detected queue full condition.
6715 		 */
6716 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
6717 		    "sata_hba_start: queue full\n", NULL);
6718 
6719 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6720 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
6721 
6722 		*rval = TRAN_BUSY;
6723 		break;
6724 
6725 	case SATA_TRAN_PORT_ERROR:
6726 		/*
6727 		 * Communication/link with device or general port error
6728 		 * detected before pkt execution begun.
6729 		 */
6730 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6731 		    SATA_ADDR_CPORT ||
6732 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6733 		    SATA_ADDR_DCPORT)
6734 			sata_log(sata_hba_inst, CE_CONT,
6735 			    "SATA port %d error",
6736 			    sata_device->satadev_addr.cport);
6737 		else
6738 			sata_log(sata_hba_inst, CE_CONT,
6739 			    "SATA port %d:%d error\n",
6740 			    sata_device->satadev_addr.cport,
6741 			    sata_device->satadev_addr.pmport);
6742 
6743 		/*
6744 		 * Update the port/device structure.
6745 		 * sata_pkt should be still valid. Since port error is
6746 		 * returned, sata_device content should reflect port
6747 		 * state - it means, that sata address have been changed,
6748 		 * because original packet's sata address refered to a device
6749 		 * attached to some port.
6750 		 */
6751 		if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT ||
6752 		    sata_device->satadev_addr.qual == SATA_ADDR_PMPORT) {
6753 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6754 			mutex_enter(&pmportinfo->pmport_mutex);
6755 			sata_update_pmport_info(sata_hba_inst, sata_device);
6756 			mutex_exit(&pmportinfo->pmport_mutex);
6757 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6758 		} else {
6759 			sata_update_port_info(sata_hba_inst, sata_device);
6760 		}
6761 
6762 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6763 		*rval = TRAN_FATAL_ERROR;
6764 		break;
6765 
6766 	case SATA_TRAN_CMD_UNSUPPORTED:
6767 		/*
6768 		 * Command rejected by HBA as unsupported. It was HBA driver
6769 		 * that rejected the command, command was not sent to
6770 		 * an attached device.
6771 		 */
6772 		if ((sdinfo != NULL) &&
6773 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
6774 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6775 			    "sat_hba_start: cmd 0x%2x rejected "
6776 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
6777 
6778 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6779 		(void) sata_txlt_invalid_command(spx);
6780 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6781 
6782 		*rval = TRAN_ACCEPT;
6783 		break;
6784 
6785 	case SATA_TRAN_BUSY:
6786 		/*
6787 		 * Command rejected by HBA because other operation prevents
6788 		 * accepting the packet, or device is in RESET condition.
6789 		 */
6790 		if (sdinfo != NULL) {
6791 			sdinfo->satadrv_state =
6792 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
6793 
6794 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
6795 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6796 				    "sata_hba_start: cmd 0x%2x rejected "
6797 				    "because of device reset condition\n",
6798 				    cmd);
6799 			} else {
6800 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6801 				    "sata_hba_start: cmd 0x%2x rejected "
6802 				    "with SATA_TRAN_BUSY status\n",
6803 				    cmd);
6804 			}
6805 		}
6806 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6807 		*rval = TRAN_BUSY;
6808 		break;
6809 
6810 	default:
6811 		/* Unrecognized HBA response */
6812 		SATA_LOG_D((sata_hba_inst, CE_WARN,
6813 		    "sata_hba_start: unrecognized HBA response "
6814 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
6815 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6816 		*rval = TRAN_FATAL_ERROR;
6817 		break;
6818 	}
6819 
6820 	/*
6821 	 * If we got here, the packet was rejected.
6822 	 * Check if we need to remember reset state clearing request
6823 	 */
6824 	if (cmd_flags.sata_clear_dev_reset) {
6825 		/*
6826 		 * Check if device is still configured - it may have
6827 		 * disapeared from the configuration
6828 		 */
6829 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6830 		if (sdinfo != NULL) {
6831 			/*
6832 			 * Restore the flag that requests clearing of
6833 			 * the device reset state,
6834 			 * so the next sata packet may carry it to HBA.
6835 			 */
6836 			if (sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT ||
6837 			    sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT) {
6838 				pminfo->pmult_event_flags |=
6839 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6840 			} else {
6841 				sdinfo->satadrv_event_flags |=
6842 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6843 			}
6844 		}
6845 	}
6846 	return (-1);
6847 }
6848 
6849 /*
6850  * Scsi response setup for invalid LBA
6851  *
6852  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
6853  */
6854 static int
6855 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
6856 {
6857 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6858 	struct scsi_extended_sense *sense;
6859 
6860 	scsipkt->pkt_reason = CMD_CMPLT;
6861 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6862 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6863 	*scsipkt->pkt_scbp = STATUS_CHECK;
6864 
6865 	*scsipkt->pkt_scbp = STATUS_CHECK;
6866 	sense = sata_arq_sense(spx);
6867 	sense->es_key = KEY_ILLEGAL_REQUEST;
6868 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
6869 
6870 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6871 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6872 
6873 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6874 	    scsipkt->pkt_comp != NULL) {
6875 		/* scsi callback required */
6876 		if (servicing_interrupt()) {
6877 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6878 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6879 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
6880 				return (TRAN_BUSY);
6881 			}
6882 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6883 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
6884 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
6885 			/* Scheduling the callback failed */
6886 			return (TRAN_BUSY);
6887 		}
6888 	}
6889 	return (TRAN_ACCEPT);
6890 }
6891 
6892 
6893 /*
6894  * Analyze device status and error registers and translate them into
6895  * appropriate scsi sense codes.
6896  * NOTE: non-packet commands only for now
6897  */
6898 static void
6899 sata_decode_device_error(sata_pkt_txlate_t *spx,
6900     struct scsi_extended_sense *sense)
6901 {
6902 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
6903 
6904 	ASSERT(sense != NULL);
6905 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
6906 	    SATA_STATUS_ERR);
6907 
6908 
6909 	if (err_reg & SATA_ERROR_ICRC) {
6910 		sense->es_key = KEY_ABORTED_COMMAND;
6911 		sense->es_add_code = 0x08; /* Communication failure */
6912 		return;
6913 	}
6914 
6915 	if (err_reg & SATA_ERROR_UNC) {
6916 		sense->es_key = KEY_MEDIUM_ERROR;
6917 		/* Information bytes (LBA) need to be set by a caller */
6918 		return;
6919 	}
6920 
6921 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
6922 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
6923 		sense->es_key = KEY_UNIT_ATTENTION;
6924 		sense->es_add_code = 0x3a; /* No media present */
6925 		return;
6926 	}
6927 
6928 	if (err_reg & SATA_ERROR_IDNF) {
6929 		if (err_reg & SATA_ERROR_ABORT) {
6930 			sense->es_key = KEY_ABORTED_COMMAND;
6931 		} else {
6932 			sense->es_key = KEY_ILLEGAL_REQUEST;
6933 			sense->es_add_code = 0x21; /* LBA out of range */
6934 		}
6935 		return;
6936 	}
6937 
6938 	if (err_reg & SATA_ERROR_ABORT) {
6939 		ASSERT(spx->txlt_sata_pkt != NULL);
6940 		sense->es_key = KEY_ABORTED_COMMAND;
6941 		return;
6942 	}
6943 }
6944 
6945 /*
6946  * Extract error LBA from sata_pkt.satapkt_cmd register fields
6947  */
6948 static void
6949 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
6950 {
6951 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
6952 
6953 	*lba = 0;
6954 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
6955 		*lba = sata_cmd->satacmd_lba_high_msb;
6956 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
6957 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
6958 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
6959 		*lba = sata_cmd->satacmd_device_reg & 0xf;
6960 	}
6961 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
6962 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
6963 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
6964 }
6965 
6966 /*
6967  * This is fixed sense format - if LBA exceeds the info field size,
6968  * no valid info will be returned (valid bit in extended sense will
6969  * be set to 0).
6970  */
6971 static struct scsi_extended_sense *
6972 sata_arq_sense(sata_pkt_txlate_t *spx)
6973 {
6974 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6975 	struct scsi_arq_status *arqs;
6976 	struct scsi_extended_sense *sense;
6977 
6978 	/* Fill ARQ sense data */
6979 	scsipkt->pkt_state |= STATE_ARQ_DONE;
6980 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
6981 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
6982 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
6983 	arqs->sts_rqpkt_reason = CMD_CMPLT;
6984 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6985 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
6986 	arqs->sts_rqpkt_resid = 0;
6987 	sense = &arqs->sts_sensedata;
6988 	bzero(sense, sizeof (struct scsi_extended_sense));
6989 	sata_fixed_sense_data_preset(sense);
6990 	return (sense);
6991 }
6992 
6993 /*
6994  * ATA Pass Through support
6995  * Sets flags indicating that an invalid value was found in some
6996  * field in the command.  It could be something illegal according to
6997  * the SAT-2 spec or it could be a feature that is not (yet?)
6998  * supported.
6999  */
7000 static int
7001 sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *spx)
7002 {
7003 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7004 	struct scsi_extended_sense *sense = sata_arq_sense(spx);
7005 
7006 	scsipkt->pkt_reason = CMD_CMPLT;
7007 	*scsipkt->pkt_scbp = STATUS_CHECK;
7008 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7009 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7010 
7011 	sense = sata_arq_sense(spx);
7012 	sense->es_key = KEY_ILLEGAL_REQUEST;
7013 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7014 
7015 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
7016 	    scsipkt->pkt_comp != NULL) {
7017 		/* scsi callback required */
7018 		if (servicing_interrupt()) {
7019 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7020 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7021 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
7022 				return (TRAN_BUSY);
7023 			}
7024 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7025 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7026 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
7027 			/* Scheduling the callback failed */
7028 			return (TRAN_BUSY);
7029 		}
7030 	}
7031 
7032 	return (TRAN_ACCEPT);
7033 }
7034 
7035 /*
7036  * Emulated SATA Read/Write command completion for zero-length requests.
7037  * This request always succedes, so in synchronous mode it always returns
7038  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
7039  * callback cannot be scheduled.
7040  */
7041 static int
7042 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
7043 {
7044 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7045 
7046 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7047 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7048 	scsipkt->pkt_reason = CMD_CMPLT;
7049 	*scsipkt->pkt_scbp = STATUS_GOOD;
7050 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
7051 		/* scsi callback required - have to schedule it */
7052 		if (servicing_interrupt()) {
7053 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7054 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7055 			    (void *)spx->txlt_scsi_pkt, TQ_NOSLEEP) == NULL) {
7056 				return (TRAN_BUSY);
7057 			}
7058 		} else if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
7059 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
7060 		    (void *)spx->txlt_scsi_pkt, TQ_SLEEP) == NULL) {
7061 			/* Scheduling the callback failed */
7062 			return (TRAN_BUSY);
7063 		}
7064 	}
7065 	return (TRAN_ACCEPT);
7066 }
7067 
7068 
7069 /*
7070  * Translate completion status of SATA read/write commands into scsi response.
7071  * pkt completion_reason is checked to determine the completion status.
7072  * Do scsi callback if necessary.
7073  *
7074  * Note: this function may be called also for synchronously executed
7075  * commands.
7076  * This function may be used only if scsi_pkt is non-NULL.
7077  */
7078 static void
7079 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
7080 {
7081 	sata_pkt_txlate_t *spx =
7082 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7083 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7084 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7085 	struct scsi_extended_sense *sense;
7086 	uint64_t lba;
7087 	struct buf *bp;
7088 	int rval;
7089 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7090 		/* Normal completion */
7091 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7092 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
7093 		scsipkt->pkt_reason = CMD_CMPLT;
7094 		*scsipkt->pkt_scbp = STATUS_GOOD;
7095 		if (spx->txlt_tmp_buf != NULL) {
7096 			/* Temporary buffer was used */
7097 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7098 			if (bp->b_flags & B_READ) {
7099 				rval = ddi_dma_sync(
7100 				    spx->txlt_buf_dma_handle, 0, 0,
7101 				    DDI_DMA_SYNC_FORCPU);
7102 				ASSERT(rval == DDI_SUCCESS);
7103 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7104 				    bp->b_bcount);
7105 			}
7106 		}
7107 	} else {
7108 		/*
7109 		 * Something went wrong - analyze return
7110 		 */
7111 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7112 		    STATE_SENT_CMD | STATE_GOT_STATUS;
7113 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7114 		*scsipkt->pkt_scbp = STATUS_CHECK;
7115 		sense = sata_arq_sense(spx);
7116 		ASSERT(sense != NULL);
7117 
7118 		/*
7119 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
7120 		 * extract from device registers the failing LBA.
7121 		 */
7122 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
7123 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
7124 			    (scmd->satacmd_lba_mid_msb != 0 ||
7125 			    scmd->satacmd_lba_high_msb != 0)) {
7126 				/*
7127 				 * We have problem reporting this cmd LBA
7128 				 * in fixed sense data format, because of
7129 				 * the size of the scsi LBA fields.
7130 				 */
7131 				sense->es_valid = 0;
7132 			} else {
7133 				sata_extract_error_lba(spx, &lba);
7134 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
7135 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
7136 				sense->es_info_3 = (lba & 0xFF00) >> 8;
7137 				sense->es_info_4 = lba & 0xFF;
7138 			}
7139 		} else {
7140 			/* Invalid extended sense info */
7141 			sense->es_valid = 0;
7142 		}
7143 
7144 		switch (sata_pkt->satapkt_reason) {
7145 		case SATA_PKT_PORT_ERROR:
7146 			/* We may want to handle DEV GONE state as well */
7147 			/*
7148 			 * We have no device data. Assume no data transfered.
7149 			 */
7150 			sense->es_key = KEY_HARDWARE_ERROR;
7151 			break;
7152 
7153 		case SATA_PKT_DEV_ERROR:
7154 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7155 			    SATA_STATUS_ERR) {
7156 				/*
7157 				 * determine dev error reason from error
7158 				 * reg content
7159 				 */
7160 				sata_decode_device_error(spx, sense);
7161 				if (sense->es_key == KEY_MEDIUM_ERROR) {
7162 					switch (scmd->satacmd_cmd_reg) {
7163 					case SATAC_READ_DMA:
7164 					case SATAC_READ_DMA_EXT:
7165 					case SATAC_READ_DMA_QUEUED:
7166 					case SATAC_READ_DMA_QUEUED_EXT:
7167 					case SATAC_READ_FPDMA_QUEUED:
7168 						/* Unrecovered read error */
7169 						sense->es_add_code =
7170 						    SD_SCSI_ASC_UNREC_READ_ERR;
7171 						break;
7172 					case SATAC_WRITE_DMA:
7173 					case SATAC_WRITE_DMA_EXT:
7174 					case SATAC_WRITE_DMA_QUEUED:
7175 					case SATAC_WRITE_DMA_QUEUED_EXT:
7176 					case SATAC_WRITE_FPDMA_QUEUED:
7177 						/* Write error */
7178 						sense->es_add_code =
7179 						    SD_SCSI_ASC_WRITE_ERR;
7180 						break;
7181 					default:
7182 						/* Internal error */
7183 						SATA_LOG_D((
7184 						    spx->txlt_sata_hba_inst,
7185 						    CE_WARN,
7186 						    "sata_txlt_rw_completion :"
7187 						    "internal error - invalid "
7188 						    "command 0x%2x",
7189 						    scmd->satacmd_cmd_reg));
7190 						break;
7191 					}
7192 				}
7193 				break;
7194 			}
7195 			/* No extended sense key - no info available */
7196 			scsipkt->pkt_reason = CMD_INCOMPLETE;
7197 			break;
7198 
7199 		case SATA_PKT_TIMEOUT:
7200 			scsipkt->pkt_reason = CMD_TIMEOUT;
7201 			scsipkt->pkt_statistics |=
7202 			    STAT_TIMEOUT | STAT_DEV_RESET;
7203 			sense->es_key = KEY_ABORTED_COMMAND;
7204 			break;
7205 
7206 		case SATA_PKT_ABORTED:
7207 			scsipkt->pkt_reason = CMD_ABORTED;
7208 			scsipkt->pkt_statistics |= STAT_ABORTED;
7209 			sense->es_key = KEY_ABORTED_COMMAND;
7210 			break;
7211 
7212 		case SATA_PKT_RESET:
7213 			scsipkt->pkt_reason = CMD_RESET;
7214 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7215 			sense->es_key = KEY_ABORTED_COMMAND;
7216 			break;
7217 
7218 		default:
7219 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7220 			    "sata_txlt_rw_completion: "
7221 			    "invalid packet completion reason"));
7222 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7223 			break;
7224 		}
7225 	}
7226 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7227 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7228 
7229 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7230 		/* scsi callback required */
7231 		scsi_hba_pkt_comp(scsipkt);
7232 }
7233 
7234 
7235 /*
7236  * Translate completion status of non-data commands (i.e. commands returning
7237  * no data).
7238  * pkt completion_reason is checked to determine the completion status.
7239  * Do scsi callback if necessary (FLAG_NOINTR == 0)
7240  *
7241  * Note: this function may be called also for synchronously executed
7242  * commands.
7243  * This function may be used only if scsi_pkt is non-NULL.
7244  */
7245 
7246 static	void
7247 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
7248 {
7249 	sata_pkt_txlate_t *spx =
7250 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7251 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7252 
7253 	sata_set_arq_data(sata_pkt);
7254 
7255 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7256 		/* scsi callback required */
7257 		scsi_hba_pkt_comp(scsipkt);
7258 }
7259 
7260 /*
7261  * Completion handler for ATA Pass Through command
7262  */
7263 static void
7264 sata_txlt_apt_completion(sata_pkt_t *sata_pkt)
7265 {
7266 	sata_pkt_txlate_t *spx =
7267 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7268 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7269 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7270 	struct buf *bp;
7271 	uint8_t sense_key = 0, addl_sense_code = 0, addl_sense_qual = 0;
7272 
7273 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7274 		/* Normal completion */
7275 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7276 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
7277 		scsipkt->pkt_reason = CMD_CMPLT;
7278 		*scsipkt->pkt_scbp = STATUS_GOOD;
7279 
7280 		/*
7281 		 * If the command has CK_COND set
7282 		 */
7283 		if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
7284 			*scsipkt->pkt_scbp = STATUS_CHECK;
7285 			sata_fill_ata_return_desc(sata_pkt,
7286 			    KEY_RECOVERABLE_ERROR,
7287 			    SD_SCSI_ASC_ATP_INFO_AVAIL, 0);
7288 		}
7289 
7290 		if (spx->txlt_tmp_buf != NULL) {
7291 			/* Temporary buffer was used */
7292 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
7293 			if (bp->b_flags & B_READ) {
7294 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
7295 				    bp->b_bcount);
7296 			}
7297 		}
7298 	} else {
7299 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7300 		    STATE_SENT_CMD | STATE_GOT_STATUS;
7301 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7302 		*scsipkt->pkt_scbp = STATUS_CHECK;
7303 
7304 		/*
7305 		 * If DF or ERR was set, the HBA should have copied out the
7306 		 * status and error registers to the satacmd structure.
7307 		 */
7308 		if (scmd->satacmd_status_reg & SATA_STATUS_DF) {
7309 			sense_key = KEY_HARDWARE_ERROR;
7310 			addl_sense_code = SD_SCSI_ASC_INTERNAL_TARGET_FAILURE;
7311 			addl_sense_qual = 0;
7312 		} else if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
7313 			if (scmd->satacmd_error_reg & SATA_ERROR_NM) {
7314 				sense_key = KEY_NOT_READY;
7315 				addl_sense_code =
7316 				    SD_SCSI_ASC_MEDIUM_NOT_PRESENT;
7317 				addl_sense_qual = 0;
7318 			} else if (scmd->satacmd_error_reg & SATA_ERROR_UNC) {
7319 				sense_key = KEY_MEDIUM_ERROR;
7320 				addl_sense_code = SD_SCSI_ASC_UNREC_READ_ERR;
7321 				addl_sense_qual = 0;
7322 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ILI) {
7323 				sense_key = KEY_DATA_PROTECT;
7324 				addl_sense_code = SD_SCSI_ASC_WRITE_PROTECTED;
7325 				addl_sense_qual = 0;
7326 			} else if (scmd->satacmd_error_reg & SATA_ERROR_IDNF) {
7327 				sense_key = KEY_ILLEGAL_REQUEST;
7328 				addl_sense_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
7329 				addl_sense_qual = 0;
7330 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
7331 				sense_key = KEY_ABORTED_COMMAND;
7332 				addl_sense_code = SD_SCSI_ASC_NO_ADD_SENSE;
7333 				addl_sense_qual = 0;
7334 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MC) {
7335 				sense_key = KEY_UNIT_ATTENTION;
7336 				addl_sense_code =
7337 				    SD_SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED;
7338 				addl_sense_qual = 0;
7339 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MCR) {
7340 				sense_key = KEY_UNIT_ATTENTION;
7341 				addl_sense_code = SD_SCSI_ASC_OP_MEDIUM_REM_REQ;
7342 				addl_sense_qual = 0;
7343 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ICRC) {
7344 				sense_key = KEY_ABORTED_COMMAND;
7345 				addl_sense_code =
7346 				    SD_SCSI_ASC_INFO_UNIT_IUCRC_ERR;
7347 				addl_sense_qual = 0;
7348 			}
7349 		}
7350 
7351 		sata_fill_ata_return_desc(sata_pkt, sense_key, addl_sense_code,
7352 		    addl_sense_qual);
7353 	}
7354 
7355 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7356 		/* scsi callback required */
7357 		scsi_hba_pkt_comp(scsipkt);
7358 }
7359 
7360 /*
7361  * j
7362  */
7363 static void
7364 sata_fill_ata_return_desc(sata_pkt_t *sata_pkt, uint8_t sense_key,
7365     uint8_t addl_sense_code, uint8_t addl_sense_qual)
7366 {
7367 	sata_pkt_txlate_t *spx =
7368 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7369 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7370 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7371 	struct sata_apt_sense_data *apt_sd =
7372 	    (struct sata_apt_sense_data *)scsipkt->pkt_scbp;
7373 	struct scsi_descr_sense_hdr *sds = &(apt_sd->apt_sd_hdr);
7374 	struct scsi_ata_status_ret_sense_descr *ata_ret_desc =
7375 	    &(apt_sd->apt_sd_sense);
7376 	int extend = 0;
7377 
7378 	if ((scsipkt->pkt_cdbp[0] == SPC3_CMD_ATA_COMMAND_PASS_THROUGH16) &&
7379 	    (scsipkt->pkt_cdbp[2] & SATL_APT_BM_EXTEND))
7380 		extend = 1;
7381 
7382 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7383 
7384 	/* update the residual count */
7385 	*(uchar_t *)&apt_sd->apt_status = STATUS_CHECK;
7386 	*(uchar_t *)&apt_sd->apt_rqpkt_status = STATUS_GOOD;
7387 	apt_sd->apt_rqpkt_reason = CMD_CMPLT;
7388 	apt_sd->apt_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7389 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7390 	apt_sd->apt_rqpkt_resid = scsipkt->pkt_scblen -
7391 	    sizeof (struct sata_apt_sense_data);
7392 
7393 	/*
7394 	 * Fill in the Descriptor sense header
7395 	 */
7396 	bzero(sds, sizeof (struct scsi_descr_sense_hdr));
7397 	sds->ds_code = CODE_FMT_DESCR_CURRENT;
7398 	sds->ds_class = CLASS_EXTENDED_SENSE;
7399 	sds->ds_key = sense_key & 0xf;
7400 	sds->ds_add_code = addl_sense_code;
7401 	sds->ds_qual_code = addl_sense_qual;
7402 	sds->ds_addl_sense_length =
7403 	    sizeof (struct scsi_ata_status_ret_sense_descr);
7404 
7405 	/*
7406 	 * Fill in the ATA Return descriptor sense data
7407 	 */
7408 	bzero(ata_ret_desc, sizeof (struct scsi_ata_status_ret_sense_descr));
7409 	ata_ret_desc->ars_descr_type = DESCR_ATA_STATUS_RETURN;
7410 	ata_ret_desc->ars_addl_length = 0xc;
7411 	ata_ret_desc->ars_error = scmd->satacmd_error_reg;
7412 	ata_ret_desc->ars_sec_count_lsb = scmd->satacmd_sec_count_lsb;
7413 	ata_ret_desc->ars_lba_low_lsb = scmd->satacmd_lba_low_lsb;
7414 	ata_ret_desc->ars_lba_mid_lsb = scmd->satacmd_lba_mid_lsb;
7415 	ata_ret_desc->ars_lba_high_lsb = scmd->satacmd_lba_high_lsb;
7416 	ata_ret_desc->ars_device = scmd->satacmd_device_reg;
7417 	ata_ret_desc->ars_status = scmd->satacmd_status_reg;
7418 
7419 	if (extend == 1) {
7420 		ata_ret_desc->ars_extend = 1;
7421 		ata_ret_desc->ars_sec_count_msb = scmd->satacmd_sec_count_msb;
7422 		ata_ret_desc->ars_lba_low_msb = scmd->satacmd_lba_low_msb;
7423 		ata_ret_desc->ars_lba_mid_msb = scmd->satacmd_lba_mid_msb;
7424 		ata_ret_desc->ars_lba_high_msb = scmd->satacmd_lba_high_msb;
7425 	} else {
7426 		ata_ret_desc->ars_extend = 0;
7427 		ata_ret_desc->ars_sec_count_msb = 0;
7428 		ata_ret_desc->ars_lba_low_msb = 0;
7429 		ata_ret_desc->ars_lba_mid_msb = 0;
7430 		ata_ret_desc->ars_lba_high_msb = 0;
7431 	}
7432 }
7433 
7434 static	void
7435 sata_set_arq_data(sata_pkt_t *sata_pkt)
7436 {
7437 	sata_pkt_txlate_t *spx =
7438 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7439 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7440 	struct scsi_extended_sense *sense;
7441 
7442 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7443 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7444 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7445 		/* Normal completion */
7446 		scsipkt->pkt_reason = CMD_CMPLT;
7447 		*scsipkt->pkt_scbp = STATUS_GOOD;
7448 	} else {
7449 		/* Something went wrong */
7450 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7451 		*scsipkt->pkt_scbp = STATUS_CHECK;
7452 		sense = sata_arq_sense(spx);
7453 		switch (sata_pkt->satapkt_reason) {
7454 		case SATA_PKT_PORT_ERROR:
7455 			/*
7456 			 * We have no device data. Assume no data transfered.
7457 			 */
7458 			sense->es_key = KEY_HARDWARE_ERROR;
7459 			break;
7460 
7461 		case SATA_PKT_DEV_ERROR:
7462 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7463 			    SATA_STATUS_ERR) {
7464 				/*
7465 				 * determine dev error reason from error
7466 				 * reg content
7467 				 */
7468 				sata_decode_device_error(spx, sense);
7469 				break;
7470 			}
7471 			/* No extended sense key - no info available */
7472 			break;
7473 
7474 		case SATA_PKT_TIMEOUT:
7475 			scsipkt->pkt_reason = CMD_TIMEOUT;
7476 			scsipkt->pkt_statistics |=
7477 			    STAT_TIMEOUT | STAT_DEV_RESET;
7478 			/* No extended sense key ? */
7479 			break;
7480 
7481 		case SATA_PKT_ABORTED:
7482 			scsipkt->pkt_reason = CMD_ABORTED;
7483 			scsipkt->pkt_statistics |= STAT_ABORTED;
7484 			/* No extended sense key ? */
7485 			break;
7486 
7487 		case SATA_PKT_RESET:
7488 			/* pkt aborted by an explicit reset from a host */
7489 			scsipkt->pkt_reason = CMD_RESET;
7490 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7491 			break;
7492 
7493 		default:
7494 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7495 			    "sata_txlt_nodata_cmd_completion: "
7496 			    "invalid packet completion reason %d",
7497 			    sata_pkt->satapkt_reason));
7498 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7499 			break;
7500 		}
7501 
7502 	}
7503 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7504 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7505 }
7506 
7507 
7508 /*
7509  * Build Mode sense R/W recovery page
7510  * NOT IMPLEMENTED
7511  */
7512 
7513 static int
7514 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7515 {
7516 #ifndef __lock_lint
7517 	_NOTE(ARGUNUSED(sdinfo))
7518 	_NOTE(ARGUNUSED(pcntrl))
7519 	_NOTE(ARGUNUSED(buf))
7520 #endif
7521 	return (0);
7522 }
7523 
7524 /*
7525  * Build Mode sense caching page  -  scsi-3 implementation.
7526  * Page length distinguishes previous format from scsi-3 format.
7527  * buf must have space for 0x12 bytes.
7528  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
7529  *
7530  */
7531 static int
7532 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7533 {
7534 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
7535 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7536 
7537 	/*
7538 	 * Most of the fields are set to 0, being not supported and/or disabled
7539 	 */
7540 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
7541 
7542 	/* Saved paramters not supported */
7543 	if (pcntrl == 3)
7544 		return (0);
7545 	if (pcntrl == 0 || pcntrl == 2) {
7546 		/*
7547 		 * For now treat current and default parameters as same
7548 		 * That may have to change, if target driver will complain
7549 		 */
7550 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
7551 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7552 
7553 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
7554 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
7555 			page->dra = 1;		/* Read Ahead disabled */
7556 			page->rcd = 1;		/* Read Cache disabled */
7557 		}
7558 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
7559 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
7560 			page->wce = 1;		/* Write Cache enabled */
7561 	} else {
7562 		/* Changeable parameters */
7563 		page->mode_page.code = MODEPAGE_CACHING;
7564 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7565 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7566 			page->dra = 1;
7567 			page->rcd = 1;
7568 		}
7569 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
7570 			page->wce = 1;
7571 	}
7572 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7573 	    sizeof (struct mode_page));
7574 }
7575 
7576 /*
7577  * Build Mode sense exception cntrl page
7578  */
7579 static int
7580 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7581 {
7582 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
7583 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7584 
7585 	/*
7586 	 * Most of the fields are set to 0, being not supported and/or disabled
7587 	 */
7588 	bzero(buf, PAGELENGTH_INFO_EXCPT);
7589 
7590 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
7591 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
7592 
7593 	/* Indicate that this is page is saveable */
7594 	page->mode_page.ps = 1;
7595 
7596 	/*
7597 	 * We will return the same data for default, current and saved page.
7598 	 * The only changeable bit is dexcpt and that bit is required
7599 	 * by the ATA specification to be preserved across power cycles.
7600 	 */
7601 	if (pcntrl != 1) {
7602 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
7603 		page->mrie = MRIE_ONLY_ON_REQUEST;
7604 	}
7605 	else
7606 		page->dexcpt = 1;	/* Only changeable parameter */
7607 
7608 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page));
7609 }
7610 
7611 
7612 static int
7613 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7614 {
7615 	struct mode_acoustic_management *page =
7616 	    (struct mode_acoustic_management *)buf;
7617 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7618 
7619 	/*
7620 	 * Most of the fields are set to 0, being not supported and/or disabled
7621 	 */
7622 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
7623 
7624 	switch (pcntrl) {
7625 	case P_CNTRL_DEFAULT:
7626 		/*  default paramters not supported */
7627 		return (0);
7628 
7629 	case P_CNTRL_CURRENT:
7630 	case P_CNTRL_SAVED:
7631 		/* Saved and current are supported and are identical */
7632 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7633 		page->mode_page.length =
7634 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7635 		page->mode_page.ps = 1;
7636 
7637 		/* Word 83 indicates if feature is supported */
7638 		/* If feature is not supported */
7639 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
7640 			page->acoustic_manag_enable =
7641 			    ACOUSTIC_DISABLED;
7642 		} else {
7643 			page->acoustic_manag_enable =
7644 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
7645 			    != 0);
7646 			/* Word 94 inidicates the value */
7647 #ifdef	_LITTLE_ENDIAN
7648 			page->acoustic_manag_level =
7649 			    (uchar_t)sata_id->ai_acoustic;
7650 			page->vendor_recommended_value =
7651 			    sata_id->ai_acoustic >> 8;
7652 #else
7653 			page->acoustic_manag_level =
7654 			    sata_id->ai_acoustic >> 8;
7655 			page->vendor_recommended_value =
7656 			    (uchar_t)sata_id->ai_acoustic;
7657 #endif
7658 		}
7659 		break;
7660 
7661 	case P_CNTRL_CHANGEABLE:
7662 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7663 		page->mode_page.length =
7664 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7665 		page->mode_page.ps = 1;
7666 
7667 		/* Word 83 indicates if the feature is supported */
7668 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
7669 			page->acoustic_manag_enable =
7670 			    ACOUSTIC_ENABLED;
7671 			page->acoustic_manag_level = 0xff;
7672 		}
7673 		break;
7674 	}
7675 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7676 	    sizeof (struct mode_page));
7677 }
7678 
7679 
7680 /*
7681  * Build Mode sense power condition page.
7682  */
7683 static int
7684 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7685 {
7686 	struct mode_info_power_cond *page = (struct mode_info_power_cond *)buf;
7687 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7688 
7689 	/*
7690 	 * Most of the fields are set to 0, being not supported and/or disabled
7691 	 * power condition page length was 0x0a
7692 	 */
7693 	bzero(buf, sizeof (struct mode_info_power_cond));
7694 
7695 	if (pcntrl == P_CNTRL_DEFAULT) {
7696 		/*  default paramters not supported */
7697 		return (0);
7698 	}
7699 
7700 	page->mode_page.code = MODEPAGE_POWER_COND;
7701 	page->mode_page.length = sizeof (struct mode_info_power_cond);
7702 
7703 	if (sata_id->ai_cap && SATA_STANDBYTIMER) {
7704 		page->standby = 1;
7705 		bcopy(sdinfo->satadrv_standby_timer, page->standby_cond_timer,
7706 		    sizeof (uchar_t) * 4);
7707 	}
7708 
7709 	return (sizeof (struct mode_info_power_cond));
7710 }
7711 
7712 /*
7713  * Process mode select caching page 8 (scsi3 format only).
7714  * Read Ahead (same as read cache) and Write Cache may be turned on and off
7715  * if these features are supported by the device. If these features are not
7716  * supported, the command will be terminated with STATUS_CHECK.
7717  * This function fails only if the SET FEATURE command sent to
7718  * the device fails. The page format is not varified, assuming that the
7719  * target driver operates correctly - if parameters length is too short,
7720  * we just drop the page.
7721  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
7722  * setting have to be changed.
7723  * SET FEATURE command is executed synchronously, i.e. we wait here until
7724  * it is completed, regardless of the scsi pkt directives.
7725  *
7726  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
7727  * changing DRA will change RCD.
7728  *
7729  * More than one SATA command may be executed to perform operations specified
7730  * by mode select pages. The first error terminates further execution.
7731  * Operations performed successully are not backed-up in such case.
7732  *
7733  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7734  * If operation resulted in changing device setup, dmod flag should be set to
7735  * one (1). If parameters were not changed, dmod flag should be set to 0.
7736  * Upon return, if operation required sending command to the device, the rval
7737  * should be set to the value returned by sata_hba_start. If operation
7738  * did not require device access, rval should be set to TRAN_ACCEPT.
7739  * The pagelen should be set to the length of the page.
7740  *
7741  * This function has to be called with a port mutex held.
7742  *
7743  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7744  */
7745 int
7746 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
7747     int parmlen, int *pagelen, int *rval, int *dmod)
7748 {
7749 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7750 	sata_drive_info_t *sdinfo;
7751 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7752 	sata_id_t *sata_id;
7753 	struct scsi_extended_sense *sense;
7754 	int wce, dra;	/* Current settings */
7755 
7756 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7757 	    &spx->txlt_sata_pkt->satapkt_device);
7758 	sata_id = &sdinfo->satadrv_id;
7759 	*dmod = 0;
7760 
7761 	/* Verify parameters length. If too short, drop it */
7762 	if ((PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7763 	    sizeof (struct mode_page)) > parmlen) {
7764 		*scsipkt->pkt_scbp = STATUS_CHECK;
7765 		sense = sata_arq_sense(spx);
7766 		sense->es_key = KEY_ILLEGAL_REQUEST;
7767 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7768 		*pagelen = parmlen;
7769 		*rval = TRAN_ACCEPT;
7770 		return (SATA_FAILURE);
7771 	}
7772 
7773 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
7774 
7775 	/* Current setting of Read Ahead (and Read Cache) */
7776 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
7777 		dra = 0;	/* 0 == not disabled */
7778 	else
7779 		dra = 1;
7780 	/* Current setting of Write Cache */
7781 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
7782 		wce = 1;
7783 	else
7784 		wce = 0;
7785 
7786 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
7787 		/* nothing to do */
7788 		*rval = TRAN_ACCEPT;
7789 		return (SATA_SUCCESS);
7790 	}
7791 
7792 	/*
7793 	 * Need to flip some setting
7794 	 * Set-up Internal SET FEATURES command(s)
7795 	 */
7796 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7797 	scmd->satacmd_addr_type = 0;
7798 	scmd->satacmd_device_reg = 0;
7799 	scmd->satacmd_status_reg = 0;
7800 	scmd->satacmd_error_reg = 0;
7801 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7802 	if (page->dra != dra || page->rcd != dra) {
7803 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7804 			/* Need to flip read ahead setting */
7805 			if (dra == 0)
7806 				/* Disable read ahead / read cache */
7807 				scmd->satacmd_features_reg =
7808 				    SATAC_SF_DISABLE_READ_AHEAD;
7809 			else
7810 				/* Enable read ahead  / read cache */
7811 				scmd->satacmd_features_reg =
7812 				    SATAC_SF_ENABLE_READ_AHEAD;
7813 
7814 			/* Transfer command to HBA */
7815 			if (sata_hba_start(spx, rval) != 0)
7816 				/*
7817 				 * Pkt not accepted for execution.
7818 				 */
7819 				return (SATA_FAILURE);
7820 
7821 			*dmod = 1;
7822 
7823 			/* Now process return */
7824 			if (spx->txlt_sata_pkt->satapkt_reason !=
7825 			    SATA_PKT_COMPLETED) {
7826 				goto failure;	/* Terminate */
7827 			}
7828 		} else {
7829 			*scsipkt->pkt_scbp = STATUS_CHECK;
7830 			sense = sata_arq_sense(spx);
7831 			sense->es_key = KEY_ILLEGAL_REQUEST;
7832 			sense->es_add_code =
7833 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7834 			*pagelen = parmlen;
7835 			*rval = TRAN_ACCEPT;
7836 			return (SATA_FAILURE);
7837 		}
7838 	}
7839 
7840 	/* Note that the packet is not removed, so it could be re-used */
7841 	if (page->wce != wce) {
7842 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
7843 			/* Need to flip Write Cache setting */
7844 			if (page->wce == 1)
7845 				/* Enable write cache */
7846 				scmd->satacmd_features_reg =
7847 				    SATAC_SF_ENABLE_WRITE_CACHE;
7848 			else
7849 				/* Disable write cache */
7850 				scmd->satacmd_features_reg =
7851 				    SATAC_SF_DISABLE_WRITE_CACHE;
7852 
7853 			/* Transfer command to HBA */
7854 			if (sata_hba_start(spx, rval) != 0)
7855 				/*
7856 				 * Pkt not accepted for execution.
7857 				 */
7858 				return (SATA_FAILURE);
7859 
7860 			*dmod = 1;
7861 
7862 			/* Now process return */
7863 			if (spx->txlt_sata_pkt->satapkt_reason !=
7864 			    SATA_PKT_COMPLETED) {
7865 				goto failure;
7866 			}
7867 		} else {
7868 			*scsipkt->pkt_scbp = STATUS_CHECK;
7869 			sense = sata_arq_sense(spx);
7870 			sense->es_key = KEY_ILLEGAL_REQUEST;
7871 			sense->es_add_code =
7872 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7873 			*pagelen = parmlen;
7874 			*rval = TRAN_ACCEPT;
7875 			return (SATA_FAILURE);
7876 		}
7877 	}
7878 	return (SATA_SUCCESS);
7879 
7880 failure:
7881 	sata_xlate_errors(spx);
7882 
7883 	return (SATA_FAILURE);
7884 }
7885 
7886 /*
7887  * Process mode select informational exceptions control page 0x1c
7888  *
7889  * The only changeable bit is dexcpt (disable exceptions).
7890  * MRIE (method of reporting informational exceptions) must be
7891  * "only on request".
7892  * This page applies to informational exceptions that report
7893  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
7894  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
7895  * Informational exception conditions occur as the result of background scan
7896  * errors, background self-test errors, or vendor specific events within a
7897  * logical unit. An informational exception condition may occur asynchronous
7898  * to any commands.
7899  *
7900  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7901  * If operation resulted in changing device setup, dmod flag should be set to
7902  * one (1). If parameters were not changed, dmod flag should be set to 0.
7903  * Upon return, if operation required sending command to the device, the rval
7904  * should be set to the value returned by sata_hba_start. If operation
7905  * did not require device access, rval should be set to TRAN_ACCEPT.
7906  * The pagelen should be set to the length of the page.
7907  *
7908  * This function has to be called with a port mutex held.
7909  *
7910  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7911  *
7912  * Cannot be called in the interrupt context.
7913  */
7914 static	int
7915 sata_mode_select_page_1c(
7916 	sata_pkt_txlate_t *spx,
7917 	struct mode_info_excpt_page *page,
7918 	int parmlen,
7919 	int *pagelen,
7920 	int *rval,
7921 	int *dmod)
7922 {
7923 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7924 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7925 	sata_drive_info_t *sdinfo;
7926 	sata_id_t *sata_id;
7927 	struct scsi_extended_sense *sense;
7928 
7929 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7930 	    &spx->txlt_sata_pkt->satapkt_device);
7931 	sata_id = &sdinfo->satadrv_id;
7932 
7933 	*dmod = 0;
7934 
7935 	/* Verify parameters length. If too short, drop it */
7936 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) > parmlen) ||
7937 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
7938 		*scsipkt->pkt_scbp = STATUS_CHECK;
7939 		sense = sata_arq_sense(spx);
7940 		sense->es_key = KEY_ILLEGAL_REQUEST;
7941 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7942 		*pagelen = parmlen;
7943 		*rval = TRAN_ACCEPT;
7944 		return (SATA_FAILURE);
7945 	}
7946 
7947 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
7948 
7949 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
7950 		*scsipkt->pkt_scbp = STATUS_CHECK;
7951 		sense = sata_arq_sense(spx);
7952 		sense->es_key = KEY_ILLEGAL_REQUEST;
7953 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7954 		*pagelen = parmlen;
7955 		*rval = TRAN_ACCEPT;
7956 		return (SATA_FAILURE);
7957 	}
7958 
7959 	/* If already in the state requested, we are done */
7960 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
7961 		/* nothing to do */
7962 		*rval = TRAN_ACCEPT;
7963 		return (SATA_SUCCESS);
7964 	}
7965 
7966 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7967 
7968 	/* Build SMART_ENABLE or SMART_DISABLE command */
7969 	scmd->satacmd_addr_type = 0;		/* N/A */
7970 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
7971 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
7972 	scmd->satacmd_features_reg = page->dexcpt ?
7973 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
7974 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
7975 	scmd->satacmd_cmd_reg = SATAC_SMART;
7976 
7977 	/* Transfer command to HBA */
7978 	if (sata_hba_start(spx, rval) != 0)
7979 		/*
7980 		 * Pkt not accepted for execution.
7981 		 */
7982 		return (SATA_FAILURE);
7983 
7984 	*dmod = 1;	/* At least may have been modified */
7985 
7986 	/* Now process return */
7987 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
7988 		return (SATA_SUCCESS);
7989 
7990 	/* Packet did not complete successfully */
7991 	sata_xlate_errors(spx);
7992 
7993 	return (SATA_FAILURE);
7994 }
7995 
7996 /*
7997  * Process mode select acoustic management control page 0x30
7998  *
7999  *
8000  * This function has to be called with a port mutex held.
8001  *
8002  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
8003  *
8004  * Cannot be called in the interrupt context.
8005  */
8006 int
8007 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
8008     mode_acoustic_management *page, int parmlen, int *pagelen,
8009     int *rval, int *dmod)
8010 {
8011 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8012 	sata_drive_info_t *sdinfo;
8013 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8014 	sata_id_t *sata_id;
8015 	struct scsi_extended_sense *sense;
8016 
8017 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
8018 	    &spx->txlt_sata_pkt->satapkt_device);
8019 	sata_id = &sdinfo->satadrv_id;
8020 	*dmod = 0;
8021 
8022 	/* If parmlen is too short or the feature is not supported, drop it */
8023 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
8024 	    sizeof (struct mode_page)) > parmlen) ||
8025 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
8026 		*scsipkt->pkt_scbp = STATUS_CHECK;
8027 		sense = sata_arq_sense(spx);
8028 		sense->es_key = KEY_ILLEGAL_REQUEST;
8029 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8030 		*pagelen = parmlen;
8031 		*rval = TRAN_ACCEPT;
8032 		return (SATA_FAILURE);
8033 	}
8034 
8035 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
8036 	    sizeof (struct mode_page);
8037 
8038 	/*
8039 	 * We can enable and disable acoustice management and
8040 	 * set the acoustic management level.
8041 	 */
8042 
8043 	/*
8044 	 * Set-up Internal SET FEATURES command(s)
8045 	 */
8046 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
8047 	scmd->satacmd_addr_type = 0;
8048 	scmd->satacmd_device_reg = 0;
8049 	scmd->satacmd_status_reg = 0;
8050 	scmd->satacmd_error_reg = 0;
8051 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
8052 	if (page->acoustic_manag_enable) {
8053 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
8054 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
8055 	} else {	/* disabling acoustic management */
8056 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
8057 	}
8058 
8059 	/* Transfer command to HBA */
8060 	if (sata_hba_start(spx, rval) != 0)
8061 		/*
8062 		 * Pkt not accepted for execution.
8063 		 */
8064 		return (SATA_FAILURE);
8065 
8066 	/* Now process return */
8067 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
8068 		sata_xlate_errors(spx);
8069 		return (SATA_FAILURE);
8070 	}
8071 
8072 	*dmod = 1;
8073 
8074 	return (SATA_SUCCESS);
8075 }
8076 
8077 /*
8078  * Process mode select power condition page 0x1a
8079  *
8080  * This function has to be called with a port mutex held.
8081  *
8082  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
8083  *
8084  * Cannot be called in the interrupt context.
8085  */
8086 int
8087 sata_mode_select_page_1a(sata_pkt_txlate_t *spx, struct
8088     mode_info_power_cond *page, int parmlen, int *pagelen,
8089     int *rval, int *dmod)
8090 {
8091 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8092 	sata_drive_info_t *sdinfo;
8093 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8094 	sata_id_t *sata_id;
8095 	struct scsi_extended_sense *sense;
8096 	uint8_t ata_count;
8097 	int i, len;
8098 
8099 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
8100 	    &spx->txlt_sata_pkt->satapkt_device);
8101 	sata_id = &sdinfo->satadrv_id;
8102 	*dmod = 0;
8103 
8104 	len = sizeof (struct mode_info_power_cond);
8105 	len += sizeof (struct mode_page);
8106 
8107 	/* If parmlen is too short or the feature is not supported, drop it */
8108 	if ((len < parmlen) || (page->idle == 1) ||
8109 	    (!(sata_id->ai_cap && SATA_STANDBYTIMER) && page->standby == 1)) {
8110 		*scsipkt->pkt_scbp = STATUS_CHECK;
8111 		sense = sata_arq_sense(spx);
8112 		sense->es_key = KEY_ILLEGAL_REQUEST;
8113 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
8114 		*pagelen = parmlen;
8115 		*rval = TRAN_ACCEPT;
8116 		return (SATA_FAILURE);
8117 	}
8118 
8119 	*pagelen = len;
8120 
8121 	/*
8122 	 * Set-up Internal STANDBY command(s)
8123 	 */
8124 	if (page->standby == 0)
8125 		goto out;
8126 
8127 	ata_count = sata_get_standby_timer(page->standby_cond_timer);
8128 
8129 	scmd->satacmd_addr_type = 0;
8130 	scmd->satacmd_sec_count_lsb = ata_count;
8131 	scmd->satacmd_lba_low_lsb = 0;
8132 	scmd->satacmd_lba_mid_lsb = 0;
8133 	scmd->satacmd_lba_high_lsb = 0;
8134 	scmd->satacmd_features_reg = 0;
8135 	scmd->satacmd_device_reg = 0;
8136 	scmd->satacmd_status_reg = 0;
8137 	scmd->satacmd_cmd_reg = SATAC_STANDBY;
8138 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8139 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
8140 
8141 	/* Transfer command to HBA */
8142 	if (sata_hba_start(spx, rval) != 0) {
8143 		return (SATA_FAILURE);
8144 	} else {
8145 		if ((scmd->satacmd_error_reg != 0) ||
8146 		    (spx->txlt_sata_pkt->satapkt_reason !=
8147 		    SATA_PKT_COMPLETED)) {
8148 			sata_xlate_errors(spx);
8149 			return (SATA_FAILURE);
8150 		}
8151 	}
8152 
8153 	for (i = 0; i < 4; i++) {
8154 		sdinfo->satadrv_standby_timer[i] = page->standby_cond_timer[i];
8155 	}
8156 out:
8157 	*dmod = 1;
8158 	return (SATA_SUCCESS);
8159 }
8160 
8161 /*
8162  * sata_build_lsense_page0() is used to create the
8163  * SCSI LOG SENSE page 0 (supported log pages)
8164  *
8165  * Currently supported pages are 0, 0x10, 0x2f, 0x30 and 0x0e
8166  * (supported log pages, self-test results, informational exceptions
8167  * Sun vendor specific ATA SMART data, and start stop cycle counter).
8168  *
8169  * Takes a sata_drive_info t * and the address of a buffer
8170  * in which to create the page information.
8171  *
8172  * Returns the number of bytes valid in the buffer.
8173  */
8174 static	int
8175 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
8176 {
8177 	struct log_parameter *lpp = (struct log_parameter *)buf;
8178 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
8179 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
8180 	sata_id_t *sata_id = &sdinfo->satadrv_id;
8181 
8182 	lpp->param_code[0] = 0;
8183 	lpp->param_code[1] = 0;
8184 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8185 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
8186 
8187 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
8188 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
8189 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
8190 			++num_pages_supported;
8191 		}
8192 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
8193 		++num_pages_supported;
8194 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
8195 		++num_pages_supported;
8196 		*page_ptr++ = PAGE_CODE_START_STOP_CYCLE_COUNTER;
8197 		++num_pages_supported;
8198 	}
8199 
8200 	lpp->param_len = num_pages_supported;
8201 
8202 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
8203 	    num_pages_supported);
8204 }
8205 
8206 /*
8207  * sata_build_lsense_page_10() is used to create the
8208  * SCSI LOG SENSE page 0x10 (self-test results)
8209  *
8210  * Takes a sata_drive_info t * and the address of a buffer
8211  * in which to create the page information as well as a sata_hba_inst_t *.
8212  *
8213  * Returns the number of bytes valid in the buffer.
8214  *
8215  * Note: Self test and SMART data is accessible in device log pages.
8216  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
8217  * of data can be transferred by a single command), or by the General Purpose
8218  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
8219  * - approximately 33MB - can be transferred by a single command.
8220  * The SCT Command response (either error or command) is the same for both
8221  * the SMART and GPL methods of issuing commands.
8222  * This function uses READ LOG EXT command when drive supports LBA48, and
8223  * SMART READ command otherwise.
8224  *
8225  * Since above commands are executed in a synchronous mode, this function
8226  * should not be called in an interrupt context.
8227  */
8228 static	int
8229 sata_build_lsense_page_10(
8230 	sata_drive_info_t *sdinfo,
8231 	uint8_t *buf,
8232 	sata_hba_inst_t *sata_hba_inst)
8233 {
8234 	struct log_parameter *lpp = (struct log_parameter *)buf;
8235 	int rval;
8236 
8237 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
8238 		struct smart_ext_selftest_log *ext_selftest_log;
8239 
8240 		ext_selftest_log = kmem_zalloc(
8241 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
8242 
8243 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
8244 		    ext_selftest_log, 0);
8245 		if (rval == 0) {
8246 			int index, start_index;
8247 			struct smart_ext_selftest_log_entry *entry;
8248 			static const struct smart_ext_selftest_log_entry empty =
8249 			    {0};
8250 			uint16_t block_num;
8251 			int count;
8252 			boolean_t only_one_block = B_FALSE;
8253 
8254 			index = ext_selftest_log->
8255 			    smart_ext_selftest_log_index[0];
8256 			index |= ext_selftest_log->
8257 			    smart_ext_selftest_log_index[1] << 8;
8258 			if (index == 0)
8259 				goto out;
8260 
8261 			--index;	/* Correct for 0 origin */
8262 			start_index = index;	/* remember where we started */
8263 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8264 			if (block_num != 0) {
8265 				rval = sata_ext_smart_selftest_read_log(
8266 				    sata_hba_inst, sdinfo, ext_selftest_log,
8267 				    block_num);
8268 				if (rval != 0)
8269 					goto out;
8270 			}
8271 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8272 			entry =
8273 			    &ext_selftest_log->
8274 			    smart_ext_selftest_log_entries[index];
8275 
8276 			for (count = 1;
8277 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8278 			    ++count) {
8279 				uint8_t status;
8280 				uint8_t code;
8281 				uint8_t sense_key;
8282 				uint8_t add_sense_code;
8283 				uint8_t add_sense_code_qual;
8284 
8285 				/* If this is an unused entry, we are done */
8286 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
8287 					/* Broken firmware on some disks */
8288 					if (index + 1 ==
8289 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
8290 						--entry;
8291 						--index;
8292 						if (bcmp(entry, &empty,
8293 						    sizeof (empty)) == 0)
8294 							goto out;
8295 					} else
8296 						goto out;
8297 				}
8298 
8299 				if (only_one_block &&
8300 				    start_index == index)
8301 					goto out;
8302 
8303 				lpp->param_code[0] = 0;
8304 				lpp->param_code[1] = count;
8305 				lpp->param_ctrl_flags =
8306 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8307 				lpp->param_len =
8308 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8309 
8310 				status = entry->smart_ext_selftest_log_status;
8311 				status >>= 4;
8312 				switch (status) {
8313 				case 0:
8314 				default:
8315 					sense_key = KEY_NO_SENSE;
8316 					add_sense_code =
8317 					    SD_SCSI_ASC_NO_ADD_SENSE;
8318 					add_sense_code_qual = 0;
8319 					break;
8320 				case 1:
8321 					sense_key = KEY_ABORTED_COMMAND;
8322 					add_sense_code =
8323 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8324 					add_sense_code_qual = SCSI_COMPONENT_81;
8325 					break;
8326 				case 2:
8327 					sense_key = KEY_ABORTED_COMMAND;
8328 					add_sense_code =
8329 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8330 					add_sense_code_qual = SCSI_COMPONENT_82;
8331 					break;
8332 				case 3:
8333 					sense_key = KEY_ABORTED_COMMAND;
8334 					add_sense_code =
8335 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8336 					add_sense_code_qual = SCSI_COMPONENT_83;
8337 					break;
8338 				case 4:
8339 					sense_key = KEY_HARDWARE_ERROR;
8340 					add_sense_code =
8341 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8342 					add_sense_code_qual = SCSI_COMPONENT_84;
8343 					break;
8344 				case 5:
8345 					sense_key = KEY_HARDWARE_ERROR;
8346 					add_sense_code =
8347 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8348 					add_sense_code_qual = SCSI_COMPONENT_85;
8349 					break;
8350 				case 6:
8351 					sense_key = KEY_HARDWARE_ERROR;
8352 					add_sense_code =
8353 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8354 					add_sense_code_qual = SCSI_COMPONENT_86;
8355 					break;
8356 				case 7:
8357 					sense_key = KEY_MEDIUM_ERROR;
8358 					add_sense_code =
8359 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8360 					add_sense_code_qual = SCSI_COMPONENT_87;
8361 					break;
8362 				case 8:
8363 					sense_key = KEY_HARDWARE_ERROR;
8364 					add_sense_code =
8365 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8366 					add_sense_code_qual = SCSI_COMPONENT_88;
8367 					break;
8368 				}
8369 				code = 0;	/* unspecified */
8370 				status |= (code << 4);
8371 				lpp->param_values[0] = status;
8372 				lpp->param_values[1] = 0; /* unspecified */
8373 				lpp->param_values[2] = entry->
8374 				    smart_ext_selftest_log_timestamp[1];
8375 				lpp->param_values[3] = entry->
8376 				    smart_ext_selftest_log_timestamp[0];
8377 				if (status != 0) {
8378 					lpp->param_values[4] = 0;
8379 					lpp->param_values[5] = 0;
8380 					lpp->param_values[6] = entry->
8381 					    smart_ext_selftest_log_failing_lba
8382 					    [5];
8383 					lpp->param_values[7] = entry->
8384 					    smart_ext_selftest_log_failing_lba
8385 					    [4];
8386 					lpp->param_values[8] = entry->
8387 					    smart_ext_selftest_log_failing_lba
8388 					    [3];
8389 					lpp->param_values[9] = entry->
8390 					    smart_ext_selftest_log_failing_lba
8391 					    [2];
8392 					lpp->param_values[10] = entry->
8393 					    smart_ext_selftest_log_failing_lba
8394 					    [1];
8395 					lpp->param_values[11] = entry->
8396 					    smart_ext_selftest_log_failing_lba
8397 					    [0];
8398 				} else {	/* No bad block address */
8399 					lpp->param_values[4] = 0xff;
8400 					lpp->param_values[5] = 0xff;
8401 					lpp->param_values[6] = 0xff;
8402 					lpp->param_values[7] = 0xff;
8403 					lpp->param_values[8] = 0xff;
8404 					lpp->param_values[9] = 0xff;
8405 					lpp->param_values[10] = 0xff;
8406 					lpp->param_values[11] = 0xff;
8407 				}
8408 
8409 				lpp->param_values[12] = sense_key;
8410 				lpp->param_values[13] = add_sense_code;
8411 				lpp->param_values[14] = add_sense_code_qual;
8412 				lpp->param_values[15] = 0; /* undefined */
8413 
8414 				lpp = (struct log_parameter *)
8415 				    (((uint8_t *)lpp) +
8416 				    SCSI_LOG_PARAM_HDR_LEN +
8417 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8418 
8419 				--index;	/* Back up to previous entry */
8420 				if (index < 0) {
8421 					if (block_num > 0) {
8422 						--block_num;
8423 					} else {
8424 						struct read_log_ext_directory
8425 						    logdir;
8426 
8427 						rval =
8428 						    sata_read_log_ext_directory(
8429 						    sata_hba_inst, sdinfo,
8430 						    &logdir);
8431 						if (rval == -1)
8432 							goto out;
8433 						if ((logdir.read_log_ext_vers
8434 						    [0] == 0) &&
8435 						    (logdir.read_log_ext_vers
8436 						    [1] == 0))
8437 							goto out;
8438 						block_num =
8439 						    logdir.read_log_ext_nblks
8440 						    [EXT_SMART_SELFTEST_LOG_PAGE
8441 						    - 1][0];
8442 						block_num |= logdir.
8443 						    read_log_ext_nblks
8444 						    [EXT_SMART_SELFTEST_LOG_PAGE
8445 						    - 1][1] << 8;
8446 						--block_num;
8447 						only_one_block =
8448 						    (block_num == 0);
8449 					}
8450 					rval = sata_ext_smart_selftest_read_log(
8451 					    sata_hba_inst, sdinfo,
8452 					    ext_selftest_log, block_num);
8453 					if (rval != 0)
8454 						goto out;
8455 
8456 					index =
8457 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
8458 					    1;
8459 				}
8460 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8461 				entry = &ext_selftest_log->
8462 				    smart_ext_selftest_log_entries[index];
8463 			}
8464 		}
8465 out:
8466 		kmem_free(ext_selftest_log,
8467 		    sizeof (struct smart_ext_selftest_log));
8468 	} else {
8469 		struct smart_selftest_log *selftest_log;
8470 
8471 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
8472 		    KM_SLEEP);
8473 
8474 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
8475 		    selftest_log);
8476 
8477 		if (rval == 0) {
8478 			int index;
8479 			int count;
8480 			struct smart_selftest_log_entry *entry;
8481 			static const struct smart_selftest_log_entry empty =
8482 			    { 0 };
8483 
8484 			index = selftest_log->smart_selftest_log_index;
8485 			if (index == 0)
8486 				goto done;
8487 			--index;	/* Correct for 0 origin */
8488 			entry = &selftest_log->
8489 			    smart_selftest_log_entries[index];
8490 			for (count = 1;
8491 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8492 			    ++count) {
8493 				uint8_t status;
8494 				uint8_t code;
8495 				uint8_t sense_key;
8496 				uint8_t add_sense_code;
8497 				uint8_t add_sense_code_qual;
8498 
8499 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
8500 					goto done;
8501 
8502 				lpp->param_code[0] = 0;
8503 				lpp->param_code[1] = count;
8504 				lpp->param_ctrl_flags =
8505 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8506 				lpp->param_len =
8507 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8508 
8509 				status = entry->smart_selftest_log_status;
8510 				status >>= 4;
8511 				switch (status) {
8512 				case 0:
8513 				default:
8514 					sense_key = KEY_NO_SENSE;
8515 					add_sense_code =
8516 					    SD_SCSI_ASC_NO_ADD_SENSE;
8517 					break;
8518 				case 1:
8519 					sense_key = KEY_ABORTED_COMMAND;
8520 					add_sense_code =
8521 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8522 					add_sense_code_qual = SCSI_COMPONENT_81;
8523 					break;
8524 				case 2:
8525 					sense_key = KEY_ABORTED_COMMAND;
8526 					add_sense_code =
8527 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8528 					add_sense_code_qual = SCSI_COMPONENT_82;
8529 					break;
8530 				case 3:
8531 					sense_key = KEY_ABORTED_COMMAND;
8532 					add_sense_code =
8533 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8534 					add_sense_code_qual = SCSI_COMPONENT_83;
8535 					break;
8536 				case 4:
8537 					sense_key = KEY_HARDWARE_ERROR;
8538 					add_sense_code =
8539 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8540 					add_sense_code_qual = SCSI_COMPONENT_84;
8541 					break;
8542 				case 5:
8543 					sense_key = KEY_HARDWARE_ERROR;
8544 					add_sense_code =
8545 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8546 					add_sense_code_qual = SCSI_COMPONENT_85;
8547 					break;
8548 				case 6:
8549 					sense_key = KEY_HARDWARE_ERROR;
8550 					add_sense_code =
8551 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8552 					add_sense_code_qual = SCSI_COMPONENT_86;
8553 					break;
8554 				case 7:
8555 					sense_key = KEY_MEDIUM_ERROR;
8556 					add_sense_code =
8557 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8558 					add_sense_code_qual = SCSI_COMPONENT_87;
8559 					break;
8560 				case 8:
8561 					sense_key = KEY_HARDWARE_ERROR;
8562 					add_sense_code =
8563 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8564 					add_sense_code_qual = SCSI_COMPONENT_88;
8565 					break;
8566 				}
8567 				code = 0;	/* unspecified */
8568 				status |= (code << 4);
8569 				lpp->param_values[0] = status;
8570 				lpp->param_values[1] = 0; /* unspecified */
8571 				lpp->param_values[2] = entry->
8572 				    smart_selftest_log_timestamp[1];
8573 				lpp->param_values[3] = entry->
8574 				    smart_selftest_log_timestamp[0];
8575 				if (status != 0) {
8576 					lpp->param_values[4] = 0;
8577 					lpp->param_values[5] = 0;
8578 					lpp->param_values[6] = 0;
8579 					lpp->param_values[7] = 0;
8580 					lpp->param_values[8] = entry->
8581 					    smart_selftest_log_failing_lba[3];
8582 					lpp->param_values[9] = entry->
8583 					    smart_selftest_log_failing_lba[2];
8584 					lpp->param_values[10] = entry->
8585 					    smart_selftest_log_failing_lba[1];
8586 					lpp->param_values[11] = entry->
8587 					    smart_selftest_log_failing_lba[0];
8588 				} else {	/* No block address */
8589 					lpp->param_values[4] = 0xff;
8590 					lpp->param_values[5] = 0xff;
8591 					lpp->param_values[6] = 0xff;
8592 					lpp->param_values[7] = 0xff;
8593 					lpp->param_values[8] = 0xff;
8594 					lpp->param_values[9] = 0xff;
8595 					lpp->param_values[10] = 0xff;
8596 					lpp->param_values[11] = 0xff;
8597 				}
8598 				lpp->param_values[12] = sense_key;
8599 				lpp->param_values[13] = add_sense_code;
8600 				lpp->param_values[14] = add_sense_code_qual;
8601 				lpp->param_values[15] = 0; /* undefined */
8602 
8603 				lpp = (struct log_parameter *)
8604 				    (((uint8_t *)lpp) +
8605 				    SCSI_LOG_PARAM_HDR_LEN +
8606 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8607 				--index;	/* back up to previous entry */
8608 				if (index < 0) {
8609 					index =
8610 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
8611 				}
8612 				entry = &selftest_log->
8613 				    smart_selftest_log_entries[index];
8614 			}
8615 		}
8616 done:
8617 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
8618 	}
8619 
8620 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
8621 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
8622 }
8623 
8624 /*
8625  * sata_build_lsense_page_2f() is used to create the
8626  * SCSI LOG SENSE page 0x2f (informational exceptions)
8627  *
8628  * Takes a sata_drive_info t * and the address of a buffer
8629  * in which to create the page information as well as a sata_hba_inst_t *.
8630  *
8631  * Returns the number of bytes valid in the buffer.
8632  *
8633  * Because it invokes function(s) that send synchronously executed command
8634  * to the HBA, it cannot be called in the interrupt context.
8635  */
8636 static	int
8637 sata_build_lsense_page_2f(
8638 	sata_drive_info_t *sdinfo,
8639 	uint8_t *buf,
8640 	sata_hba_inst_t *sata_hba_inst)
8641 {
8642 	struct log_parameter *lpp = (struct log_parameter *)buf;
8643 	int rval;
8644 	uint8_t *smart_data;
8645 	uint8_t temp;
8646 	sata_id_t *sata_id;
8647 #define	SMART_NO_TEMP	0xff
8648 
8649 	lpp->param_code[0] = 0;
8650 	lpp->param_code[1] = 0;
8651 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8652 
8653 	/* Now get the SMART status w.r.t. threshold exceeded */
8654 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
8655 	switch (rval) {
8656 	case 1:
8657 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
8658 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
8659 		break;
8660 	case 0:
8661 	case -1:	/* failed to get data */
8662 		lpp->param_values[0] = 0;	/* No failure predicted */
8663 		lpp->param_values[1] = 0;
8664 		break;
8665 #if defined(SATA_DEBUG)
8666 	default:
8667 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
8668 		/* NOTREACHED */
8669 #endif
8670 	}
8671 
8672 	sata_id = &sdinfo->satadrv_id;
8673 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
8674 		temp = SMART_NO_TEMP;
8675 	else {
8676 		/* Now get the temperature */
8677 		smart_data = kmem_zalloc(512, KM_SLEEP);
8678 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
8679 		    SCT_STATUS_LOG_PAGE, 1);
8680 		if (rval == -1)
8681 			temp = SMART_NO_TEMP;
8682 		else {
8683 			temp = smart_data[200];
8684 			if (temp & 0x80) {
8685 				if (temp & 0x7f)
8686 					temp = 0;
8687 				else
8688 					temp = SMART_NO_TEMP;
8689 			}
8690 		}
8691 		kmem_free(smart_data, 512);
8692 	}
8693 
8694 	lpp->param_values[2] = temp;	/* most recent temperature */
8695 	lpp->param_values[3] = 0;	/* required vendor specific byte */
8696 
8697 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
8698 
8699 
8700 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
8701 }
8702 
8703 /*
8704  * sata_build_lsense_page_30() is used to create the
8705  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
8706  *
8707  * Takes a sata_drive_info t * and the address of a buffer
8708  * in which to create the page information as well as a sata_hba_inst_t *.
8709  *
8710  * Returns the number of bytes valid in the buffer.
8711  */
8712 static int
8713 sata_build_lsense_page_30(
8714 	sata_drive_info_t *sdinfo,
8715 	uint8_t *buf,
8716 	sata_hba_inst_t *sata_hba_inst)
8717 {
8718 	struct smart_data *smart_data = (struct smart_data *)buf;
8719 	int rval;
8720 
8721 	/* Now do the SMART READ DATA */
8722 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
8723 	if (rval == -1)
8724 		return (0);
8725 
8726 	return (sizeof (struct smart_data));
8727 }
8728 
8729 /*
8730  * sata_build_lsense_page_0e() is used to create the
8731  * SCSI LOG SENSE page 0e (start-stop cycle counter page)
8732  *
8733  * Date of Manufacture (0x0001)
8734  *	YEAR = "0000"
8735  *	WEEK = "00"
8736  * Accounting Date (0x0002)
8737  *	6 ASCII space character(20h)
8738  * Specified cycle count over device lifetime
8739  *	VALUE - THRESH - the delta between max and min;
8740  * Accumulated start-stop cycles
8741  *	VALUE - WORST - the accumulated cycles;
8742  *
8743  * ID FLAG THRESH VALUE WORST RAW on start/stop counter attribute
8744  *
8745  * Takes a sata_drive_info t * and the address of a buffer
8746  * in which to create the page information as well as a sata_hba_inst_t *.
8747  *
8748  * Returns the number of bytes valid in the buffer.
8749  */
8750 static	int
8751 sata_build_lsense_page_0e(sata_drive_info_t *sdinfo, uint8_t *buf,
8752 	sata_pkt_txlate_t *spx)
8753 {
8754 	struct start_stop_cycle_counter_log *log_page;
8755 	int i, rval, index;
8756 	uint8_t smart_data[512], id, value, worst, thresh;
8757 	uint32_t max_count, cycles;
8758 
8759 	/* Now do the SMART READ DATA */
8760 	rval = sata_fetch_smart_data(spx->txlt_sata_hba_inst, sdinfo,
8761 	    (struct smart_data *)smart_data);
8762 	if (rval == -1)
8763 		return (0);
8764 	for (i = 0, id = 0; i < SMART_START_STOP_COUNT_ID * 2; i++) {
8765 		index = (i * 12) + 2;
8766 		id = smart_data[index];
8767 		if (id != SMART_START_STOP_COUNT_ID)
8768 			continue;
8769 		else {
8770 			thresh = smart_data[index + 2];
8771 			value = smart_data[index + 3];
8772 			worst = smart_data[index + 4];
8773 			break;
8774 		}
8775 	}
8776 	if (id != SMART_START_STOP_COUNT_ID)
8777 		return (0);
8778 	max_count = value - thresh;
8779 	cycles = value - worst;
8780 
8781 	log_page = (struct start_stop_cycle_counter_log *)buf;
8782 	bzero(log_page, sizeof (struct start_stop_cycle_counter_log));
8783 	log_page->code = 0x0e;
8784 	log_page->page_len_low = 0x24;
8785 
8786 	log_page->manufactor_date_low = 0x1;
8787 	log_page->param_1.fmt_link = 0x1; /* 01b */
8788 	log_page->param_len_1 = 0x06;
8789 	for (i = 0; i < 4; i++) {
8790 		log_page->year_manu[i] = 0x30;
8791 		if (i < 2)
8792 			log_page->week_manu[i] = 0x30;
8793 	}
8794 
8795 	log_page->account_date_low = 0x02;
8796 	log_page->param_2.fmt_link = 0x01; /* 01b */
8797 	log_page->param_len_2 = 0x06;
8798 	for (i = 0; i < 4; i++) {
8799 		log_page->year_account[i] = 0x20;
8800 		if (i < 2)
8801 			log_page->week_account[i] = 0x20;
8802 	}
8803 
8804 	log_page->lifetime_code_low = 0x03;
8805 	log_page->param_3.fmt_link = 0x03; /* 11b */
8806 	log_page->param_len_3 = 0x04;
8807 	/* VALUE - THRESH - the delta between max and min */
8808 	log_page->cycle_code_low = 0x04;
8809 	log_page->param_4.fmt_link = 0x03; /* 11b */
8810 	log_page->param_len_4 = 0x04;
8811 	/* WORST - THRESH - the distance from 'now' to min */
8812 
8813 	for (i = 0; i < 4; i++) {
8814 		log_page->cycle_lifetime[i] =
8815 		    (max_count >> (8 * (3 - i))) & 0xff;
8816 		log_page->cycle_accumulated[i] =
8817 		    (cycles >> (8 * (3 - i))) & 0xff;
8818 	}
8819 
8820 	return (sizeof (struct start_stop_cycle_counter_log));
8821 }
8822 
8823 /*
8824  * This function was used for build a ATA read verify sector command
8825  */
8826 static void
8827 sata_build_read_verify_cmd(sata_cmd_t *scmd, uint16_t sec, uint64_t lba)
8828 {
8829 	scmd->satacmd_cmd_reg = SATAC_RDVER;
8830 	scmd->satacmd_addr_type = ATA_ADDR_LBA28;
8831 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8832 
8833 	scmd->satacmd_sec_count_lsb = sec & 0xff;
8834 	scmd->satacmd_lba_low_lsb = lba & 0xff;
8835 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
8836 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
8837 	scmd->satacmd_device_reg = (SATA_ADH_LBA | (lba >> 24) & 0xf);
8838 	scmd->satacmd_features_reg = 0;
8839 	scmd->satacmd_status_reg = 0;
8840 	scmd->satacmd_error_reg = 0;
8841 }
8842 
8843 /*
8844  * This function was used for building an ATA
8845  * command, and only command register need to
8846  * be defined, other register will be zero or na.
8847  */
8848 static void
8849 sata_build_generic_cmd(sata_cmd_t *scmd, uint8_t cmd)
8850 {
8851 	scmd->satacmd_addr_type = 0;
8852 	scmd->satacmd_cmd_reg = cmd;
8853 	scmd->satacmd_device_reg = 0;
8854 	scmd->satacmd_sec_count_lsb = 0;
8855 	scmd->satacmd_lba_low_lsb = 0;
8856 	scmd->satacmd_lba_mid_lsb = 0;
8857 	scmd->satacmd_lba_high_lsb = 0;
8858 	scmd->satacmd_features_reg = 0;
8859 	scmd->satacmd_status_reg = 0;
8860 	scmd->satacmd_error_reg = 0;
8861 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8862 }
8863 
8864 /*
8865  * This function was used for changing the standby
8866  * timer format from SCSI to ATA.
8867  */
8868 static uint8_t
8869 sata_get_standby_timer(uint8_t *timer)
8870 {
8871 	uint32_t i = 0, count = 0;
8872 	uint8_t ata_count;
8873 
8874 	for (i = 0; i < 4; i++) {
8875 		count = count << 8 | timer[i];
8876 	}
8877 
8878 	if (count == 0)
8879 		return (0);
8880 
8881 	if (count >= 1 && count <= 12000)
8882 		ata_count = (count -1) / 50 + 1;
8883 	else if (count > 12000 && count <= 12600)
8884 		ata_count = 0xfc;
8885 	else if (count > 12601 && count <= 12750)
8886 		ata_count = 0xff;
8887 	else if (count > 12750 && count <= 17999)
8888 		ata_count = 0xf1;
8889 	else if (count > 18000 && count <= 198000)
8890 		ata_count = count / 18000 + 240;
8891 	else
8892 		ata_count = 0xfd;
8893 	return (ata_count);
8894 }
8895 
8896 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
8897 
8898 /*
8899  * Start command for ATAPI device.
8900  * This function processes scsi_pkt requests.
8901  * Now CD/DVD, tape and ATAPI disk devices are supported.
8902  * Most commands are packet without any translation into Packet Command.
8903  * Some may be trapped and executed as SATA commands (not clear which one).
8904  *
8905  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
8906  * execution).
8907  * Returns other TRAN_XXXX codes if command is not accepted or completed
8908  * (see return values for sata_hba_start()).
8909  *
8910  * Note:
8911  * Inquiry cdb format differs between transport version 2 and 3.
8912  * However, the transport version 3 devices that were checked did not adhere
8913  * to the specification (ignored MSB of the allocation length). Therefore,
8914  * the transport version is not checked, but Inquiry allocation length is
8915  * truncated to 255 bytes if the original allocation length set-up by the
8916  * target driver is greater than 255 bytes.
8917  */
8918 static int
8919 sata_txlt_atapi(sata_pkt_txlate_t *spx)
8920 {
8921 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8922 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8923 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8924 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
8925 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
8926 	    &spx->txlt_sata_pkt->satapkt_device);
8927 	int cport = SATA_TXLT_CPORT(spx);
8928 	int cdblen;
8929 	int rval, reason;
8930 	int synch;
8931 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
8932 
8933 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
8934 
8935 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
8936 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
8937 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8938 		return (rval);
8939 	}
8940 
8941 	/*
8942 	 * ATAPI device executes some ATA commands in addition to those
8943 	 * commands sent via PACKET command. These ATA commands may be
8944 	 * executed by the regular SATA translation functions. None needs
8945 	 * to be captured now.
8946 	 *
8947 	 * Commands sent via PACKET command include:
8948 	 *	MMC command set for ATAPI CD/DVD device
8949 	 *	SSC command set for ATAPI TAPE device
8950 	 *	SBC command set for ATAPI disk device
8951 	 *
8952 	 */
8953 
8954 	/* Check the size of cdb */
8955 
8956 	switch (GETGROUP(cdbp)) {
8957 	case CDB_GROUPID_3:   /* Reserved, per SPC-4 */
8958 		/*
8959 		 * opcodes 0x7e and 0x7f identify variable-length CDBs and
8960 		 * therefore require special handling.  Return failure, for now.
8961 		 */
8962 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8963 		return (TRAN_BADPKT);
8964 
8965 	case CDB_GROUPID_6:   /* Vendor-specific, per SPC-4 */
8966 	case CDB_GROUPID_7:   /* Vendor-specific, per SPC-4 */
8967 		/* obtain length from the scsi_pkt */
8968 		cdblen = scsipkt->pkt_cdblen;
8969 		break;
8970 
8971 	default:
8972 		/* CDB's length is statically known, per SPC-4 */
8973 		cdblen = scsi_cdb_size[GETGROUP(cdbp)];
8974 		break;
8975 	}
8976 
8977 	if (cdblen <= 0 || cdblen > sdinfo->satadrv_atapi_cdb_len) {
8978 		sata_log(NULL, CE_WARN,
8979 		    "sata: invalid ATAPI cdb length %d",
8980 		    cdblen);
8981 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8982 		return (TRAN_BADPKT);
8983 	}
8984 
8985 	SATAATAPITRACE(spx, cdblen);
8986 
8987 	/*
8988 	 * For non-read/write commands we need to
8989 	 * map buffer
8990 	 */
8991 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
8992 	case SCMD_READ:
8993 	case SCMD_READ_G1:
8994 	case SCMD_READ_G5:
8995 	case SCMD_READ_G4:
8996 	case SCMD_WRITE:
8997 	case SCMD_WRITE_G1:
8998 	case SCMD_WRITE_G5:
8999 	case SCMD_WRITE_G4:
9000 		break;
9001 	default:
9002 		if (bp != NULL) {
9003 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
9004 				bp_mapin(bp);
9005 		}
9006 		break;
9007 	}
9008 	/*
9009 	 * scmd->satacmd_flags.sata_data_direction default -
9010 	 * SATA_DIR_NODATA_XFER - is set by
9011 	 * sata_txlt_generic_pkt_info().
9012 	 */
9013 	if (scmd->satacmd_bp) {
9014 		if (scmd->satacmd_bp->b_flags & B_READ) {
9015 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9016 		} else {
9017 			scmd->satacmd_flags.sata_data_direction =
9018 			    SATA_DIR_WRITE;
9019 		}
9020 	}
9021 
9022 	/*
9023 	 * Set up ATAPI packet command.
9024 	 */
9025 
9026 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9027 
9028 	/* Copy cdb into sata_cmd */
9029 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9030 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9031 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
9032 
9033 	/* See note in the command header */
9034 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
9035 		if (scmd->satacmd_acdb[3] != 0)
9036 			scmd->satacmd_acdb[4] = 255;
9037 	}
9038 
9039 #ifdef SATA_DEBUG
9040 	if (sata_debug_flags & SATA_DBG_ATAPI) {
9041 		uint8_t *p = scmd->satacmd_acdb;
9042 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
9043 
9044 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
9045 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
9046 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
9047 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9048 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9049 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
9050 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
9051 	}
9052 #endif
9053 
9054 	/*
9055 	 * Preset request sense data to NO SENSE.
9056 	 * If there is no way to get error information via Request Sense,
9057 	 * the packet request sense data would not have to be modified by HBA,
9058 	 * but it could be returned as is.
9059 	 */
9060 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
9061 	sata_fixed_sense_data_preset(
9062 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9063 
9064 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
9065 		/* Need callback function */
9066 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
9067 		synch = FALSE;
9068 	} else
9069 		synch = TRUE;
9070 
9071 	/* Transfer command to HBA */
9072 	if (sata_hba_start(spx, &rval) != 0) {
9073 		/* Pkt not accepted for execution */
9074 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
9075 		return (rval);
9076 	}
9077 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
9078 	/*
9079 	 * If execution is non-synchronous,
9080 	 * a callback function will handle potential errors, translate
9081 	 * the response and will do a callback to a target driver.
9082 	 * If it was synchronous, use the same framework callback to check
9083 	 * an execution status.
9084 	 */
9085 	if (synch) {
9086 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
9087 		    "synchronous execution status %x\n",
9088 		    spx->txlt_sata_pkt->satapkt_reason);
9089 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
9090 	}
9091 	return (TRAN_ACCEPT);
9092 }
9093 
9094 
9095 /*
9096  * ATAPI Packet command completion.
9097  *
9098  * Failure of the command passed via Packet command are considered device
9099  * error. SATA HBA driver would have to retrieve error data (via Request
9100  * Sense command delivered via error retrieval sata packet) and copy it
9101  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
9102  */
9103 static void
9104 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
9105 {
9106 	sata_pkt_txlate_t *spx =
9107 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
9108 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
9109 	struct scsi_extended_sense *sense;
9110 	struct buf *bp;
9111 	int rval;
9112 
9113 #ifdef SATA_DEBUG
9114 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
9115 #endif
9116 
9117 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
9118 	    STATE_SENT_CMD | STATE_GOT_STATUS;
9119 
9120 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
9121 		/* Normal completion */
9122 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
9123 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
9124 		scsipkt->pkt_reason = CMD_CMPLT;
9125 		*scsipkt->pkt_scbp = STATUS_GOOD;
9126 		if (spx->txlt_tmp_buf != NULL) {
9127 			/* Temporary buffer was used */
9128 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
9129 			if (bp->b_flags & B_READ) {
9130 				rval = ddi_dma_sync(
9131 				    spx->txlt_buf_dma_handle, 0, 0,
9132 				    DDI_DMA_SYNC_FORCPU);
9133 				ASSERT(rval == DDI_SUCCESS);
9134 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
9135 				    bp->b_bcount);
9136 			}
9137 		}
9138 	} else {
9139 		/*
9140 		 * Something went wrong - analyze return
9141 		 */
9142 		*scsipkt->pkt_scbp = STATUS_CHECK;
9143 		sense = sata_arq_sense(spx);
9144 
9145 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9146 			/*
9147 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
9148 			 * Under this condition ERR bit is set for ATA command,
9149 			 * and CHK bit set for ATAPI command.
9150 			 *
9151 			 * Please check st_intr & sdintr about how pkt_reason
9152 			 * is used.
9153 			 */
9154 			scsipkt->pkt_reason = CMD_CMPLT;
9155 
9156 			/*
9157 			 * We may not have ARQ data if there was a double
9158 			 * error. But sense data in sata packet was pre-set
9159 			 * with NO SENSE so it is valid even if HBA could
9160 			 * not retrieve a real sense data.
9161 			 * Just copy this sense data into scsi pkt sense area.
9162 			 */
9163 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
9164 			    SATA_ATAPI_MIN_RQSENSE_LEN);
9165 #ifdef SATA_DEBUG
9166 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
9167 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9168 				    "sata_txlt_atapi_completion: %02x\n"
9169 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
9170 				    "          %02x %02x %02x %02x %02x %02x "
9171 				    "          %02x %02x %02x %02x %02x %02x\n",
9172 				    scsipkt->pkt_reason,
9173 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9174 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9175 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9176 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9177 				    rqsp[16], rqsp[17]);
9178 			}
9179 #endif
9180 		} else {
9181 			switch (sata_pkt->satapkt_reason) {
9182 			case SATA_PKT_PORT_ERROR:
9183 				/*
9184 				 * We have no device data.
9185 				 */
9186 				scsipkt->pkt_reason = CMD_INCOMPLETE;
9187 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
9188 				    STATE_GOT_TARGET | STATE_SENT_CMD |
9189 				    STATE_GOT_STATUS);
9190 				sense->es_key = KEY_HARDWARE_ERROR;
9191 				break;
9192 
9193 			case SATA_PKT_TIMEOUT:
9194 				scsipkt->pkt_reason = CMD_TIMEOUT;
9195 				scsipkt->pkt_statistics |=
9196 				    STAT_TIMEOUT | STAT_DEV_RESET;
9197 				/*
9198 				 * Need to check if HARDWARE_ERROR/
9199 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
9200 				 * appropriate.
9201 				 */
9202 				break;
9203 
9204 			case SATA_PKT_ABORTED:
9205 				scsipkt->pkt_reason = CMD_ABORTED;
9206 				scsipkt->pkt_statistics |= STAT_ABORTED;
9207 				/* Should we set key COMMAND_ABPRTED? */
9208 				break;
9209 
9210 			case SATA_PKT_RESET:
9211 				scsipkt->pkt_reason = CMD_RESET;
9212 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
9213 				/*
9214 				 * May be we should set Unit Attention /
9215 				 * Reset. Perhaps the same should be
9216 				 * returned for disks....
9217 				 */
9218 				sense->es_key = KEY_UNIT_ATTENTION;
9219 				sense->es_add_code = SD_SCSI_ASC_RESET;
9220 				break;
9221 
9222 			default:
9223 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
9224 				    "sata_txlt_atapi_completion: "
9225 				    "invalid packet completion reason"));
9226 				scsipkt->pkt_reason = CMD_TRAN_ERR;
9227 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
9228 				    STATE_GOT_TARGET | STATE_SENT_CMD |
9229 				    STATE_GOT_STATUS);
9230 				break;
9231 			}
9232 		}
9233 	}
9234 
9235 	SATAATAPITRACE(spx, 0);
9236 
9237 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
9238 	    scsipkt->pkt_comp != NULL) {
9239 		/* scsi callback required */
9240 		(*scsipkt->pkt_comp)(scsipkt);
9241 	}
9242 }
9243 
9244 /*
9245  * Set up error retrieval sata command for ATAPI Packet Command error data
9246  * recovery.
9247  *
9248  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
9249  * returns SATA_FAILURE otherwise.
9250  */
9251 
9252 static int
9253 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
9254 {
9255 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
9256 	sata_cmd_t *scmd;
9257 	struct buf *bp;
9258 
9259 	/*
9260 	 * Allocate dma-able buffer error data.
9261 	 * Buffer allocation will take care of buffer alignment and other DMA
9262 	 * attributes.
9263 	 */
9264 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
9265 	if (bp == NULL) {
9266 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
9267 		    "sata_get_err_retrieval_pkt: "
9268 		    "cannot allocate buffer for error data", NULL);
9269 		return (SATA_FAILURE);
9270 	}
9271 	bp_mapin(bp); /* make data buffer accessible */
9272 
9273 	/* Operation modes are up to the caller */
9274 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9275 
9276 	/* Synchronous mode, no callback - may be changed by the caller */
9277 	spkt->satapkt_comp = NULL;
9278 	spkt->satapkt_time = sata_default_pkt_time;
9279 
9280 	scmd = &spkt->satapkt_cmd;
9281 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9282 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9283 
9284 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9285 
9286 	/*
9287 	 * Set-up acdb. Request Sense CDB (packet command content) is
9288 	 * not in DMA-able buffer. Its handling is HBA-specific (how
9289 	 * it is transfered into packet FIS).
9290 	 */
9291 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9292 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
9293 	/* Following zeroing of pad bytes may not be necessary */
9294 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
9295 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
9296 
9297 	/*
9298 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
9299 	 * before accessing it. Handle is in usual place in translate struct.
9300 	 */
9301 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
9302 
9303 	/*
9304 	 * Preset request sense data to NO SENSE.
9305 	 * Here it is redundant, only for a symetry with scsi-originated
9306 	 * packets. It should not be used for anything but debugging.
9307 	 */
9308 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
9309 	sata_fixed_sense_data_preset(
9310 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9311 
9312 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9313 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9314 
9315 	return (SATA_SUCCESS);
9316 }
9317 
9318 /*
9319  * Set-up ATAPI packet command.
9320  * Data transfer direction has to be set-up in sata_cmd structure prior to
9321  * calling this function.
9322  *
9323  * Returns void
9324  */
9325 
9326 static void
9327 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
9328 {
9329 	scmd->satacmd_addr_type = 0;		/* N/A */
9330 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
9331 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
9332 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
9333 	scmd->satacmd_lba_high_lsb =
9334 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
9335 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
9336 
9337 	/*
9338 	 * We want all data to be transfered via DMA.
9339 	 * But specify it only if drive supports DMA and DMA mode is
9340 	 * selected - some drives are sensitive about it.
9341 	 * Hopefully it wil work for all drives....
9342 	 */
9343 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
9344 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
9345 
9346 	/*
9347 	 * Features register requires special care for devices that use
9348 	 * Serial ATA bridge - they need an explicit specification of
9349 	 * the data transfer direction for Packet DMA commands.
9350 	 * Setting this bit is harmless if DMA is not used.
9351 	 *
9352 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
9353 	 * spec they follow.
9354 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
9355 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
9356 	 * ATA/ATAPI-7 support is explicitly indicated.
9357 	 */
9358 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
9359 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
9360 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
9361 		/*
9362 		 * Specification of major version is valid and version 7
9363 		 * is supported. It does automatically imply that all
9364 		 * spec features are supported. For now, we assume that
9365 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
9366 		 */
9367 		if ((sdinfo->satadrv_id.ai_dirdma &
9368 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
9369 			if (scmd->satacmd_flags.sata_data_direction ==
9370 			    SATA_DIR_READ)
9371 			scmd->satacmd_features_reg |=
9372 			    SATA_ATAPI_F_DATA_DIR_READ;
9373 		}
9374 	}
9375 }
9376 
9377 
9378 #ifdef SATA_DEBUG
9379 
9380 /* Display 18 bytes of Inquiry data */
9381 static void
9382 sata_show_inqry_data(uint8_t *buf)
9383 {
9384 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
9385 	uint8_t *p;
9386 
9387 	cmn_err(CE_NOTE, "Inquiry data:");
9388 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
9389 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
9390 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
9391 	cmn_err(CE_NOTE, "ATAPI transport version %d",
9392 	    SATA_ATAPI_TRANS_VERSION(inq));
9393 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
9394 	    inq->inq_rdf, inq->inq_aenc);
9395 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
9396 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
9397 	p = (uint8_t *)inq->inq_vid;
9398 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
9399 	    "%02x %02x %02x %02x",
9400 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9401 	p = (uint8_t *)inq->inq_vid;
9402 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
9403 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9404 
9405 	p = (uint8_t *)inq->inq_pid;
9406 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
9407 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
9408 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9409 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9410 	p = (uint8_t *)inq->inq_pid;
9411 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
9412 	    "%c %c %c %c %c %c %c %c",
9413 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9414 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9415 
9416 	p = (uint8_t *)inq->inq_revision;
9417 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
9418 	    p[0], p[1], p[2], p[3]);
9419 	p = (uint8_t *)inq->inq_revision;
9420 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
9421 	    p[0], p[1], p[2], p[3]);
9422 
9423 }
9424 
9425 
9426 static void
9427 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
9428 {
9429 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
9430 
9431 	if (scsi_pkt == NULL)
9432 		return;
9433 	if (count != 0) {
9434 		/* saving cdb */
9435 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
9436 		    SATA_ATAPI_MAX_CDB_LEN);
9437 		bcopy(scsi_pkt->pkt_cdbp,
9438 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
9439 	} else {
9440 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
9441 		    sts_sensedata,
9442 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
9443 		    SATA_ATAPI_MIN_RQSENSE_LEN);
9444 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
9445 		    scsi_pkt->pkt_reason;
9446 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
9447 		    spx->txlt_sata_pkt->satapkt_reason;
9448 
9449 		if (++sata_atapi_trace_index >= 64)
9450 			sata_atapi_trace_index = 0;
9451 	}
9452 }
9453 
9454 #endif
9455 
9456 /*
9457  * Fetch inquiry data from ATAPI device
9458  * Returns SATA_SUCCESS if operation was successfull, SATA_FAILURE otherwise.
9459  *
9460  * Note:
9461  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
9462  * where the caller expects to see the inquiry data.
9463  *
9464  */
9465 
9466 static int
9467 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
9468     sata_address_t *saddr, struct scsi_inquiry *inq)
9469 {
9470 	sata_pkt_txlate_t *spx;
9471 	sata_pkt_t *spkt;
9472 	struct buf *bp;
9473 	sata_drive_info_t *sdinfo;
9474 	sata_cmd_t *scmd;
9475 	int rval;
9476 	uint8_t *rqsp;
9477 #ifdef SATA_DEBUG
9478 	char msg_buf[MAXPATHLEN];
9479 #endif
9480 
9481 	ASSERT(sata_hba != NULL);
9482 
9483 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9484 	spx->txlt_sata_hba_inst = sata_hba;
9485 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9486 	spkt = sata_pkt_alloc(spx, NULL);
9487 	if (spkt == NULL) {
9488 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9489 		return (SATA_FAILURE);
9490 	}
9491 	/* address is needed now */
9492 	spkt->satapkt_device.satadev_addr = *saddr;
9493 
9494 	/* scsi_inquiry size buffer */
9495 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
9496 	if (bp == NULL) {
9497 		sata_pkt_free(spx);
9498 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9499 		SATA_LOG_D((sata_hba, CE_WARN,
9500 		    "sata_get_atapi_inquiry_data: "
9501 		    "cannot allocate data buffer"));
9502 		return (SATA_FAILURE);
9503 	}
9504 	bp_mapin(bp); /* make data buffer accessible */
9505 
9506 	scmd = &spkt->satapkt_cmd;
9507 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9508 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9509 
9510 	/* Use synchronous mode */
9511 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9512 	spkt->satapkt_comp = NULL;
9513 	spkt->satapkt_time = sata_default_pkt_time;
9514 
9515 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9516 
9517 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9518 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9519 
9520 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
9521 	sdinfo = sata_get_device_info(sata_hba,
9522 	    &spx->txlt_sata_pkt->satapkt_device);
9523 	if (sdinfo == NULL) {
9524 		/* we have to be carefull about the disapearing device */
9525 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9526 		rval = SATA_FAILURE;
9527 		goto cleanup;
9528 	}
9529 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9530 
9531 	/*
9532 	 * Set-up acdb. This works for atapi transport version 2 and later.
9533 	 */
9534 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9535 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9536 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9537 	scmd->satacmd_acdb[1] = 0x00;
9538 	scmd->satacmd_acdb[2] = 0x00;
9539 	scmd->satacmd_acdb[3] = 0x00;
9540 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9541 	scmd->satacmd_acdb[5] = 0x00;
9542 
9543 	sata_fixed_sense_data_preset(
9544 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9545 
9546 	/* Transfer command to HBA */
9547 	if (sata_hba_start(spx, &rval) != 0) {
9548 		/* Pkt not accepted for execution */
9549 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9550 		    "sata_get_atapi_inquiry_data: "
9551 		    "Packet not accepted for execution - ret: %02x", rval);
9552 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9553 		rval = SATA_FAILURE;
9554 		goto cleanup;
9555 	}
9556 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9557 
9558 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9559 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9560 		    "sata_get_atapi_inquiry_data: "
9561 		    "Packet completed successfully - ret: %02x", rval);
9562 		if (spx->txlt_buf_dma_handle != NULL) {
9563 			/*
9564 			 * Sync buffer. Handle is in usual place in translate
9565 			 * struct.
9566 			 */
9567 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9568 			    DDI_DMA_SYNC_FORCPU);
9569 			ASSERT(rval == DDI_SUCCESS);
9570 		}
9571 		/*
9572 		 * Normal completion - copy data into caller's buffer
9573 		 */
9574 		bcopy(bp->b_un.b_addr, (uint8_t *)inq,
9575 		    sizeof (struct scsi_inquiry));
9576 #ifdef SATA_DEBUG
9577 		if (sata_debug_flags & SATA_DBG_ATAPI) {
9578 			sata_show_inqry_data((uint8_t *)inq);
9579 		}
9580 #endif
9581 		rval = SATA_SUCCESS;
9582 	} else {
9583 		/*
9584 		 * Something went wrong - analyze return - check rqsense data
9585 		 */
9586 		rval = SATA_FAILURE;
9587 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9588 			/*
9589 			 * ARQ data hopefull show something other than NO SENSE
9590 			 */
9591 			rqsp = scmd->satacmd_rqsense;
9592 #ifdef SATA_DEBUG
9593 			if (sata_debug_flags & SATA_DBG_ATAPI) {
9594 				msg_buf[0] = '\0';
9595 				(void) snprintf(msg_buf, MAXPATHLEN,
9596 				    "ATAPI packet completion reason: %02x\n"
9597 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
9598 				    "          %02x %02x %02x %02x %02x %02x\n"
9599 				    "          %02x %02x %02x %02x %02x %02x",
9600 				    spkt->satapkt_reason,
9601 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9602 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9603 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9604 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9605 				    rqsp[16], rqsp[17]);
9606 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9607 				    "%s", msg_buf);
9608 			}
9609 #endif
9610 		} else {
9611 			switch (spkt->satapkt_reason) {
9612 			case SATA_PKT_PORT_ERROR:
9613 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9614 				    "sata_get_atapi_inquiry_data: "
9615 				    "packet reason: port error", NULL);
9616 				break;
9617 
9618 			case SATA_PKT_TIMEOUT:
9619 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9620 				    "sata_get_atapi_inquiry_data: "
9621 				    "packet reason: timeout", NULL);
9622 				break;
9623 
9624 			case SATA_PKT_ABORTED:
9625 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9626 				    "sata_get_atapi_inquiry_data: "
9627 				    "packet reason: aborted", NULL);
9628 				break;
9629 
9630 			case SATA_PKT_RESET:
9631 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9632 				    "sata_get_atapi_inquiry_data: "
9633 				    "packet reason: reset\n", NULL);
9634 				break;
9635 			default:
9636 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9637 				    "sata_get_atapi_inquiry_data: "
9638 				    "invalid packet reason: %02x\n",
9639 				    spkt->satapkt_reason);
9640 				break;
9641 			}
9642 		}
9643 	}
9644 cleanup:
9645 	sata_free_local_buffer(spx);
9646 	sata_pkt_free(spx);
9647 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9648 	return (rval);
9649 }
9650 
9651 
9652 
9653 
9654 
9655 #if 0
9656 #ifdef SATA_DEBUG
9657 
9658 /*
9659  * Test ATAPI packet command.
9660  * Single threaded test: send packet command in synch mode, process completion
9661  *
9662  */
9663 static void
9664 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
9665 {
9666 	sata_pkt_txlate_t *spx;
9667 	sata_pkt_t *spkt;
9668 	struct buf *bp;
9669 	sata_device_t sata_device;
9670 	sata_drive_info_t *sdinfo;
9671 	sata_cmd_t *scmd;
9672 	int rval;
9673 	uint8_t *rqsp;
9674 
9675 	ASSERT(sata_hba_inst != NULL);
9676 	sata_device.satadev_addr.cport = cport;
9677 	sata_device.satadev_addr.pmport = 0;
9678 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
9679 	sata_device.satadev_rev = SATA_DEVICE_REV;
9680 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9681 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
9682 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9683 	if (sdinfo == NULL) {
9684 		sata_log(sata_hba_inst, CE_WARN,
9685 		    "sata_test_atapi_packet_command: "
9686 		    "no device info for cport %d",
9687 		    sata_device.satadev_addr.cport);
9688 		return;
9689 	}
9690 
9691 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9692 	spx->txlt_sata_hba_inst = sata_hba_inst;
9693 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9694 	spkt = sata_pkt_alloc(spx, NULL);
9695 	if (spkt == NULL) {
9696 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9697 		return;
9698 	}
9699 	/* address is needed now */
9700 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
9701 
9702 	/* 1024k buffer */
9703 	bp = sata_alloc_local_buffer(spx, 1024);
9704 	if (bp == NULL) {
9705 		sata_pkt_free(spx);
9706 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9707 		sata_log(sata_hba_inst, CE_WARN,
9708 		    "sata_test_atapi_packet_command: "
9709 		    "cannot allocate data buffer");
9710 		return;
9711 	}
9712 	bp_mapin(bp); /* make data buffer accessible */
9713 
9714 	scmd = &spkt->satapkt_cmd;
9715 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9716 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9717 
9718 	/* Use synchronous mode */
9719 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9720 
9721 	/* Synchronous mode, no callback - may be changed by the caller */
9722 	spkt->satapkt_comp = NULL;
9723 	spkt->satapkt_time = sata_default_pkt_time;
9724 
9725 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9726 
9727 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9728 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9729 
9730 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9731 
9732 	/* Set-up acdb. */
9733 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9734 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9735 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9736 	scmd->satacmd_acdb[1] = 0x00;
9737 	scmd->satacmd_acdb[2] = 0x00;
9738 	scmd->satacmd_acdb[3] = 0x00;
9739 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9740 	scmd->satacmd_acdb[5] = 0x00;
9741 
9742 	sata_fixed_sense_data_preset(
9743 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9744 
9745 	/* Transfer command to HBA */
9746 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9747 	if (sata_hba_start(spx, &rval) != 0) {
9748 		/* Pkt not accepted for execution */
9749 		sata_log(sata_hba_inst, CE_WARN,
9750 		    "sata_test_atapi_packet_command: "
9751 		    "Packet not accepted for execution - ret: %02x", rval);
9752 		mutex_exit(
9753 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9754 		goto cleanup;
9755 	}
9756 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9757 
9758 	if (spx->txlt_buf_dma_handle != NULL) {
9759 		/*
9760 		 * Sync buffer. Handle is in usual place in translate struct.
9761 		 */
9762 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9763 		    DDI_DMA_SYNC_FORCPU);
9764 		ASSERT(rval == DDI_SUCCESS);
9765 	}
9766 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9767 		sata_log(sata_hba_inst, CE_WARN,
9768 		    "sata_test_atapi_packet_command: "
9769 		    "Packet completed successfully");
9770 		/*
9771 		 * Normal completion - show inquiry data
9772 		 */
9773 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
9774 	} else {
9775 		/*
9776 		 * Something went wrong - analyze return - check rqsense data
9777 		 */
9778 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9779 			/*
9780 			 * ARQ data hopefull show something other than NO SENSE
9781 			 */
9782 			rqsp = scmd->satacmd_rqsense;
9783 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9784 			    "ATAPI packet completion reason: %02x\n"
9785 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
9786 			    "          %02x %02x %02x %02x %02x %02x "
9787 			    "          %02x %02x %02x %02x %02x %02x\n",
9788 			    spkt->satapkt_reason,
9789 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9790 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9791 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9792 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9793 			    rqsp[16], rqsp[17]);
9794 		} else {
9795 			switch (spkt->satapkt_reason) {
9796 			case SATA_PKT_PORT_ERROR:
9797 				sata_log(sata_hba_inst, CE_WARN,
9798 				    "sata_test_atapi_packet_command: "
9799 				    "packet reason: port error\n");
9800 				break;
9801 
9802 			case SATA_PKT_TIMEOUT:
9803 				sata_log(sata_hba_inst, CE_WARN,
9804 				    "sata_test_atapi_packet_command: "
9805 				    "packet reason: timeout\n");
9806 				break;
9807 
9808 			case SATA_PKT_ABORTED:
9809 				sata_log(sata_hba_inst, CE_WARN,
9810 				    "sata_test_atapi_packet_command: "
9811 				    "packet reason: aborted\n");
9812 				break;
9813 
9814 			case SATA_PKT_RESET:
9815 				sata_log(sata_hba_inst, CE_WARN,
9816 				    "sata_test_atapi_packet_command: "
9817 				    "packet reason: reset\n");
9818 				break;
9819 			default:
9820 				sata_log(sata_hba_inst, CE_WARN,
9821 				    "sata_test_atapi_packet_command: "
9822 				    "invalid packet reason: %02x\n",
9823 				    spkt->satapkt_reason);
9824 				break;
9825 			}
9826 		}
9827 	}
9828 cleanup:
9829 	sata_free_local_buffer(spx);
9830 	sata_pkt_free(spx);
9831 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9832 }
9833 
9834 #endif /* SATA_DEBUG */
9835 #endif /* 1 */
9836 
9837 
9838 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
9839 
9840 /*
9841  * Validate sata_tran info
9842  * SATA_FAILURE returns if structure is inconsistent or structure revision
9843  * does not match one used by the framework.
9844  *
9845  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
9846  * required function pointers.
9847  * Returns SATA_FAILURE otherwise.
9848  */
9849 static int
9850 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
9851 {
9852 	/*
9853 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
9854 	 * of the SATA interface.
9855 	 */
9856 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
9857 		sata_log(NULL, CE_WARN,
9858 		    "sata: invalid sata_hba_tran version %d for driver %s",
9859 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
9860 		return (SATA_FAILURE);
9861 	}
9862 
9863 	if (dip != sata_tran->sata_tran_hba_dip) {
9864 		SATA_LOG_D((NULL, CE_WARN,
9865 		    "sata: inconsistent sata_tran_hba_dip "
9866 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
9867 		return (SATA_FAILURE);
9868 	}
9869 
9870 	if (sata_tran->sata_tran_probe_port == NULL ||
9871 	    sata_tran->sata_tran_start == NULL ||
9872 	    sata_tran->sata_tran_abort == NULL ||
9873 	    sata_tran->sata_tran_reset_dport == NULL ||
9874 	    sata_tran->sata_tran_hotplug_ops == NULL ||
9875 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
9876 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
9877 	    NULL) {
9878 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
9879 		    "required functions"));
9880 	}
9881 	return (SATA_SUCCESS);
9882 }
9883 
9884 /*
9885  * Remove HBA instance from sata_hba_list.
9886  */
9887 static void
9888 sata_remove_hba_instance(dev_info_t *dip)
9889 {
9890 	sata_hba_inst_t	*sata_hba_inst;
9891 
9892 	mutex_enter(&sata_mutex);
9893 	for (sata_hba_inst = sata_hba_list;
9894 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
9895 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9896 		if (sata_hba_inst->satahba_dip == dip)
9897 			break;
9898 	}
9899 
9900 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
9901 #ifdef SATA_DEBUG
9902 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
9903 		    "unknown HBA instance\n");
9904 #endif
9905 		ASSERT(FALSE);
9906 	}
9907 	if (sata_hba_inst == sata_hba_list) {
9908 		sata_hba_list = sata_hba_inst->satahba_next;
9909 		if (sata_hba_list) {
9910 			sata_hba_list->satahba_prev =
9911 			    (struct sata_hba_inst *)NULL;
9912 		}
9913 		if (sata_hba_inst == sata_hba_list_tail) {
9914 			sata_hba_list_tail = NULL;
9915 		}
9916 	} else if (sata_hba_inst == sata_hba_list_tail) {
9917 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
9918 		if (sata_hba_list_tail) {
9919 			sata_hba_list_tail->satahba_next =
9920 			    (struct sata_hba_inst *)NULL;
9921 		}
9922 	} else {
9923 		sata_hba_inst->satahba_prev->satahba_next =
9924 		    sata_hba_inst->satahba_next;
9925 		sata_hba_inst->satahba_next->satahba_prev =
9926 		    sata_hba_inst->satahba_prev;
9927 	}
9928 	mutex_exit(&sata_mutex);
9929 }
9930 
9931 /*
9932  * Probe all SATA ports of the specified HBA instance.
9933  * The assumption is that there are no target and attachment point minor nodes
9934  * created by the boot subsystems, so we do not need to prune device tree.
9935  *
9936  * This function is called only from sata_hba_attach(). It does not have to
9937  * be protected by controller mutex, because the hba_attached flag is not set
9938  * yet and no one would be touching this HBA instance other than this thread.
9939  * Determines if port is active and what type of the device is attached
9940  * (if any). Allocates necessary structures for each port.
9941  *
9942  * An AP (Attachement Point) node is created for each SATA device port even
9943  * when there is no device attached.
9944  */
9945 
9946 static 	void
9947 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
9948 {
9949 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9950 	int			ncport;
9951 	sata_cport_info_t 	*cportinfo;
9952 	sata_drive_info_t	*drive;
9953 	sata_device_t		sata_device;
9954 	int			rval;
9955 	dev_t			minor_number;
9956 	char			name[16];
9957 	clock_t			start_time, cur_time;
9958 
9959 	/*
9960 	 * Probe controller ports first, to find port status and
9961 	 * any port multiplier attached.
9962 	 */
9963 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
9964 		/* allocate cport structure */
9965 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
9966 		ASSERT(cportinfo != NULL);
9967 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
9968 
9969 		mutex_enter(&cportinfo->cport_mutex);
9970 
9971 		cportinfo->cport_addr.cport = ncport;
9972 		cportinfo->cport_addr.pmport = 0;
9973 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
9974 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
9975 		cportinfo->cport_state |= SATA_STATE_PROBING;
9976 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
9977 
9978 		/*
9979 		 * Regardless if a port is usable or not, create
9980 		 * an attachment point
9981 		 */
9982 		mutex_exit(&cportinfo->cport_mutex);
9983 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
9984 		    ncport, 0, SATA_ADDR_CPORT);
9985 		(void) sprintf(name, "%d", ncport);
9986 		if (ddi_create_minor_node(dip, name, S_IFCHR,
9987 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
9988 		    DDI_SUCCESS) {
9989 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
9990 			    "cannot create SATA attachment point for port %d",
9991 			    ncport);
9992 		}
9993 
9994 		/* Probe port */
9995 		start_time = ddi_get_lbolt();
9996 	reprobe_cport:
9997 		sata_device.satadev_addr.cport = ncport;
9998 		sata_device.satadev_addr.pmport = 0;
9999 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
10000 		sata_device.satadev_rev = SATA_DEVICE_REV;
10001 
10002 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10003 		    (dip, &sata_device);
10004 
10005 		mutex_enter(&cportinfo->cport_mutex);
10006 		cportinfo->cport_scr = sata_device.satadev_scr;
10007 		if (rval != SATA_SUCCESS) {
10008 			/* Something went wrong? Fail the port */
10009 			cportinfo->cport_state = SATA_PSTATE_FAILED;
10010 			mutex_exit(&cportinfo->cport_mutex);
10011 			continue;
10012 		}
10013 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
10014 		cportinfo->cport_state |= SATA_STATE_PROBED;
10015 		cportinfo->cport_dev_type = sata_device.satadev_type;
10016 
10017 		cportinfo->cport_state |= SATA_STATE_READY;
10018 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
10019 			mutex_exit(&cportinfo->cport_mutex);
10020 			continue;
10021 		}
10022 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
10023 			/*
10024 			 * There is some device attached.
10025 			 * Allocate device info structure
10026 			 */
10027 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
10028 				mutex_exit(&cportinfo->cport_mutex);
10029 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
10030 				    kmem_zalloc(sizeof (sata_drive_info_t),
10031 				    KM_SLEEP);
10032 				mutex_enter(&cportinfo->cport_mutex);
10033 			}
10034 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
10035 			drive->satadrv_addr = cportinfo->cport_addr;
10036 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
10037 			drive->satadrv_type = cportinfo->cport_dev_type;
10038 			drive->satadrv_state = SATA_STATE_UNKNOWN;
10039 
10040 			mutex_exit(&cportinfo->cport_mutex);
10041 			if (sata_add_device(dip, sata_hba_inst, &sata_device) !=
10042 			    SATA_SUCCESS) {
10043 				/*
10044 				 * Plugged device was not correctly identified.
10045 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
10046 				 */
10047 				cur_time = ddi_get_lbolt();
10048 				if ((cur_time - start_time) <
10049 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
10050 					/* sleep for a while */
10051 					delay(drv_usectohz(
10052 					    SATA_DEV_RETRY_DLY));
10053 					goto reprobe_cport;
10054 				}
10055 			}
10056 		} else { /* SATA_DTYPE_PMULT */
10057 			mutex_exit(&cportinfo->cport_mutex);
10058 
10059 			/* Allocate sata_pmult_info and sata_pmport_info */
10060 			if (sata_alloc_pmult(sata_hba_inst, &sata_device) !=
10061 			    SATA_SUCCESS)
10062 				continue;
10063 
10064 			/* Log the information of the port multiplier */
10065 			sata_show_pmult_info(sata_hba_inst, &sata_device);
10066 
10067 			/* Probe its pmports */
10068 			sata_probe_pmports(sata_hba_inst, ncport);
10069 		}
10070 	}
10071 }
10072 
10073 /*
10074  * Probe all device ports behind a port multiplier.
10075  *
10076  * PMult-related structure should be allocated before by sata_alloc_pmult().
10077  *
10078  * NOTE1: Only called from sata_probe_ports()
10079  * NOTE2: No mutex should be hold.
10080  */
10081 static void
10082 sata_probe_pmports(sata_hba_inst_t *sata_hba_inst, uint8_t ncport)
10083 {
10084 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
10085 	sata_pmult_info_t	*pmultinfo = NULL;
10086 	sata_pmport_info_t 	*pmportinfo = NULL;
10087 	sata_drive_info_t	*drive = NULL;
10088 	sata_device_t		sata_device;
10089 
10090 	clock_t			start_time, cur_time;
10091 	int			npmport;
10092 	int			rval;
10093 
10094 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, ncport);
10095 
10096 	/* Probe Port Multiplier ports */
10097 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports; npmport++) {
10098 		pmportinfo = pmultinfo->pmult_dev_port[npmport];
10099 		start_time = ddi_get_lbolt();
10100 reprobe_pmport:
10101 		sata_device.satadev_addr.cport = ncport;
10102 		sata_device.satadev_addr.pmport = npmport;
10103 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
10104 		sata_device.satadev_rev = SATA_DEVICE_REV;
10105 
10106 		/* Let HBA driver probe it. */
10107 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10108 		    (dip, &sata_device);
10109 		mutex_enter(&pmportinfo->pmport_mutex);
10110 
10111 		pmportinfo->pmport_scr = sata_device.satadev_scr;
10112 
10113 		if (rval != SATA_SUCCESS) {
10114 			pmportinfo->pmport_state =
10115 			    SATA_PSTATE_FAILED;
10116 			mutex_exit(&pmportinfo->pmport_mutex);
10117 			continue;
10118 		}
10119 		pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
10120 		pmportinfo->pmport_state |= SATA_STATE_PROBED;
10121 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
10122 
10123 		pmportinfo->pmport_state |= SATA_STATE_READY;
10124 		if (pmportinfo->pmport_dev_type ==
10125 		    SATA_DTYPE_NONE) {
10126 			SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
10127 			    "no device found at port %d:%d", ncport, npmport);
10128 			mutex_exit(&pmportinfo->pmport_mutex);
10129 			continue;
10130 		}
10131 		/* Port multipliers cannot be chained */
10132 		ASSERT(pmportinfo->pmport_dev_type != SATA_DTYPE_PMULT);
10133 		/*
10134 		 * There is something attached to Port
10135 		 * Multiplier device port
10136 		 * Allocate device info structure
10137 		 */
10138 		if (pmportinfo->pmport_sata_drive == NULL) {
10139 			mutex_exit(&pmportinfo->pmport_mutex);
10140 			pmportinfo->pmport_sata_drive =
10141 			    kmem_zalloc(sizeof (sata_drive_info_t), KM_SLEEP);
10142 			mutex_enter(&pmportinfo->pmport_mutex);
10143 		}
10144 		drive = pmportinfo->pmport_sata_drive;
10145 		drive->satadrv_addr.cport = pmportinfo->pmport_addr.cport;
10146 		drive->satadrv_addr.pmport = npmport;
10147 		drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
10148 		drive->satadrv_type = pmportinfo-> pmport_dev_type;
10149 		drive->satadrv_state = SATA_STATE_UNKNOWN;
10150 
10151 		mutex_exit(&pmportinfo->pmport_mutex);
10152 		rval = sata_add_device(dip, sata_hba_inst, &sata_device);
10153 
10154 		if (rval != SATA_SUCCESS) {
10155 			/*
10156 			 * Plugged device was not correctly identified.
10157 			 * Retry, within the SATA_DEV_IDENTIFY_TIMEOUT
10158 			 */
10159 			cur_time = ddi_get_lbolt();
10160 			if ((cur_time - start_time) < drv_usectohz(
10161 			    SATA_DEV_IDENTIFY_TIMEOUT)) {
10162 				/* sleep for a while */
10163 				delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10164 				goto reprobe_pmport;
10165 			}
10166 		}
10167 	}
10168 }
10169 
10170 /*
10171  * Add SATA device for specified HBA instance & port (SCSI target
10172  * device nodes).
10173  * This function is called (indirectly) only from sata_hba_attach().
10174  * A target node is created when there is a supported type device attached,
10175  * but may be removed if it cannot be put online.
10176  *
10177  * This function cannot be called from an interrupt context.
10178  *
10179  * Create target nodes for disk, CD/DVD, Tape and ATAPI disk devices
10180  *
10181  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
10182  * device identification failed - adding a device could be retried.
10183  *
10184  */
10185 static 	int
10186 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst,
10187     sata_device_t *sata_device)
10188 {
10189 	sata_cport_info_t 	*cportinfo;
10190 	sata_pmult_info_t	*pminfo;
10191 	sata_pmport_info_t	*pmportinfo;
10192 	dev_info_t		*cdip;		/* child dip */
10193 	sata_address_t		*saddr = &sata_device->satadev_addr;
10194 	uint8_t			cport, pmport;
10195 	int			rval;
10196 
10197 	cport = saddr->cport;
10198 	pmport = saddr->pmport;
10199 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10200 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
10201 
10202 	/*
10203 	 * Some device is attached to a controller port.
10204 	 * We rely on controllers distinquishing between no-device,
10205 	 * attached port multiplier and other kind of attached device.
10206 	 * We need to get Identify Device data and determine
10207 	 * positively the dev type before trying to attach
10208 	 * the target driver.
10209 	 */
10210 	sata_device->satadev_rev = SATA_DEVICE_REV;
10211 	switch (saddr->qual) {
10212 	case SATA_ADDR_CPORT:
10213 		/*
10214 		 * Add a non-port-multiplier device at controller port.
10215 		 */
10216 		saddr->qual = SATA_ADDR_DCPORT;
10217 
10218 		rval = sata_probe_device(sata_hba_inst, sata_device);
10219 		if (rval != SATA_SUCCESS ||
10220 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN)
10221 			return (SATA_FAILURE);
10222 
10223 		mutex_enter(&cportinfo->cport_mutex);
10224 		sata_show_drive_info(sata_hba_inst,
10225 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
10226 
10227 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10228 			/*
10229 			 * Could not determine device type or
10230 			 * a device is not supported.
10231 			 * Degrade this device to unknown.
10232 			 */
10233 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10234 			mutex_exit(&cportinfo->cport_mutex);
10235 			return (SATA_SUCCESS);
10236 		}
10237 		cportinfo->cport_dev_type = sata_device->satadev_type;
10238 		cportinfo->cport_tgtnode_clean = B_TRUE;
10239 		mutex_exit(&cportinfo->cport_mutex);
10240 
10241 		/*
10242 		 * Initialize device to the desired state. Even if it
10243 		 * fails, the device will still attach but syslog
10244 		 * will show the warning.
10245 		 */
10246 		if (sata_initialize_device(sata_hba_inst,
10247 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
10248 			/* Retry */
10249 			rval = sata_initialize_device(sata_hba_inst,
10250 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
10251 
10252 			if (rval == SATA_RETRY)
10253 				sata_log(sata_hba_inst, CE_WARN,
10254 				    "SATA device at port %d - "
10255 				    "default device features could not be set."
10256 				    " Device may not operate as expected.",
10257 				    cport);
10258 		}
10259 
10260 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10261 		if (cdip == NULL) {
10262 			/*
10263 			 * Attaching target node failed.
10264 			 * We retain sata_drive_info structure...
10265 			 */
10266 			return (SATA_SUCCESS);
10267 		}
10268 
10269 		mutex_enter(&cportinfo->cport_mutex);
10270 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
10271 		    satadrv_state = SATA_STATE_READY;
10272 		mutex_exit(&cportinfo->cport_mutex);
10273 
10274 		break;
10275 
10276 	case SATA_ADDR_PMPORT:
10277 		saddr->qual = SATA_ADDR_DPMPORT;
10278 
10279 		mutex_enter(&cportinfo->cport_mutex);
10280 		/* It must be a Port Multiplier at the controller port */
10281 		ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
10282 
10283 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
10284 		pmportinfo = pminfo->pmult_dev_port[saddr->pmport];
10285 		mutex_exit(&cportinfo->cport_mutex);
10286 
10287 		rval = sata_probe_device(sata_hba_inst, sata_device);
10288 		if (rval != SATA_SUCCESS ||
10289 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
10290 			return (SATA_FAILURE);
10291 		}
10292 
10293 		mutex_enter(&pmportinfo->pmport_mutex);
10294 		sata_show_drive_info(sata_hba_inst,
10295 		    SATA_PMPORTINFO_DRV_INFO(pmportinfo));
10296 
10297 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
10298 			/*
10299 			 * Could not determine device type.
10300 			 * Degrade this device to unknown.
10301 			 */
10302 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
10303 			mutex_exit(&pmportinfo->pmport_mutex);
10304 			return (SATA_SUCCESS);
10305 		}
10306 		pmportinfo->pmport_dev_type = sata_device->satadev_type;
10307 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
10308 		mutex_exit(&pmportinfo->pmport_mutex);
10309 
10310 		/*
10311 		 * Initialize device to the desired state.
10312 		 * Even if it fails, the device will still
10313 		 * attach but syslog will show the warning.
10314 		 */
10315 		if (sata_initialize_device(sata_hba_inst,
10316 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
10317 			/* Retry */
10318 			rval = sata_initialize_device(sata_hba_inst,
10319 			    pmportinfo->pmport_sata_drive);
10320 
10321 			if (rval == SATA_RETRY)
10322 				sata_log(sata_hba_inst, CE_WARN,
10323 				    "SATA device at port %d:%d - "
10324 				    "default device features could not be set."
10325 				    " Device may not operate as expected.",
10326 				    cport, pmport);
10327 		}
10328 
10329 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
10330 		if (cdip == NULL) {
10331 			/*
10332 			 * Attaching target node failed.
10333 			 * We retain sata_drive_info structure...
10334 			 */
10335 			return (SATA_SUCCESS);
10336 		}
10337 		mutex_enter(&pmportinfo->pmport_mutex);
10338 		pmportinfo->pmport_sata_drive->satadrv_state |=
10339 		    SATA_STATE_READY;
10340 		mutex_exit(&pmportinfo->pmport_mutex);
10341 
10342 		break;
10343 
10344 	default:
10345 		return (SATA_FAILURE);
10346 	}
10347 
10348 	return (SATA_SUCCESS);
10349 }
10350 
10351 /*
10352  * Clean up target node at specific address.
10353  *
10354  * NOTE: No Mutex should be hold.
10355  */
10356 static int
10357 sata_offline_device(sata_hba_inst_t *sata_hba_inst,
10358     sata_device_t *sata_device, sata_drive_info_t *sdinfo)
10359 {
10360 	uint8_t cport, pmport, qual;
10361 	dev_info_t *tdip;
10362 
10363 	cport = sata_device->satadev_addr.cport;
10364 	pmport = sata_device->satadev_addr.pmport;
10365 	qual = sata_device->satadev_addr.qual;
10366 
10367 	if (qual == SATA_ADDR_DCPORT) {
10368 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10369 		    "sata_hba_ioctl: disconnect device at port %d", cport));
10370 	} else {
10371 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10372 		    "sata_hba_ioctl: disconnect device at port %d:%d",
10373 		    cport, pmport));
10374 	}
10375 
10376 	/* We are addressing attached device, not a port */
10377 	sata_device->satadev_addr.qual =
10378 	    sdinfo->satadrv_addr.qual;
10379 	tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
10380 	    &sata_device->satadev_addr);
10381 	if (tdip != NULL && ndi_devi_offline(tdip,
10382 	    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10383 		/*
10384 		 * Problem :
10385 		 * The target node remained attached.
10386 		 * This happens when the device file was open
10387 		 * or a node was waiting for resources.
10388 		 * Cannot do anything about it.
10389 		 */
10390 		if (qual == SATA_ADDR_DCPORT) {
10391 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10392 			    "sata_hba_ioctl: disconnect: could "
10393 			    "not unconfigure device before "
10394 			    "disconnecting the SATA port %d",
10395 			    cport));
10396 		} else {
10397 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10398 			    "sata_hba_ioctl: disconnect: could "
10399 			    "not unconfigure device before "
10400 			    "disconnecting the SATA port %d:%d",
10401 			    cport, pmport));
10402 		}
10403 		/*
10404 		 * Set DEVICE REMOVED state in the target
10405 		 * node. It will prevent access to the device
10406 		 * even when a new device is attached, until
10407 		 * the old target node is released, removed and
10408 		 * recreated for a new  device.
10409 		 */
10410 		sata_set_device_removed(tdip);
10411 
10412 		/*
10413 		 * Instruct event daemon to try the target
10414 		 * node cleanup later.
10415 		 */
10416 		sata_set_target_node_cleanup(
10417 		    sata_hba_inst, &sata_device->satadev_addr);
10418 	}
10419 
10420 
10421 	return (SATA_SUCCESS);
10422 }
10423 
10424 
10425 /*
10426  * Create scsi target node for attached device, create node properties and
10427  * attach the node.
10428  * The node could be removed if the device onlining fails.
10429  *
10430  * A dev_info_t pointer is returned if operation is successful, NULL is
10431  * returned otherwise.
10432  */
10433 
10434 static dev_info_t *
10435 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
10436 			sata_address_t *sata_addr)
10437 {
10438 	dev_info_t *cdip = NULL;
10439 	int rval;
10440 	char *nname = NULL;
10441 	char **compatible = NULL;
10442 	int ncompatible;
10443 	struct scsi_inquiry inq;
10444 	sata_device_t sata_device;
10445 	sata_drive_info_t *sdinfo;
10446 	int target;
10447 	int i;
10448 
10449 	sata_device.satadev_rev = SATA_DEVICE_REV;
10450 	sata_device.satadev_addr = *sata_addr;
10451 
10452 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
10453 
10454 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
10455 
10456 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
10457 	    sata_addr->pmport, sata_addr->qual);
10458 
10459 	if (sdinfo == NULL) {
10460 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10461 		    sata_addr->cport)));
10462 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10463 		    "sata_create_target_node: no sdinfo for target %x",
10464 		    target));
10465 		return (NULL);
10466 	}
10467 
10468 	/*
10469 	 * create or get scsi inquiry data, expected by
10470 	 * scsi_hba_nodename_compatible_get()
10471 	 * SATA hard disks get Identify Data translated into Inguiry Data.
10472 	 * ATAPI devices respond directly to Inquiry request.
10473 	 */
10474 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10475 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
10476 		    (uint8_t *)&inq);
10477 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10478 		    sata_addr->cport)));
10479 	} else { /* Assume supported ATAPI device */
10480 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10481 		    sata_addr->cport)));
10482 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
10483 		    &inq) == SATA_FAILURE)
10484 			return (NULL);
10485 		/*
10486 		 * Save supported ATAPI transport version
10487 		 */
10488 		sdinfo->satadrv_atapi_trans_ver =
10489 		    SATA_ATAPI_TRANS_VERSION(&inq);
10490 	}
10491 
10492 	/* determine the node name and compatible */
10493 	scsi_hba_nodename_compatible_get(&inq, NULL,
10494 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
10495 
10496 #ifdef SATA_DEBUG
10497 	if (sata_debug_flags & SATA_DBG_NODES) {
10498 		if (nname == NULL) {
10499 			cmn_err(CE_NOTE, "sata_create_target_node: "
10500 			    "cannot determine nodename for target %d\n",
10501 			    target);
10502 		} else {
10503 			cmn_err(CE_WARN, "sata_create_target_node: "
10504 			    "target %d nodename: %s\n", target, nname);
10505 		}
10506 		if (compatible == NULL) {
10507 			cmn_err(CE_WARN,
10508 			    "sata_create_target_node: no compatible name\n");
10509 		} else {
10510 			for (i = 0; i < ncompatible; i++) {
10511 				cmn_err(CE_WARN, "sata_create_target_node: "
10512 				    "compatible name: %s\n", compatible[i]);
10513 			}
10514 		}
10515 	}
10516 #endif
10517 
10518 	/* if nodename can't be determined, log error and exit */
10519 	if (nname == NULL) {
10520 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10521 		    "sata_create_target_node: cannot determine nodename "
10522 		    "for target %d\n", target));
10523 		scsi_hba_nodename_compatible_free(nname, compatible);
10524 		return (NULL);
10525 	}
10526 	/*
10527 	 * Create scsi target node
10528 	 */
10529 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
10530 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10531 	    "device-type", "scsi");
10532 
10533 	if (rval != DDI_PROP_SUCCESS) {
10534 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10535 		    "updating device_type prop failed %d", rval));
10536 		goto fail;
10537 	}
10538 
10539 	/*
10540 	 * Create target node properties: target & lun
10541 	 */
10542 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
10543 	if (rval != DDI_PROP_SUCCESS) {
10544 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10545 		    "updating target prop failed %d", rval));
10546 		goto fail;
10547 	}
10548 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
10549 	if (rval != DDI_PROP_SUCCESS) {
10550 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10551 		    "updating target prop failed %d", rval));
10552 		goto fail;
10553 	}
10554 
10555 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
10556 		/*
10557 		 * Add "variant" property
10558 		 */
10559 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10560 		    "variant", "atapi");
10561 		if (rval != DDI_PROP_SUCCESS) {
10562 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10563 			    "sata_create_target_node: variant atapi "
10564 			    "property could not be created: %d", rval));
10565 			goto fail;
10566 		}
10567 	}
10568 	/* decorate the node with compatible */
10569 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
10570 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
10571 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10572 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
10573 		    (void *)cdip));
10574 		goto fail;
10575 	}
10576 
10577 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10578 		/*
10579 		 * Add "sata-phy" property
10580 		 */
10581 		if (ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "sata-phy",
10582 		    (int)sata_addr->cport) != DDI_PROP_SUCCESS) {
10583 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10584 			    "sata_create_target_node: failed to create "
10585 			    "\"sata-phy\" property: port %d",
10586 			    sata_addr->cport));
10587 		}
10588 	}
10589 
10590 
10591 	/*
10592 	 * Now, try to attach the driver. If probing of the device fails,
10593 	 * the target node may be removed
10594 	 */
10595 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
10596 
10597 	scsi_hba_nodename_compatible_free(nname, compatible);
10598 
10599 	if (rval == NDI_SUCCESS)
10600 		return (cdip);
10601 
10602 	/* target node was removed - are we sure? */
10603 	return (NULL);
10604 
10605 fail:
10606 	scsi_hba_nodename_compatible_free(nname, compatible);
10607 	ddi_prop_remove_all(cdip);
10608 	rval = ndi_devi_free(cdip);
10609 	if (rval != NDI_SUCCESS) {
10610 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10611 		    "node removal failed %d", rval));
10612 	}
10613 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
10614 	    "cannot create target node for SATA device at port %d",
10615 	    sata_addr->cport);
10616 	return (NULL);
10617 }
10618 
10619 /*
10620  * Remove a target node.
10621  */
10622 static void
10623 sata_remove_target_node(sata_hba_inst_t *sata_hba_inst,
10624 			sata_address_t *sata_addr)
10625 {
10626 	dev_info_t *tdip;
10627 	uint8_t cport = sata_addr->cport;
10628 	uint8_t pmport = sata_addr->pmport;
10629 	uint8_t qual = sata_addr->qual;
10630 
10631 	/* Note the sata daemon uses the address of the port/pmport */
10632 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
10633 
10634 	/* Remove target node */
10635 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), cport, pmport);
10636 	if (tdip != NULL) {
10637 		/*
10638 		 * Target node exists.  Unconfigure device
10639 		 * then remove the target node (one ndi
10640 		 * operation).
10641 		 */
10642 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10643 			/*
10644 			 * PROBLEM - no device, but target node remained. This
10645 			 * happens when the file was open or node was waiting
10646 			 * for resources.
10647 			 */
10648 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10649 			    "sata_remove_target_node: "
10650 			    "Failed to remove target node for "
10651 			    "detached SATA device."));
10652 			/*
10653 			 * Set target node state to DEVI_DEVICE_REMOVED. But
10654 			 * re-check first that the node still exists.
10655 			 */
10656 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
10657 			    cport, pmport);
10658 			if (tdip != NULL) {
10659 				sata_set_device_removed(tdip);
10660 				/*
10661 				 * Instruct event daemon to retry the cleanup
10662 				 * later.
10663 				 */
10664 				sata_set_target_node_cleanup(sata_hba_inst,
10665 				    sata_addr);
10666 			}
10667 		}
10668 
10669 		if (qual == SATA_ADDR_CPORT)
10670 			sata_log(sata_hba_inst, CE_WARN,
10671 			    "SATA device detached at port %d", cport);
10672 		else
10673 			sata_log(sata_hba_inst, CE_WARN,
10674 			    "SATA device detached at port %d:%d",
10675 			    cport, pmport);
10676 	}
10677 #ifdef SATA_DEBUG
10678 	else {
10679 		if (qual == SATA_ADDR_CPORT)
10680 			sata_log(sata_hba_inst, CE_WARN,
10681 			    "target node not found at port %d", cport);
10682 		else
10683 			sata_log(sata_hba_inst, CE_WARN,
10684 			    "target node not found at port %d:%d",
10685 			    cport, pmport);
10686 	}
10687 #endif
10688 }
10689 
10690 
10691 /*
10692  * Re-probe sata port, check for a device and attach info
10693  * structures when necessary. Identify Device data is fetched, if possible.
10694  * Assumption: sata address is already validated.
10695  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10696  * the presence of a device and its type.
10697  *
10698  * flag arg specifies that the function should try multiple times to identify
10699  * device type and to initialize it, or it should return immediately on failure.
10700  * SATA_DEV_IDENTIFY_RETRY - retry
10701  * SATA_DEV_IDENTIFY_NORETRY - no retry
10702  *
10703  * SATA_FAILURE is returned if one of the operations failed.
10704  *
10705  * This function cannot be called in interrupt context - it may sleep.
10706  *
10707  * Note: Port multiplier is supported.
10708  */
10709 static int
10710 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10711     int flag)
10712 {
10713 	sata_cport_info_t *cportinfo;
10714 	sata_pmult_info_t *pmultinfo;
10715 	sata_drive_info_t *sdinfo, *osdinfo;
10716 	boolean_t init_device = B_FALSE;
10717 	int prev_device_type = SATA_DTYPE_NONE;
10718 	int prev_device_settings = 0;
10719 	int prev_device_state = 0;
10720 	clock_t start_time;
10721 	int retry = B_FALSE;
10722 	uint8_t cport = sata_device->satadev_addr.cport;
10723 	int rval_probe, rval_init;
10724 
10725 	/*
10726 	 * If target is pmport, sata_reprobe_pmport() will handle it.
10727 	 */
10728 	if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT ||
10729 	    sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT)
10730 		return (sata_reprobe_pmport(sata_hba_inst, sata_device, flag));
10731 
10732 	/* We only care about host sata cport for now */
10733 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
10734 	    sata_device->satadev_addr.cport);
10735 
10736 	/*
10737 	 * If a port multiplier was previously attached (we have no idea it
10738 	 * still there or not), sata_reprobe_pmult() will handle it.
10739 	 */
10740 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT)
10741 		return (sata_reprobe_pmult(sata_hba_inst, sata_device, flag));
10742 
10743 	/* Store sata_drive_info when a non-pmult device was attached. */
10744 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10745 	if (osdinfo != NULL) {
10746 		/*
10747 		 * We are re-probing port with a previously attached device.
10748 		 * Save previous device type and settings.
10749 		 */
10750 		prev_device_type = cportinfo->cport_dev_type;
10751 		prev_device_settings = osdinfo->satadrv_settings;
10752 		prev_device_state = osdinfo->satadrv_state;
10753 	}
10754 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
10755 		start_time = ddi_get_lbolt();
10756 		retry = B_TRUE;
10757 	}
10758 retry_probe:
10759 
10760 	/* probe port */
10761 	mutex_enter(&cportinfo->cport_mutex);
10762 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10763 	cportinfo->cport_state |= SATA_STATE_PROBING;
10764 	mutex_exit(&cportinfo->cport_mutex);
10765 
10766 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10767 	    (SATA_DIP(sata_hba_inst), sata_device);
10768 
10769 	mutex_enter(&cportinfo->cport_mutex);
10770 	if (rval_probe != SATA_SUCCESS) {
10771 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10772 		mutex_exit(&cportinfo->cport_mutex);
10773 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
10774 		    "SATA port %d probing failed",
10775 		    cportinfo->cport_addr.cport));
10776 		return (SATA_FAILURE);
10777 	}
10778 
10779 	/*
10780 	 * update sata port state and set device type
10781 	 */
10782 	sata_update_port_info(sata_hba_inst, sata_device);
10783 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10784 
10785 	/*
10786 	 * Sanity check - Port is active? Is the link active?
10787 	 * Is there any device attached?
10788 	 */
10789 	if ((cportinfo->cport_state &
10790 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10791 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10792 	    SATA_PORT_DEVLINK_UP) {
10793 		/*
10794 		 * Port in non-usable state or no link active/no device.
10795 		 * Free info structure if necessary (direct attached drive
10796 		 * only, for now!
10797 		 */
10798 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10799 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10800 		/* Add here differentiation for device attached or not */
10801 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10802 		mutex_exit(&cportinfo->cport_mutex);
10803 		if (sdinfo != NULL)
10804 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10805 		return (SATA_SUCCESS);
10806 	}
10807 
10808 	cportinfo->cport_state |= SATA_STATE_READY;
10809 	cportinfo->cport_state |= SATA_STATE_PROBED;
10810 
10811 	cportinfo->cport_dev_type = sata_device->satadev_type;
10812 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10813 
10814 	/*
10815 	 * If we are re-probing the port, there may be
10816 	 * sata_drive_info structure attached
10817 	 */
10818 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10819 
10820 		/*
10821 		 * There is no device, so remove device info structure,
10822 		 * if necessary.
10823 		 */
10824 		/* Device change: Drive -> None */
10825 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10826 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10827 		if (sdinfo != NULL) {
10828 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10829 			sata_log(sata_hba_inst, CE_WARN,
10830 			    "SATA device detached "
10831 			    "from port %d", cportinfo->cport_addr.cport);
10832 		}
10833 		mutex_exit(&cportinfo->cport_mutex);
10834 		return (SATA_SUCCESS);
10835 
10836 	}
10837 
10838 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10839 
10840 		/* Device (may) change: Drive -> Drive */
10841 		if (sdinfo == NULL) {
10842 			/*
10843 			 * There is some device attached, but there is
10844 			 * no sata_drive_info structure - allocate one
10845 			 */
10846 			mutex_exit(&cportinfo->cport_mutex);
10847 			sdinfo = kmem_zalloc(
10848 			    sizeof (sata_drive_info_t), KM_SLEEP);
10849 			mutex_enter(&cportinfo->cport_mutex);
10850 			/*
10851 			 * Recheck, that the port state did not change when we
10852 			 * released mutex.
10853 			 */
10854 			if (cportinfo->cport_state & SATA_STATE_READY) {
10855 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
10856 				sdinfo->satadrv_addr = cportinfo->cport_addr;
10857 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
10858 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10859 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10860 			} else {
10861 				/*
10862 				 * Port is not in ready state, we
10863 				 * cannot attach a device.
10864 				 */
10865 				mutex_exit(&cportinfo->cport_mutex);
10866 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
10867 				return (SATA_SUCCESS);
10868 			}
10869 			/*
10870 			 * Since we are adding device, presumably new one,
10871 			 * indicate that it  should be initalized,
10872 			 * as well as some internal framework states).
10873 			 */
10874 			init_device = B_TRUE;
10875 		}
10876 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10877 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10878 	} else {
10879 		/* Device change: Drive -> PMult */
10880 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10881 		if (sdinfo != NULL) {
10882 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10883 			sata_log(sata_hba_inst, CE_WARN,
10884 			    "SATA device detached "
10885 			    "from port %d", cportinfo->cport_addr.cport);
10886 		}
10887 
10888 		sata_log(sata_hba_inst, CE_WARN,
10889 		    "SATA port multiplier detected at port %d",
10890 		    cportinfo->cport_addr.cport);
10891 
10892 		mutex_exit(&cportinfo->cport_mutex);
10893 		if (sata_alloc_pmult(sata_hba_inst, sata_device) !=
10894 		    SATA_SUCCESS)
10895 			return (SATA_FAILURE);
10896 		sata_show_pmult_info(sata_hba_inst, sata_device);
10897 		mutex_enter(&cportinfo->cport_mutex);
10898 
10899 		/*
10900 		 * Mark all the port multiplier port behind the port
10901 		 * multiplier behind with link events, so that the sata daemon
10902 		 * will update their status.
10903 		 */
10904 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10905 		pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10906 		mutex_exit(&cportinfo->cport_mutex);
10907 		return (SATA_SUCCESS);
10908 	}
10909 	mutex_exit(&cportinfo->cport_mutex);
10910 
10911 	/*
10912 	 * Figure out what kind of device we are really
10913 	 * dealing with. Failure of identifying device does not fail this
10914 	 * function.
10915 	 */
10916 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
10917 	rval_init = SATA_FAILURE;
10918 	mutex_enter(&cportinfo->cport_mutex);
10919 	if (rval_probe == SATA_SUCCESS) {
10920 		/*
10921 		 * If we are dealing with the same type of a device as before,
10922 		 * restore its settings flags.
10923 		 */
10924 		if (osdinfo != NULL &&
10925 		    sata_device->satadev_type == prev_device_type)
10926 			sdinfo->satadrv_settings = prev_device_settings;
10927 
10928 		mutex_exit(&cportinfo->cport_mutex);
10929 		rval_init = SATA_SUCCESS;
10930 		/* Set initial device features, if necessary */
10931 		if (init_device == B_TRUE) {
10932 			rval_init = sata_initialize_device(sata_hba_inst,
10933 			    sdinfo);
10934 		}
10935 		if (rval_init == SATA_SUCCESS)
10936 			return (rval_init);
10937 		/* else we will retry if retry was asked for */
10938 
10939 	} else {
10940 		/*
10941 		 * If there was some device info before we probe the device,
10942 		 * restore previous device setting, so we can retry from scratch
10943 		 * later. Providing, of course, that device has not disapear
10944 		 * during probing process.
10945 		 */
10946 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
10947 			if (osdinfo != NULL) {
10948 				cportinfo->cport_dev_type = prev_device_type;
10949 				sdinfo->satadrv_type = prev_device_type;
10950 				sdinfo->satadrv_state = prev_device_state;
10951 			}
10952 		} else {
10953 			/* device is gone */
10954 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10955 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10956 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10957 			mutex_exit(&cportinfo->cport_mutex);
10958 			return (SATA_SUCCESS);
10959 		}
10960 		mutex_exit(&cportinfo->cport_mutex);
10961 	}
10962 
10963 	if (retry) {
10964 		clock_t cur_time = ddi_get_lbolt();
10965 		/*
10966 		 * A device was not successfully identified or initialized.
10967 		 * Track retry time for device identification.
10968 		 */
10969 		if ((cur_time - start_time) <
10970 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10971 			/* sleep for a while */
10972 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10973 			goto retry_probe;
10974 		}
10975 		/* else no more retries */
10976 		mutex_enter(&cportinfo->cport_mutex);
10977 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10978 			if (rval_init == SATA_RETRY) {
10979 				/*
10980 				 * Setting drive features have failed, but
10981 				 * because the drive is still accessible,
10982 				 * keep it and emit a warning message.
10983 				 */
10984 				sata_log(sata_hba_inst, CE_WARN,
10985 				    "SATA device at port %d - desired "
10986 				    "drive features could not be set. "
10987 				    "Device may not operate as expected.",
10988 				    cportinfo->cport_addr.cport);
10989 			} else {
10990 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
10991 				    satadrv_state = SATA_DSTATE_FAILED;
10992 			}
10993 		}
10994 		mutex_exit(&cportinfo->cport_mutex);
10995 	}
10996 	return (SATA_SUCCESS);
10997 }
10998 
10999 /*
11000  * Reprobe a controller port that connected to a port multiplier.
11001  *
11002  * NOTE: No Mutex should be hold.
11003  */
11004 static int
11005 sata_reprobe_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
11006     int flag)
11007 {
11008 	_NOTE(ARGUNUSED(flag))
11009 	sata_cport_info_t *cportinfo;
11010 	sata_pmult_info_t *pmultinfo;
11011 	uint8_t cport = sata_device->satadev_addr.cport;
11012 	int rval_probe;
11013 
11014 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11015 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
11016 
11017 	/* probe port */
11018 	mutex_enter(&cportinfo->cport_mutex);
11019 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11020 	cportinfo->cport_state |= SATA_STATE_PROBING;
11021 	mutex_exit(&cportinfo->cport_mutex);
11022 
11023 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11024 	    (SATA_DIP(sata_hba_inst), sata_device);
11025 
11026 	mutex_enter(&cportinfo->cport_mutex);
11027 	if (rval_probe != SATA_SUCCESS) {
11028 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11029 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmult: "
11030 		    "SATA port %d probing failed", cport));
11031 		sata_log(sata_hba_inst, CE_WARN,
11032 		    "SATA port multiplier detached at port %d", cport);
11033 		mutex_exit(&cportinfo->cport_mutex);
11034 		sata_free_pmult(sata_hba_inst, sata_device);
11035 		return (SATA_FAILURE);
11036 	}
11037 
11038 	/*
11039 	 * update sata port state and set device type
11040 	 */
11041 	sata_update_port_info(sata_hba_inst, sata_device);
11042 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
11043 	cportinfo->cport_state |= SATA_STATE_PROBED;
11044 
11045 	/*
11046 	 * Sanity check - Port is active? Is the link active?
11047 	 * Is there any device attached?
11048 	 */
11049 	if ((cportinfo->cport_state &
11050 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11051 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11052 	    SATA_PORT_DEVLINK_UP ||
11053 	    (sata_device->satadev_type == SATA_DTYPE_NONE)) {
11054 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11055 		mutex_exit(&cportinfo->cport_mutex);
11056 		sata_free_pmult(sata_hba_inst, sata_device);
11057 		sata_log(sata_hba_inst, CE_WARN,
11058 		    "SATA port multiplier detached at port %d", cport);
11059 		return (SATA_SUCCESS);
11060 	}
11061 
11062 	/*
11063 	 * Device changed: PMult -> Non-PMult
11064 	 *
11065 	 * This situation is uncommon, most possibly being caused by errors
11066 	 * after which the port multiplier is not correct initialized and
11067 	 * recognized. In that case the new device will be marked as unknown
11068 	 * and will not be automatically probed in this routine. Instead
11069 	 * system administrator could manually restart it via cfgadm(1M).
11070 	 */
11071 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
11072 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11073 		mutex_exit(&cportinfo->cport_mutex);
11074 		sata_free_pmult(sata_hba_inst, sata_device);
11075 		sata_log(sata_hba_inst, CE_WARN,
11076 		    "SATA port multiplier detached at port %d", cport);
11077 		return (SATA_FAILURE);
11078 	}
11079 
11080 	/*
11081 	 * Now we know it is a port multiplier. However, if this is not the
11082 	 * previously attached port multiplier - they may have different
11083 	 * pmport numbers - we need to re-allocate data structures for every
11084 	 * pmport and drive.
11085 	 *
11086 	 * Port multipliers of the same model have identical values in these
11087 	 * registers, so it is still necessary to update the information of
11088 	 * all drives attached to the previous port multiplier afterwards.
11089 	 */
11090 	/* Device changed: PMult -> another PMult */
11091 	mutex_exit(&cportinfo->cport_mutex);
11092 	sata_free_pmult(sata_hba_inst, sata_device);
11093 	if (sata_alloc_pmult(sata_hba_inst, sata_device) != SATA_SUCCESS)
11094 		return (SATA_FAILURE);
11095 	mutex_enter(&cportinfo->cport_mutex);
11096 
11097 	SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11098 	    "SATA port multiplier [changed] at port %d", cport);
11099 	sata_log(sata_hba_inst, CE_WARN,
11100 	    "SATA port multiplier detected at port %d", cport);
11101 
11102 	/*
11103 	 * Mark all the port multiplier port behind the port
11104 	 * multiplier behind with link events, so that the sata daemon
11105 	 * will update their status.
11106 	 */
11107 	pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
11108 	mutex_exit(&cportinfo->cport_mutex);
11109 
11110 	return (SATA_SUCCESS);
11111 }
11112 
11113 /*
11114  * Re-probe a port multiplier port, check for a device and attach info
11115  * structures when necessary. Identify Device data is fetched, if possible.
11116  * Assumption: sata address is already validated as port multiplier port.
11117  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
11118  * the presence of a device and its type.
11119  *
11120  * flag arg specifies that the function should try multiple times to identify
11121  * device type and to initialize it, or it should return immediately on failure.
11122  * SATA_DEV_IDENTIFY_RETRY - retry
11123  * SATA_DEV_IDENTIFY_NORETRY - no retry
11124  *
11125  * SATA_FAILURE is returned if one of the operations failed.
11126  *
11127  * This function cannot be called in interrupt context - it may sleep.
11128  *
11129  * NOTE: Should be only called by sata_probe_port() in case target port is a
11130  *       port multiplier port.
11131  * NOTE: No Mutex should be hold.
11132  */
11133 static int
11134 sata_reprobe_pmport(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
11135     int flag)
11136 {
11137 	sata_cport_info_t *cportinfo = NULL;
11138 	sata_pmport_info_t *pmportinfo = NULL;
11139 	sata_drive_info_t *sdinfo, *osdinfo;
11140 	sata_device_t sdevice;
11141 	boolean_t init_device = B_FALSE;
11142 	int prev_device_type = SATA_DTYPE_NONE;
11143 	int prev_device_settings = 0;
11144 	int prev_device_state = 0;
11145 	clock_t start_time;
11146 	uint8_t cport = sata_device->satadev_addr.cport;
11147 	uint8_t pmport = sata_device->satadev_addr.pmport;
11148 	int rval;
11149 
11150 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11151 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
11152 	osdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11153 
11154 	if (osdinfo != NULL) {
11155 		/*
11156 		 * We are re-probing port with a previously attached device.
11157 		 * Save previous device type and settings.
11158 		 */
11159 		prev_device_type = pmportinfo->pmport_dev_type;
11160 		prev_device_settings = osdinfo->satadrv_settings;
11161 		prev_device_state = osdinfo->satadrv_state;
11162 	}
11163 
11164 	start_time = ddi_get_lbolt();
11165 
11166 	/* check parent status */
11167 	mutex_enter(&cportinfo->cport_mutex);
11168 	if ((cportinfo->cport_state &
11169 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11170 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11171 	    SATA_PORT_DEVLINK_UP) {
11172 		mutex_exit(&cportinfo->cport_mutex);
11173 		return (SATA_FAILURE);
11174 	}
11175 	mutex_exit(&cportinfo->cport_mutex);
11176 
11177 retry_probe_pmport:
11178 
11179 	/* probe port */
11180 	mutex_enter(&pmportinfo->pmport_mutex);
11181 	pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11182 	pmportinfo->pmport_state |= SATA_STATE_PROBING;
11183 	mutex_exit(&pmportinfo->pmport_mutex);
11184 
11185 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11186 	    (SATA_DIP(sata_hba_inst), sata_device);
11187 
11188 	/* might need retry because we cannot touch registers. */
11189 	if (rval == SATA_FAILURE) {
11190 		mutex_enter(&pmportinfo->pmport_mutex);
11191 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
11192 		mutex_exit(&pmportinfo->pmport_mutex);
11193 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
11194 		    "SATA port %d:%d probing failed",
11195 		    cport, pmport));
11196 		return (SATA_FAILURE);
11197 	} else if (rval == SATA_RETRY) {
11198 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
11199 		    "SATA port %d:%d probing failed, retrying...",
11200 		    cport, pmport));
11201 		clock_t cur_time = ddi_get_lbolt();
11202 		/*
11203 		 * A device was not successfully identified or initialized.
11204 		 * Track retry time for device identification.
11205 		 */
11206 		if ((cur_time - start_time) <
11207 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11208 			/* sleep for a while */
11209 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11210 			goto retry_probe_pmport;
11211 		} else {
11212 			mutex_enter(&pmportinfo->pmport_mutex);
11213 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11214 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11215 				    satadrv_state = SATA_DSTATE_FAILED;
11216 			mutex_exit(&pmportinfo->pmport_mutex);
11217 			return (SATA_SUCCESS);
11218 		}
11219 	}
11220 
11221 	/*
11222 	 * Sanity check - Controller port is active? Is the link active?
11223 	 * Is it still a port multiplier?
11224 	 */
11225 	if ((cportinfo->cport_state &
11226 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11227 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11228 	    SATA_PORT_DEVLINK_UP ||
11229 	    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
11230 		/*
11231 		 * Port in non-usable state or no link active/no
11232 		 * device. Free info structure.
11233 		 */
11234 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11235 
11236 		sdevice.satadev_addr.cport = cport;
11237 		sdevice.satadev_addr.pmport = pmport;
11238 		sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
11239 		mutex_exit(&cportinfo->cport_mutex);
11240 
11241 		sata_free_pmult(sata_hba_inst, &sdevice);
11242 		return (SATA_FAILURE);
11243 	}
11244 
11245 	/* SATA_SUCCESS NOW */
11246 	/*
11247 	 * update sata port state and set device type
11248 	 */
11249 	mutex_enter(&pmportinfo->pmport_mutex);
11250 	sata_update_pmport_info(sata_hba_inst, sata_device);
11251 	pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
11252 
11253 	/*
11254 	 * Sanity check - Port is active? Is the link active?
11255 	 * Is there any device attached?
11256 	 */
11257 	if ((pmportinfo->pmport_state &
11258 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
11259 	    (pmportinfo->pmport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
11260 	    SATA_PORT_DEVLINK_UP) {
11261 		/*
11262 		 * Port in non-usable state or no link active/no device.
11263 		 * Free info structure if necessary (direct attached drive
11264 		 * only, for now!
11265 		 */
11266 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11267 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11268 		/* Add here differentiation for device attached or not */
11269 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11270 		mutex_exit(&pmportinfo->pmport_mutex);
11271 		if (sdinfo != NULL)
11272 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11273 		return (SATA_SUCCESS);
11274 	}
11275 
11276 	pmportinfo->pmport_state |= SATA_STATE_READY;
11277 	pmportinfo->pmport_dev_type = sata_device->satadev_type;
11278 	sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
11279 
11280 	/*
11281 	 * If we are re-probing the port, there may be
11282 	 * sata_drive_info structure attached
11283 	 * (or sata_pm_info, if PMult is supported).
11284 	 */
11285 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
11286 		/*
11287 		 * There is no device, so remove device info structure,
11288 		 * if necessary.
11289 		 */
11290 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11291 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11292 		if (sdinfo != NULL) {
11293 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11294 			sata_log(sata_hba_inst, CE_WARN,
11295 			    "SATA device detached from port %d:%d",
11296 			    cport, pmport);
11297 		}
11298 		mutex_exit(&pmportinfo->pmport_mutex);
11299 		return (SATA_SUCCESS);
11300 	}
11301 
11302 	/* this should not be a pmult */
11303 	ASSERT(sata_device->satadev_type != SATA_DTYPE_PMULT);
11304 	if (sdinfo == NULL) {
11305 		/*
11306 		 * There is some device attached, but there is
11307 		 * no sata_drive_info structure - allocate one
11308 		 */
11309 		mutex_exit(&pmportinfo->pmport_mutex);
11310 		sdinfo = kmem_zalloc(sizeof (sata_drive_info_t),
11311 		    KM_SLEEP);
11312 		mutex_enter(&pmportinfo->pmport_mutex);
11313 		/*
11314 		 * Recheck, that the port state did not change when we
11315 		 * released mutex.
11316 		 */
11317 		if (pmportinfo->pmport_state & SATA_STATE_READY) {
11318 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = sdinfo;
11319 			sdinfo->satadrv_addr = pmportinfo->pmport_addr;
11320 			sdinfo->satadrv_addr.qual = SATA_ADDR_DPMPORT;
11321 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11322 			sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11323 		} else {
11324 			/*
11325 			 * Port is not in ready state, we
11326 			 * cannot attach a device.
11327 			 */
11328 			mutex_exit(&pmportinfo->pmport_mutex);
11329 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11330 			return (SATA_SUCCESS);
11331 		}
11332 		/*
11333 		 * Since we are adding device, presumably new one,
11334 		 * indicate that it  should be initalized,
11335 		 * as well as some internal framework states).
11336 		 */
11337 		init_device = B_TRUE;
11338 	}
11339 
11340 	pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
11341 	sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
11342 
11343 	mutex_exit(&pmportinfo->pmport_mutex);
11344 	/*
11345 	 * Figure out what kind of device we are really
11346 	 * dealing with.
11347 	 */
11348 	rval = sata_probe_device(sata_hba_inst, sata_device);
11349 
11350 	mutex_enter(&pmportinfo->pmport_mutex);
11351 	if (rval == SATA_SUCCESS) {
11352 		/*
11353 		 * If we are dealing with the same type of a device as before,
11354 		 * restore its settings flags.
11355 		 */
11356 		if (osdinfo != NULL &&
11357 		    sata_device->satadev_type == prev_device_type)
11358 			sdinfo->satadrv_settings = prev_device_settings;
11359 
11360 		mutex_exit(&pmportinfo->pmport_mutex);
11361 		/* Set initial device features, if necessary */
11362 		if (init_device == B_TRUE) {
11363 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
11364 		}
11365 		if (rval == SATA_SUCCESS)
11366 			return (rval);
11367 	} else {
11368 		/*
11369 		 * If there was some device info before we probe the device,
11370 		 * restore previous device setting, so we can retry from scratch
11371 		 * later. Providing, of course, that device has not disappeared
11372 		 * during probing process.
11373 		 */
11374 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
11375 			if (osdinfo != NULL) {
11376 				pmportinfo->pmport_dev_type = prev_device_type;
11377 				sdinfo->satadrv_type = prev_device_type;
11378 				sdinfo->satadrv_state = prev_device_state;
11379 			}
11380 		} else {
11381 			/* device is gone */
11382 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11383 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
11384 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11385 			mutex_exit(&pmportinfo->pmport_mutex);
11386 			return (SATA_SUCCESS);
11387 		}
11388 		mutex_exit(&pmportinfo->pmport_mutex);
11389 	}
11390 
11391 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
11392 		clock_t cur_time = ddi_get_lbolt();
11393 		/*
11394 		 * A device was not successfully identified or initialized.
11395 		 * Track retry time for device identification.
11396 		 */
11397 		if ((cur_time - start_time) <
11398 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11399 			/* sleep for a while */
11400 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11401 			goto retry_probe_pmport;
11402 		} else {
11403 			mutex_enter(&pmportinfo->pmport_mutex);
11404 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11405 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11406 				    satadrv_state = SATA_DSTATE_FAILED;
11407 			mutex_exit(&pmportinfo->pmport_mutex);
11408 		}
11409 	}
11410 	return (SATA_SUCCESS);
11411 }
11412 
11413 /*
11414  * Allocated related structure for a port multiplier and its device ports
11415  *
11416  * Port multiplier should be ready and probed, and related information like
11417  * the number of the device ports should be store in sata_device_t.
11418  *
11419  * NOTE: No Mutex should be hold.
11420  */
11421 static int
11422 sata_alloc_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11423 {
11424 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
11425 	sata_cport_info_t *cportinfo = NULL;
11426 	sata_pmult_info_t *pmultinfo = NULL;
11427 	sata_pmport_info_t *pmportinfo = NULL;
11428 	sata_device_t sd;
11429 	dev_t minor_number;
11430 	char name[16];
11431 	uint8_t cport = sata_device->satadev_addr.cport;
11432 	int rval;
11433 	int npmport;
11434 
11435 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11436 
11437 	/* This function might be called while a port-mult is hot-plugged. */
11438 	mutex_enter(&cportinfo->cport_mutex);
11439 
11440 	/* dev_type's not updated when get called from sata_reprobe_port() */
11441 	if (SATA_CPORTINFO_PMULT_INFO(cportinfo) == NULL) {
11442 		/* Create a pmult_info structure */
11443 		SATA_CPORTINFO_PMULT_INFO(cportinfo) =
11444 		    kmem_zalloc(sizeof (sata_pmult_info_t), KM_SLEEP);
11445 	}
11446 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11447 
11448 	pmultinfo->pmult_addr = sata_device->satadev_addr;
11449 	pmultinfo->pmult_addr.qual = SATA_ADDR_PMULT;
11450 	pmultinfo->pmult_state = SATA_STATE_PROBING;
11451 
11452 	/*
11453 	 * Probe the port multiplier with qualifier SATA_ADDR_PMULT_SPEC,
11454 	 * The HBA driver should initialize and register the port multiplier,
11455 	 * sata_register_pmult() will fill following fields,
11456 	 *   + sata_pmult_info.pmult_gscr
11457 	 *   + sata_pmult_info.pmult_num_dev_ports
11458 	 */
11459 	sd.satadev_addr = sata_device->satadev_addr;
11460 	sd.satadev_addr.qual = SATA_ADDR_PMULT_SPEC;
11461 	mutex_exit(&cportinfo->cport_mutex);
11462 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11463 	    (SATA_DIP(sata_hba_inst), &sd);
11464 	mutex_enter(&cportinfo->cport_mutex);
11465 
11466 	if (rval != SATA_SUCCESS ||
11467 	    (sd.satadev_type != SATA_DTYPE_PMULT) ||
11468 	    !(sd.satadev_state & SATA_DSTATE_PMULT_INIT)) {
11469 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
11470 		kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11471 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11472 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11473 		mutex_exit(&cportinfo->cport_mutex);
11474 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11475 		    "sata_alloc_pmult: failed to initialize pmult "
11476 		    "at port %d.", cport)
11477 		return (SATA_FAILURE);
11478 	}
11479 
11480 	/* Initialize pmport_info structure */
11481 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11482 	    npmport++) {
11483 
11484 		/* if everything is allocated, skip */
11485 		if (SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) != NULL)
11486 			continue;
11487 
11488 		pmportinfo = kmem_zalloc(sizeof (sata_pmport_info_t), KM_SLEEP);
11489 		mutex_init(&pmportinfo->pmport_mutex, NULL, MUTEX_DRIVER, NULL);
11490 		mutex_exit(&cportinfo->cport_mutex);
11491 
11492 		mutex_enter(&pmportinfo->pmport_mutex);
11493 		pmportinfo->pmport_addr.cport = cport;
11494 		pmportinfo->pmport_addr.pmport = (uint8_t)npmport;
11495 		pmportinfo->pmport_addr.qual = SATA_ADDR_PMPORT;
11496 		pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11497 		mutex_exit(&pmportinfo->pmport_mutex);
11498 
11499 		mutex_enter(&cportinfo->cport_mutex);
11500 		SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) = pmportinfo;
11501 
11502 		/* Create an attachment point */
11503 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
11504 		    cport, (uint8_t)npmport, SATA_ADDR_PMPORT);
11505 		(void) sprintf(name, "%d.%d", cport, npmport);
11506 
11507 		if (ddi_create_minor_node(dip, name, S_IFCHR, minor_number,
11508 		    DDI_NT_SATA_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
11509 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
11510 			    "cannot create SATA attachment point for "
11511 			    "port %d:%d", cport, npmport);
11512 		}
11513 	}
11514 
11515 	pmultinfo->pmult_state &= ~SATA_STATE_PROBING;
11516 	pmultinfo->pmult_state |= (SATA_STATE_PROBED|SATA_STATE_READY);
11517 	cportinfo->cport_dev_type = SATA_DTYPE_PMULT;
11518 
11519 	mutex_exit(&cportinfo->cport_mutex);
11520 	return (SATA_SUCCESS);
11521 }
11522 
11523 /*
11524  * Free data structures when a port multiplier is removed.
11525  *
11526  * NOTE: No Mutex should be hold.
11527  */
11528 static void
11529 sata_free_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11530 {
11531 	sata_cport_info_t *cportinfo;
11532 	sata_pmult_info_t *pmultinfo;
11533 	sata_pmport_info_t *pmportinfo;
11534 	sata_device_t pmport_device;
11535 	sata_drive_info_t *sdinfo;
11536 	dev_info_t *tdip;
11537 	char name[16];
11538 	uint8_t cport = sata_device->satadev_addr.cport;
11539 	int npmport;
11540 
11541 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11542 
11543 	/* This function might be called while port-mult is hot plugged. */
11544 	mutex_enter(&cportinfo->cport_mutex);
11545 
11546 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11547 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11548 	ASSERT(pmultinfo != NULL);
11549 
11550 	/* Free pmport_info structure */
11551 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11552 	    npmport++) {
11553 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
11554 		if (pmportinfo == NULL)
11555 			continue;
11556 		mutex_exit(&cportinfo->cport_mutex);
11557 
11558 		mutex_enter(&pmportinfo->pmport_mutex);
11559 		sdinfo = pmportinfo->pmport_sata_drive;
11560 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11561 		mutex_exit(&pmportinfo->pmport_mutex);
11562 
11563 		/* Remove attachment point. */
11564 		name[0] = '\0';
11565 		(void) sprintf(name, "%d.%d", cport, npmport);
11566 		ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
11567 		sata_log(sata_hba_inst, CE_NOTE,
11568 		    "Remove attachment point of port %d:%d",
11569 		    cport, npmport);
11570 
11571 		/*
11572 		 * Rumove target node
11573 		 */
11574 		bzero(&pmport_device, sizeof (sata_device_t));
11575 		pmport_device.satadev_rev = SATA_DEVICE_REV;
11576 		pmport_device.satadev_addr.cport = cport;
11577 		pmport_device.satadev_addr.pmport = (uint8_t)npmport;
11578 		pmport_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
11579 
11580 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11581 		    &(pmport_device.satadev_addr));
11582 		if (tdip != NULL && ndi_devi_offline(tdip,
11583 		    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11584 			/*
11585 			 * Problem :
11586 			 * The target node remained attached.
11587 			 * This happens when the device file was open
11588 			 * or a node was waiting for resources.
11589 			 * Cannot do anything about it.
11590 			 */
11591 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11592 			    "sata_free_pmult: could not unconfigure device "
11593 			    "before disconnecting the SATA port %d:%d",
11594 			    cport, npmport));
11595 
11596 			/*
11597 			 * Set DEVICE REMOVED state in the target
11598 			 * node. It will prevent access to the device
11599 			 * even when a new device is attached, until
11600 			 * the old target node is released, removed and
11601 			 * recreated for a new  device.
11602 			 */
11603 			sata_set_device_removed(tdip);
11604 
11605 			/*
11606 			 * Instruct event daemon to try the target
11607 			 * node cleanup later.
11608 			 */
11609 			sata_set_target_node_cleanup(
11610 			    sata_hba_inst, &(pmport_device.satadev_addr));
11611 
11612 		}
11613 		mutex_enter(&cportinfo->cport_mutex);
11614 
11615 		/*
11616 		 * Add here differentiation for device attached or not
11617 		 */
11618 		if (sdinfo != NULL)  {
11619 			sata_log(sata_hba_inst, CE_WARN,
11620 			    "SATA device detached from port %d:%d",
11621 			    cport, npmport);
11622 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11623 		}
11624 
11625 		mutex_destroy(&pmportinfo->pmport_mutex);
11626 		kmem_free(pmportinfo, sizeof (sata_pmport_info_t));
11627 	}
11628 
11629 	kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11630 
11631 	cportinfo->cport_devp.cport_sata_pmult = NULL;
11632 
11633 	sata_log(sata_hba_inst, CE_WARN,
11634 	    "SATA port multiplier detached at port %d", cport);
11635 
11636 	mutex_exit(&cportinfo->cport_mutex);
11637 }
11638 
11639 /*
11640  * Initialize device
11641  * Specified device is initialized to a default state.
11642  *
11643  * Returns SATA_SUCCESS if all device features are set successfully,
11644  * SATA_RETRY if device is accessible but device features were not set
11645  * successfully, and SATA_FAILURE otherwise.
11646  */
11647 static int
11648 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
11649     sata_drive_info_t *sdinfo)
11650 {
11651 	int rval;
11652 
11653 	sata_save_drive_settings(sdinfo);
11654 
11655 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
11656 
11657 	sata_init_write_cache_mode(sdinfo);
11658 
11659 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
11660 
11661 	/* Determine current data transfer mode */
11662 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
11663 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11664 	} else if ((sdinfo->satadrv_id.ai_validinfo &
11665 	    SATA_VALIDINFO_88) != 0 &&
11666 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
11667 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11668 	} else if ((sdinfo->satadrv_id.ai_dworddma &
11669 	    SATA_MDMA_SEL_MASK) != 0) {
11670 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11671 	} else
11672 		/* DMA supported, not no DMA transfer mode is selected !? */
11673 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11674 
11675 	if ((sdinfo->satadrv_id.ai_cmdset83 & 0x20) &&
11676 	    (sdinfo->satadrv_id.ai_features86 & 0x20))
11677 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
11678 	else
11679 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
11680 
11681 	return (rval);
11682 }
11683 
11684 
11685 /*
11686  * Initialize write cache mode.
11687  *
11688  * The default write cache setting for SATA HDD is provided by sata_write_cache
11689  * static variable. ATAPI CD/DVDs devices have write cache default is
11690  * determined by sata_atapicdvd_write_cache static variable.
11691  * ATAPI tape devices have write cache default is determined by
11692  * sata_atapitape_write_cache static variable.
11693  * ATAPI disk devices have write cache default is determined by
11694  * sata_atapidisk_write_cache static variable.
11695  * 1 - enable
11696  * 0 - disable
11697  * any other value - current drive setting
11698  *
11699  * Although there is not reason to disable write cache on CD/DVD devices,
11700  * tape devices and ATAPI disk devices, the default setting control is provided
11701  * for the maximun flexibility.
11702  *
11703  * In the future, it may be overridden by the
11704  * disk-write-cache-enable property setting, if it is defined.
11705  * Returns SATA_SUCCESS if all device features are set successfully,
11706  * SATA_FAILURE otherwise.
11707  */
11708 static void
11709 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
11710 {
11711 	switch (sdinfo->satadrv_type) {
11712 	case SATA_DTYPE_ATADISK:
11713 		if (sata_write_cache == 1)
11714 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11715 		else if (sata_write_cache == 0)
11716 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11717 		/*
11718 		 * When sata_write_cache value is not 0 or 1,
11719 		 * a current setting of the drive's write cache is used.
11720 		 */
11721 		break;
11722 	case SATA_DTYPE_ATAPICD:
11723 		if (sata_atapicdvd_write_cache == 1)
11724 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11725 		else if (sata_atapicdvd_write_cache == 0)
11726 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11727 		/*
11728 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
11729 		 * a current setting of the drive's write cache is used.
11730 		 */
11731 		break;
11732 	case SATA_DTYPE_ATAPITAPE:
11733 		if (sata_atapitape_write_cache == 1)
11734 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11735 		else if (sata_atapitape_write_cache == 0)
11736 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11737 		/*
11738 		 * When sata_atapitape_write_cache value is not 0 or 1,
11739 		 * a current setting of the drive's write cache is used.
11740 		 */
11741 		break;
11742 	case SATA_DTYPE_ATAPIDISK:
11743 		if (sata_atapidisk_write_cache == 1)
11744 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11745 		else if (sata_atapidisk_write_cache == 0)
11746 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11747 		/*
11748 		 * When sata_atapidisk_write_cache value is not 0 or 1,
11749 		 * a current setting of the drive's write cache is used.
11750 		 */
11751 		break;
11752 	}
11753 }
11754 
11755 
11756 /*
11757  * Validate sata address.
11758  * Specified cport, pmport and qualifier has to match
11759  * passed sata_scsi configuration info.
11760  * The presence of an attached device is not verified.
11761  *
11762  * Returns 0 when address is valid, -1 otherwise.
11763  */
11764 static int
11765 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
11766 	int pmport, int qual)
11767 {
11768 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
11769 		goto invalid_address;
11770 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11771 		goto invalid_address;
11772 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
11773 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
11774 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
11775 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
11776 		goto invalid_address;
11777 
11778 	return (0);
11779 
11780 invalid_address:
11781 	return (-1);
11782 
11783 }
11784 
11785 /*
11786  * Validate scsi address
11787  * SCSI target address is translated into SATA cport/pmport and compared
11788  * with a controller port/device configuration. LUN has to be 0.
11789  * Returns 0 if a scsi target refers to an attached device,
11790  * returns 1 if address is valid but no valid device is attached,
11791  * returns 2 if address is valid but device type is unknown (not valid device),
11792  * returns -1 if bad address or device is of an unsupported type.
11793  * Upon return sata_device argument is set.
11794  *
11795  * Port multiplier is supported now.
11796  */
11797 static int
11798 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
11799 	struct scsi_address *ap, sata_device_t *sata_device)
11800 {
11801 	int cport, pmport, qual, rval;
11802 
11803 	rval = -1;	/* Invalid address */
11804 	if (ap->a_lun != 0)
11805 		goto out;
11806 
11807 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
11808 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
11809 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
11810 
11811 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
11812 		goto out;
11813 
11814 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
11815 	    0) {
11816 
11817 		sata_cport_info_t *cportinfo;
11818 		sata_pmult_info_t *pmultinfo;
11819 		sata_drive_info_t *sdinfo = NULL;
11820 
11821 		sata_device->satadev_addr.qual = qual;
11822 		sata_device->satadev_addr.cport = cport;
11823 		sata_device->satadev_addr.pmport = pmport;
11824 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
11825 
11826 		rval = 1;	/* Valid sata address */
11827 
11828 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11829 		if (qual == SATA_ADDR_DCPORT) {
11830 			if (cportinfo == NULL ||
11831 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
11832 				goto out;
11833 
11834 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11835 			if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN &&
11836 			    sdinfo != NULL) {
11837 				rval = 2;
11838 				goto out;
11839 			}
11840 
11841 			if ((cportinfo->cport_dev_type &
11842 			    SATA_VALID_DEV_TYPE) == 0) {
11843 				rval = -1;
11844 				goto out;
11845 			}
11846 
11847 		} else if (qual == SATA_ADDR_DPMPORT) {
11848 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11849 			if (pmultinfo == NULL) {
11850 				rval = -1;
11851 				goto out;
11852 			}
11853 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
11854 			    NULL ||
11855 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11856 			    pmport) == SATA_DTYPE_NONE)
11857 				goto out;
11858 
11859 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
11860 			    pmport);
11861 			if (SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11862 			    pmport) == SATA_DTYPE_UNKNOWN && sdinfo != NULL) {
11863 				rval = 2;
11864 				goto out;
11865 			}
11866 
11867 			if ((SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11868 			    pmport) && SATA_VALID_DEV_TYPE) == 0) {
11869 				rval = -1;
11870 				goto out;
11871 			}
11872 
11873 		} else {
11874 			rval = -1;
11875 			goto out;
11876 		}
11877 		if ((sdinfo == NULL) ||
11878 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
11879 			goto out;
11880 
11881 		sata_device->satadev_type = sdinfo->satadrv_type;
11882 
11883 		return (0);
11884 	}
11885 out:
11886 	if (rval > 0) {
11887 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
11888 		    "sata_validate_scsi_address: no valid target %x lun %x",
11889 		    ap->a_target, ap->a_lun);
11890 	}
11891 	return (rval);
11892 }
11893 
11894 /*
11895  * Find dip corresponding to passed device number
11896  *
11897  * Returns NULL if invalid device number is passed or device cannot be found,
11898  * Returns dip is device is found.
11899  */
11900 static dev_info_t *
11901 sata_devt_to_devinfo(dev_t dev)
11902 {
11903 	dev_info_t *dip;
11904 #ifndef __lock_lint
11905 	struct devnames *dnp;
11906 	major_t major = getmajor(dev);
11907 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
11908 
11909 	if (major >= devcnt)
11910 		return (NULL);
11911 
11912 	dnp = &devnamesp[major];
11913 	LOCK_DEV_OPS(&(dnp->dn_lock));
11914 	dip = dnp->dn_head;
11915 	while (dip && (ddi_get_instance(dip) != instance)) {
11916 		dip = ddi_get_next(dip);
11917 	}
11918 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
11919 #endif
11920 
11921 	return (dip);
11922 }
11923 
11924 
11925 /*
11926  * Probe device.
11927  * This function issues Identify Device command and initializes local
11928  * sata_drive_info structure if the device can be identified.
11929  * The device type is determined by examining Identify Device
11930  * command response.
11931  * If the sata_hba_inst has linked drive info structure for this
11932  * device address, the Identify Device data is stored into sata_drive_info
11933  * structure linked to the port info structure.
11934  *
11935  * sata_device has to refer to the valid sata port(s) for HBA described
11936  * by sata_hba_inst structure.
11937  *
11938  * Returns:
11939  *	SATA_SUCCESS if device type was successfully probed and port-linked
11940  *		drive info structure was updated;
11941  * 	SATA_FAILURE if there is no device, or device was not probed
11942  *		successully;
11943  *	SATA_RETRY if device probe can be retried later.
11944  * If a device cannot be identified, sata_device's dev_state and dev_type
11945  * fields are set to unknown.
11946  * There are no retries in this function. Any retries should be managed by
11947  * the caller.
11948  */
11949 
11950 
11951 static int
11952 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11953 {
11954 	sata_pmport_info_t *pmportinfo;
11955 	sata_drive_info_t *sdinfo;
11956 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
11957 	int rval;
11958 
11959 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
11960 	    sata_device->satadev_addr.cport) &
11961 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
11962 
11963 	sata_device->satadev_type = SATA_DTYPE_NONE;
11964 
11965 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11966 	    sata_device->satadev_addr.cport)));
11967 
11968 	if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT) {
11969 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
11970 		    sata_device->satadev_addr.cport,
11971 		    sata_device->satadev_addr.pmport);
11972 		ASSERT(pmportinfo != NULL);
11973 	}
11974 
11975 	/* Get pointer to port-linked sata device info structure */
11976 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11977 	if (sdinfo != NULL) {
11978 		sdinfo->satadrv_state &=
11979 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
11980 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
11981 	} else {
11982 		/* No device to probe */
11983 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11984 		    sata_device->satadev_addr.cport)));
11985 		sata_device->satadev_type = SATA_DTYPE_NONE;
11986 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
11987 		return (SATA_FAILURE);
11988 	}
11989 	/*
11990 	 * Need to issue both types of identify device command and
11991 	 * determine device type by examining retreived data/status.
11992 	 * First, ATA Identify Device.
11993 	 */
11994 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
11995 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
11996 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11997 	    sata_device->satadev_addr.cport)));
11998 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
11999 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
12000 	if (rval == SATA_RETRY) {
12001 		/* We may try to check for ATAPI device */
12002 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
12003 			/*
12004 			 * HBA supports ATAPI - try to issue Identify Packet
12005 			 * Device command.
12006 			 */
12007 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
12008 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
12009 		}
12010 	}
12011 	if (rval == SATA_SUCCESS) {
12012 		/*
12013 		 * Got something responding positively to ATA Identify Device
12014 		 * or to Identify Packet Device cmd.
12015 		 * Save last used device type.
12016 		 */
12017 		sata_device->satadev_type = new_sdinfo.satadrv_type;
12018 
12019 		/* save device info, if possible */
12020 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12021 		    sata_device->satadev_addr.cport)));
12022 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12023 		if (sdinfo == NULL) {
12024 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12025 			    sata_device->satadev_addr.cport)));
12026 			return (SATA_FAILURE);
12027 		}
12028 		/*
12029 		 * Copy drive info into the port-linked drive info structure.
12030 		 */
12031 		*sdinfo = new_sdinfo;
12032 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
12033 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
12034 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
12035 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
12036 			    sata_device->satadev_addr.cport) =
12037 			    sdinfo->satadrv_type;
12038 		else { /* SATA_ADDR_DPMPORT */
12039 			mutex_enter(&pmportinfo->pmport_mutex);
12040 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
12041 			    sata_device->satadev_addr.cport,
12042 			    sata_device->satadev_addr.pmport) =
12043 			    sdinfo->satadrv_type;
12044 			mutex_exit(&pmportinfo->pmport_mutex);
12045 		}
12046 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12047 		    sata_device->satadev_addr.cport)));
12048 		return (SATA_SUCCESS);
12049 	}
12050 
12051 	/*
12052 	 * It may be SATA_RETRY or SATA_FAILURE return.
12053 	 * Looks like we cannot determine the device type at this time.
12054 	 */
12055 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
12056 	    sata_device->satadev_addr.cport)));
12057 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
12058 	if (sdinfo != NULL) {
12059 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
12060 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12061 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
12062 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
12063 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
12064 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
12065 			    sata_device->satadev_addr.cport) =
12066 			    SATA_DTYPE_UNKNOWN;
12067 		else {
12068 			/* SATA_ADDR_DPMPORT */
12069 			mutex_enter(&pmportinfo->pmport_mutex);
12070 			if ((SATA_PMULT_INFO(sata_hba_inst,
12071 			    sata_device->satadev_addr.cport) != NULL) &&
12072 			    (SATA_PMPORT_INFO(sata_hba_inst,
12073 			    sata_device->satadev_addr.cport,
12074 			    sata_device->satadev_addr.pmport) != NULL))
12075 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
12076 				    sata_device->satadev_addr.cport,
12077 				    sata_device->satadev_addr.pmport) =
12078 				    SATA_DTYPE_UNKNOWN;
12079 			mutex_exit(&pmportinfo->pmport_mutex);
12080 		}
12081 	}
12082 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
12083 	    sata_device->satadev_addr.cport)));
12084 	return (rval);
12085 }
12086 
12087 
12088 /*
12089  * Get pointer to sata_drive_info structure.
12090  *
12091  * The sata_device has to contain address (cport, pmport and qualifier) for
12092  * specified sata_scsi structure.
12093  *
12094  * Returns NULL if device address is not valid for this HBA configuration.
12095  * Otherwise, returns a pointer to sata_drive_info structure.
12096  *
12097  * This function should be called with a port mutex held.
12098  */
12099 static sata_drive_info_t *
12100 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
12101     sata_device_t *sata_device)
12102 {
12103 	uint8_t cport = sata_device->satadev_addr.cport;
12104 	uint8_t pmport = sata_device->satadev_addr.pmport;
12105 	uint8_t qual = sata_device->satadev_addr.qual;
12106 
12107 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
12108 		return (NULL);
12109 
12110 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
12111 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
12112 		/* Port not probed yet */
12113 		return (NULL);
12114 
12115 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
12116 		return (NULL);
12117 
12118 	if (qual == SATA_ADDR_DCPORT) {
12119 		/* Request for a device on a controller port */
12120 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
12121 		    SATA_DTYPE_PMULT)
12122 			/* Port multiplier attached */
12123 			return (NULL);
12124 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
12125 	}
12126 	if (qual == SATA_ADDR_DPMPORT) {
12127 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
12128 		    SATA_DTYPE_PMULT)
12129 			return (NULL);
12130 
12131 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
12132 			return (NULL);
12133 
12134 		if (!(SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) &
12135 		    (SATA_STATE_PROBED | SATA_STATE_READY)))
12136 			/* Port multiplier port not probed yet */
12137 			return (NULL);
12138 
12139 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
12140 	}
12141 
12142 	/* we should not get here */
12143 	return (NULL);
12144 }
12145 
12146 
12147 /*
12148  * sata_identify_device.
12149  * Send Identify Device command to SATA HBA driver.
12150  * If command executes successfully, update sata_drive_info structure pointed
12151  * to by sdinfo argument, including Identify Device data.
12152  * If command fails, invalidate data in sata_drive_info.
12153  *
12154  * Cannot be called from interrupt level.
12155  *
12156  * Returns:
12157  * SATA_SUCCESS if the device was identified as a supported device,
12158  * SATA_RETRY if the device was not identified but could be retried,
12159  * SATA_FAILURE if the device was not identified and identify attempt
12160  *	should not be retried.
12161  */
12162 static int
12163 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
12164     sata_drive_info_t *sdinfo)
12165 {
12166 	uint16_t cfg_word;
12167 	int rval;
12168 
12169 	/* fetch device identify data */
12170 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
12171 	    sdinfo)) != SATA_SUCCESS)
12172 		goto fail_unknown;
12173 
12174 	cfg_word = sdinfo->satadrv_id.ai_config;
12175 
12176 	/* Set the correct device type */
12177 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
12178 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
12179 	} else if (cfg_word == SATA_CFA_TYPE) {
12180 		/* It's a Compact Flash media via CF-to-SATA HDD adapter */
12181 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
12182 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
12183 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
12184 		case SATA_ATAPI_CDROM_DEV:
12185 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
12186 			break;
12187 		case SATA_ATAPI_SQACC_DEV:
12188 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
12189 			break;
12190 		case SATA_ATAPI_DIRACC_DEV:
12191 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
12192 			break;
12193 		default:
12194 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12195 		}
12196 	} else {
12197 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12198 	}
12199 
12200 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12201 		if (sdinfo->satadrv_capacity == 0) {
12202 			/* Non-LBA disk. Too bad... */
12203 			sata_log(sata_hba_inst, CE_WARN,
12204 			    "SATA disk device at port %d does not support LBA",
12205 			    sdinfo->satadrv_addr.cport);
12206 			rval = SATA_FAILURE;
12207 			goto fail_unknown;
12208 		}
12209 	}
12210 #if 0
12211 	/* Left for historical reason */
12212 	/*
12213 	 * Some initial version of SATA spec indicated that at least
12214 	 * UDMA mode 4 has to be supported. It is not metioned in
12215 	 * SerialATA 2.6, so this restriction is removed.
12216 	 */
12217 	/* Check for Ultra DMA modes 6 through 0 being supported */
12218 	for (i = 6; i >= 0; --i) {
12219 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
12220 			break;
12221 	}
12222 
12223 	/*
12224 	 * At least UDMA 4 mode has to be supported. If mode 4 or
12225 	 * higher are not supported by the device, fail this
12226 	 * device.
12227 	 */
12228 	if (i < 4) {
12229 		/* No required Ultra DMA mode supported */
12230 		sata_log(sata_hba_inst, CE_WARN,
12231 		    "SATA disk device at port %d does not support UDMA "
12232 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
12233 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12234 		    "mode 4 or higher required, %d supported", i));
12235 		rval = SATA_FAILURE;
12236 		goto fail_unknown;
12237 	}
12238 #endif
12239 
12240 	/*
12241 	 * For Disk devices, if it doesn't support UDMA mode, we would
12242 	 * like to return failure directly.
12243 	 */
12244 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
12245 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
12246 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
12247 		sata_log(sata_hba_inst, CE_WARN,
12248 		    "SATA disk device at port %d does not support UDMA",
12249 		    sdinfo->satadrv_addr.cport);
12250 		rval = SATA_FAILURE;
12251 		goto fail_unknown;
12252 	}
12253 
12254 	return (SATA_SUCCESS);
12255 
12256 fail_unknown:
12257 	/* Invalidate sata_drive_info ? */
12258 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
12259 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
12260 	return (rval);
12261 }
12262 
12263 /*
12264  * Log/display device information
12265  */
12266 static void
12267 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
12268     sata_drive_info_t *sdinfo)
12269 {
12270 	int valid_version;
12271 	char msg_buf[MAXPATHLEN];
12272 	int i;
12273 
12274 	/* Show HBA path */
12275 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
12276 
12277 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
12278 
12279 	switch (sdinfo->satadrv_type) {
12280 	case SATA_DTYPE_ATADISK:
12281 		(void) sprintf(msg_buf, "SATA disk device at");
12282 		break;
12283 
12284 	case SATA_DTYPE_ATAPICD:
12285 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
12286 		break;
12287 
12288 	case SATA_DTYPE_ATAPITAPE:
12289 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
12290 		break;
12291 
12292 	case SATA_DTYPE_ATAPIDISK:
12293 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
12294 		break;
12295 
12296 	case SATA_DTYPE_UNKNOWN:
12297 		(void) sprintf(msg_buf,
12298 		    "Unsupported SATA device type (cfg 0x%x) at ",
12299 		    sdinfo->satadrv_id.ai_config);
12300 		break;
12301 	}
12302 
12303 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
12304 		cmn_err(CE_CONT, "?\t%s port %d\n",
12305 		    msg_buf, sdinfo->satadrv_addr.cport);
12306 	else
12307 		cmn_err(CE_CONT, "?\t%s port %d:%d\n",
12308 		    msg_buf, sdinfo->satadrv_addr.cport,
12309 		    sdinfo->satadrv_addr.pmport);
12310 
12311 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
12312 	    sizeof (sdinfo->satadrv_id.ai_model));
12313 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
12314 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
12315 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
12316 
12317 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
12318 	    sizeof (sdinfo->satadrv_id.ai_fw));
12319 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
12320 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
12321 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
12322 
12323 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
12324 	    sizeof (sdinfo->satadrv_id.ai_drvser));
12325 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
12326 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
12327 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12328 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12329 	} else {
12330 		/*
12331 		 * Some drives do not implement serial number and may
12332 		 * violate the spec by providing spaces rather than zeros
12333 		 * in serial number field. Scan the buffer to detect it.
12334 		 */
12335 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
12336 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
12337 				break;
12338 		}
12339 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
12340 			cmn_err(CE_CONT, "?\tserial number - none\n");
12341 		} else {
12342 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
12343 		}
12344 	}
12345 
12346 #ifdef SATA_DEBUG
12347 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
12348 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
12349 		int i;
12350 		for (i = 14; i >= 2; i--) {
12351 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
12352 				valid_version = i;
12353 				break;
12354 			}
12355 		}
12356 		cmn_err(CE_CONT,
12357 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
12358 		    valid_version,
12359 		    sdinfo->satadrv_id.ai_majorversion,
12360 		    sdinfo->satadrv_id.ai_minorversion);
12361 	}
12362 #endif
12363 	/* Log some info */
12364 	cmn_err(CE_CONT, "?\tsupported features:\n");
12365 	msg_buf[0] = '\0';
12366 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12367 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
12368 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
12369 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
12370 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
12371 	}
12372 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
12373 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
12374 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
12375 		(void) strlcat(msg_buf, ", Native Command Queueing",
12376 		    MAXPATHLEN);
12377 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
12378 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
12379 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
12380 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
12381 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
12382 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
12383 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
12384 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
12385 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
12386 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
12387 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
12388 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
12389 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
12390 	if (sdinfo->satadrv_features_support &
12391 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
12392 		msg_buf[0] = '\0';
12393 		(void) snprintf(msg_buf, MAXPATHLEN,
12394 		    "Supported queue depth %d",
12395 		    sdinfo->satadrv_queue_depth);
12396 		if (!(sata_func_enable &
12397 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
12398 			(void) strlcat(msg_buf,
12399 			    " - queueing disabled globally", MAXPATHLEN);
12400 		else if (sdinfo->satadrv_queue_depth >
12401 		    sdinfo->satadrv_max_queue_depth) {
12402 			(void) snprintf(&msg_buf[strlen(msg_buf)],
12403 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
12404 			    (int)sdinfo->satadrv_max_queue_depth);
12405 		}
12406 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
12407 	}
12408 
12409 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12410 #ifdef __i386
12411 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
12412 		    sdinfo->satadrv_capacity);
12413 #else
12414 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
12415 		    sdinfo->satadrv_capacity);
12416 #endif
12417 		cmn_err(CE_CONT, "?%s", msg_buf);
12418 	}
12419 }
12420 
12421 /*
12422  * Log/display port multiplier information
12423  * No Mutex should be hold.
12424  */
12425 static void
12426 sata_show_pmult_info(sata_hba_inst_t *sata_hba_inst,
12427     sata_device_t *sata_device)
12428 {
12429 	_NOTE(ARGUNUSED(sata_hba_inst))
12430 
12431 	int cport = sata_device->satadev_addr.cport;
12432 	sata_pmult_info_t *pmultinfo;
12433 	char msg_buf[MAXPATHLEN];
12434 	uint32_t gscr0, gscr1, gscr2, gscr64;
12435 
12436 	mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12437 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
12438 	if (pmultinfo == NULL) {
12439 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12440 		return;
12441 	}
12442 
12443 	gscr0 = pmultinfo->pmult_gscr.gscr0;
12444 	gscr1 = pmultinfo->pmult_gscr.gscr1;
12445 	gscr2 = pmultinfo->pmult_gscr.gscr2;
12446 	gscr64 = pmultinfo->pmult_gscr.gscr64;
12447 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12448 
12449 	cmn_err(CE_CONT, "?Port Multiplier %d device-ports found at port %d",
12450 	    sata_device->satadev_add_info, sata_device->satadev_addr.cport);
12451 
12452 	(void) sprintf(msg_buf, "\tVendor_ID 0x%04x, Module_ID 0x%04x",
12453 	    gscr0 & 0xffff, (gscr0 >> 16) & 0xffff);
12454 	cmn_err(CE_CONT, "?%s", msg_buf);
12455 
12456 	(void) strcpy(msg_buf, "\tSupport SATA PMP Spec ");
12457 	if (gscr1 & (1 << 3))
12458 		(void) strlcat(msg_buf, "1.2", MAXPATHLEN);
12459 	else if (gscr1 & (1 << 2))
12460 		(void) strlcat(msg_buf, "1.1", MAXPATHLEN);
12461 	else if (gscr1 & (1 << 1))
12462 		(void) strlcat(msg_buf, "1.0", MAXPATHLEN);
12463 	else
12464 		(void) strlcat(msg_buf, "unknown", MAXPATHLEN);
12465 	cmn_err(CE_CONT, "?%s", msg_buf);
12466 
12467 	(void) strcpy(msg_buf, "\tSupport ");
12468 	if (gscr64 & (1 << 3))
12469 		(void) strlcat(msg_buf, "Asy-Notif, ",
12470 		    MAXPATHLEN);
12471 	if (gscr64 & (1 << 2))
12472 		(void) strlcat(msg_buf, "Dyn-SSC, ", MAXPATHLEN);
12473 	if (gscr64 & (1 << 1))
12474 		(void) strlcat(msg_buf, "Iss-PMREQ, ", MAXPATHLEN);
12475 	if (gscr64 & (1 << 0))
12476 		(void) strlcat(msg_buf, "BIST", MAXPATHLEN);
12477 	if ((gscr64 & 0xf) == 0)
12478 		(void) strlcat(msg_buf, "nothing", MAXPATHLEN);
12479 	cmn_err(CE_CONT, "?%s", msg_buf);
12480 
12481 	(void) sprintf(msg_buf, "\tNumber of exposed device fan-out ports: %d",
12482 	    gscr2 & SATA_PMULT_PORTNUM_MASK);
12483 	cmn_err(CE_CONT, "?%s", msg_buf);
12484 }
12485 
12486 /*
12487  * sata_save_drive_settings extracts current setting of the device and stores
12488  * it for future reference, in case the device setup would need to be restored
12489  * after the device reset.
12490  *
12491  * For all devices read ahead and write cache settings are saved, if the
12492  * device supports these features at all.
12493  * For ATAPI devices the Removable Media Status Notification setting is saved.
12494  */
12495 static void
12496 sata_save_drive_settings(sata_drive_info_t *sdinfo)
12497 {
12498 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
12499 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
12500 
12501 		/* Current setting of Read Ahead (and Read Cache) */
12502 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
12503 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
12504 		else
12505 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
12506 
12507 		/* Current setting of Write Cache */
12508 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
12509 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12510 		else
12511 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12512 	}
12513 
12514 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
12515 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
12516 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
12517 		else
12518 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
12519 	}
12520 }
12521 
12522 
12523 /*
12524  * sata_check_capacity function determines a disk capacity
12525  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
12526  *
12527  * NOTE: CHS mode is not supported! If a device does not support LBA,
12528  * this function is not called.
12529  *
12530  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
12531  */
12532 static uint64_t
12533 sata_check_capacity(sata_drive_info_t *sdinfo)
12534 {
12535 	uint64_t capacity = 0;
12536 	int i;
12537 
12538 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
12539 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
12540 		/* Capacity valid only for LBA-addressable disk devices */
12541 		return (0);
12542 
12543 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
12544 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
12545 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
12546 		/* LBA48 mode supported and enabled */
12547 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
12548 		    SATA_DEV_F_LBA28;
12549 		for (i = 3;  i >= 0;  --i) {
12550 			capacity <<= 16;
12551 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
12552 		}
12553 	} else {
12554 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
12555 		capacity <<= 16;
12556 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
12557 		if (capacity >= 0x1000000)
12558 			/* LBA28 mode */
12559 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
12560 	}
12561 	return (capacity);
12562 }
12563 
12564 
12565 /*
12566  * Allocate consistent buffer for DMA transfer
12567  *
12568  * Cannot be called from interrupt level or with mutex held - it may sleep.
12569  *
12570  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
12571  */
12572 static struct buf *
12573 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
12574 {
12575 	struct scsi_address ap;
12576 	struct buf *bp;
12577 	ddi_dma_attr_t	cur_dma_attr;
12578 
12579 	ASSERT(spx->txlt_sata_pkt != NULL);
12580 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
12581 	ap.a_target = SATA_TO_SCSI_TARGET(
12582 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
12583 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
12584 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
12585 	ap.a_lun = 0;
12586 
12587 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
12588 	    B_READ, SLEEP_FUNC, NULL);
12589 
12590 	if (bp != NULL) {
12591 		/* Allocate DMA resources for this buffer */
12592 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
12593 		/*
12594 		 * We use a local version of the dma_attr, to account
12595 		 * for a device addressing limitations.
12596 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
12597 		 * will cause dma attributes to be adjusted to a lowest
12598 		 * acceptable level.
12599 		 */
12600 		sata_adjust_dma_attr(NULL,
12601 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
12602 
12603 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
12604 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
12605 			scsi_free_consistent_buf(bp);
12606 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12607 			bp = NULL;
12608 		}
12609 	}
12610 	return (bp);
12611 }
12612 
12613 /*
12614  * Release local buffer (consistent buffer for DMA transfer) allocated
12615  * via sata_alloc_local_buffer().
12616  */
12617 static void
12618 sata_free_local_buffer(sata_pkt_txlate_t *spx)
12619 {
12620 	ASSERT(spx->txlt_sata_pkt != NULL);
12621 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
12622 
12623 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
12624 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
12625 
12626 	sata_common_free_dma_rsrcs(spx);
12627 
12628 	/* Free buffer */
12629 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
12630 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12631 }
12632 
12633 /*
12634  * Allocate sata_pkt
12635  * Pkt structure version and embedded strcutures version are initialized.
12636  * sata_pkt and sata_pkt_txlate structures are cross-linked.
12637  *
12638  * Since this may be called in interrupt context by sata_scsi_init_pkt,
12639  * callback argument determines if it can sleep or not.
12640  * Hence, it should not be called from interrupt context.
12641  *
12642  * If successful, non-NULL pointer to a sata pkt is returned.
12643  * Upon failure, NULL pointer is returned.
12644  */
12645 static sata_pkt_t *
12646 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
12647 {
12648 	sata_pkt_t *spkt;
12649 	int kmsflag;
12650 
12651 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
12652 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
12653 	if (spkt == NULL) {
12654 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12655 		    "sata_pkt_alloc: failed"));
12656 		return (NULL);
12657 	}
12658 	spkt->satapkt_rev = SATA_PKT_REV;
12659 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
12660 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
12661 	spkt->satapkt_framework_private = spx;
12662 	spx->txlt_sata_pkt = spkt;
12663 	return (spkt);
12664 }
12665 
12666 /*
12667  * Free sata pkt allocated via sata_pkt_alloc()
12668  */
12669 static void
12670 sata_pkt_free(sata_pkt_txlate_t *spx)
12671 {
12672 	ASSERT(spx->txlt_sata_pkt != NULL);
12673 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
12674 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
12675 	spx->txlt_sata_pkt = NULL;
12676 }
12677 
12678 
12679 /*
12680  * Adjust DMA attributes.
12681  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
12682  * from 8 bits to 16 bits, depending on a command being used.
12683  * Limiting max block count arbitrarily to 256 for all read/write
12684  * commands may affects performance, so check both the device and
12685  * controller capability before adjusting dma attributes.
12686  */
12687 void
12688 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
12689     ddi_dma_attr_t *adj_dma_attr)
12690 {
12691 	uint32_t count_max;
12692 
12693 	/* Copy original attributes */
12694 	*adj_dma_attr = *dma_attr;
12695 	/*
12696 	 * Things to consider: device addressing capability,
12697 	 * "excessive" controller DMA capabilities.
12698 	 * If a device is being probed/initialized, there are
12699 	 * no device info - use default limits then.
12700 	 */
12701 	if (sdinfo == NULL) {
12702 		count_max = dma_attr->dma_attr_granular * 0x100;
12703 		if (dma_attr->dma_attr_count_max > count_max)
12704 			adj_dma_attr->dma_attr_count_max = count_max;
12705 		if (dma_attr->dma_attr_maxxfer > count_max)
12706 			adj_dma_attr->dma_attr_maxxfer = count_max;
12707 		return;
12708 	}
12709 
12710 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12711 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
12712 			/*
12713 			 * 16-bit sector count may be used - we rely on
12714 			 * the assumption that only read and write cmds
12715 			 * will request more than 256 sectors worth of data
12716 			 */
12717 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
12718 		} else {
12719 			/*
12720 			 * 8-bit sector count will be used - default limits
12721 			 * for dma attributes
12722 			 */
12723 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
12724 		}
12725 		/*
12726 		 * Adjust controler dma attributes, if necessary
12727 		 */
12728 		if (dma_attr->dma_attr_count_max > count_max)
12729 			adj_dma_attr->dma_attr_count_max = count_max;
12730 		if (dma_attr->dma_attr_maxxfer > count_max)
12731 			adj_dma_attr->dma_attr_maxxfer = count_max;
12732 	}
12733 }
12734 
12735 
12736 /*
12737  * Allocate DMA resources for the buffer
12738  * This function handles initial DMA resource allocation as well as
12739  * DMA window shift and may be called repeatedly for the same DMA window
12740  * until all DMA cookies in the DMA window are processed.
12741  * To guarantee that there is always a coherent set of cookies to process
12742  * by SATA HBA driver (observing alignment, device granularity, etc.),
12743  * the number of slots for DMA cookies is equal to lesser of  a number of
12744  * cookies in a DMA window and a max number of scatter/gather entries.
12745  *
12746  * Returns DDI_SUCCESS upon successful operation.
12747  * Return failure code of a failing command or DDI_FAILURE when
12748  * internal cleanup failed.
12749  */
12750 static int
12751 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
12752     int (*callback)(caddr_t), caddr_t arg,
12753     ddi_dma_attr_t *cur_dma_attr)
12754 {
12755 	int	rval;
12756 	off_t	offset;
12757 	size_t	size;
12758 	int	max_sg_len, req_len, i;
12759 	uint_t	dma_flags;
12760 	struct buf	*bp;
12761 	uint64_t	cur_txfer_len;
12762 
12763 
12764 	ASSERT(spx->txlt_sata_pkt != NULL);
12765 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
12766 	ASSERT(bp != NULL);
12767 
12768 
12769 	if (spx->txlt_buf_dma_handle == NULL) {
12770 		/*
12771 		 * No DMA resources allocated so far - this is a first call
12772 		 * for this sata pkt.
12773 		 */
12774 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
12775 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
12776 
12777 		if (rval != DDI_SUCCESS) {
12778 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12779 			    "sata_dma_buf_setup: no buf DMA resources %x",
12780 			    rval));
12781 			return (rval);
12782 		}
12783 
12784 		if (bp->b_flags & B_READ)
12785 			dma_flags = DDI_DMA_READ;
12786 		else
12787 			dma_flags = DDI_DMA_WRITE;
12788 
12789 		if (flags & PKT_CONSISTENT)
12790 			dma_flags |= DDI_DMA_CONSISTENT;
12791 
12792 		if (flags & PKT_DMA_PARTIAL)
12793 			dma_flags |= DDI_DMA_PARTIAL;
12794 
12795 		/*
12796 		 * Check buffer alignment and size against dma attributes
12797 		 * Consider dma_attr_align only. There may be requests
12798 		 * with the size lower than device granularity, but they
12799 		 * will not read/write from/to the device, so no adjustment
12800 		 * is necessary. The dma_attr_minxfer theoretically should
12801 		 * be considered, but no HBA driver is checking it.
12802 		 */
12803 		if (IS_P2ALIGNED(bp->b_un.b_addr,
12804 		    cur_dma_attr->dma_attr_align)) {
12805 			rval = ddi_dma_buf_bind_handle(
12806 			    spx->txlt_buf_dma_handle,
12807 			    bp, dma_flags, callback, arg,
12808 			    &spx->txlt_dma_cookie,
12809 			    &spx->txlt_curwin_num_dma_cookies);
12810 		} else { /* Buffer is not aligned */
12811 
12812 			int	(*ddicallback)(caddr_t);
12813 			size_t	bufsz;
12814 
12815 			/* Check id sleeping is allowed */
12816 			ddicallback = (callback == NULL_FUNC) ?
12817 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
12818 
12819 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12820 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
12821 			    (void *)bp->b_un.b_addr, bp->b_bcount);
12822 
12823 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
12824 				/*
12825 				 * CPU will need to access data in the buffer
12826 				 * (for copying) so map it.
12827 				 */
12828 				bp_mapin(bp);
12829 
12830 			ASSERT(spx->txlt_tmp_buf == NULL);
12831 
12832 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
12833 			rval = ddi_dma_mem_alloc(
12834 			    spx->txlt_buf_dma_handle,
12835 			    bp->b_bcount,
12836 			    &sata_acc_attr,
12837 			    DDI_DMA_STREAMING,
12838 			    ddicallback, NULL,
12839 			    &spx->txlt_tmp_buf,
12840 			    &bufsz,
12841 			    &spx->txlt_tmp_buf_handle);
12842 
12843 			if (rval != DDI_SUCCESS) {
12844 				/* DMA mapping failed */
12845 				(void) ddi_dma_free_handle(
12846 				    &spx->txlt_buf_dma_handle);
12847 				spx->txlt_buf_dma_handle = NULL;
12848 #ifdef SATA_DEBUG
12849 				mbuffail_count++;
12850 #endif
12851 				SATADBG1(SATA_DBG_DMA_SETUP,
12852 				    spx->txlt_sata_hba_inst,
12853 				    "sata_dma_buf_setup: "
12854 				    "buf dma mem alloc failed %x\n", rval);
12855 				return (rval);
12856 			}
12857 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
12858 			    cur_dma_attr->dma_attr_align));
12859 
12860 #ifdef SATA_DEBUG
12861 			mbuf_count++;
12862 
12863 			if (bp->b_bcount != bufsz)
12864 				/*
12865 				 * This will require special handling, because
12866 				 * DMA cookies will be based on the temporary
12867 				 * buffer size, not the original buffer
12868 				 * b_bcount, so the residue may have to
12869 				 * be counted differently.
12870 				 */
12871 				SATADBG2(SATA_DBG_DMA_SETUP,
12872 				    spx->txlt_sata_hba_inst,
12873 				    "sata_dma_buf_setup: bp size %x != "
12874 				    "bufsz %x\n", bp->b_bcount, bufsz);
12875 #endif
12876 			if (dma_flags & DDI_DMA_WRITE) {
12877 				/*
12878 				 * Write operation - copy data into
12879 				 * an aligned temporary buffer. Buffer will be
12880 				 * synced for device by ddi_dma_addr_bind_handle
12881 				 */
12882 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
12883 				    bp->b_bcount);
12884 			}
12885 
12886 			rval = ddi_dma_addr_bind_handle(
12887 			    spx->txlt_buf_dma_handle,
12888 			    NULL,
12889 			    spx->txlt_tmp_buf,
12890 			    bufsz, dma_flags, ddicallback, 0,
12891 			    &spx->txlt_dma_cookie,
12892 			    &spx->txlt_curwin_num_dma_cookies);
12893 		}
12894 
12895 		switch (rval) {
12896 		case DDI_DMA_PARTIAL_MAP:
12897 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12898 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
12899 			/*
12900 			 * Partial DMA mapping.
12901 			 * Retrieve number of DMA windows for this request.
12902 			 */
12903 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
12904 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
12905 				if (spx->txlt_tmp_buf != NULL) {
12906 					ddi_dma_mem_free(
12907 					    &spx->txlt_tmp_buf_handle);
12908 					spx->txlt_tmp_buf = NULL;
12909 				}
12910 				(void) ddi_dma_unbind_handle(
12911 				    spx->txlt_buf_dma_handle);
12912 				(void) ddi_dma_free_handle(
12913 				    &spx->txlt_buf_dma_handle);
12914 				spx->txlt_buf_dma_handle = NULL;
12915 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12916 				    "sata_dma_buf_setup: numwin failed\n"));
12917 				return (DDI_FAILURE);
12918 			}
12919 			SATADBG2(SATA_DBG_DMA_SETUP,
12920 			    spx->txlt_sata_hba_inst,
12921 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
12922 			    spx->txlt_num_dma_win,
12923 			    spx->txlt_curwin_num_dma_cookies);
12924 			spx->txlt_cur_dma_win = 0;
12925 			break;
12926 
12927 		case DDI_DMA_MAPPED:
12928 			/* DMA fully mapped */
12929 			spx->txlt_num_dma_win = 1;
12930 			spx->txlt_cur_dma_win = 0;
12931 			SATADBG1(SATA_DBG_DMA_SETUP,
12932 			    spx->txlt_sata_hba_inst,
12933 			    "sata_dma_buf_setup: windows: 1 "
12934 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
12935 			break;
12936 
12937 		default:
12938 			/* DMA mapping failed */
12939 			if (spx->txlt_tmp_buf != NULL) {
12940 				ddi_dma_mem_free(
12941 				    &spx->txlt_tmp_buf_handle);
12942 				spx->txlt_tmp_buf = NULL;
12943 			}
12944 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12945 			spx->txlt_buf_dma_handle = NULL;
12946 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12947 			    "sata_dma_buf_setup: buf dma handle binding "
12948 			    "failed %x\n", rval));
12949 			return (rval);
12950 		}
12951 		spx->txlt_curwin_processed_dma_cookies = 0;
12952 		spx->txlt_dma_cookie_list = NULL;
12953 	} else {
12954 		/*
12955 		 * DMA setup is reused. Check if we need to process more
12956 		 * cookies in current window, or to get next window, if any.
12957 		 */
12958 
12959 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
12960 		    spx->txlt_curwin_num_dma_cookies);
12961 
12962 		if (spx->txlt_curwin_processed_dma_cookies ==
12963 		    spx->txlt_curwin_num_dma_cookies) {
12964 			/*
12965 			 * All cookies from current DMA window were processed.
12966 			 * Get next DMA window.
12967 			 */
12968 			spx->txlt_cur_dma_win++;
12969 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
12970 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
12971 				    spx->txlt_cur_dma_win, &offset, &size,
12972 				    &spx->txlt_dma_cookie,
12973 				    &spx->txlt_curwin_num_dma_cookies);
12974 				spx->txlt_curwin_processed_dma_cookies = 0;
12975 			} else {
12976 				/* No more windows! End of request! */
12977 				/* What to do? - panic for now */
12978 				ASSERT(spx->txlt_cur_dma_win >=
12979 				    spx->txlt_num_dma_win);
12980 
12981 				spx->txlt_curwin_num_dma_cookies = 0;
12982 				spx->txlt_curwin_processed_dma_cookies = 0;
12983 				spx->txlt_sata_pkt->
12984 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
12985 				return (DDI_SUCCESS);
12986 			}
12987 		}
12988 	}
12989 	/* There better be at least one DMA cookie outstanding */
12990 	ASSERT((spx->txlt_curwin_num_dma_cookies -
12991 	    spx->txlt_curwin_processed_dma_cookies) > 0);
12992 
12993 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
12994 		/* The default cookie slot was used in previous run */
12995 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
12996 		spx->txlt_dma_cookie_list = NULL;
12997 		spx->txlt_dma_cookie_list_len = 0;
12998 	}
12999 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
13000 		/*
13001 		 * Processing a new DMA window - set-up dma cookies list.
13002 		 * We may reuse previously allocated cookie array if it is
13003 		 * possible.
13004 		 */
13005 		if (spx->txlt_dma_cookie_list != NULL &&
13006 		    spx->txlt_dma_cookie_list_len <
13007 		    spx->txlt_curwin_num_dma_cookies) {
13008 			/*
13009 			 * New DMA window contains more cookies than
13010 			 * the previous one. We need larger cookie list - free
13011 			 * the old one.
13012 			 */
13013 			(void) kmem_free(spx->txlt_dma_cookie_list,
13014 			    spx->txlt_dma_cookie_list_len *
13015 			    sizeof (ddi_dma_cookie_t));
13016 			spx->txlt_dma_cookie_list = NULL;
13017 			spx->txlt_dma_cookie_list_len = 0;
13018 		}
13019 		if (spx->txlt_dma_cookie_list == NULL) {
13020 			/*
13021 			 * Calculate lesser of number of cookies in this
13022 			 * DMA window and number of s/g entries.
13023 			 */
13024 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
13025 			req_len = MIN(max_sg_len,
13026 			    spx->txlt_curwin_num_dma_cookies);
13027 
13028 			/* Allocate new dma cookie array if necessary */
13029 			if (req_len == 1) {
13030 				/* Only one cookie - no need for a list */
13031 				spx->txlt_dma_cookie_list =
13032 				    &spx->txlt_dma_cookie;
13033 				spx->txlt_dma_cookie_list_len = 1;
13034 			} else {
13035 				/*
13036 				 * More than one cookie - try to allocate space.
13037 				 */
13038 				spx->txlt_dma_cookie_list = kmem_zalloc(
13039 				    sizeof (ddi_dma_cookie_t) * req_len,
13040 				    callback == NULL_FUNC ? KM_NOSLEEP :
13041 				    KM_SLEEP);
13042 				if (spx->txlt_dma_cookie_list == NULL) {
13043 					SATADBG1(SATA_DBG_DMA_SETUP,
13044 					    spx->txlt_sata_hba_inst,
13045 					    "sata_dma_buf_setup: cookie list "
13046 					    "allocation failed\n", NULL);
13047 					/*
13048 					 * We could not allocate space for
13049 					 * neccessary number of dma cookies in
13050 					 * this window, so we fail this request.
13051 					 * Next invocation would try again to
13052 					 * allocate space for cookie list.
13053 					 * Note:Packet residue was not modified.
13054 					 */
13055 					return (DDI_DMA_NORESOURCES);
13056 				} else {
13057 					spx->txlt_dma_cookie_list_len = req_len;
13058 				}
13059 			}
13060 		}
13061 		/*
13062 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
13063 		 * First cookie was already fetched.
13064 		 */
13065 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
13066 		cur_txfer_len =
13067 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
13068 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
13069 		spx->txlt_curwin_processed_dma_cookies++;
13070 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
13071 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
13072 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
13073 			    &spx->txlt_dma_cookie_list[i]);
13074 			cur_txfer_len +=
13075 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
13076 			spx->txlt_curwin_processed_dma_cookies++;
13077 			spx->txlt_sata_pkt->
13078 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
13079 		}
13080 	} else {
13081 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
13082 		    "sata_dma_buf_setup: sliding within DMA window, "
13083 		    "cur cookie %d, total cookies %d\n",
13084 		    spx->txlt_curwin_processed_dma_cookies,
13085 		    spx->txlt_curwin_num_dma_cookies);
13086 
13087 		/*
13088 		 * Not all cookies from the current dma window were used because
13089 		 * of s/g limitation.
13090 		 * There is no need to re-size the list - it was set at
13091 		 * optimal size, or only default entry is used (s/g = 1).
13092 		 */
13093 		if (spx->txlt_dma_cookie_list == NULL) {
13094 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
13095 			spx->txlt_dma_cookie_list_len = 1;
13096 		}
13097 		/*
13098 		 * Since we are processing remaining cookies in a DMA window,
13099 		 * there may be less of them than the number of entries in the
13100 		 * current dma cookie list.
13101 		 */
13102 		req_len = MIN(spx->txlt_dma_cookie_list_len,
13103 		    (spx->txlt_curwin_num_dma_cookies -
13104 		    spx->txlt_curwin_processed_dma_cookies));
13105 
13106 		/* Fetch the next batch of cookies */
13107 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
13108 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
13109 			    &spx->txlt_dma_cookie_list[i]);
13110 			cur_txfer_len +=
13111 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
13112 			spx->txlt_sata_pkt->
13113 			    satapkt_cmd.satacmd_num_dma_cookies++;
13114 			spx->txlt_curwin_processed_dma_cookies++;
13115 		}
13116 	}
13117 
13118 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
13119 
13120 	/* Point sata_cmd to the cookie list */
13121 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
13122 	    &spx->txlt_dma_cookie_list[0];
13123 
13124 	/* Remember number of DMA cookies passed in sata packet */
13125 	spx->txlt_num_dma_cookies =
13126 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
13127 
13128 	ASSERT(cur_txfer_len != 0);
13129 	if (cur_txfer_len <= bp->b_bcount)
13130 		spx->txlt_total_residue -= cur_txfer_len;
13131 	else {
13132 		/*
13133 		 * Temporary DMA buffer has been padded by
13134 		 * ddi_dma_mem_alloc()!
13135 		 * This requires special handling, because DMA cookies are
13136 		 * based on the temporary buffer size, not the b_bcount,
13137 		 * and we have extra bytes to transfer - but the packet
13138 		 * residue has to stay correct because we will copy only
13139 		 * the requested number of bytes.
13140 		 */
13141 		spx->txlt_total_residue -= bp->b_bcount;
13142 	}
13143 
13144 	return (DDI_SUCCESS);
13145 }
13146 
13147 /*
13148  * Common routine for releasing DMA resources
13149  */
13150 static void
13151 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
13152 {
13153 	if (spx->txlt_buf_dma_handle != NULL) {
13154 		if (spx->txlt_tmp_buf != NULL)  {
13155 			/*
13156 			 * Intermediate DMA buffer was allocated.
13157 			 * Free allocated buffer and associated access handle.
13158 			 */
13159 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
13160 			spx->txlt_tmp_buf = NULL;
13161 		}
13162 		/*
13163 		 * Free DMA resources - cookies and handles
13164 		 */
13165 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
13166 		if (spx->txlt_dma_cookie_list != NULL) {
13167 			if (spx->txlt_dma_cookie_list !=
13168 			    &spx->txlt_dma_cookie) {
13169 				(void) kmem_free(spx->txlt_dma_cookie_list,
13170 				    spx->txlt_dma_cookie_list_len *
13171 				    sizeof (ddi_dma_cookie_t));
13172 				spx->txlt_dma_cookie_list = NULL;
13173 			}
13174 		}
13175 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
13176 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
13177 		spx->txlt_buf_dma_handle = NULL;
13178 	}
13179 }
13180 
13181 /*
13182  * Free DMA resources
13183  * Used by the HBA driver to release DMA resources that it does not use.
13184  *
13185  * Returns Void
13186  */
13187 void
13188 sata_free_dma_resources(sata_pkt_t *sata_pkt)
13189 {
13190 	sata_pkt_txlate_t *spx;
13191 
13192 	if (sata_pkt == NULL)
13193 		return;
13194 
13195 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
13196 
13197 	sata_common_free_dma_rsrcs(spx);
13198 }
13199 
13200 /*
13201  * Fetch Device Identify data.
13202  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
13203  * command to a device and get the device identify data.
13204  * The device_info structure has to be set to device type (for selecting proper
13205  * device identify command).
13206  *
13207  * Returns:
13208  * SATA_SUCCESS if cmd succeeded
13209  * SATA_RETRY if cmd was rejected and could be retried,
13210  * SATA_FAILURE if cmd failed and should not be retried (port error)
13211  *
13212  * Cannot be called in an interrupt context.
13213  */
13214 
13215 static int
13216 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
13217     sata_drive_info_t *sdinfo)
13218 {
13219 	struct buf *bp;
13220 	sata_pkt_t *spkt;
13221 	sata_cmd_t *scmd;
13222 	sata_pkt_txlate_t *spx;
13223 	int rval;
13224 
13225 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13226 	spx->txlt_sata_hba_inst = sata_hba_inst;
13227 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
13228 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13229 	if (spkt == NULL) {
13230 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13231 		return (SATA_RETRY); /* may retry later */
13232 	}
13233 	/* address is needed now */
13234 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13235 
13236 	/*
13237 	 * Allocate buffer for Identify Data return data
13238 	 */
13239 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
13240 	if (bp == NULL) {
13241 		sata_pkt_free(spx);
13242 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
13243 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13244 		    "sata_fetch_device_identify_data: "
13245 		    "cannot allocate buffer for ID"));
13246 		return (SATA_RETRY); /* may retry later */
13247 	}
13248 
13249 	/* Fill sata_pkt */
13250 	sdinfo->satadrv_state = SATA_STATE_PROBING;
13251 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13252 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13253 	/* Synchronous mode, no callback */
13254 	spkt->satapkt_comp = NULL;
13255 	/* Timeout 30s */
13256 	spkt->satapkt_time = sata_default_pkt_time;
13257 
13258 	scmd = &spkt->satapkt_cmd;
13259 	scmd->satacmd_bp = bp;
13260 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
13261 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13262 
13263 	/* Build Identify Device cmd in the sata_pkt */
13264 	scmd->satacmd_addr_type = 0;		/* N/A */
13265 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
13266 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
13267 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
13268 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
13269 	scmd->satacmd_features_reg = 0;		/* N/A */
13270 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
13271 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
13272 		/* Identify Packet Device cmd */
13273 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
13274 	} else {
13275 		/* Identify Device cmd - mandatory for all other devices */
13276 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
13277 	}
13278 
13279 	/* Send pkt to SATA HBA driver */
13280 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
13281 
13282 #ifdef SATA_INJECT_FAULTS
13283 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13284 #endif
13285 
13286 	if (rval == SATA_TRAN_ACCEPTED &&
13287 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
13288 		if (spx->txlt_buf_dma_handle != NULL) {
13289 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
13290 			    DDI_DMA_SYNC_FORKERNEL);
13291 			ASSERT(rval == DDI_SUCCESS);
13292 		}
13293 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
13294 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
13295 			SATA_LOG_D((sata_hba_inst, CE_WARN,
13296 			    "SATA disk device at port %d - "
13297 			    "partial Identify Data",
13298 			    sdinfo->satadrv_addr.cport));
13299 			rval = SATA_RETRY; /* may retry later */
13300 			goto fail;
13301 		}
13302 		/* Update sata_drive_info */
13303 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
13304 		    sizeof (sata_id_t));
13305 
13306 		sdinfo->satadrv_features_support = 0;
13307 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
13308 			/*
13309 			 * Retrieve capacity (disks only) and addressing mode
13310 			 */
13311 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
13312 		} else {
13313 			/*
13314 			 * For ATAPI devices one would have to issue
13315 			 * Get Capacity cmd for media capacity. Not here.
13316 			 */
13317 			sdinfo->satadrv_capacity = 0;
13318 			/*
13319 			 * Check what cdb length is supported
13320 			 */
13321 			if ((sdinfo->satadrv_id.ai_config &
13322 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
13323 				sdinfo->satadrv_atapi_cdb_len = 16;
13324 			else
13325 				sdinfo->satadrv_atapi_cdb_len = 12;
13326 		}
13327 		/* Setup supported features flags */
13328 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
13329 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
13330 
13331 		/* Check for SATA GEN and NCQ support */
13332 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
13333 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
13334 			/* SATA compliance */
13335 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
13336 				sdinfo->satadrv_features_support |=
13337 				    SATA_DEV_F_NCQ;
13338 			if (sdinfo->satadrv_id.ai_satacap &
13339 			    (SATA_1_SPEED | SATA_2_SPEED)) {
13340 				if (sdinfo->satadrv_id.ai_satacap &
13341 				    SATA_2_SPEED)
13342 					sdinfo->satadrv_features_support |=
13343 					    SATA_DEV_F_SATA2;
13344 				if (sdinfo->satadrv_id.ai_satacap &
13345 				    SATA_1_SPEED)
13346 					sdinfo->satadrv_features_support |=
13347 					    SATA_DEV_F_SATA1;
13348 			} else {
13349 				sdinfo->satadrv_features_support |=
13350 				    SATA_DEV_F_SATA1;
13351 			}
13352 		}
13353 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
13354 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
13355 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
13356 
13357 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
13358 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
13359 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
13360 			++sdinfo->satadrv_queue_depth;
13361 			/* Adjust according to controller capabilities */
13362 			sdinfo->satadrv_max_queue_depth = MIN(
13363 			    sdinfo->satadrv_queue_depth,
13364 			    SATA_QDEPTH(sata_hba_inst));
13365 			/* Adjust according to global queue depth limit */
13366 			sdinfo->satadrv_max_queue_depth = MIN(
13367 			    sdinfo->satadrv_max_queue_depth,
13368 			    sata_current_max_qdepth);
13369 			if (sdinfo->satadrv_max_queue_depth == 0)
13370 				sdinfo->satadrv_max_queue_depth = 1;
13371 		} else
13372 			sdinfo->satadrv_max_queue_depth = 1;
13373 
13374 		rval = SATA_SUCCESS;
13375 	} else {
13376 		/*
13377 		 * Woops, no Identify Data.
13378 		 */
13379 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
13380 			rval = SATA_RETRY; /* may retry later */
13381 		} else if (rval == SATA_TRAN_ACCEPTED) {
13382 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
13383 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
13384 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
13385 			    spkt->satapkt_reason == SATA_PKT_RESET)
13386 				rval = SATA_RETRY; /* may retry later */
13387 			else
13388 				rval = SATA_FAILURE;
13389 		} else {
13390 			rval = SATA_FAILURE;
13391 		}
13392 	}
13393 fail:
13394 	/* Free allocated resources */
13395 	sata_free_local_buffer(spx);
13396 	sata_pkt_free(spx);
13397 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13398 
13399 	return (rval);
13400 }
13401 
13402 
13403 /*
13404  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
13405  * UDMA mode is checked first, followed by MWDMA mode.
13406  * set correctly, so this function is setting it to the highest supported level.
13407  * Older SATA spec required that the device supports at least DMA 4 mode and
13408  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
13409  * restriction has been removed.
13410  *
13411  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
13412  * Returns SATA_FAILURE if proper DMA mode could not be selected.
13413  *
13414  * NOTE: This function should be called only if DMA mode is supported.
13415  */
13416 static int
13417 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
13418 {
13419 	sata_pkt_t *spkt;
13420 	sata_cmd_t *scmd;
13421 	sata_pkt_txlate_t *spx;
13422 	int i, mode;
13423 	uint8_t subcmd;
13424 	int rval = SATA_SUCCESS;
13425 
13426 	ASSERT(sdinfo != NULL);
13427 	ASSERT(sata_hba_inst != NULL);
13428 
13429 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
13430 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
13431 		/* Find highest Ultra DMA mode supported */
13432 		for (mode = 6; mode >= 0; --mode) {
13433 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
13434 				break;
13435 		}
13436 #if 0
13437 		/* Left for historical reasons */
13438 		/*
13439 		 * Some initial version of SATA spec indicated that at least
13440 		 * UDMA mode 4 has to be supported. It is not mentioned in
13441 		 * SerialATA 2.6, so this restriction is removed.
13442 		 */
13443 		if (mode < 4)
13444 			return (SATA_FAILURE);
13445 #endif
13446 
13447 		/*
13448 		 * For disk, we're still going to set DMA mode whatever is
13449 		 * selected by default
13450 		 *
13451 		 * We saw an old maxtor sata drive will select Ultra DMA and
13452 		 * Multi-Word DMA simultaneouly by default, which is going
13453 		 * to cause DMA command timed out, so we need to select DMA
13454 		 * mode even when it's already done by default
13455 		 */
13456 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13457 
13458 			/* Find UDMA mode currently selected */
13459 			for (i = 6; i >= 0; --i) {
13460 				if (sdinfo->satadrv_id.ai_ultradma &
13461 				    (1 << (i + 8)))
13462 					break;
13463 			}
13464 			if (i >= mode)
13465 				/* Nothing to do */
13466 				return (SATA_SUCCESS);
13467 		}
13468 
13469 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
13470 
13471 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
13472 		/* Find highest MultiWord DMA mode supported */
13473 		for (mode = 2; mode >= 0; --mode) {
13474 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
13475 				break;
13476 		}
13477 
13478 		/*
13479 		 * For disk, We're still going to set DMA mode whatever is
13480 		 * selected by default
13481 		 *
13482 		 * We saw an old maxtor sata drive will select Ultra DMA and
13483 		 * Multi-Word DMA simultaneouly by default, which is going
13484 		 * to cause DMA command timed out, so we need to select DMA
13485 		 * mode even when it's already done by default
13486 		 */
13487 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13488 
13489 			/* Find highest MultiWord DMA mode selected */
13490 			for (i = 2; i >= 0; --i) {
13491 				if (sdinfo->satadrv_id.ai_dworddma &
13492 				    (1 << (i + 8)))
13493 					break;
13494 			}
13495 			if (i >= mode)
13496 				/* Nothing to do */
13497 				return (SATA_SUCCESS);
13498 		}
13499 
13500 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
13501 	} else
13502 		return (SATA_SUCCESS);
13503 
13504 	/*
13505 	 * Set DMA mode via SET FEATURES COMMAND.
13506 	 * Prepare packet for SET FEATURES COMMAND.
13507 	 */
13508 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13509 	spx->txlt_sata_hba_inst = sata_hba_inst;
13510 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13511 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13512 	if (spkt == NULL) {
13513 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13514 		    "sata_set_dma_mode: could not set DMA mode %d", mode));
13515 		rval = SATA_FAILURE;
13516 		goto done;
13517 	}
13518 	/* Fill sata_pkt */
13519 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13520 	/* Timeout 30s */
13521 	spkt->satapkt_time = sata_default_pkt_time;
13522 	/* Synchronous mode, no callback, interrupts */
13523 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13524 	spkt->satapkt_comp = NULL;
13525 	scmd = &spkt->satapkt_cmd;
13526 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13527 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13528 	scmd->satacmd_addr_type = 0;
13529 	scmd->satacmd_device_reg = 0;
13530 	scmd->satacmd_status_reg = 0;
13531 	scmd->satacmd_error_reg = 0;
13532 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13533 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
13534 	scmd->satacmd_sec_count_lsb = subcmd | mode;
13535 
13536 	/* Transfer command to HBA */
13537 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
13538 	    spkt) != SATA_TRAN_ACCEPTED ||
13539 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13540 		/* Pkt execution failed */
13541 		rval = SATA_FAILURE;
13542 	}
13543 done:
13544 
13545 	/* Free allocated resources */
13546 	if (spkt != NULL)
13547 		sata_pkt_free(spx);
13548 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13549 
13550 	return (rval);
13551 }
13552 
13553 
13554 /*
13555  * Set device caching mode.
13556  * One of the following operations should be specified:
13557  * SATAC_SF_ENABLE_READ_AHEAD
13558  * SATAC_SF_DISABLE_READ_AHEAD
13559  * SATAC_SF_ENABLE_WRITE_CACHE
13560  * SATAC_SF_DISABLE_WRITE_CACHE
13561  *
13562  * If operation fails, system log messgage is emitted.
13563  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
13564  * command was sent but did not succeed, and SATA_FAILURE otherwise.
13565  */
13566 
13567 static int
13568 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13569     int cache_op)
13570 {
13571 	sata_pkt_t *spkt;
13572 	sata_cmd_t *scmd;
13573 	sata_pkt_txlate_t *spx;
13574 	int rval = SATA_SUCCESS;
13575 	int hba_rval;
13576 	char *infop;
13577 
13578 	ASSERT(sdinfo != NULL);
13579 	ASSERT(sata_hba_inst != NULL);
13580 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
13581 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
13582 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
13583 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
13584 
13585 
13586 	/* Prepare packet for SET FEATURES COMMAND */
13587 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13588 	spx->txlt_sata_hba_inst = sata_hba_inst;
13589 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13590 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13591 	if (spkt == NULL) {
13592 		rval = SATA_FAILURE;
13593 		goto failure;
13594 	}
13595 	/* Fill sata_pkt */
13596 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13597 	/* Timeout 30s */
13598 	spkt->satapkt_time = sata_default_pkt_time;
13599 	/* Synchronous mode, no callback, interrupts */
13600 	spkt->satapkt_op_mode =
13601 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13602 	spkt->satapkt_comp = NULL;
13603 	scmd = &spkt->satapkt_cmd;
13604 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13605 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13606 	scmd->satacmd_addr_type = 0;
13607 	scmd->satacmd_device_reg = 0;
13608 	scmd->satacmd_status_reg = 0;
13609 	scmd->satacmd_error_reg = 0;
13610 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13611 	scmd->satacmd_features_reg = cache_op;
13612 
13613 	/* Transfer command to HBA */
13614 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
13615 	    SATA_DIP(sata_hba_inst), spkt);
13616 
13617 #ifdef SATA_INJECT_FAULTS
13618 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13619 #endif
13620 
13621 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
13622 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13623 		/* Pkt execution failed */
13624 		switch (cache_op) {
13625 		case SATAC_SF_ENABLE_READ_AHEAD:
13626 			infop = "enabling read ahead failed";
13627 			break;
13628 		case SATAC_SF_DISABLE_READ_AHEAD:
13629 			infop = "disabling read ahead failed";
13630 			break;
13631 		case SATAC_SF_ENABLE_WRITE_CACHE:
13632 			infop = "enabling write cache failed";
13633 			break;
13634 		case SATAC_SF_DISABLE_WRITE_CACHE:
13635 			infop = "disabling write cache failed";
13636 			break;
13637 		}
13638 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13639 		rval = SATA_RETRY;
13640 	}
13641 failure:
13642 	/* Free allocated resources */
13643 	if (spkt != NULL)
13644 		sata_pkt_free(spx);
13645 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13646 	return (rval);
13647 }
13648 
13649 /*
13650  * Set Removable Media Status Notification (enable/disable)
13651  * state == 0 , disable
13652  * state != 0 , enable
13653  *
13654  * If operation fails, system log messgage is emitted.
13655  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
13656  */
13657 
13658 static int
13659 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13660     int state)
13661 {
13662 	sata_pkt_t *spkt;
13663 	sata_cmd_t *scmd;
13664 	sata_pkt_txlate_t *spx;
13665 	int rval = SATA_SUCCESS;
13666 	char *infop;
13667 
13668 	ASSERT(sdinfo != NULL);
13669 	ASSERT(sata_hba_inst != NULL);
13670 
13671 	/* Prepare packet for SET FEATURES COMMAND */
13672 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13673 	spx->txlt_sata_hba_inst = sata_hba_inst;
13674 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13675 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13676 	if (spkt == NULL) {
13677 		rval = SATA_FAILURE;
13678 		goto failure;
13679 	}
13680 	/* Fill sata_pkt */
13681 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13682 	/* Timeout 30s */
13683 	spkt->satapkt_time = sata_default_pkt_time;
13684 	/* Synchronous mode, no callback, interrupts */
13685 	spkt->satapkt_op_mode =
13686 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13687 	spkt->satapkt_comp = NULL;
13688 	scmd = &spkt->satapkt_cmd;
13689 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13690 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13691 	scmd->satacmd_addr_type = 0;
13692 	scmd->satacmd_device_reg = 0;
13693 	scmd->satacmd_status_reg = 0;
13694 	scmd->satacmd_error_reg = 0;
13695 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13696 	if (state == 0)
13697 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
13698 	else
13699 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
13700 
13701 	/* Transfer command to HBA */
13702 	if (((*SATA_START_FUNC(sata_hba_inst))(
13703 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
13704 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13705 		/* Pkt execution failed */
13706 		if (state == 0)
13707 			infop = "disabling Removable Media Status "
13708 			    "Notification failed";
13709 		else
13710 			infop = "enabling Removable Media Status "
13711 			    "Notification failed";
13712 
13713 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13714 		rval = SATA_FAILURE;
13715 	}
13716 failure:
13717 	/* Free allocated resources */
13718 	if (spkt != NULL)
13719 		sata_pkt_free(spx);
13720 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13721 	return (rval);
13722 }
13723 
13724 
13725 /*
13726  * Update state and copy port ss* values from passed sata_device structure.
13727  * sata_address is validated - if not valid, nothing is changed in sata_scsi
13728  * configuration struct.
13729  *
13730  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
13731  * regardless of the state in device argument.
13732  *
13733  * Port mutex should be held while calling this function.
13734  */
13735 static void
13736 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
13737     sata_device_t *sata_device)
13738 {
13739 	sata_cport_info_t *cportinfo;
13740 
13741 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
13742 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
13743 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
13744 		    sata_device->satadev_addr.cport)
13745 			return;
13746 
13747 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
13748 		    sata_device->satadev_addr.cport);
13749 
13750 		ASSERT(mutex_owned(&cportinfo->cport_mutex));
13751 		cportinfo->cport_scr = sata_device->satadev_scr;
13752 
13753 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
13754 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
13755 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13756 		cportinfo->cport_state |=
13757 		    sata_device->satadev_state & SATA_PSTATE_VALID;
13758 	}
13759 }
13760 
13761 void
13762 sata_update_pmport_info(sata_hba_inst_t *sata_hba_inst,
13763     sata_device_t *sata_device)
13764 {
13765 	sata_pmport_info_t *pmportinfo;
13766 
13767 	if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT &&
13768 	    sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
13769 	    SATA_NUM_PMPORTS(sata_hba_inst,
13770 	    sata_device->satadev_addr.cport) <
13771 	    sata_device->satadev_addr.pmport) {
13772 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
13773 		    "sata_update_port_info: error address %p.",
13774 		    &sata_device->satadev_addr);
13775 		return;
13776 	}
13777 
13778 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
13779 	    sata_device->satadev_addr.cport,
13780 	    sata_device->satadev_addr.pmport);
13781 
13782 	ASSERT(mutex_owned(&pmportinfo->pmport_mutex));
13783 	pmportinfo->pmport_scr = sata_device->satadev_scr;
13784 
13785 	/* Preserve SATA_PSTATE_SHUTDOWN flag */
13786 	pmportinfo->pmport_state &=
13787 	    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13788 	pmportinfo->pmport_state |=
13789 	    sata_device->satadev_state & SATA_PSTATE_VALID;
13790 }
13791 
13792 /*
13793  * Extract SATA port specification from an IOCTL argument.
13794  *
13795  * This function return the port the user land send us as is, unless it
13796  * cannot retrieve port spec, then -1 is returned.
13797  *
13798  * Support port multiplier.
13799  */
13800 static int32_t
13801 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
13802 {
13803 	int32_t port;
13804 
13805 	/* Extract port number from nvpair in dca structure  */
13806 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
13807 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
13808 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
13809 		    port));
13810 		port = -1;
13811 	}
13812 
13813 	return (port);
13814 }
13815 
13816 /*
13817  * Get dev_info_t pointer to the device node pointed to by port argument.
13818  * NOTE: target argument is a value used in ioctls to identify
13819  * the AP - it is not a sata_address.
13820  * It is a combination of cport, pmport and address qualifier, encodded same
13821  * way as a scsi target number.
13822  * At this moment it carries only cport number.
13823  *
13824  * PMult hotplug is supported now.
13825  *
13826  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13827  */
13828 
13829 static dev_info_t *
13830 sata_get_target_dip(dev_info_t *dip, uint8_t cport, uint8_t pmport)
13831 {
13832 	dev_info_t	*cdip = NULL;
13833 	int		target, tgt;
13834 	int 		circ;
13835 	uint8_t		qual;
13836 
13837 	sata_hba_inst_t	*sata_hba_inst;
13838 	scsi_hba_tran_t *scsi_hba_tran;
13839 
13840 	/* Get target id */
13841 	scsi_hba_tran = ddi_get_driver_private(dip);
13842 	if (scsi_hba_tran == NULL)
13843 		return (NULL);
13844 
13845 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
13846 
13847 	if (sata_hba_inst == NULL)
13848 		return (NULL);
13849 
13850 	/* Identify a port-mult by cport_info.cport_dev_type */
13851 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT)
13852 		qual = SATA_ADDR_DPMPORT;
13853 	else
13854 		qual = SATA_ADDR_DCPORT;
13855 
13856 	target = SATA_TO_SCSI_TARGET(cport, pmport, qual);
13857 
13858 	/* Retrieve target dip */
13859 	ndi_devi_enter(dip, &circ);
13860 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13861 		dev_info_t *next = ddi_get_next_sibling(cdip);
13862 
13863 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13864 		    DDI_PROP_DONTPASS, "target", -1);
13865 		if (tgt == -1) {
13866 			/*
13867 			 * This is actually an error condition, but not
13868 			 * a fatal one. Just continue the search.
13869 			 */
13870 			cdip = next;
13871 			continue;
13872 		}
13873 
13874 		if (tgt == target)
13875 			break;
13876 
13877 		cdip = next;
13878 	}
13879 	ndi_devi_exit(dip, circ);
13880 
13881 	return (cdip);
13882 }
13883 
13884 /*
13885  * Get dev_info_t pointer to the device node pointed to by port argument.
13886  * NOTE: target argument is a value used in ioctls to identify
13887  * the AP - it is not a sata_address.
13888  * It is a combination of cport, pmport and address qualifier, encoded same
13889  * way as a scsi target number.
13890  *
13891  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13892  */
13893 
13894 static dev_info_t *
13895 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
13896 {
13897 	dev_info_t	*cdip = NULL;
13898 	int		target, tgt;
13899 	int 		circ;
13900 
13901 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
13902 
13903 	ndi_devi_enter(dip, &circ);
13904 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13905 		dev_info_t *next = ddi_get_next_sibling(cdip);
13906 
13907 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13908 		    DDI_PROP_DONTPASS, "target", -1);
13909 		if (tgt == -1) {
13910 			/*
13911 			 * This is actually an error condition, but not
13912 			 * a fatal one. Just continue the search.
13913 			 */
13914 			cdip = next;
13915 			continue;
13916 		}
13917 
13918 		if (tgt == target)
13919 			break;
13920 
13921 		cdip = next;
13922 	}
13923 	ndi_devi_exit(dip, circ);
13924 
13925 	return (cdip);
13926 }
13927 
13928 /*
13929  * Process sata port disconnect request.
13930  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
13931  * before this request. Nevertheless, if a device is still configured,
13932  * we need to attempt to offline and unconfigure device.
13933  * Regardless of the unconfigure operation results the port is marked as
13934  * deactivated and no access to the attached device is possible.
13935  * If the target node remains because unconfigure operation failed, its state
13936  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
13937  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
13938  * the device and remove old target node.
13939  *
13940  * This function invokes sata_hba_inst->satahba_tran->
13941  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13942  * If successful, the device structure (if any) attached to the specified port
13943  * is removed and state of the port marked appropriately.
13944  * Failure of the port_deactivate may keep port in the physically active state,
13945  * or may fail the port.
13946  *
13947  * NOTE: Port multiplier is supported.
13948  */
13949 
13950 static int
13951 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
13952     sata_device_t *sata_device)
13953 {
13954 	sata_drive_info_t *sdinfo = NULL, *subsdinfo = NULL;
13955 	sata_cport_info_t *cportinfo = NULL;
13956 	sata_pmport_info_t *pmportinfo = NULL;
13957 	sata_pmult_info_t *pmultinfo = NULL;
13958 	sata_device_t subsdevice;
13959 	int cport, pmport, qual;
13960 	int rval = SATA_SUCCESS;
13961 	int npmport = 0;
13962 	int rv = 0;
13963 
13964 	cport = sata_device->satadev_addr.cport;
13965 	pmport = sata_device->satadev_addr.pmport;
13966 	qual = sata_device->satadev_addr.qual;
13967 
13968 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13969 	if (qual == SATA_ADDR_DCPORT)
13970 		qual = SATA_ADDR_CPORT;
13971 	else
13972 		qual = SATA_ADDR_PMPORT;
13973 
13974 	/*
13975 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
13976 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13977 	 * Do the sanity check.
13978 	 */
13979 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
13980 		/* No physical port deactivation supported. */
13981 		return (EINVAL);
13982 	}
13983 
13984 	/* Check the current state of the port */
13985 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
13986 	    (SATA_DIP(sata_hba_inst), sata_device);
13987 
13988 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
13989 
13990 	/*
13991 	 * Processing port mulitiplier
13992 	 */
13993 	if (qual == SATA_ADDR_CPORT &&
13994 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
13995 		mutex_enter(&cportinfo->cport_mutex);
13996 
13997 		/* Check controller port status */
13998 		sata_update_port_info(sata_hba_inst, sata_device);
13999 		if (rval != SATA_SUCCESS ||
14000 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14001 			/*
14002 			 * Device port status is unknown or it is in failed
14003 			 * state
14004 			 */
14005 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14006 			    SATA_PSTATE_FAILED;
14007 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14008 			    "sata_hba_ioctl: connect: failed to deactivate "
14009 			    "SATA port %d", cport);
14010 			mutex_exit(&cportinfo->cport_mutex);
14011 			return (EIO);
14012 		}
14013 
14014 		/* Disconnect all sub-devices. */
14015 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14016 		if (pmultinfo != NULL) {
14017 
14018 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
14019 			    sata_hba_inst, cport); npmport ++) {
14020 				subsdinfo = SATA_PMPORT_DRV_INFO(
14021 				    sata_hba_inst, cport, npmport);
14022 				if (subsdinfo == NULL)
14023 					continue;
14024 
14025 				subsdevice.satadev_addr = subsdinfo->
14026 				    satadrv_addr;
14027 
14028 				mutex_exit(&cportinfo->cport_mutex);
14029 				if (sata_ioctl_disconnect(sata_hba_inst,
14030 				    &subsdevice) == SATA_SUCCESS) {
14031 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14032 					"[Remove] device at port %d:%d "
14033 					"successfully.", cport, npmport);
14034 				}
14035 				mutex_enter(&cportinfo->cport_mutex);
14036 			}
14037 		}
14038 
14039 		/* Disconnect the port multiplier */
14040 		cportinfo->cport_state &= ~SATA_STATE_READY;
14041 		mutex_exit(&cportinfo->cport_mutex);
14042 
14043 		sata_device->satadev_addr.qual = qual;
14044 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14045 		    (SATA_DIP(sata_hba_inst), sata_device);
14046 
14047 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14048 		    SE_NO_HINT);
14049 
14050 		mutex_enter(&cportinfo->cport_mutex);
14051 		sata_update_port_info(sata_hba_inst, sata_device);
14052 		if (rval != SATA_SUCCESS &&
14053 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14054 			cportinfo->cport_state = SATA_PSTATE_FAILED;
14055 			rv = EIO;
14056 		} else {
14057 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14058 		}
14059 		mutex_exit(&cportinfo->cport_mutex);
14060 
14061 		return (rv);
14062 	}
14063 
14064 	/*
14065 	 * Process non-port-multiplier device - it could be a drive connected
14066 	 * to a port multiplier port or a controller port.
14067 	 */
14068 	if (qual == SATA_ADDR_PMPORT) {
14069 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14070 		mutex_enter(&pmportinfo->pmport_mutex);
14071 		sata_update_pmport_info(sata_hba_inst, sata_device);
14072 		if (rval != SATA_SUCCESS ||
14073 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14074 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
14075 			    SATA_PSTATE_FAILED;
14076 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
14077 			    "sata_hba_ioctl: connect: failed to deactivate "
14078 			    "SATA port %d:%d", cport, pmport);
14079 			mutex_exit(&pmportinfo->pmport_mutex);
14080 			return (EIO);
14081 		}
14082 
14083 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
14084 			sdinfo = pmportinfo->pmport_sata_drive;
14085 			ASSERT(sdinfo != NULL);
14086 		}
14087 
14088 		/*
14089 		 * Set port's dev_state to not ready - this will disable
14090 		 * an access to a potentially attached device.
14091 		 */
14092 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
14093 
14094 		/* Remove and release sata_drive info structure. */
14095 		if (sdinfo != NULL) {
14096 			if ((sdinfo->satadrv_type &
14097 			    SATA_VALID_DEV_TYPE) != 0) {
14098 				/*
14099 				 * If a target node exists, try to offline
14100 				 * a device and remove target node.
14101 				 */
14102 				mutex_exit(&pmportinfo->pmport_mutex);
14103 				(void) sata_offline_device(sata_hba_inst,
14104 				    sata_device, sdinfo);
14105 				mutex_enter(&pmportinfo->pmport_mutex);
14106 			}
14107 
14108 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
14109 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
14110 			(void) kmem_free((void *)sdinfo,
14111 			    sizeof (sata_drive_info_t));
14112 		}
14113 		mutex_exit(&pmportinfo->pmport_mutex);
14114 
14115 	} else if (qual == SATA_ADDR_CPORT) {
14116 		mutex_enter(&cportinfo->cport_mutex);
14117 		sata_update_port_info(sata_hba_inst, sata_device);
14118 		if (rval != SATA_SUCCESS ||
14119 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14120 			/*
14121 			 * Device port status is unknown or it is in failed
14122 			 * state
14123 			 */
14124 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14125 			    SATA_PSTATE_FAILED;
14126 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14127 			    "sata_hba_ioctl: connect: failed to deactivate "
14128 			    "SATA port %d", cport);
14129 			mutex_exit(&cportinfo->cport_mutex);
14130 			return (EIO);
14131 		}
14132 
14133 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
14134 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14135 			ASSERT(pmultinfo != NULL);
14136 		} else if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14137 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14138 			ASSERT(sdinfo != NULL);
14139 		}
14140 		cportinfo->cport_state &= ~SATA_STATE_READY;
14141 
14142 		if (sdinfo != NULL) {
14143 			if ((sdinfo->satadrv_type &
14144 			    SATA_VALID_DEV_TYPE) != 0) {
14145 				/*
14146 				 * If a target node exists, try to offline
14147 				 * a device and remove target node.
14148 				 */
14149 				mutex_exit(&cportinfo->cport_mutex);
14150 				(void) sata_offline_device(sata_hba_inst,
14151 				    sata_device, sdinfo);
14152 				mutex_enter(&cportinfo->cport_mutex);
14153 			}
14154 
14155 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14156 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14157 			(void) kmem_free((void *)sdinfo,
14158 			    sizeof (sata_drive_info_t));
14159 		}
14160 		mutex_exit(&cportinfo->cport_mutex);
14161 	}
14162 
14163 	/* Just ask HBA driver to deactivate port */
14164 	sata_device->satadev_addr.qual = qual;
14165 
14166 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14167 	    (SATA_DIP(sata_hba_inst), sata_device);
14168 
14169 	/*
14170 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14171 	 * without the hint (to force listener to investivate the state).
14172 	 */
14173 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14174 	    SE_NO_HINT);
14175 
14176 	if (qual == SATA_ADDR_PMPORT) {
14177 		mutex_enter(&pmportinfo->pmport_mutex);
14178 		sata_update_pmport_info(sata_hba_inst, sata_device);
14179 
14180 		if (rval != SATA_SUCCESS &&
14181 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14182 			/*
14183 			 * Port deactivation failure - do not change port
14184 			 * state unless the state returned by HBA indicates a
14185 			 * port failure.
14186 			 *
14187 			 * NOTE: device structures were released, so devices
14188 			 * now are invisible! Port reset is needed to
14189 			 * re-enumerate devices.
14190 			 */
14191 			pmportinfo->pmport_state = SATA_PSTATE_FAILED;
14192 			rv = EIO;
14193 		} else {
14194 			/*
14195 			 * Deactivation succeded. From now on the sata framework
14196 			 * will not care what is happening to the device, until
14197 			 * the port is activated again.
14198 			 */
14199 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14200 		}
14201 		mutex_exit(&pmportinfo->pmport_mutex);
14202 	} else if (qual == SATA_ADDR_CPORT) {
14203 		mutex_enter(&cportinfo->cport_mutex);
14204 		sata_update_port_info(sata_hba_inst, sata_device);
14205 
14206 		if (rval != SATA_SUCCESS &&
14207 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
14208 			cportinfo->cport_state = SATA_PSTATE_FAILED;
14209 			rv = EIO;
14210 		} else {
14211 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14212 		}
14213 		mutex_exit(&cportinfo->cport_mutex);
14214 	}
14215 
14216 	return (rv);
14217 }
14218 
14219 
14220 
14221 /*
14222  * Process sata port connect request
14223  * The sata cfgadm pluging will invoke this operation only if port was found
14224  * in the disconnect state (failed state is also treated as the disconnected
14225  * state).
14226  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
14227  * sata_tran_hotplug_ops->sata_tran_port_activate().
14228  * If successful and a device is found attached to the port,
14229  * the initialization sequence is executed to attach a device structure to
14230  * a port structure. The state of the port and a device would be set
14231  * appropriately.
14232  * The device is not set in configured state (system-wise) by this operation.
14233  *
14234  * Note, that activating the port may generate link events,
14235  * so it is important that following processing and the
14236  * event processing does not interfere with each other!
14237  *
14238  * This operation may remove port failed state and will
14239  * try to make port active and in good standing.
14240  *
14241  * NOTE: Port multiplier is supported.
14242  */
14243 
14244 static int
14245 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
14246     sata_device_t *sata_device)
14247 {
14248 	sata_pmport_info_t	*pmportinfo = NULL;
14249 	uint8_t cport, pmport, qual;
14250 	int rv = 0;
14251 
14252 	cport = sata_device->satadev_addr.cport;
14253 	pmport = sata_device->satadev_addr.pmport;
14254 	qual = sata_device->satadev_addr.qual;
14255 
14256 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14257 	if (qual == SATA_ADDR_DCPORT)
14258 		qual = SATA_ADDR_CPORT;
14259 	else
14260 		qual = SATA_ADDR_PMPORT;
14261 
14262 	if (qual == SATA_ADDR_PMPORT)
14263 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14264 
14265 	/*
14266 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
14267 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
14268 	 * Perform sanity check now.
14269 	 */
14270 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
14271 		/* No physical port activation supported. */
14272 		return (EINVAL);
14273 	}
14274 
14275 	/* Just ask HBA driver to activate port */
14276 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14277 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14278 		/*
14279 		 * Port activation failure.
14280 		 */
14281 		if (qual == SATA_ADDR_CPORT) {
14282 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14283 			    cport)->cport_mutex);
14284 			sata_update_port_info(sata_hba_inst, sata_device);
14285 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14286 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14287 				    SATA_PSTATE_FAILED;
14288 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14289 				    "sata_hba_ioctl: connect: failed to "
14290 				    "activate SATA port %d", cport);
14291 			}
14292 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14293 			    cport)->cport_mutex);
14294 		} else { /* port multiplier device port */
14295 			mutex_enter(&pmportinfo->pmport_mutex);
14296 			sata_update_pmport_info(sata_hba_inst, sata_device);
14297 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14298 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14299 				    pmport) = SATA_PSTATE_FAILED;
14300 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
14301 				    "sata_hba_ioctl: connect: failed to "
14302 				    "activate SATA port %d:%d", cport, pmport);
14303 			}
14304 			mutex_exit(&pmportinfo->pmport_mutex);
14305 		}
14306 		return (EIO);
14307 	}
14308 
14309 	/* Virgin port state - will be updated by the port re-probe. */
14310 	if (qual == SATA_ADDR_CPORT) {
14311 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14312 		    cport)->cport_mutex);
14313 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
14314 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14315 		    cport)->cport_mutex);
14316 	} else { /* port multiplier device port */
14317 		mutex_enter(&pmportinfo->pmport_mutex);
14318 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
14319 		mutex_exit(&pmportinfo->pmport_mutex);
14320 	}
14321 
14322 	/*
14323 	 * Probe the port to find its state and attached device.
14324 	 */
14325 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14326 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
14327 		rv = EIO;
14328 
14329 	/*
14330 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14331 	 * without the hint
14332 	 */
14333 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14334 	    SE_NO_HINT);
14335 
14336 	/*
14337 	 * If there is a device attached to the port, emit
14338 	 * a message.
14339 	 */
14340 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
14341 
14342 		if (qual == SATA_ADDR_CPORT) {
14343 			if (sata_device->satadev_type == SATA_DTYPE_PMULT) {
14344 				sata_log(sata_hba_inst, CE_WARN,
14345 				    "SATA port multiplier detected "
14346 				    "at port %d", cport);
14347 			} else {
14348 				sata_log(sata_hba_inst, CE_WARN,
14349 				    "SATA device detected at port %d", cport);
14350 				if (sata_device->satadev_type ==
14351 				    SATA_DTYPE_UNKNOWN) {
14352 				/*
14353 				 * A device was not successfully identified
14354 				 */
14355 				sata_log(sata_hba_inst, CE_WARN,
14356 				    "Could not identify SATA "
14357 				    "device at port %d", cport);
14358 				}
14359 			}
14360 		} else { /* port multiplier device port */
14361 			sata_log(sata_hba_inst, CE_WARN,
14362 			    "SATA device detected at port %d:%d",
14363 			    cport, pmport);
14364 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14365 				/*
14366 				 * A device was not successfully identified
14367 				 */
14368 				sata_log(sata_hba_inst, CE_WARN,
14369 				    "Could not identify SATA "
14370 				    "device at port %d:%d", cport, pmport);
14371 			}
14372 		}
14373 	}
14374 
14375 	return (rv);
14376 }
14377 
14378 
14379 /*
14380  * Process sata device unconfigure request.
14381  * The unconfigure operation uses generic nexus operation to
14382  * offline a device. It leaves a target device node attached.
14383  * and obviously sata_drive_info attached as well, because
14384  * from the hardware point of view nothing has changed.
14385  */
14386 static int
14387 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
14388     sata_device_t *sata_device)
14389 {
14390 	int rv = 0;
14391 	dev_info_t *tdip;
14392 
14393 	/* We are addressing attached device, not a port */
14394 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
14395 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14396 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
14397 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14398 
14399 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14400 	    &sata_device->satadev_addr)) != NULL) {
14401 
14402 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
14403 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14404 			    "sata_hba_ioctl: unconfigure: "
14405 			    "failed to unconfigure device at SATA port %d:%d",
14406 			    sata_device->satadev_addr.cport,
14407 			    sata_device->satadev_addr.pmport));
14408 			rv = EIO;
14409 		}
14410 		/*
14411 		 * The target node devi_state should be marked with
14412 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
14413 		 * This would be the indication for cfgadm that
14414 		 * the AP node occupant state is 'unconfigured'.
14415 		 */
14416 
14417 	} else {
14418 		/*
14419 		 * This would indicate a failure on the part of cfgadm
14420 		 * to detect correct state of the node prior to this
14421 		 * call - one cannot unconfigure non-existing device.
14422 		 */
14423 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14424 		    "sata_hba_ioctl: unconfigure: "
14425 		    "attempt to unconfigure non-existing device "
14426 		    "at SATA port %d:%d",
14427 		    sata_device->satadev_addr.cport,
14428 		    sata_device->satadev_addr.pmport));
14429 		rv = ENXIO;
14430 	}
14431 	return (rv);
14432 }
14433 
14434 /*
14435  * Process sata device configure request
14436  * If port is in a failed state, operation is aborted - one has to use
14437  * an explicit connect or port activate request to try to get a port into
14438  * non-failed mode. Port reset wil also work in such situation.
14439  * If the port is in disconnected (shutdown) state, the connect operation is
14440  * attempted prior to any other action.
14441  * When port is in the active state, there is a device attached and the target
14442  * node exists, a device was most likely offlined.
14443  * If target node does not exist, a new target node is created. In both cases
14444  * an attempt is made to online (configure) the device.
14445  *
14446  * NOTE: Port multiplier is supported.
14447  */
14448 static int
14449 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
14450     sata_device_t *sata_device)
14451 {
14452 	int cport, pmport, qual;
14453 	int rval;
14454 	boolean_t target = TRUE;
14455 	sata_cport_info_t *cportinfo;
14456 	sata_pmport_info_t *pmportinfo = NULL;
14457 	dev_info_t *tdip;
14458 	sata_drive_info_t *sdinfo;
14459 
14460 	cport = sata_device->satadev_addr.cport;
14461 	pmport = sata_device->satadev_addr.pmport;
14462 	qual = sata_device->satadev_addr.qual;
14463 
14464 	/* Get current port state */
14465 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14466 	    (SATA_DIP(sata_hba_inst), sata_device);
14467 
14468 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14469 	if (qual == SATA_ADDR_DPMPORT) {
14470 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14471 		mutex_enter(&pmportinfo->pmport_mutex);
14472 		sata_update_pmport_info(sata_hba_inst, sata_device);
14473 		if (rval != SATA_SUCCESS ||
14474 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14475 			/*
14476 			 * Obviously, device on a failed port is not visible
14477 			 */
14478 			mutex_exit(&pmportinfo->pmport_mutex);
14479 			return (ENXIO);
14480 		}
14481 		mutex_exit(&pmportinfo->pmport_mutex);
14482 	} else {
14483 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14484 		    cport)->cport_mutex);
14485 		sata_update_port_info(sata_hba_inst, sata_device);
14486 		if (rval != SATA_SUCCESS ||
14487 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14488 			/*
14489 			 * Obviously, device on a failed port is not visible
14490 			 */
14491 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14492 			    cport)->cport_mutex);
14493 			return (ENXIO);
14494 		}
14495 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14496 		    cport)->cport_mutex);
14497 	}
14498 
14499 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
14500 		/* need to activate port */
14501 		target = FALSE;
14502 
14503 		/* Sanity check */
14504 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14505 			return (ENXIO);
14506 
14507 		/* Just let HBA driver to activate port */
14508 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14509 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14510 			/*
14511 			 * Port activation failure - do not change port state
14512 			 * unless the state returned by HBA indicates a port
14513 			 * failure.
14514 			 */
14515 			if (qual == SATA_ADDR_DPMPORT) {
14516 				mutex_enter(&pmportinfo->pmport_mutex);
14517 				sata_update_pmport_info(sata_hba_inst,
14518 				    sata_device);
14519 				if (sata_device->satadev_state &
14520 				    SATA_PSTATE_FAILED)
14521 					pmportinfo->pmport_state =
14522 					    SATA_PSTATE_FAILED;
14523 				mutex_exit(&pmportinfo->pmport_mutex);
14524 			} else {
14525 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14526 				    cport)->cport_mutex);
14527 				sata_update_port_info(sata_hba_inst,
14528 				    sata_device);
14529 				if (sata_device->satadev_state &
14530 				    SATA_PSTATE_FAILED)
14531 					cportinfo->cport_state =
14532 					    SATA_PSTATE_FAILED;
14533 				mutex_exit(&SATA_CPORT_INFO(
14534 				    sata_hba_inst, cport)->cport_mutex);
14535 			}
14536 		}
14537 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14538 		    "sata_hba_ioctl: configure: "
14539 		    "failed to activate SATA port %d:%d",
14540 		    cport, pmport));
14541 		return (EIO);
14542 	}
14543 	/*
14544 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14545 	 * without the hint.
14546 	 */
14547 	sata_gen_sysevent(sata_hba_inst,
14548 	    &sata_device->satadev_addr, SE_NO_HINT);
14549 
14550 	/* Virgin port state */
14551 	if (qual == SATA_ADDR_DPMPORT) {
14552 		mutex_enter(&pmportinfo->pmport_mutex);
14553 		pmportinfo->pmport_state = 0;
14554 		mutex_exit(&pmportinfo->pmport_mutex);
14555 	} else {
14556 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14557 		    cport)-> cport_mutex);
14558 		cportinfo->cport_state = 0;
14559 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14560 		    cport)->cport_mutex);
14561 	}
14562 	/*
14563 	 * Always reprobe port, to get current device info.
14564 	 */
14565 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14566 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14567 		return (EIO);
14568 
14569 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == FALSE) {
14570 		if (qual == SATA_ADDR_DPMPORT) {
14571 			/*
14572 			 * That's the transition from "inactive" port
14573 			 * to active one with device attached.
14574 			 */
14575 			sata_log(sata_hba_inst, CE_WARN,
14576 			    "SATA device detected at port %d:%d",
14577 			    cport, pmport);
14578 		} else {
14579 			/*
14580 			 * When PM is attached to the cport and cport is
14581 			 * activated, every PM device port needs to be reprobed.
14582 			 * We need to emit message for all devices detected
14583 			 * at port multiplier's device ports.
14584 			 * Add such code here.
14585 			 * For now, just inform about device attached to
14586 			 * cport.
14587 			 */
14588 			sata_log(sata_hba_inst, CE_WARN,
14589 			    "SATA device detected at port %d", cport);
14590 		}
14591 	}
14592 
14593 	/*
14594 	 * This is where real configuration operation starts.
14595 	 *
14596 	 * When PM is attached to the cport and cport is activated,
14597 	 * devices attached PM device ports may have to be configured
14598 	 * explicitly. This may change when port multiplier is supported.
14599 	 * For now, configure only disks and other valid target devices.
14600 	 */
14601 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
14602 		if (qual == SATA_ADDR_DCPORT) {
14603 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14604 				/*
14605 				 * A device was not successfully identified
14606 				 */
14607 				sata_log(sata_hba_inst, CE_WARN,
14608 				    "Could not identify SATA "
14609 				    "device at port %d", cport);
14610 			}
14611 		} else { /* port multiplier device port */
14612 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14613 				/*
14614 				 * A device was not successfully identified
14615 				 */
14616 				sata_log(sata_hba_inst, CE_WARN,
14617 				    "Could not identify SATA "
14618 				    "device at port %d:%d", cport, pmport);
14619 			}
14620 		}
14621 		return (ENXIO);		/* No device to configure */
14622 	}
14623 
14624 	/*
14625 	 * Here we may have a device in reset condition,
14626 	 * but because we are just configuring it, there is
14627 	 * no need to process the reset other than just
14628 	 * to clear device reset condition in the HBA driver.
14629 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
14630 	 * cause a first command sent the HBA driver with the request
14631 	 * to clear device reset condition.
14632 	 */
14633 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14634 	if (qual == SATA_ADDR_DPMPORT)
14635 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14636 	else
14637 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14638 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
14639 	if (sdinfo == NULL) {
14640 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14641 		return (ENXIO);
14642 	}
14643 	if (sdinfo->satadrv_event_flags &
14644 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
14645 		sdinfo->satadrv_event_flags = 0;
14646 	}
14647 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
14648 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14649 
14650 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14651 	    &sata_device->satadev_addr)) != NULL) {
14652 		/*
14653 		 * Target node exists. Verify, that it belongs
14654 		 * to existing, attached device and not to
14655 		 * a removed device.
14656 		 */
14657 		if (sata_check_device_removed(tdip) == B_TRUE) {
14658 			if (qual == SATA_ADDR_DPMPORT)
14659 				sata_log(sata_hba_inst, CE_WARN,
14660 				    "SATA device at port %d cannot be "
14661 				    "configured. "
14662 				    "Application(s) accessing "
14663 				    "previously attached device "
14664 				    "have to release it before newly "
14665 				    "inserted device can be made accessible.",
14666 				    cport);
14667 			else
14668 				sata_log(sata_hba_inst, CE_WARN,
14669 				    "SATA device at port %d:%d cannot be"
14670 				    "configured. "
14671 				    "Application(s) accessing "
14672 				    "previously attached device "
14673 				    "have to release it before newly "
14674 				    "inserted device can be made accessible.",
14675 				    cport, pmport);
14676 			return (EIO);
14677 		}
14678 		/*
14679 		 * Device was not removed and re-inserted.
14680 		 * Try to online it.
14681 		 */
14682 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
14683 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14684 			    "sata_hba_ioctl: configure: "
14685 			    "onlining device at SATA port "
14686 			    "%d:%d failed", cport, pmport));
14687 			return (EIO);
14688 		}
14689 
14690 		if (qual == SATA_ADDR_DPMPORT) {
14691 			mutex_enter(&pmportinfo->pmport_mutex);
14692 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14693 			mutex_exit(&pmportinfo->pmport_mutex);
14694 		} else {
14695 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14696 			    cport)->cport_mutex);
14697 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14698 			mutex_exit(&SATA_CPORT_INFO(
14699 			    sata_hba_inst, cport)->cport_mutex);
14700 		}
14701 	} else {
14702 		/*
14703 		 * No target node - need to create a new target node.
14704 		 */
14705 		if (qual == SATA_ADDR_DPMPORT) {
14706 			mutex_enter(&pmportinfo->pmport_mutex);
14707 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14708 			mutex_exit(&pmportinfo->pmport_mutex);
14709 		} else {
14710 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14711 			    cport_mutex);
14712 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14713 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14714 			    cport_mutex);
14715 		}
14716 
14717 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
14718 		    sata_hba_inst, &sata_device->satadev_addr);
14719 		if (tdip == NULL) {
14720 			/* Configure operation failed */
14721 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14722 			    "sata_hba_ioctl: configure: "
14723 			    "configuring SATA device at port %d:%d "
14724 			    "failed", cport, pmport));
14725 			return (EIO);
14726 		}
14727 	}
14728 	return (0);
14729 }
14730 
14731 
14732 /*
14733  * Process ioctl deactivate port request.
14734  * Arbitrarily unconfigure attached device, if any.
14735  * Even if the unconfigure fails, proceed with the
14736  * port deactivation.
14737  *
14738  * NOTE: Port Multiplier is supported now.
14739  */
14740 
14741 static int
14742 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
14743     sata_device_t *sata_device)
14744 {
14745 	int cport, pmport, qual;
14746 	int rval, rv = 0;
14747 	int npmport;
14748 	sata_cport_info_t *cportinfo;
14749 	sata_pmport_info_t *pmportinfo;
14750 	sata_pmult_info_t *pmultinfo;
14751 	dev_info_t *tdip;
14752 	sata_drive_info_t *sdinfo = NULL;
14753 	sata_device_t subsdevice;
14754 
14755 	/* Sanity check */
14756 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
14757 		return (ENOTSUP);
14758 
14759 	cport = sata_device->satadev_addr.cport;
14760 	pmport = sata_device->satadev_addr.pmport;
14761 	qual = sata_device->satadev_addr.qual;
14762 
14763 	/* SCSI_TO_SATA_ADDR_QUAL() translate ap_id into a device qualifier */
14764 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14765 	if (qual == SATA_ADDR_DCPORT)
14766 		qual = SATA_ADDR_CPORT;
14767 	else
14768 		qual = SATA_ADDR_PMPORT;
14769 
14770 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14771 	if (qual == SATA_ADDR_PMPORT)
14772 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14773 
14774 	/*
14775 	 * Processing port multiplier
14776 	 */
14777 	if (qual == SATA_ADDR_CPORT &&
14778 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
14779 		mutex_enter(&cportinfo->cport_mutex);
14780 
14781 		/* Deactivate all sub-deices */
14782 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14783 		if (pmultinfo != NULL) {
14784 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
14785 			    sata_hba_inst, cport); npmport++) {
14786 
14787 				subsdevice.satadev_addr.cport = cport;
14788 				subsdevice.satadev_addr.pmport =
14789 				    (uint8_t)npmport;
14790 				subsdevice.satadev_addr.qual =
14791 				    SATA_ADDR_DPMPORT;
14792 
14793 				SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14794 				    "sata_hba_ioctl: deactivate: trying to "
14795 				    "deactivate SATA port %d:%d",
14796 				    cport, npmport);
14797 
14798 				mutex_exit(&cportinfo->cport_mutex);
14799 				if (sata_ioctl_deactivate(sata_hba_inst,
14800 				    &subsdevice) == SATA_SUCCESS) {
14801 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14802 					    "[Deactivate] device at port %d:%d "
14803 					    "successfully.", cport, npmport);
14804 				}
14805 				mutex_enter(&cportinfo->cport_mutex);
14806 			}
14807 		}
14808 
14809 		/* Deactivate the port multiplier now. */
14810 		cportinfo->cport_state &= ~SATA_STATE_READY;
14811 		mutex_exit(&cportinfo->cport_mutex);
14812 
14813 		sata_device->satadev_addr.qual = qual;
14814 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14815 		    (SATA_DIP(sata_hba_inst), sata_device);
14816 
14817 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14818 		    SE_NO_HINT);
14819 
14820 		mutex_enter(&cportinfo->cport_mutex);
14821 		sata_update_port_info(sata_hba_inst, sata_device);
14822 		if (rval != SATA_SUCCESS) {
14823 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14824 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14825 			}
14826 			rv = EIO;
14827 		} else {
14828 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14829 		}
14830 		mutex_exit(&cportinfo->cport_mutex);
14831 
14832 		return (rv);
14833 	}
14834 
14835 	/*
14836 	 * Process non-port-multiplier device - it could be a drive connected
14837 	 * to a port multiplier port or a controller port.
14838 	 */
14839 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14840 	if (qual == SATA_ADDR_CPORT) {
14841 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14842 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14843 			/* deal only with valid devices */
14844 			if ((cportinfo->cport_dev_type &
14845 			    SATA_VALID_DEV_TYPE) != 0)
14846 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14847 		}
14848 		cportinfo->cport_state &= ~SATA_STATE_READY;
14849 	} else {
14850 		/* Port multiplier device port */
14851 		mutex_enter(&pmportinfo->pmport_mutex);
14852 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14853 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
14854 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
14855 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
14856 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
14857 		mutex_exit(&pmportinfo->pmport_mutex);
14858 	}
14859 
14860 	if (sdinfo != NULL) {
14861 		/*
14862 		 * If a target node exists, try to offline a device and
14863 		 * to remove a target node.
14864 		 */
14865 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14866 		    cport_mutex);
14867 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14868 		    &sata_device->satadev_addr);
14869 		if (tdip != NULL) {
14870 			/* target node exist */
14871 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14872 			    "sata_hba_ioctl: port deactivate: "
14873 			    "target node exists.", NULL);
14874 
14875 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
14876 			    NDI_SUCCESS) {
14877 				SATA_LOG_D((sata_hba_inst, CE_WARN,
14878 				    "sata_hba_ioctl: port deactivate: "
14879 				    "failed to unconfigure device at port "
14880 				    "%d:%d before deactivating the port",
14881 				    cport, pmport));
14882 				/*
14883 				 * Set DEVICE REMOVED state in the target
14884 				 * node. It will prevent an access to
14885 				 * the device even when a new device is
14886 				 * attached, until the old target node is
14887 				 * released, removed and recreated for a new
14888 				 * device.
14889 				 */
14890 				sata_set_device_removed(tdip);
14891 
14892 				/*
14893 				 * Instruct the event daemon to try the
14894 				 * target node cleanup later.
14895 				 */
14896 				sata_set_target_node_cleanup(sata_hba_inst,
14897 				    &sata_device->satadev_addr);
14898 			}
14899 		}
14900 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14901 		    cport_mutex);
14902 		/*
14903 		 * In any case, remove and release sata_drive_info
14904 		 * structure.
14905 		 */
14906 		if (qual == SATA_ADDR_CPORT) {
14907 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14908 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14909 		} else { /* port multiplier device port */
14910 			mutex_enter(&pmportinfo->pmport_mutex);
14911 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
14912 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
14913 			mutex_exit(&pmportinfo->pmport_mutex);
14914 		}
14915 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
14916 	}
14917 
14918 	if (qual == SATA_ADDR_CPORT) {
14919 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
14920 		    SATA_STATE_PROBING);
14921 	} else if (qual == SATA_ADDR_PMPORT) {
14922 		mutex_enter(&pmportinfo->pmport_mutex);
14923 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
14924 		    SATA_STATE_PROBING);
14925 		mutex_exit(&pmportinfo->pmport_mutex);
14926 	}
14927 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14928 
14929 	/* Just let HBA driver to deactivate port */
14930 	sata_device->satadev_addr.qual = qual;
14931 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14932 	    (SATA_DIP(sata_hba_inst), sata_device);
14933 
14934 	/*
14935 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14936 	 * without the hint
14937 	 */
14938 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14939 	    SE_NO_HINT);
14940 
14941 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14942 	sata_update_port_info(sata_hba_inst, sata_device);
14943 	if (qual == SATA_ADDR_CPORT) {
14944 		if (rval != SATA_SUCCESS) {
14945 			/*
14946 			 * Port deactivation failure - do not change port state
14947 			 * unless the state returned by HBA indicates a port
14948 			 * failure.
14949 			 */
14950 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14951 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14952 				    SATA_PSTATE_FAILED;
14953 			}
14954 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14955 			    "sata_hba_ioctl: port deactivate: "
14956 			    "cannot deactivate SATA port %d", cport));
14957 			rv = EIO;
14958 		} else {
14959 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14960 		}
14961 	} else {
14962 		mutex_enter(&pmportinfo->pmport_mutex);
14963 		if (rval != SATA_SUCCESS) {
14964 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14965 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14966 				    pmport) = SATA_PSTATE_FAILED;
14967 			}
14968 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14969 			    "sata_hba_ioctl: port deactivate: "
14970 			    "cannot deactivate SATA port %d:%d",
14971 			    cport, pmport));
14972 			rv = EIO;
14973 		} else {
14974 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14975 		}
14976 		mutex_exit(&pmportinfo->pmport_mutex);
14977 	}
14978 
14979 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14980 
14981 	return (rv);
14982 }
14983 
14984 /*
14985  * Process ioctl port activate request.
14986  *
14987  * NOTE: Port multiplier is supported now.
14988  */
14989 static int
14990 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
14991     sata_device_t *sata_device)
14992 {
14993 	int cport, pmport, qual;
14994 	sata_cport_info_t *cportinfo;
14995 	sata_pmport_info_t *pmportinfo = NULL;
14996 	boolean_t dev_existed = TRUE;
14997 
14998 	/* Sanity check */
14999 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
15000 		return (ENOTSUP);
15001 
15002 	cport = sata_device->satadev_addr.cport;
15003 	pmport = sata_device->satadev_addr.pmport;
15004 	qual = sata_device->satadev_addr.qual;
15005 
15006 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
15007 
15008 	/*
15009 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
15010 	 * is a device. But what we are dealing with is port/pmport.
15011 	 */
15012 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
15013 	if (qual == SATA_ADDR_DCPORT)
15014 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
15015 	else
15016 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
15017 
15018 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15019 	if (qual == SATA_ADDR_PMPORT) {
15020 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
15021 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
15022 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
15023 			dev_existed = FALSE;
15024 	} else { /* cport */
15025 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
15026 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
15027 			dev_existed = FALSE;
15028 	}
15029 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15030 
15031 	/* Just let HBA driver to activate port, if necessary */
15032 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
15033 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15034 		/*
15035 		 * Port activation failure - do not change port state unless
15036 		 * the state returned by HBA indicates a port failure.
15037 		 */
15038 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15039 		    cport)->cport_mutex);
15040 		sata_update_port_info(sata_hba_inst, sata_device);
15041 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
15042 			if (qual == SATA_ADDR_PMPORT) {
15043 				mutex_enter(&pmportinfo->pmport_mutex);
15044 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
15045 				mutex_exit(&pmportinfo->pmport_mutex);
15046 			} else
15047 				cportinfo->cport_state = SATA_PSTATE_FAILED;
15048 
15049 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15050 			    cport)->cport_mutex);
15051 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15052 			    "sata_hba_ioctl: port activate: cannot activate "
15053 			    "SATA port %d:%d", cport, pmport));
15054 			return (EIO);
15055 		}
15056 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15057 	}
15058 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15059 	if (qual == SATA_ADDR_PMPORT) {
15060 		mutex_enter(&pmportinfo->pmport_mutex);
15061 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
15062 		mutex_exit(&pmportinfo->pmport_mutex);
15063 	} else
15064 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
15065 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15066 
15067 	/*
15068 	 * Re-probe port to find its current state and possibly attached device.
15069 	 * Port re-probing may change the cportinfo device type if device is
15070 	 * found attached.
15071 	 * If port probing failed, the device type would be set to
15072 	 * SATA_DTYPE_NONE.
15073 	 */
15074 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
15075 	    SATA_DEV_IDENTIFY_RETRY);
15076 
15077 	/*
15078 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
15079 	 * without the hint.
15080 	 */
15081 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
15082 	    SE_NO_HINT);
15083 
15084 	if (dev_existed == FALSE) {
15085 		if (qual == SATA_ADDR_PMPORT &&
15086 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
15087 			/*
15088 			 * That's the transition from the "inactive" port state
15089 			 * or the active port without a device attached to the
15090 			 * active port state with a device attached.
15091 			 */
15092 			sata_log(sata_hba_inst, CE_WARN,
15093 			    "SATA device detected at port %d:%d",
15094 			    cport, pmport);
15095 		} else if (qual == SATA_ADDR_CPORT &&
15096 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
15097 			/*
15098 			 * That's the transition from the "inactive" port state
15099 			 * or the active port without a device attached to the
15100 			 * active port state with a device attached.
15101 			 */
15102 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
15103 				sata_log(sata_hba_inst, CE_WARN,
15104 				    "SATA device detected at port %d", cport);
15105 			} else {
15106 				sata_log(sata_hba_inst, CE_WARN,
15107 				    "SATA port multiplier detected at port %d",
15108 				    cport);
15109 			}
15110 		}
15111 	}
15112 	return (0);
15113 }
15114 
15115 
15116 
15117 /*
15118  * Process ioctl reset port request.
15119  *
15120  * NOTE: Port-Multiplier is supported.
15121  */
15122 static int
15123 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
15124     sata_device_t *sata_device)
15125 {
15126 	int cport, pmport, qual;
15127 	int rv = 0;
15128 
15129 	cport = sata_device->satadev_addr.cport;
15130 	pmport = sata_device->satadev_addr.pmport;
15131 	qual = sata_device->satadev_addr.qual;
15132 
15133 	/*
15134 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
15135 	 * is a device. But what we are dealing with is port/pmport.
15136 	 */
15137 	if (qual == SATA_ADDR_DCPORT)
15138 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
15139 	else
15140 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
15141 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
15142 
15143 	/* Sanity check */
15144 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15145 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15146 		    "sata_hba_ioctl: sata_hba_tran missing required "
15147 		    "function sata_tran_reset_dport"));
15148 		return (ENOTSUP);
15149 	}
15150 
15151 	/* Ask HBA to reset port */
15152 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
15153 	    sata_device) != SATA_SUCCESS) {
15154 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15155 		    "sata_hba_ioctl: reset port: failed %d:%d",
15156 		    cport, pmport));
15157 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15158 		    cport_mutex);
15159 		sata_update_port_info(sata_hba_inst, sata_device);
15160 		if (qual == SATA_ADDR_CPORT)
15161 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15162 			    SATA_PSTATE_FAILED;
15163 		else {
15164 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
15165 			    pmport));
15166 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15167 			    SATA_PSTATE_FAILED;
15168 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
15169 			    pmport));
15170 		}
15171 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15172 		    cport_mutex);
15173 		rv = EIO;
15174 	}
15175 	/*
15176 	 * Beacuse the port was reset, it should be probed and
15177 	 * attached device reinitialized. At this point the
15178 	 * port state is unknown - it's state is HBA-specific.
15179 	 * Re-probe port to get its state.
15180 	 */
15181 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15182 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
15183 		rv = EIO;
15184 	}
15185 	return (rv);
15186 }
15187 
15188 /*
15189  * Process ioctl reset device request.
15190  *
15191  * NOTE: Port multiplier is supported.
15192  */
15193 static int
15194 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
15195     sata_device_t *sata_device)
15196 {
15197 	sata_drive_info_t *sdinfo = NULL;
15198 	sata_pmult_info_t *pmultinfo = NULL;
15199 	int cport, pmport;
15200 	int rv = 0;
15201 
15202 	/* Sanity check */
15203 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15204 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15205 		    "sata_hba_ioctl: sata_hba_tran missing required "
15206 		    "function sata_tran_reset_dport"));
15207 		return (ENOTSUP);
15208 	}
15209 
15210 	cport = sata_device->satadev_addr.cport;
15211 	pmport = sata_device->satadev_addr.pmport;
15212 
15213 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15214 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
15215 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
15216 		    SATA_DTYPE_PMULT)
15217 			pmultinfo = SATA_CPORT_INFO(sata_hba_inst, cport)->
15218 			    cport_devp.cport_sata_pmult;
15219 		else
15220 			sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15221 			    sata_device->satadev_addr.cport);
15222 	} else { /* port multiplier */
15223 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
15224 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15225 		    sata_device->satadev_addr.cport,
15226 		    sata_device->satadev_addr.pmport);
15227 	}
15228 	if (sdinfo == NULL && pmultinfo == NULL) {
15229 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15230 		return (EINVAL);
15231 	}
15232 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15233 
15234 	/* Ask HBA to reset device */
15235 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15236 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15237 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15238 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
15239 		    cport, pmport));
15240 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15241 		    cport_mutex);
15242 		sata_update_port_info(sata_hba_inst, sata_device);
15243 		/*
15244 		 * Device info structure remains attached. Another device reset
15245 		 * or port disconnect/connect and re-probing is
15246 		 * needed to change it's state
15247 		 */
15248 		if (sdinfo != NULL) {
15249 			sdinfo->satadrv_state &= ~SATA_STATE_READY;
15250 			sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
15251 		} else if (pmultinfo != NULL) {
15252 			pmultinfo->pmult_state &= ~SATA_STATE_READY;
15253 			pmultinfo->pmult_state |= SATA_DSTATE_FAILED;
15254 		}
15255 
15256 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
15257 		rv = EIO;
15258 	}
15259 	/*
15260 	 * If attached device was a port multiplier, some extra processing
15261 	 * may be needed to bring it back. SATA specification requies a
15262 	 * mandatory software reset on host port to reliably enumerate a port
15263 	 * multiplier, the HBA driver should handle that after reset
15264 	 * operation.
15265 	 */
15266 	return (rv);
15267 }
15268 
15269 
15270 /*
15271  * Process ioctl reset all request.
15272  */
15273 static int
15274 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
15275 {
15276 	sata_device_t sata_device;
15277 	int rv = 0;
15278 	int tcport;
15279 	int tpmport = 0;
15280 
15281 	sata_device.satadev_rev = SATA_DEVICE_REV;
15282 
15283 	/*
15284 	 * There is no protection here for configured devices.
15285 	 */
15286 	/* Sanity check */
15287 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
15288 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15289 		    "sata_hba_ioctl: sata_hba_tran missing required "
15290 		    "function sata_tran_reset_dport"));
15291 		return (ENOTSUP);
15292 	}
15293 
15294 	/*
15295 	 * Need to lock all ports, not just one.
15296 	 * If any port is locked by event processing, fail the whole operation.
15297 	 * One port is already locked, but for simplicity lock it again.
15298 	 */
15299 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15300 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15301 		    cport_mutex);
15302 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
15303 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
15304 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15305 			    cport_mutex);
15306 			rv = EBUSY;
15307 			break;
15308 		} else {
15309 			/*
15310 			 * It is enough to lock cport in command-based
15311 			 * switching mode.
15312 			 */
15313 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
15314 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
15315 		}
15316 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15317 		    cport_mutex);
15318 	}
15319 
15320 	if (rv == 0) {
15321 		/*
15322 		 * All cports were successfully locked.
15323 		 * Reset main SATA controller.
15324 		 * Set the device address to port 0, to have a valid device
15325 		 * address.
15326 		 */
15327 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
15328 		sata_device.satadev_addr.cport = 0;
15329 		sata_device.satadev_addr.pmport = 0;
15330 
15331 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
15332 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
15333 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15334 			    "sata_hba_ioctl: reset controller failed"));
15335 			return (EIO);
15336 		}
15337 		/*
15338 		 * Because ports were reset, port states are unknown.
15339 		 * They should be re-probed to get their state and
15340 		 * attached devices should be reinitialized.
15341 		 */
15342 		for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst);
15343 		    tcport++) {
15344 			sata_device.satadev_addr.cport = tcport;
15345 			sata_device.satadev_addr.pmport = tpmport;
15346 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
15347 
15348 			/*
15349 			 * The sata_reprobe_port() will mark a
15350 			 * SATA_EVNT_DEVICE_RESET event on the port
15351 			 * multiplier, all its sub-ports will be probed by
15352 			 * sata daemon afterwards.
15353 			 */
15354 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
15355 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15356 				rv = EIO;
15357 		}
15358 	}
15359 	/*
15360 	 * Unlock all ports
15361 	 */
15362 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
15363 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15364 		    cport_mutex);
15365 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
15366 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
15367 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
15368 		    cport_mutex);
15369 	}
15370 
15371 	/*
15372 	 * This operation returns EFAULT if either reset
15373 	 * controller failed or a re-probing of any port failed.
15374 	 */
15375 	return (rv);
15376 }
15377 
15378 
15379 /*
15380  * Process ioctl port self test request.
15381  *
15382  * NOTE: Port multiplier code is not completed nor tested.
15383  */
15384 static int
15385 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
15386     sata_device_t *sata_device)
15387 {
15388 	int cport, pmport, qual;
15389 	int rv = 0;
15390 
15391 	/* Sanity check */
15392 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
15393 		return (ENOTSUP);
15394 
15395 	cport = sata_device->satadev_addr.cport;
15396 	pmport = sata_device->satadev_addr.pmport;
15397 	qual = sata_device->satadev_addr.qual;
15398 
15399 	/*
15400 	 * There is no protection here for a configured
15401 	 * device attached to this port.
15402 	 */
15403 
15404 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
15405 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15406 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15407 		    "sata_hba_ioctl: port selftest: "
15408 		    "failed port %d:%d", cport, pmport));
15409 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15410 		    cport_mutex);
15411 		sata_update_port_info(sata_hba_inst, sata_device);
15412 		if (qual == SATA_ADDR_CPORT)
15413 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15414 			    SATA_PSTATE_FAILED;
15415 		else { /* port multiplier device port */
15416 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
15417 			    cport, pmport));
15418 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15419 			    SATA_PSTATE_FAILED;
15420 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
15421 			    cport, pmport));
15422 		}
15423 
15424 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15425 		    cport_mutex);
15426 		return (EIO);
15427 	}
15428 	/*
15429 	 * Beacuse the port was reset in the course of testing, it should be
15430 	 * re-probed and attached device state should be restored. At this
15431 	 * point the port state is unknown - it's state is HBA-specific.
15432 	 * Force port re-probing to get it into a known state.
15433 	 */
15434 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15435 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15436 		rv = EIO;
15437 	return (rv);
15438 }
15439 
15440 
15441 /*
15442  * sata_cfgadm_state:
15443  * Use the sata port state and state of the target node to figure out
15444  * the cfgadm_state.
15445  *
15446  * The port argument is a value with encoded cport,
15447  * pmport and address qualifier, in the same manner as a scsi target number.
15448  * SCSI_TO_SATA_CPORT macro extracts cport number,
15449  * SCSI_TO_SATA_PMPORT extracts pmport number and
15450  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
15451  *
15452  * Port multiplier is supported.
15453  */
15454 
15455 static void
15456 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
15457     devctl_ap_state_t *ap_state)
15458 {
15459 	uint8_t		cport, pmport, qual;
15460 	uint32_t	port_state, pmult_state;
15461 	uint32_t	dev_type;
15462 	sata_drive_info_t *sdinfo;
15463 
15464 	cport = SCSI_TO_SATA_CPORT(port);
15465 	pmport = SCSI_TO_SATA_PMPORT(port);
15466 	qual = SCSI_TO_SATA_ADDR_QUAL(port);
15467 
15468 	/* Check cport state */
15469 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
15470 	if (port_state & SATA_PSTATE_SHUTDOWN ||
15471 	    port_state & SATA_PSTATE_FAILED) {
15472 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15473 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15474 		if (port_state & SATA_PSTATE_FAILED)
15475 			ap_state->ap_condition = AP_COND_FAILED;
15476 		else
15477 			ap_state->ap_condition = AP_COND_UNKNOWN;
15478 
15479 		return;
15480 	}
15481 
15482 	/* cport state is okay. Now check pmport state */
15483 	if (qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) {
15484 		/* Sanity check */
15485 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
15486 		    SATA_DTYPE_PMULT || SATA_PMPORT_INFO(sata_hba_inst,
15487 		    cport, pmport) == NULL)
15488 			return;
15489 		port_state = SATA_PMPORT_STATE(sata_hba_inst, cport, pmport);
15490 		if (port_state & SATA_PSTATE_SHUTDOWN ||
15491 		    port_state & SATA_PSTATE_FAILED) {
15492 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15493 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15494 			if (port_state & SATA_PSTATE_FAILED)
15495 				ap_state->ap_condition = AP_COND_FAILED;
15496 			else
15497 				ap_state->ap_condition = AP_COND_UNKNOWN;
15498 
15499 			return;
15500 		}
15501 	}
15502 
15503 	/* Port is enabled and ready */
15504 	if (qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_CPORT)
15505 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst, cport);
15506 	else
15507 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport, pmport);
15508 
15509 	switch (dev_type) {
15510 	case SATA_DTYPE_NONE:
15511 	{
15512 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15513 		ap_state->ap_condition = AP_COND_OK;
15514 		/* No device attached */
15515 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
15516 		break;
15517 	}
15518 	case SATA_DTYPE_PMULT:
15519 	{
15520 		/* Need to check port multiplier state */
15521 		ASSERT(qual == SATA_ADDR_DCPORT);
15522 		pmult_state = SATA_PMULT_INFO(sata_hba_inst, cport)->
15523 		    pmult_state;
15524 		if (pmult_state & (SATA_PSTATE_SHUTDOWN|SATA_PSTATE_FAILED)) {
15525 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15526 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15527 			if (pmult_state & SATA_PSTATE_FAILED)
15528 				ap_state->ap_condition = AP_COND_FAILED;
15529 			else
15530 				ap_state->ap_condition = AP_COND_UNKNOWN;
15531 
15532 			return;
15533 		}
15534 
15535 		/* Port multiplier is not configurable */
15536 		ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
15537 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15538 		ap_state->ap_condition = AP_COND_OK;
15539 		break;
15540 	}
15541 
15542 	case SATA_DTYPE_ATADISK:
15543 	case SATA_DTYPE_ATAPICD:
15544 	case SATA_DTYPE_ATAPITAPE:
15545 	case SATA_DTYPE_ATAPIDISK:
15546 	{
15547 		dev_info_t *tdip = NULL;
15548 		dev_info_t *dip = NULL;
15549 		int circ;
15550 
15551 		dip = SATA_DIP(sata_hba_inst);
15552 		tdip = sata_get_target_dip(dip, cport, pmport);
15553 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15554 		if (tdip != NULL) {
15555 			ndi_devi_enter(dip, &circ);
15556 			mutex_enter(&(DEVI(tdip)->devi_lock));
15557 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
15558 				/*
15559 				 * There could be the case where previously
15560 				 * configured and opened device was removed
15561 				 * and unknown device was plugged.
15562 				 * In such case we want to show a device, and
15563 				 * its configured or unconfigured state but
15564 				 * indicate unusable condition untill the
15565 				 * old target node is released and removed.
15566 				 */
15567 				ap_state->ap_condition = AP_COND_UNUSABLE;
15568 			} else {
15569 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
15570 				    cport));
15571 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15572 				    cport);
15573 				if (sdinfo != NULL) {
15574 					if ((sdinfo->satadrv_state &
15575 					    SATA_DSTATE_FAILED) != 0)
15576 						ap_state->ap_condition =
15577 						    AP_COND_FAILED;
15578 					else
15579 						ap_state->ap_condition =
15580 						    AP_COND_OK;
15581 				} else {
15582 					ap_state->ap_condition =
15583 					    AP_COND_UNKNOWN;
15584 				}
15585 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
15586 				    cport));
15587 			}
15588 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
15589 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
15590 				ap_state->ap_ostate =
15591 				    AP_OSTATE_UNCONFIGURED;
15592 			} else {
15593 				ap_state->ap_ostate =
15594 				    AP_OSTATE_CONFIGURED;
15595 			}
15596 			mutex_exit(&(DEVI(tdip)->devi_lock));
15597 			ndi_devi_exit(dip, circ);
15598 		} else {
15599 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15600 			ap_state->ap_condition = AP_COND_UNKNOWN;
15601 		}
15602 		break;
15603 	}
15604 	default:
15605 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15606 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15607 		ap_state->ap_condition = AP_COND_UNKNOWN;
15608 		/*
15609 		 * This is actually internal error condition (non fatal),
15610 		 * because we have already checked all defined device types.
15611 		 */
15612 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15613 		    "sata_cfgadm_state: Internal error: "
15614 		    "unknown device type"));
15615 		break;
15616 	}
15617 }
15618 
15619 
15620 /*
15621  * Process ioctl get device path request.
15622  *
15623  * NOTE: Port multiplier has no target dip. Devices connected to port
15624  * multiplier have target node attached to the HBA node. The only difference
15625  * between them and the directly-attached device node is a target address.
15626  */
15627 static int
15628 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
15629     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15630 {
15631 	char path[MAXPATHLEN];
15632 	uint32_t size;
15633 	dev_info_t *tdip;
15634 
15635 	(void) strcpy(path, "/devices");
15636 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
15637 	    &sata_device->satadev_addr)) == NULL) {
15638 		/*
15639 		 * No such device. If this is a request for a size, do not
15640 		 * return EINVAL for non-existing target, because cfgadm
15641 		 * will then indicate a meaningless ioctl failure.
15642 		 * If this is a request for a path, indicate invalid
15643 		 * argument.
15644 		 */
15645 		if (ioc->get_size == 0)
15646 			return (EINVAL);
15647 	} else {
15648 		(void) ddi_pathname(tdip, path + strlen(path));
15649 	}
15650 	size = strlen(path) + 1;
15651 
15652 	if (ioc->get_size != 0) {
15653 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
15654 		    mode) != 0)
15655 			return (EFAULT);
15656 	} else {
15657 		if (ioc->bufsiz != size)
15658 			return (EINVAL);
15659 
15660 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
15661 		    mode) != 0)
15662 			return (EFAULT);
15663 	}
15664 	return (0);
15665 }
15666 
15667 /*
15668  * Process ioctl get attachment point type request.
15669  *
15670  * NOTE: Port multiplier is supported.
15671  */
15672 static	int
15673 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
15674     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15675 {
15676 	uint32_t	type_len;
15677 	const char	*ap_type;
15678 	int		dev_type;
15679 
15680 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15681 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
15682 		    sata_device->satadev_addr.cport);
15683 	else /* pmport */
15684 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
15685 		    sata_device->satadev_addr.cport,
15686 		    sata_device->satadev_addr.pmport);
15687 
15688 	switch (dev_type) {
15689 	case SATA_DTYPE_NONE:
15690 		ap_type = "port";
15691 		break;
15692 
15693 	case SATA_DTYPE_ATADISK:
15694 	case SATA_DTYPE_ATAPIDISK:
15695 		ap_type = "disk";
15696 		break;
15697 
15698 	case SATA_DTYPE_ATAPICD:
15699 		ap_type = "cd/dvd";
15700 		break;
15701 
15702 	case SATA_DTYPE_ATAPITAPE:
15703 		ap_type = "tape";
15704 		break;
15705 
15706 	case SATA_DTYPE_PMULT:
15707 		ap_type = "sata-pmult";
15708 		break;
15709 
15710 	case SATA_DTYPE_UNKNOWN:
15711 		ap_type = "unknown";
15712 		break;
15713 
15714 	default:
15715 		ap_type = "unsupported";
15716 		break;
15717 
15718 	} /* end of dev_type switch */
15719 
15720 	type_len = strlen(ap_type) + 1;
15721 
15722 	if (ioc->get_size) {
15723 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
15724 		    mode) != 0)
15725 			return (EFAULT);
15726 	} else {
15727 		if (ioc->bufsiz != type_len)
15728 			return (EINVAL);
15729 
15730 		if (ddi_copyout((void *)ap_type, ioc->buf,
15731 		    ioc->bufsiz, mode) != 0)
15732 			return (EFAULT);
15733 	}
15734 	return (0);
15735 
15736 }
15737 
15738 /*
15739  * Process ioctl get device model info request.
15740  * This operation should return to cfgadm the device model
15741  * information string
15742  *
15743  * NOTE: Port multiplier is supported.
15744  */
15745 static	int
15746 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
15747     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15748 {
15749 	sata_drive_info_t *sdinfo;
15750 	uint32_t info_len;
15751 	char ap_info[SATA_ID_MODEL_LEN + 1];
15752 
15753 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15754 	    sata_device->satadev_addr.cport)->cport_mutex);
15755 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15756 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15757 		    sata_device->satadev_addr.cport);
15758 	else /* port multiplier */
15759 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15760 		    sata_device->satadev_addr.cport,
15761 		    sata_device->satadev_addr.pmport);
15762 	if (sdinfo == NULL) {
15763 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15764 		    sata_device->satadev_addr.cport)->cport_mutex);
15765 		return (EINVAL);
15766 	}
15767 
15768 #ifdef	_LITTLE_ENDIAN
15769 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15770 #else	/* _LITTLE_ENDIAN */
15771 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15772 #endif	/* _LITTLE_ENDIAN */
15773 
15774 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15775 	    sata_device->satadev_addr.cport)->cport_mutex);
15776 
15777 	ap_info[SATA_ID_MODEL_LEN] = '\0';
15778 
15779 	info_len = strlen(ap_info) + 1;
15780 
15781 	if (ioc->get_size) {
15782 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15783 		    mode) != 0)
15784 			return (EFAULT);
15785 	} else {
15786 		if (ioc->bufsiz < info_len)
15787 			return (EINVAL);
15788 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15789 		    mode) != 0)
15790 			return (EFAULT);
15791 	}
15792 	return (0);
15793 }
15794 
15795 
15796 /*
15797  * Process ioctl get device firmware revision info request.
15798  * This operation should return to cfgadm the device firmware revision
15799  * information string
15800  *
15801  * Port multiplier is supported.
15802  */
15803 static	int
15804 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
15805     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15806 {
15807 	sata_drive_info_t *sdinfo;
15808 	uint32_t info_len;
15809 	char ap_info[SATA_ID_FW_LEN + 1];
15810 
15811 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15812 	    sata_device->satadev_addr.cport)->cport_mutex);
15813 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15814 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15815 		    sata_device->satadev_addr.cport);
15816 	else /* port multiplier */
15817 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15818 		    sata_device->satadev_addr.cport,
15819 		    sata_device->satadev_addr.pmport);
15820 	if (sdinfo == NULL) {
15821 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15822 		    sata_device->satadev_addr.cport)->cport_mutex);
15823 		return (EINVAL);
15824 	}
15825 
15826 #ifdef	_LITTLE_ENDIAN
15827 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15828 #else	/* _LITTLE_ENDIAN */
15829 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15830 #endif	/* _LITTLE_ENDIAN */
15831 
15832 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15833 	    sata_device->satadev_addr.cport)->cport_mutex);
15834 
15835 	ap_info[SATA_ID_FW_LEN] = '\0';
15836 
15837 	info_len = strlen(ap_info) + 1;
15838 
15839 	if (ioc->get_size) {
15840 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15841 		    mode) != 0)
15842 			return (EFAULT);
15843 	} else {
15844 		if (ioc->bufsiz < info_len)
15845 			return (EINVAL);
15846 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15847 		    mode) != 0)
15848 			return (EFAULT);
15849 	}
15850 	return (0);
15851 }
15852 
15853 
15854 /*
15855  * Process ioctl get device serial number info request.
15856  * This operation should return to cfgadm the device serial number string.
15857  *
15858  * NOTE: Port multiplier is supported.
15859  */
15860 static	int
15861 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
15862     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15863 {
15864 	sata_drive_info_t *sdinfo;
15865 	uint32_t info_len;
15866 	char ap_info[SATA_ID_SERIAL_LEN + 1];
15867 
15868 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15869 	    sata_device->satadev_addr.cport)->cport_mutex);
15870 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15871 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15872 		    sata_device->satadev_addr.cport);
15873 	else /* port multiplier */
15874 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15875 		    sata_device->satadev_addr.cport,
15876 		    sata_device->satadev_addr.pmport);
15877 	if (sdinfo == NULL) {
15878 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15879 		    sata_device->satadev_addr.cport)->cport_mutex);
15880 		return (EINVAL);
15881 	}
15882 
15883 #ifdef	_LITTLE_ENDIAN
15884 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15885 #else	/* _LITTLE_ENDIAN */
15886 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15887 #endif	/* _LITTLE_ENDIAN */
15888 
15889 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15890 	    sata_device->satadev_addr.cport)->cport_mutex);
15891 
15892 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
15893 
15894 	info_len = strlen(ap_info) + 1;
15895 
15896 	if (ioc->get_size) {
15897 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15898 		    mode) != 0)
15899 			return (EFAULT);
15900 	} else {
15901 		if (ioc->bufsiz < info_len)
15902 			return (EINVAL);
15903 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15904 		    mode) != 0)
15905 			return (EFAULT);
15906 	}
15907 	return (0);
15908 }
15909 
15910 
15911 /*
15912  * Preset scsi extended sense data (to NO SENSE)
15913  * First 18 bytes of the sense data are preset to current valid sense
15914  * with a key NO SENSE data.
15915  *
15916  * Returns void
15917  */
15918 static void
15919 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
15920 {
15921 	sense->es_valid = 1;		/* Valid sense */
15922 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
15923 	sense->es_key = KEY_NO_SENSE;
15924 	sense->es_info_1 = 0;
15925 	sense->es_info_2 = 0;
15926 	sense->es_info_3 = 0;
15927 	sense->es_info_4 = 0;
15928 	sense->es_add_len = 10;	/* Additional length - replace with a def */
15929 	sense->es_cmd_info[0] = 0;
15930 	sense->es_cmd_info[1] = 0;
15931 	sense->es_cmd_info[2] = 0;
15932 	sense->es_cmd_info[3] = 0;
15933 	sense->es_add_code = 0;
15934 	sense->es_qual_code = 0;
15935 }
15936 
15937 /*
15938  * Register a legacy cmdk-style devid for the target (disk) device.
15939  *
15940  * Note: This function is called only when the HBA devinfo node has the
15941  * property "use-cmdk-devid-format" set. This property indicates that
15942  * devid compatible with old cmdk (target) driver is to be generated
15943  * for any target device attached to this controller. This will take
15944  * precedence over the devid generated by sd (target) driver.
15945  * This function is derived from cmdk_devid_setup() function in cmdk.c.
15946  */
15947 static void
15948 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
15949 {
15950 	char	*hwid;
15951 	int	modlen;
15952 	int	serlen;
15953 	int	rval;
15954 	ddi_devid_t	devid;
15955 
15956 	/*
15957 	 * device ID is a concatanation of model number, "=", serial number.
15958 	 */
15959 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
15960 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
15961 	    sizeof (sdinfo->satadrv_id.ai_model));
15962 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
15963 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
15964 	if (modlen == 0)
15965 		goto err;
15966 	hwid[modlen++] = '=';
15967 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
15968 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15969 	swab(&hwid[modlen], &hwid[modlen],
15970 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15971 	serlen = sata_check_modser(&hwid[modlen],
15972 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15973 	if (serlen == 0)
15974 		goto err;
15975 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
15976 
15977 	/* initialize/register devid */
15978 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
15979 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
15980 		rval = ddi_devid_register(dip, devid);
15981 		/*
15982 		 * Free up the allocated devid buffer.
15983 		 * NOTE: This doesn't mean unregistering devid.
15984 		 */
15985 		ddi_devid_free(devid);
15986 	}
15987 
15988 	if (rval != DDI_SUCCESS)
15989 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
15990 		    " on port %d", sdinfo->satadrv_addr.cport);
15991 err:
15992 	kmem_free(hwid, LEGACY_HWID_LEN);
15993 }
15994 
15995 /*
15996  * valid model/serial string must contain a non-zero non-space characters.
15997  * trim trailing spaces/NULLs.
15998  */
15999 static int
16000 sata_check_modser(char *buf, int buf_len)
16001 {
16002 	boolean_t ret;
16003 	char *s;
16004 	int i;
16005 	int tb;
16006 	char ch;
16007 
16008 	ret = B_FALSE;
16009 	s = buf;
16010 	for (i = 0; i < buf_len; i++) {
16011 		ch = *s++;
16012 		if (ch != ' ' && ch != '\0')
16013 			tb = i + 1;
16014 		if (ch != ' ' && ch != '\0' && ch != '0')
16015 			ret = B_TRUE;
16016 	}
16017 
16018 	if (ret == B_FALSE)
16019 		return (0); /* invalid string */
16020 
16021 	return (tb); /* return length */
16022 }
16023 
16024 /*
16025  * sata_set_drive_features function compares current device features setting
16026  * with the saved device features settings and, if there is a difference,
16027  * it restores device features setting to the previously saved state.
16028  * It also arbitrarily tries to select the highest supported DMA mode.
16029  * Device Identify or Identify Packet Device data has to be current.
16030  * At the moment read ahead and write cache are considered for all devices.
16031  * For atapi devices, Removable Media Status Notification is set in addition
16032  * to common features.
16033  *
16034  * This function cannot be called in the interrupt context (it may sleep).
16035  *
16036  * The input argument sdinfo should point to the drive info structure
16037  * to be updated after features are set. Note, that only
16038  * device (packet) identify data is updated, not the flags indicating the
16039  * supported features.
16040  *
16041  * Returns SATA_SUCCESS if successful or there was nothing to do.
16042  * Device Identify data in the drive info structure pointed to by the sdinfo
16043  * arguments is updated even when no features were set or changed.
16044  *
16045  * Returns SATA_FAILURE if device features could not be set or DMA mode
16046  * for a disk cannot be set and device identify data cannot be fetched.
16047  *
16048  * Returns SATA_RETRY if device features could not be set (other than disk
16049  * DMA mode) but the device identify data was fetched successfully.
16050  *
16051  * Note: This function may fail the port, making it inaccessible.
16052  * In such case the explicit port disconnect/connect or physical device
16053  * detach/attach is required to re-evaluate port state again.
16054  */
16055 
16056 static int
16057 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
16058     sata_drive_info_t *sdinfo, int restore)
16059 {
16060 	int rval = SATA_SUCCESS;
16061 	int rval_set;
16062 	sata_drive_info_t new_sdinfo;
16063 	char *finfo = "sata_set_drive_features: cannot";
16064 	char *finfox;
16065 	int cache_op;
16066 
16067 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
16068 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
16069 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
16070 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
16071 		/*
16072 		 * Cannot get device identification - caller may retry later
16073 		 */
16074 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16075 		    "%s fetch device identify data\n", finfo);
16076 		return (SATA_FAILURE);
16077 	}
16078 	finfox = (restore != 0) ? " restore device features" :
16079 	    " initialize device features\n";
16080 
16081 	switch (sdinfo->satadrv_type) {
16082 	case SATA_DTYPE_ATADISK:
16083 		/* Arbitrarily set UDMA mode */
16084 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
16085 		    SATA_SUCCESS) {
16086 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16087 			    "%s set UDMA mode\n", finfo));
16088 			return (SATA_FAILURE);
16089 		}
16090 		break;
16091 	case SATA_DTYPE_ATAPICD:
16092 	case SATA_DTYPE_ATAPITAPE:
16093 	case SATA_DTYPE_ATAPIDISK:
16094 		/*  Set Removable Media Status Notification, if necessary */
16095 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
16096 		    restore != 0) {
16097 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
16098 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
16099 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
16100 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
16101 				/* Current setting does not match saved one */
16102 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
16103 				    sdinfo->satadrv_settings &
16104 				    SATA_DEV_RMSN) != SATA_SUCCESS)
16105 					rval = SATA_FAILURE;
16106 			}
16107 		}
16108 		/*
16109 		 * We have to set Multiword DMA or UDMA, if it is supported, as
16110 		 * we want to use DMA transfer mode whenever possible.
16111 		 * Some devices require explicit setting of the DMA mode.
16112 		 */
16113 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
16114 			/* Set highest supported DMA mode */
16115 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
16116 			    SATA_SUCCESS) {
16117 				SATA_LOG_D((sata_hba_inst, CE_WARN,
16118 				    "%s set UDMA mode\n", finfo));
16119 				rval = SATA_FAILURE;
16120 			}
16121 		}
16122 		break;
16123 	}
16124 
16125 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
16126 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
16127 		/*
16128 		 * neither READ AHEAD nor WRITE CACHE is supported
16129 		 * - do nothing
16130 		 */
16131 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16132 		    "settable features not supported\n", NULL);
16133 		goto update_sdinfo;
16134 	}
16135 
16136 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
16137 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
16138 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
16139 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
16140 		/*
16141 		 * both READ AHEAD and WRITE CACHE are enabled
16142 		 * - Nothing to do
16143 		 */
16144 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16145 		    "no device features to set\n", NULL);
16146 		goto update_sdinfo;
16147 	}
16148 
16149 	cache_op = 0;
16150 
16151 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
16152 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
16153 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
16154 			/* Enable read ahead / read cache */
16155 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
16156 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16157 			    "enabling read cache\n", NULL);
16158 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
16159 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
16160 			/* Disable read ahead  / read cache */
16161 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
16162 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16163 			    "disabling read cache\n", NULL);
16164 		}
16165 
16166 		if (cache_op != 0) {
16167 			/* Try to set read cache mode */
16168 			rval_set = sata_set_cache_mode(sata_hba_inst,
16169 			    &new_sdinfo, cache_op);
16170 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
16171 				rval = rval_set;
16172 		}
16173 	}
16174 
16175 	cache_op = 0;
16176 
16177 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
16178 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
16179 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
16180 			/* Enable write cache */
16181 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
16182 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16183 			    "enabling write cache\n", NULL);
16184 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
16185 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
16186 			/* Disable write cache */
16187 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
16188 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
16189 			    "disabling write cache\n", NULL);
16190 		}
16191 
16192 		if (cache_op != 0) {
16193 			/* Try to set write cache mode */
16194 			rval_set = sata_set_cache_mode(sata_hba_inst,
16195 			    &new_sdinfo, cache_op);
16196 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
16197 				rval = rval_set;
16198 		}
16199 	}
16200 	if (rval != SATA_SUCCESS)
16201 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16202 		    "%s %s", finfo, finfox));
16203 
16204 update_sdinfo:
16205 	/*
16206 	 * We need to fetch Device Identify data again
16207 	 */
16208 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
16209 		/*
16210 		 * Cannot get device identification - retry later
16211 		 */
16212 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16213 		    "%s re-fetch device identify data\n", finfo));
16214 		rval = SATA_FAILURE;
16215 	}
16216 	/* Copy device sata info. */
16217 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
16218 
16219 	return (rval);
16220 }
16221 
16222 
16223 /*
16224  *
16225  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
16226  * unable to determine.
16227  *
16228  * Cannot be called in an interrupt context.
16229  *
16230  * Called by sata_build_lsense_page_2f()
16231  */
16232 
16233 static int
16234 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
16235     sata_drive_info_t *sdinfo)
16236 {
16237 	sata_pkt_t *spkt;
16238 	sata_cmd_t *scmd;
16239 	sata_pkt_txlate_t *spx;
16240 	int rval;
16241 
16242 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16243 	spx->txlt_sata_hba_inst = sata_hba_inst;
16244 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16245 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16246 	if (spkt == NULL) {
16247 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16248 		return (-1);
16249 	}
16250 	/* address is needed now */
16251 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16252 
16253 
16254 	/* Fill sata_pkt */
16255 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16256 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16257 	/* Synchronous mode, no callback */
16258 	spkt->satapkt_comp = NULL;
16259 	/* Timeout 30s */
16260 	spkt->satapkt_time = sata_default_pkt_time;
16261 
16262 	scmd = &spkt->satapkt_cmd;
16263 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
16264 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
16265 
16266 	/* Set up which registers need to be returned */
16267 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
16268 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
16269 
16270 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
16271 	scmd->satacmd_addr_type = 0;		/* N/A */
16272 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16273 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16274 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16275 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16276 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
16277 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16278 	scmd->satacmd_cmd_reg = SATAC_SMART;
16279 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16280 	    sdinfo->satadrv_addr.cport)));
16281 
16282 
16283 	/* Send pkt to SATA HBA driver */
16284 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16285 	    SATA_TRAN_ACCEPTED ||
16286 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16287 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16288 		    sdinfo->satadrv_addr.cport)));
16289 		/*
16290 		 * Whoops, no SMART RETURN STATUS
16291 		 */
16292 		rval = -1;
16293 	} else {
16294 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16295 		    sdinfo->satadrv_addr.cport)));
16296 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
16297 			rval = -1;
16298 			goto fail;
16299 		}
16300 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
16301 			rval = -1;
16302 			goto fail;
16303 		}
16304 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
16305 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
16306 			rval = 0;
16307 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
16308 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
16309 			rval = 1;
16310 		else {
16311 			rval = -1;
16312 			goto fail;
16313 		}
16314 	}
16315 fail:
16316 	/* Free allocated resources */
16317 	sata_pkt_free(spx);
16318 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16319 
16320 	return (rval);
16321 }
16322 
16323 /*
16324  *
16325  * Returns 0 if succeeded, -1 otherwise
16326  *
16327  * Cannot be called in an interrupt context.
16328  *
16329  */
16330 static int
16331 sata_fetch_smart_data(
16332 	sata_hba_inst_t *sata_hba_inst,
16333 	sata_drive_info_t *sdinfo,
16334 	struct smart_data *smart_data)
16335 {
16336 	sata_pkt_t *spkt;
16337 	sata_cmd_t *scmd;
16338 	sata_pkt_txlate_t *spx;
16339 	int rval;
16340 
16341 #if ! defined(lint)
16342 	ASSERT(sizeof (struct smart_data) == 512);
16343 #endif
16344 
16345 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16346 	spx->txlt_sata_hba_inst = sata_hba_inst;
16347 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16348 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16349 	if (spkt == NULL) {
16350 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16351 		return (-1);
16352 	}
16353 	/* address is needed now */
16354 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16355 
16356 
16357 	/* Fill sata_pkt */
16358 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16359 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16360 	/* Synchronous mode, no callback */
16361 	spkt->satapkt_comp = NULL;
16362 	/* Timeout 30s */
16363 	spkt->satapkt_time = sata_default_pkt_time;
16364 
16365 	scmd = &spkt->satapkt_cmd;
16366 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16367 
16368 	/*
16369 	 * Allocate buffer for SMART data
16370 	 */
16371 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16372 	    sizeof (struct smart_data));
16373 	if (scmd->satacmd_bp == NULL) {
16374 		sata_pkt_free(spx);
16375 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16376 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16377 		    "sata_fetch_smart_data: "
16378 		    "cannot allocate buffer"));
16379 		return (-1);
16380 	}
16381 
16382 
16383 	/* Build SMART_READ_DATA cmd in the sata_pkt */
16384 	scmd->satacmd_addr_type = 0;		/* N/A */
16385 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16386 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16387 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16388 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16389 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
16390 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16391 	scmd->satacmd_cmd_reg = SATAC_SMART;
16392 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16393 	    sdinfo->satadrv_addr.cport)));
16394 
16395 	/* Send pkt to SATA HBA driver */
16396 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16397 	    SATA_TRAN_ACCEPTED ||
16398 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16399 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16400 		    sdinfo->satadrv_addr.cport)));
16401 		/*
16402 		 * Whoops, no SMART DATA available
16403 		 */
16404 		rval = -1;
16405 		goto fail;
16406 	} else {
16407 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16408 		    sdinfo->satadrv_addr.cport)));
16409 		if (spx->txlt_buf_dma_handle != NULL) {
16410 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16411 			    DDI_DMA_SYNC_FORKERNEL);
16412 			ASSERT(rval == DDI_SUCCESS);
16413 		}
16414 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
16415 		    sizeof (struct smart_data));
16416 	}
16417 
16418 fail:
16419 	/* Free allocated resources */
16420 	sata_free_local_buffer(spx);
16421 	sata_pkt_free(spx);
16422 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16423 
16424 	return (rval);
16425 }
16426 
16427 /*
16428  * Used by LOG SENSE page 0x10
16429  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
16430  * Note: cannot be called in the interrupt context.
16431  *
16432  * return 0 for success, -1 otherwise
16433  *
16434  */
16435 static int
16436 sata_ext_smart_selftest_read_log(
16437 	sata_hba_inst_t *sata_hba_inst,
16438 	sata_drive_info_t *sdinfo,
16439 	struct smart_ext_selftest_log *ext_selftest_log,
16440 	uint16_t block_num)
16441 {
16442 	sata_pkt_txlate_t *spx;
16443 	sata_pkt_t *spkt;
16444 	sata_cmd_t *scmd;
16445 	int rval;
16446 
16447 #if ! defined(lint)
16448 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
16449 #endif
16450 
16451 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16452 	spx->txlt_sata_hba_inst = sata_hba_inst;
16453 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16454 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16455 	if (spkt == NULL) {
16456 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16457 		return (-1);
16458 	}
16459 	/* address is needed now */
16460 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16461 
16462 
16463 	/* Fill sata_pkt */
16464 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16465 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16466 	/* Synchronous mode, no callback */
16467 	spkt->satapkt_comp = NULL;
16468 	/* Timeout 30s */
16469 	spkt->satapkt_time = sata_default_pkt_time;
16470 
16471 	scmd = &spkt->satapkt_cmd;
16472 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16473 
16474 	/*
16475 	 * Allocate buffer for SMART extended self-test log
16476 	 */
16477 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16478 	    sizeof (struct smart_ext_selftest_log));
16479 	if (scmd->satacmd_bp == NULL) {
16480 		sata_pkt_free(spx);
16481 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16482 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16483 		    "sata_ext_smart_selftest_log: "
16484 		    "cannot allocate buffer"));
16485 		return (-1);
16486 	}
16487 
16488 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
16489 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16490 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
16491 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
16492 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
16493 	scmd->satacmd_lba_low_msb = 0;
16494 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
16495 	scmd->satacmd_lba_mid_msb = block_num >> 8;
16496 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16497 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16498 
16499 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16500 	    sdinfo->satadrv_addr.cport)));
16501 
16502 	/* Send pkt to SATA HBA driver */
16503 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16504 	    SATA_TRAN_ACCEPTED ||
16505 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16506 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16507 		    sdinfo->satadrv_addr.cport)));
16508 
16509 		/*
16510 		 * Whoops, no SMART selftest log info available
16511 		 */
16512 		rval = -1;
16513 		goto fail;
16514 	} else {
16515 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16516 		    sdinfo->satadrv_addr.cport)));
16517 
16518 		if (spx->txlt_buf_dma_handle != NULL) {
16519 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16520 			    DDI_DMA_SYNC_FORKERNEL);
16521 			ASSERT(rval == DDI_SUCCESS);
16522 		}
16523 		bcopy(scmd->satacmd_bp->b_un.b_addr,
16524 		    (uint8_t *)ext_selftest_log,
16525 		    sizeof (struct smart_ext_selftest_log));
16526 		rval = 0;
16527 	}
16528 
16529 fail:
16530 	/* Free allocated resources */
16531 	sata_free_local_buffer(spx);
16532 	sata_pkt_free(spx);
16533 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16534 
16535 	return (rval);
16536 }
16537 
16538 /*
16539  * Returns 0 for success, -1 otherwise
16540  *
16541  * SMART self-test log data is returned in buffer pointed to by selftest_log
16542  */
16543 static int
16544 sata_smart_selftest_log(
16545 	sata_hba_inst_t *sata_hba_inst,
16546 	sata_drive_info_t *sdinfo,
16547 	struct smart_selftest_log *selftest_log)
16548 {
16549 	sata_pkt_t *spkt;
16550 	sata_cmd_t *scmd;
16551 	sata_pkt_txlate_t *spx;
16552 	int rval;
16553 
16554 #if ! defined(lint)
16555 	ASSERT(sizeof (struct smart_selftest_log) == 512);
16556 #endif
16557 
16558 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16559 	spx->txlt_sata_hba_inst = sata_hba_inst;
16560 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16561 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16562 	if (spkt == NULL) {
16563 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16564 		return (-1);
16565 	}
16566 	/* address is needed now */
16567 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16568 
16569 
16570 	/* Fill sata_pkt */
16571 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16572 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16573 	/* Synchronous mode, no callback */
16574 	spkt->satapkt_comp = NULL;
16575 	/* Timeout 30s */
16576 	spkt->satapkt_time = sata_default_pkt_time;
16577 
16578 	scmd = &spkt->satapkt_cmd;
16579 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16580 
16581 	/*
16582 	 * Allocate buffer for SMART SELFTEST LOG
16583 	 */
16584 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16585 	    sizeof (struct smart_selftest_log));
16586 	if (scmd->satacmd_bp == NULL) {
16587 		sata_pkt_free(spx);
16588 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16589 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16590 		    "sata_smart_selftest_log: "
16591 		    "cannot allocate buffer"));
16592 		return (-1);
16593 	}
16594 
16595 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16596 	scmd->satacmd_addr_type = 0;		/* N/A */
16597 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
16598 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
16599 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16600 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16601 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16602 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16603 	scmd->satacmd_cmd_reg = SATAC_SMART;
16604 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16605 	    sdinfo->satadrv_addr.cport)));
16606 
16607 	/* Send pkt to SATA HBA driver */
16608 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16609 	    SATA_TRAN_ACCEPTED ||
16610 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16611 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16612 		    sdinfo->satadrv_addr.cport)));
16613 		/*
16614 		 * Whoops, no SMART DATA available
16615 		 */
16616 		rval = -1;
16617 		goto fail;
16618 	} else {
16619 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16620 		    sdinfo->satadrv_addr.cport)));
16621 		if (spx->txlt_buf_dma_handle != NULL) {
16622 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16623 			    DDI_DMA_SYNC_FORKERNEL);
16624 			ASSERT(rval == DDI_SUCCESS);
16625 		}
16626 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
16627 		    sizeof (struct smart_selftest_log));
16628 		rval = 0;
16629 	}
16630 
16631 fail:
16632 	/* Free allocated resources */
16633 	sata_free_local_buffer(spx);
16634 	sata_pkt_free(spx);
16635 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16636 
16637 	return (rval);
16638 }
16639 
16640 
16641 /*
16642  * Returns 0 for success, -1 otherwise
16643  *
16644  * SMART READ LOG data is returned in buffer pointed to by smart_log
16645  */
16646 static int
16647 sata_smart_read_log(
16648 	sata_hba_inst_t *sata_hba_inst,
16649 	sata_drive_info_t *sdinfo,
16650 	uint8_t *smart_log,		/* where the data should be returned */
16651 	uint8_t which_log,		/* which log should be returned */
16652 	uint8_t log_size)		/* # of 512 bytes in log */
16653 {
16654 	sata_pkt_t *spkt;
16655 	sata_cmd_t *scmd;
16656 	sata_pkt_txlate_t *spx;
16657 	int rval;
16658 
16659 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16660 	spx->txlt_sata_hba_inst = sata_hba_inst;
16661 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16662 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16663 	if (spkt == NULL) {
16664 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16665 		return (-1);
16666 	}
16667 	/* address is needed now */
16668 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16669 
16670 
16671 	/* Fill sata_pkt */
16672 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16673 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16674 	/* Synchronous mode, no callback */
16675 	spkt->satapkt_comp = NULL;
16676 	/* Timeout 30s */
16677 	spkt->satapkt_time = sata_default_pkt_time;
16678 
16679 	scmd = &spkt->satapkt_cmd;
16680 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16681 
16682 	/*
16683 	 * Allocate buffer for SMART READ LOG
16684 	 */
16685 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
16686 	if (scmd->satacmd_bp == NULL) {
16687 		sata_pkt_free(spx);
16688 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16689 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16690 		    "sata_smart_read_log: " "cannot allocate buffer"));
16691 		return (-1);
16692 	}
16693 
16694 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16695 	scmd->satacmd_addr_type = 0;		/* N/A */
16696 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
16697 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
16698 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16699 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16700 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16701 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16702 	scmd->satacmd_cmd_reg = SATAC_SMART;
16703 
16704 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16705 	    sdinfo->satadrv_addr.cport)));
16706 
16707 	/* Send pkt to SATA HBA driver */
16708 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16709 	    SATA_TRAN_ACCEPTED ||
16710 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16711 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16712 		    sdinfo->satadrv_addr.cport)));
16713 
16714 		/*
16715 		 * Whoops, no SMART DATA available
16716 		 */
16717 		rval = -1;
16718 		goto fail;
16719 	} else {
16720 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16721 		    sdinfo->satadrv_addr.cport)));
16722 
16723 		if (spx->txlt_buf_dma_handle != NULL) {
16724 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16725 			    DDI_DMA_SYNC_FORKERNEL);
16726 			ASSERT(rval == DDI_SUCCESS);
16727 		}
16728 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
16729 		rval = 0;
16730 	}
16731 
16732 fail:
16733 	/* Free allocated resources */
16734 	sata_free_local_buffer(spx);
16735 	sata_pkt_free(spx);
16736 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16737 
16738 	return (rval);
16739 }
16740 
16741 /*
16742  * Used by LOG SENSE page 0x10
16743  *
16744  * return 0 for success, -1 otherwise
16745  *
16746  */
16747 static int
16748 sata_read_log_ext_directory(
16749 	sata_hba_inst_t *sata_hba_inst,
16750 	sata_drive_info_t *sdinfo,
16751 	struct read_log_ext_directory *logdir)
16752 {
16753 	sata_pkt_txlate_t *spx;
16754 	sata_pkt_t *spkt;
16755 	sata_cmd_t *scmd;
16756 	int rval;
16757 
16758 #if ! defined(lint)
16759 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
16760 #endif
16761 
16762 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16763 	spx->txlt_sata_hba_inst = sata_hba_inst;
16764 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16765 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16766 	if (spkt == NULL) {
16767 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16768 		return (-1);
16769 	}
16770 
16771 	/* Fill sata_pkt */
16772 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16773 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16774 	/* Synchronous mode, no callback */
16775 	spkt->satapkt_comp = NULL;
16776 	/* Timeout 30s */
16777 	spkt->satapkt_time = sata_default_pkt_time;
16778 
16779 	scmd = &spkt->satapkt_cmd;
16780 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16781 
16782 	/*
16783 	 * Allocate buffer for SMART READ LOG EXTENDED command
16784 	 */
16785 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16786 	    sizeof (struct read_log_ext_directory));
16787 	if (scmd->satacmd_bp == NULL) {
16788 		sata_pkt_free(spx);
16789 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16790 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16791 		    "sata_read_log_ext_directory: "
16792 		    "cannot allocate buffer"));
16793 		return (-1);
16794 	}
16795 
16796 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
16797 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16798 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
16799 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
16800 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
16801 	scmd->satacmd_lba_low_msb = 0;
16802 	scmd->satacmd_lba_mid_lsb = 0;
16803 	scmd->satacmd_lba_mid_msb = 0;
16804 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16805 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16806 
16807 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16808 	    sdinfo->satadrv_addr.cport)));
16809 
16810 	/* Send pkt to SATA HBA driver */
16811 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16812 	    SATA_TRAN_ACCEPTED ||
16813 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16814 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16815 		    sdinfo->satadrv_addr.cport)));
16816 		/*
16817 		 * Whoops, no SMART selftest log info available
16818 		 */
16819 		rval = -1;
16820 		goto fail;
16821 	} else {
16822 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16823 		    sdinfo->satadrv_addr.cport)));
16824 		if (spx->txlt_buf_dma_handle != NULL) {
16825 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16826 			    DDI_DMA_SYNC_FORKERNEL);
16827 			ASSERT(rval == DDI_SUCCESS);
16828 		}
16829 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
16830 		    sizeof (struct read_log_ext_directory));
16831 		rval = 0;
16832 	}
16833 
16834 fail:
16835 	/* Free allocated resources */
16836 	sata_free_local_buffer(spx);
16837 	sata_pkt_free(spx);
16838 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16839 
16840 	return (rval);
16841 }
16842 
16843 /*
16844  * Set up error retrieval sata command for NCQ command error data
16845  * recovery.
16846  *
16847  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
16848  * returns SATA_FAILURE otherwise.
16849  */
16850 static int
16851 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
16852 {
16853 #ifndef __lock_lint
16854 	_NOTE(ARGUNUSED(sdinfo))
16855 #endif
16856 
16857 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
16858 	sata_cmd_t *scmd;
16859 	struct buf *bp;
16860 
16861 	/* Operation modes are up to the caller */
16862 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16863 
16864 	/* Synchronous mode, no callback - may be changed by the caller */
16865 	spkt->satapkt_comp = NULL;
16866 	spkt->satapkt_time = sata_default_pkt_time;
16867 
16868 	scmd = &spkt->satapkt_cmd;
16869 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
16870 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
16871 
16872 	/*
16873 	 * Allocate dma_able buffer error data.
16874 	 * Buffer allocation will take care of buffer alignment and other DMA
16875 	 * attributes.
16876 	 */
16877 	bp = sata_alloc_local_buffer(spx,
16878 	    sizeof (struct sata_ncq_error_recovery_page));
16879 	if (bp == NULL)
16880 		return (SATA_FAILURE);
16881 
16882 	bp_mapin(bp); /* make data buffer accessible */
16883 	scmd->satacmd_bp = bp;
16884 
16885 	/*
16886 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
16887 	 * before accessing it. Handle is in usual place in translate struct.
16888 	 */
16889 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
16890 
16891 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
16892 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
16893 
16894 	return (SATA_SUCCESS);
16895 }
16896 
16897 /*
16898  * sata_xlate_errors() is used to translate (S)ATA error
16899  * information to SCSI information returned in the SCSI
16900  * packet.
16901  */
16902 static void
16903 sata_xlate_errors(sata_pkt_txlate_t *spx)
16904 {
16905 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
16906 	struct scsi_extended_sense *sense;
16907 
16908 	scsipkt->pkt_reason = CMD_INCOMPLETE;
16909 	*scsipkt->pkt_scbp = STATUS_CHECK;
16910 	sense = sata_arq_sense(spx);
16911 
16912 	switch (spx->txlt_sata_pkt->satapkt_reason) {
16913 	case SATA_PKT_PORT_ERROR:
16914 		/*
16915 		 * We have no device data. Assume no data transfered.
16916 		 */
16917 		sense->es_key = KEY_HARDWARE_ERROR;
16918 		break;
16919 
16920 	case SATA_PKT_DEV_ERROR:
16921 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
16922 		    SATA_STATUS_ERR) {
16923 			/*
16924 			 * determine dev error reason from error
16925 			 * reg content
16926 			 */
16927 			sata_decode_device_error(spx, sense);
16928 			break;
16929 		}
16930 		/* No extended sense key - no info available */
16931 		break;
16932 
16933 	case SATA_PKT_TIMEOUT:
16934 		scsipkt->pkt_reason = CMD_TIMEOUT;
16935 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
16936 		/* No extended sense key */
16937 		break;
16938 
16939 	case SATA_PKT_ABORTED:
16940 		scsipkt->pkt_reason = CMD_ABORTED;
16941 		scsipkt->pkt_statistics |= STAT_ABORTED;
16942 		/* No extended sense key */
16943 		break;
16944 
16945 	case SATA_PKT_RESET:
16946 		/*
16947 		 * pkt aborted either by an explicit reset request from
16948 		 * a host, or due to error recovery
16949 		 */
16950 		scsipkt->pkt_reason = CMD_RESET;
16951 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
16952 		break;
16953 
16954 	default:
16955 		scsipkt->pkt_reason = CMD_TRAN_ERR;
16956 		break;
16957 	}
16958 }
16959 
16960 
16961 
16962 
16963 /*
16964  * Log sata message
16965  * dev pathname msg line preceeds the logged message.
16966  */
16967 
16968 static	void
16969 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
16970 {
16971 	char pathname[128];
16972 	dev_info_t *dip = NULL;
16973 	va_list ap;
16974 
16975 	mutex_enter(&sata_log_mutex);
16976 
16977 	va_start(ap, fmt);
16978 	(void) vsprintf(sata_log_buf, fmt, ap);
16979 	va_end(ap);
16980 
16981 	if (sata_hba_inst != NULL) {
16982 		dip = SATA_DIP(sata_hba_inst);
16983 		(void) ddi_pathname(dip, pathname);
16984 	} else {
16985 		pathname[0] = 0;
16986 	}
16987 	if (level == CE_CONT) {
16988 		if (sata_debug_flags == 0)
16989 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
16990 		else
16991 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
16992 	} else {
16993 		if (level != CE_NOTE) {
16994 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
16995 		} else if (sata_msg) {
16996 			cmn_err(level, "%s:\n %s", pathname,
16997 			    sata_log_buf);
16998 		}
16999 	}
17000 
17001 	/* sata trace debug */
17002 	sata_trace_debug(dip, sata_log_buf);
17003 
17004 	mutex_exit(&sata_log_mutex);
17005 }
17006 
17007 
17008 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
17009 
17010 /*
17011  * Start or terminate the thread, depending on flag arg and current state
17012  */
17013 static void
17014 sata_event_thread_control(int startstop)
17015 {
17016 	static 	int sata_event_thread_terminating = 0;
17017 	static 	int sata_event_thread_starting = 0;
17018 	int i;
17019 
17020 	mutex_enter(&sata_event_mutex);
17021 
17022 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
17023 	    sata_event_thread_terminating == 1)) {
17024 		mutex_exit(&sata_event_mutex);
17025 		return;
17026 	}
17027 	if (startstop == 1 && sata_event_thread_starting == 1) {
17028 		mutex_exit(&sata_event_mutex);
17029 		return;
17030 	}
17031 	if (startstop == 1 && sata_event_thread_terminating == 1) {
17032 		sata_event_thread_starting = 1;
17033 		/* wait til terminate operation completes */
17034 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
17035 		while (sata_event_thread_terminating == 1) {
17036 			if (i-- <= 0) {
17037 				sata_event_thread_starting = 0;
17038 				mutex_exit(&sata_event_mutex);
17039 #ifdef SATA_DEBUG
17040 				cmn_err(CE_WARN, "sata_event_thread_control: "
17041 				    "timeout waiting for thread to terminate");
17042 #endif
17043 				return;
17044 			}
17045 			mutex_exit(&sata_event_mutex);
17046 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
17047 			mutex_enter(&sata_event_mutex);
17048 		}
17049 	}
17050 	if (startstop == 1) {
17051 		if (sata_event_thread == NULL) {
17052 			sata_event_thread = thread_create(NULL, 0,
17053 			    (void (*)())sata_event_daemon,
17054 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
17055 		}
17056 		sata_event_thread_starting = 0;
17057 		mutex_exit(&sata_event_mutex);
17058 		return;
17059 	}
17060 
17061 	/*
17062 	 * If we got here, thread may need to be terminated
17063 	 */
17064 	if (sata_event_thread != NULL) {
17065 		int i;
17066 		/* Signal event thread to go away */
17067 		sata_event_thread_terminating = 1;
17068 		sata_event_thread_terminate = 1;
17069 		cv_signal(&sata_event_cv);
17070 		/*
17071 		 * Wait til daemon terminates.
17072 		 */
17073 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
17074 		while (sata_event_thread_terminate == 1) {
17075 			mutex_exit(&sata_event_mutex);
17076 			if (i-- <= 0) {
17077 				/* Daemon did not go away !!! */
17078 #ifdef SATA_DEBUG
17079 				cmn_err(CE_WARN, "sata_event_thread_control: "
17080 				    "cannot terminate event daemon thread");
17081 #endif
17082 				mutex_enter(&sata_event_mutex);
17083 				break;
17084 			}
17085 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
17086 			mutex_enter(&sata_event_mutex);
17087 		}
17088 		sata_event_thread_terminating = 0;
17089 	}
17090 	ASSERT(sata_event_thread_terminating == 0);
17091 	ASSERT(sata_event_thread_starting == 0);
17092 	mutex_exit(&sata_event_mutex);
17093 }
17094 
17095 
17096 /*
17097  * SATA HBA event notification function.
17098  * Events reported by SATA HBA drivers per HBA instance relate to a change in
17099  * a port and/or device state or a controller itself.
17100  * Events for different addresses/addr types cannot be combined.
17101  * A warning message is generated for each event type.
17102  * Events are not processed by this function, so only the
17103  * event flag(s)is set for an affected entity and the event thread is
17104  * waken up. Event daemon thread processes all events.
17105  *
17106  * NOTE: Since more than one event may be reported at the same time, one
17107  * cannot determine a sequence of events when opposite event are reported, eg.
17108  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
17109  * is taking precedence over reported events, i.e. may cause ignoring some
17110  * events.
17111  */
17112 #define	SATA_EVENT_MAX_MSG_LENGTH	79
17113 
17114 void
17115 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
17116 {
17117 	sata_hba_inst_t *sata_hba_inst = NULL;
17118 	sata_address_t *saddr;
17119 	sata_pmult_info_t *pmultinfo;
17120 	sata_drive_info_t *sdinfo;
17121 	sata_port_stats_t *pstats;
17122 	sata_cport_info_t *cportinfo;
17123 	sata_pmport_info_t *pmportinfo;
17124 	int cport, pmport;
17125 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
17126 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
17127 	char *lcp;
17128 	static char *err_msg_evnt_1 =
17129 	    "sata_hba_event_notify: invalid port event 0x%x ";
17130 	static char *err_msg_evnt_2 =
17131 	    "sata_hba_event_notify: invalid device event 0x%x ";
17132 	int linkevent;
17133 
17134 	/*
17135 	 * There is a possibility that an event will be generated on HBA
17136 	 * that has not completed attachment or is detaching. We still want
17137 	 * to process events until HBA is detached.
17138 	 */
17139 	mutex_enter(&sata_mutex);
17140 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17141 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17142 		if (SATA_DIP(sata_hba_inst) == dip)
17143 			if (sata_hba_inst->satahba_attached == 1)
17144 				break;
17145 	}
17146 	mutex_exit(&sata_mutex);
17147 	if (sata_hba_inst == NULL)
17148 		/* HBA not attached */
17149 		return;
17150 
17151 	ASSERT(sata_device != NULL);
17152 
17153 	/*
17154 	 * Validate address before - do not proceed with invalid address.
17155 	 */
17156 	saddr = &sata_device->satadev_addr;
17157 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
17158 		return;
17159 
17160 	cport = saddr->cport;
17161 	pmport = saddr->pmport;
17162 
17163 	buf1[0] = buf2[0] = '\0';
17164 
17165 	/*
17166 	 * If event relates to port or device, check port state.
17167 	 * Port has to be initialized, or we cannot accept an event.
17168 	 */
17169 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
17170 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT | SATA_ADDR_PMULT)) != 0) {
17171 		mutex_enter(&sata_hba_inst->satahba_mutex);
17172 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17173 		mutex_exit(&sata_hba_inst->satahba_mutex);
17174 		if (cportinfo == NULL || cportinfo->cport_state == 0)
17175 			return;
17176 	}
17177 
17178 	if ((saddr->qual & (SATA_ADDR_PMULT | SATA_ADDR_PMPORT |
17179 	    SATA_ADDR_DPMPORT)) != 0) {
17180 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
17181 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17182 			    "sata_hba_event_notify: Non-pmult device (0x%x)"
17183 			    "is attached to port %d, ignore pmult/pmport "
17184 			    "event 0x%x", cportinfo->cport_dev_type,
17185 			    cport, event));
17186 			return;
17187 		}
17188 
17189 		mutex_enter(&cportinfo->cport_mutex);
17190 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17191 		mutex_exit(&cportinfo->cport_mutex);
17192 
17193 		/*
17194 		 * The daemon might be processing attachment of port
17195 		 * multiplier, in that case we should ignore events on its
17196 		 * sub-devices.
17197 		 *
17198 		 * NOTE: Only pmult_state is checked in sata_hba_event_notify.
17199 		 * The pmport_state is checked by sata daemon.
17200 		 */
17201 		if (pmultinfo == NULL ||
17202 		    pmultinfo->pmult_state == SATA_STATE_UNKNOWN) {
17203 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17204 			    "sata_hba_event_notify: pmult is not"
17205 			    "available at port %d:%d, ignore event 0x%x",
17206 			    cport, pmport, event));
17207 			return;
17208 		}
17209 	}
17210 
17211 	if ((saddr->qual &
17212 	    (SATA_ADDR_PMPORT | SATA_ADDR_DPMPORT)) != 0) {
17213 
17214 		mutex_enter(&cportinfo->cport_mutex);
17215 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport)) {
17216 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17217 			    "sata_hba_event_notify: invalid/"
17218 			    "un-implemented port %d:%d (%d ports), "
17219 			    "ignore event 0x%x", cport, pmport,
17220 			    SATA_NUM_PMPORTS(sata_hba_inst, cport), event));
17221 			mutex_exit(&cportinfo->cport_mutex);
17222 			return;
17223 		}
17224 		mutex_exit(&cportinfo->cport_mutex);
17225 
17226 		mutex_enter(&sata_hba_inst->satahba_mutex);
17227 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17228 		    cport, pmport);
17229 		mutex_exit(&sata_hba_inst->satahba_mutex);
17230 
17231 		/* pmport is implemented/valid? */
17232 		if (pmportinfo == NULL) {
17233 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17234 			    "sata_hba_event_notify: invalid/"
17235 			    "un-implemented port %d:%d, ignore "
17236 			    "event 0x%x", cport, pmport, event));
17237 			return;
17238 		}
17239 	}
17240 
17241 	/*
17242 	 * Events refer to devices, ports and controllers - each has
17243 	 * unique address. Events for different addresses cannot be combined.
17244 	 */
17245 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
17246 
17247 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17248 
17249 		/* qualify this event(s) */
17250 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
17251 			/* Invalid event for the device port */
17252 			(void) sprintf(buf2, err_msg_evnt_1,
17253 			    event & SATA_EVNT_PORT_EVENTS);
17254 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17255 			goto event_info;
17256 		}
17257 		if (saddr->qual == SATA_ADDR_CPORT) {
17258 			/* Controller's device port event */
17259 
17260 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
17261 			    cport_event_flags |=
17262 			    event & SATA_EVNT_PORT_EVENTS;
17263 			pstats =
17264 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
17265 			    cport_stats;
17266 		} else {
17267 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17268 			mutex_enter(&pmportinfo->pmport_mutex);
17269 			/* Port multiplier's device port event */
17270 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17271 			    pmport_event_flags |=
17272 			    event & SATA_EVNT_PORT_EVENTS;
17273 			pstats =
17274 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
17275 			    pmport_stats;
17276 			mutex_exit(&pmportinfo->pmport_mutex);
17277 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17278 		}
17279 
17280 		/*
17281 		 * Add to statistics and log the message. We have to do it
17282 		 * here rather than in the event daemon, because there may be
17283 		 * multiple events occuring before they are processed.
17284 		 */
17285 		linkevent = event &
17286 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
17287 		if (linkevent) {
17288 			if (linkevent == (SATA_EVNT_LINK_LOST |
17289 			    SATA_EVNT_LINK_ESTABLISHED)) {
17290 				/* This is likely event combination */
17291 				(void) strlcat(buf1, "link lost/established, ",
17292 				    SATA_EVENT_MAX_MSG_LENGTH);
17293 
17294 				if (pstats->link_lost < 0xffffffffffffffffULL)
17295 					pstats->link_lost++;
17296 				if (pstats->link_established <
17297 				    0xffffffffffffffffULL)
17298 					pstats->link_established++;
17299 				linkevent = 0;
17300 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
17301 				(void) strlcat(buf1, "link lost, ",
17302 				    SATA_EVENT_MAX_MSG_LENGTH);
17303 
17304 				if (pstats->link_lost < 0xffffffffffffffffULL)
17305 					pstats->link_lost++;
17306 			} else {
17307 				(void) strlcat(buf1, "link established, ",
17308 				    SATA_EVENT_MAX_MSG_LENGTH);
17309 				if (pstats->link_established <
17310 				    0xffffffffffffffffULL)
17311 					pstats->link_established++;
17312 			}
17313 		}
17314 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
17315 			(void) strlcat(buf1, "device attached, ",
17316 			    SATA_EVENT_MAX_MSG_LENGTH);
17317 			if (pstats->device_attached < 0xffffffffffffffffULL)
17318 				pstats->device_attached++;
17319 		}
17320 		if (event & SATA_EVNT_DEVICE_DETACHED) {
17321 			(void) strlcat(buf1, "device detached, ",
17322 			    SATA_EVENT_MAX_MSG_LENGTH);
17323 			if (pstats->device_detached < 0xffffffffffffffffULL)
17324 				pstats->device_detached++;
17325 		}
17326 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
17327 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17328 			    "port %d power level changed", cport);
17329 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
17330 				pstats->port_pwr_changed++;
17331 		}
17332 
17333 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
17334 			/* There should be no other events for this address */
17335 			(void) sprintf(buf2, err_msg_evnt_1,
17336 			    event & ~SATA_EVNT_PORT_EVENTS);
17337 		}
17338 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17339 
17340 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
17341 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17342 
17343 		/* qualify this event */
17344 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
17345 			/* Invalid event for a device */
17346 			(void) sprintf(buf2, err_msg_evnt_2,
17347 			    event & SATA_EVNT_DEVICE_RESET);
17348 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17349 			goto event_info;
17350 		}
17351 		/* drive event */
17352 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
17353 		if (sdinfo != NULL) {
17354 			if (event & SATA_EVNT_DEVICE_RESET) {
17355 				(void) strlcat(buf1, "device reset, ",
17356 				    SATA_EVENT_MAX_MSG_LENGTH);
17357 				if (sdinfo->satadrv_stats.drive_reset <
17358 				    0xffffffffffffffffULL)
17359 					sdinfo->satadrv_stats.drive_reset++;
17360 				sdinfo->satadrv_event_flags |=
17361 				    SATA_EVNT_DEVICE_RESET;
17362 			}
17363 		}
17364 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
17365 			/* Invalid event for a device */
17366 			(void) sprintf(buf2, err_msg_evnt_2,
17367 			    event & ~SATA_EVNT_DRIVE_EVENTS);
17368 		}
17369 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17370 	} else if (saddr->qual == SATA_ADDR_PMULT) {
17371 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17372 
17373 		/* qualify this event */
17374 		if ((event & (SATA_EVNT_DEVICE_RESET |
17375 		    SATA_EVNT_PMULT_LINK_CHANGED)) == 0) {
17376 			/* Invalid event for a port multiplier */
17377 			(void) sprintf(buf2, err_msg_evnt_2,
17378 			    event & SATA_EVNT_DEVICE_RESET);
17379 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17380 			goto event_info;
17381 		}
17382 
17383 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17384 
17385 		if (event & SATA_EVNT_DEVICE_RESET) {
17386 
17387 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17388 			    "[Reset] port-mult on cport %d", cport);
17389 			pmultinfo->pmult_event_flags |=
17390 			    SATA_EVNT_DEVICE_RESET;
17391 			(void) strlcat(buf1, "pmult reset, ",
17392 			    SATA_EVENT_MAX_MSG_LENGTH);
17393 		}
17394 
17395 		if (event & SATA_EVNT_PMULT_LINK_CHANGED) {
17396 
17397 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17398 			    "pmult link changed on cport %d", cport);
17399 			pmultinfo->pmult_event_flags |=
17400 			    SATA_EVNT_PMULT_LINK_CHANGED;
17401 			(void) strlcat(buf1, "pmult link changed, ",
17402 			    SATA_EVENT_MAX_MSG_LENGTH);
17403 		}
17404 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17405 
17406 	} else {
17407 		if (saddr->qual != SATA_ADDR_NULL) {
17408 			/* Wrong address qualifier */
17409 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17410 			    "sata_hba_event_notify: invalid address 0x%x",
17411 			    *(uint32_t *)saddr));
17412 			return;
17413 		}
17414 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
17415 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
17416 			/* Invalid event for the controller */
17417 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17418 			    "sata_hba_event_notify: invalid event 0x%x for "
17419 			    "controller",
17420 			    event & SATA_EVNT_CONTROLLER_EVENTS));
17421 			return;
17422 		}
17423 		buf1[0] = '\0';
17424 		/* This may be a frequent and not interesting event */
17425 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17426 		    "controller power level changed\n", NULL);
17427 
17428 		mutex_enter(&sata_hba_inst->satahba_mutex);
17429 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
17430 		    0xffffffffffffffffULL)
17431 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
17432 
17433 		sata_hba_inst->satahba_event_flags |=
17434 		    SATA_EVNT_PWR_LEVEL_CHANGED;
17435 		mutex_exit(&sata_hba_inst->satahba_mutex);
17436 	}
17437 	/*
17438 	 * If we got here, there is something to do with this HBA
17439 	 * instance.
17440 	 */
17441 	mutex_enter(&sata_hba_inst->satahba_mutex);
17442 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17443 	mutex_exit(&sata_hba_inst->satahba_mutex);
17444 	mutex_enter(&sata_mutex);
17445 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
17446 	mutex_exit(&sata_mutex);
17447 
17448 	/* Tickle event thread */
17449 	mutex_enter(&sata_event_mutex);
17450 	if (sata_event_thread_active == 0)
17451 		cv_signal(&sata_event_cv);
17452 	mutex_exit(&sata_event_mutex);
17453 
17454 event_info:
17455 	if (buf1[0] != '\0') {
17456 		lcp = strrchr(buf1, ',');
17457 		if (lcp != NULL)
17458 			*lcp = '\0';
17459 	}
17460 	if (saddr->qual == SATA_ADDR_CPORT ||
17461 	    saddr->qual == SATA_ADDR_DCPORT) {
17462 		if (buf1[0] != '\0') {
17463 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17464 			    cport, buf1);
17465 		}
17466 		if (buf2[0] != '\0') {
17467 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17468 			    cport, buf2);
17469 		}
17470 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
17471 	    saddr->qual == SATA_ADDR_DPMPORT) {
17472 		if (buf1[0] != '\0') {
17473 			sata_log(sata_hba_inst, CE_NOTE,
17474 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
17475 		}
17476 		if (buf2[0] != '\0') {
17477 			sata_log(sata_hba_inst, CE_NOTE,
17478 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
17479 		}
17480 	}
17481 }
17482 
17483 
17484 /*
17485  * Event processing thread.
17486  * Arg is a pointer to the sata_hba_list pointer.
17487  * It is not really needed, because sata_hba_list is global and static
17488  */
17489 static void
17490 sata_event_daemon(void *arg)
17491 {
17492 #ifndef __lock_lint
17493 	_NOTE(ARGUNUSED(arg))
17494 #endif
17495 	sata_hba_inst_t *sata_hba_inst;
17496 	clock_t delta;
17497 
17498 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17499 	    "SATA event daemon started\n", NULL);
17500 loop:
17501 	/*
17502 	 * Process events here. Walk through all registered HBAs
17503 	 */
17504 	mutex_enter(&sata_mutex);
17505 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17506 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17507 		ASSERT(sata_hba_inst != NULL);
17508 		mutex_enter(&sata_hba_inst->satahba_mutex);
17509 		if (sata_hba_inst->satahba_attached == 0 ||
17510 		    (sata_hba_inst->satahba_event_flags &
17511 		    SATA_EVNT_SKIP) != 0) {
17512 			mutex_exit(&sata_hba_inst->satahba_mutex);
17513 			continue;
17514 		}
17515 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
17516 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
17517 			mutex_exit(&sata_hba_inst->satahba_mutex);
17518 			mutex_exit(&sata_mutex);
17519 			/* Got the controller with pending event */
17520 			sata_process_controller_events(sata_hba_inst);
17521 			/*
17522 			 * Since global mutex was released, there is a
17523 			 * possibility that HBA list has changed, so start
17524 			 * over from the top. Just processed controller
17525 			 * will be passed-over because of the SKIP flag.
17526 			 */
17527 			goto loop;
17528 		}
17529 		mutex_exit(&sata_hba_inst->satahba_mutex);
17530 	}
17531 	/* Clear SKIP flag in all controllers */
17532 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17533 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17534 		mutex_enter(&sata_hba_inst->satahba_mutex);
17535 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
17536 		mutex_exit(&sata_hba_inst->satahba_mutex);
17537 	}
17538 	mutex_exit(&sata_mutex);
17539 
17540 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17541 	    "SATA EVENT DAEMON suspending itself", NULL);
17542 
17543 #ifdef SATA_DEBUG
17544 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
17545 		sata_log(sata_hba_inst, CE_WARN,
17546 		    "SATA EVENTS PROCESSING DISABLED\n");
17547 		thread_exit(); /* Daemon will not run again */
17548 	}
17549 #endif
17550 	mutex_enter(&sata_event_mutex);
17551 	sata_event_thread_active = 0;
17552 	mutex_exit(&sata_event_mutex);
17553 	/*
17554 	 * Go to sleep/suspend itself and wake up either because new event or
17555 	 * wait timeout. Exit if there is a termination request (driver
17556 	 * unload).
17557 	 */
17558 	delta = drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
17559 	do {
17560 		mutex_enter(&sata_event_mutex);
17561 		(void) cv_reltimedwait(&sata_event_cv, &sata_event_mutex,
17562 		    delta, TR_CLOCK_TICK);
17563 
17564 		if (sata_event_thread_active != 0) {
17565 			mutex_exit(&sata_event_mutex);
17566 			continue;
17567 		}
17568 
17569 		/* Check if it is time to go away */
17570 		if (sata_event_thread_terminate == 1) {
17571 			/*
17572 			 * It is up to the thread setting above flag to make
17573 			 * sure that this thread is not killed prematurely.
17574 			 */
17575 			sata_event_thread_terminate = 0;
17576 			sata_event_thread = NULL;
17577 			mutex_exit(&sata_event_mutex);
17578 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17579 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
17580 			thread_exit();  { _NOTE(NOT_REACHED) }
17581 		}
17582 		mutex_exit(&sata_event_mutex);
17583 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
17584 
17585 	mutex_enter(&sata_event_mutex);
17586 	sata_event_thread_active = 1;
17587 	mutex_exit(&sata_event_mutex);
17588 
17589 	mutex_enter(&sata_mutex);
17590 	sata_event_pending &= ~SATA_EVNT_MAIN;
17591 	mutex_exit(&sata_mutex);
17592 
17593 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17594 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
17595 
17596 	goto loop;
17597 }
17598 
17599 /*
17600  * Specific HBA instance event processing.
17601  *
17602  * NOTE: At the moment, device event processing is limited to hard disks
17603  * only.
17604  * Port multiplier is supported now.
17605  */
17606 static void
17607 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
17608 {
17609 	int ncport;
17610 	uint32_t event_flags;
17611 	sata_address_t *saddr;
17612 	sata_cport_info_t *cportinfo;
17613 	sata_pmult_info_t *pmultinfo;
17614 
17615 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
17616 	    "Processing controller %d event(s)",
17617 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
17618 
17619 	mutex_enter(&sata_hba_inst->satahba_mutex);
17620 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
17621 	event_flags = sata_hba_inst->satahba_event_flags;
17622 	mutex_exit(&sata_hba_inst->satahba_mutex);
17623 	/*
17624 	 * Process controller power change first
17625 	 * HERE
17626 	 */
17627 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
17628 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
17629 
17630 	/*
17631 	 * Search through ports/devices to identify affected port/device.
17632 	 * We may have to process events for more than one port/device.
17633 	 */
17634 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
17635 		/*
17636 		 * Not all ports may be processed in attach by the time we
17637 		 * get an event. Check if port info is initialized.
17638 		 */
17639 		mutex_enter(&sata_hba_inst->satahba_mutex);
17640 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
17641 		mutex_exit(&sata_hba_inst->satahba_mutex);
17642 		if (cportinfo == NULL || cportinfo->cport_state == NULL)
17643 			continue;
17644 
17645 		/* We have initialized controller port info */
17646 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17647 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
17648 		    cport_event_flags;
17649 		/* Check if port was locked by IOCTL processing */
17650 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
17651 			/*
17652 			 * We ignore port events because port is busy
17653 			 * with AP control processing. Set again
17654 			 * controller and main event flag, so that
17655 			 * events may be processed by the next daemon
17656 			 * run.
17657 			 */
17658 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17659 			mutex_enter(&sata_hba_inst->satahba_mutex);
17660 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17661 			mutex_exit(&sata_hba_inst->satahba_mutex);
17662 			mutex_enter(&sata_mutex);
17663 			sata_event_pending |= SATA_EVNT_MAIN;
17664 			mutex_exit(&sata_mutex);
17665 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
17666 			    "Event processing postponed until "
17667 			    "AP control processing completes",
17668 			    NULL);
17669 			/* Check other ports */
17670 			continue;
17671 		} else {
17672 			/*
17673 			 * Set BSY flag so that AP control would not
17674 			 * interfere with events processing for
17675 			 * this port.
17676 			 */
17677 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17678 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
17679 		}
17680 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17681 
17682 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
17683 
17684 		if ((event_flags &
17685 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17686 			/*
17687 			 * Got port event.
17688 			 * We need some hierarchy of event processing as they
17689 			 * are affecting each other:
17690 			 * 1. port failed
17691 			 * 2. device detached/attached
17692 			 * 3. link events - link events may trigger device
17693 			 *    detached or device attached events in some
17694 			 *    circumstances.
17695 			 * 4. port power level changed
17696 			 */
17697 			if (event_flags & SATA_EVNT_PORT_FAILED) {
17698 				sata_process_port_failed_event(sata_hba_inst,
17699 				    saddr);
17700 			}
17701 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17702 				sata_process_device_detached(sata_hba_inst,
17703 				    saddr);
17704 			}
17705 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17706 				sata_process_device_attached(sata_hba_inst,
17707 				    saddr);
17708 			}
17709 			if (event_flags &
17710 			    (SATA_EVNT_LINK_ESTABLISHED |
17711 			    SATA_EVNT_LINK_LOST)) {
17712 				sata_process_port_link_events(sata_hba_inst,
17713 				    saddr);
17714 			}
17715 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
17716 				sata_process_port_pwr_change(sata_hba_inst,
17717 				    saddr);
17718 			}
17719 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17720 				sata_process_target_node_cleanup(
17721 				    sata_hba_inst, saddr);
17722 			}
17723 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
17724 				sata_process_device_autoonline(
17725 				    sata_hba_inst, saddr);
17726 			}
17727 		}
17728 
17729 
17730 		/*
17731 		 * Scan port multiplier and all its sub-ports event flags.
17732 		 * The events are marked by
17733 		 * (1) sata_pmult_info.pmult_event_flags
17734 		 * (2) sata_pmport_info.pmport_event_flags
17735 		 */
17736 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17737 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
17738 			/*
17739 			 * There should be another extra check: this
17740 			 * port multiplier still exists?
17741 			 */
17742 			pmultinfo = SATA_PMULT_INFO(sata_hba_inst,
17743 			    ncport);
17744 
17745 			if (pmultinfo != NULL) {
17746 				mutex_exit(&(SATA_CPORT_MUTEX(
17747 				    sata_hba_inst, ncport)));
17748 				sata_process_pmult_events(
17749 				    sata_hba_inst, ncport);
17750 				mutex_enter(&(SATA_CPORT_MUTEX(
17751 				    sata_hba_inst, ncport)));
17752 			} else {
17753 				SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17754 				    "Port-multiplier is gone. "
17755 				    "Ignore all sub-device events "
17756 				    "at port %d.", ncport);
17757 			}
17758 		}
17759 
17760 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
17761 		    SATA_DTYPE_NONE) &&
17762 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
17763 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
17764 			    satadrv_event_flags &
17765 			    (SATA_EVNT_DEVICE_RESET |
17766 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17767 				/* Have device event */
17768 				sata_process_device_reset(sata_hba_inst,
17769 				    saddr);
17770 			}
17771 		}
17772 		/* Release PORT_BUSY flag */
17773 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17774 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17775 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17776 
17777 	} /* End of loop through the controller SATA ports */
17778 }
17779 
17780 /*
17781  * Specific port multiplier instance event processing. At the moment, device
17782  * event processing is limited to link/attach event only.
17783  *
17784  * NOTE: power management event is not supported yet.
17785  */
17786 static void
17787 sata_process_pmult_events(sata_hba_inst_t *sata_hba_inst, uint8_t cport)
17788 {
17789 	sata_cport_info_t *cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17790 	sata_pmult_info_t *pmultinfo;
17791 	sata_pmport_info_t *pmportinfo;
17792 	sata_address_t *saddr;
17793 	sata_device_t sata_device;
17794 	uint32_t event_flags;
17795 	int npmport;
17796 	int rval;
17797 
17798 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17799 	    "Processing pmult event(s) on cport %d of controller %d",
17800 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17801 
17802 	/* First process events on port multiplier */
17803 	mutex_enter(&cportinfo->cport_mutex);
17804 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17805 	event_flags = pmultinfo->pmult_event_flags;
17806 
17807 	/*
17808 	 * Reset event (of port multiplier) has higher priority because the
17809 	 * port multiplier itself might be failed or removed after reset.
17810 	 */
17811 	if (event_flags & SATA_EVNT_DEVICE_RESET) {
17812 		/*
17813 		 * The status of the sub-links are uncertain,
17814 		 * so mark all sub-ports as RESET
17815 		 */
17816 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(
17817 		    sata_hba_inst, cport); npmport ++) {
17818 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17819 			    cport, npmport);
17820 			if (pmportinfo == NULL) {
17821 				/* That's weird. */
17822 				SATA_LOG_D((sata_hba_inst, CE_WARN,
17823 				    "sata_hba_event_notify: "
17824 				    "invalid/un-implemented "
17825 				    "port %d:%d (%d ports), ",
17826 				    cport, npmport, SATA_NUM_PMPORTS(
17827 				    sata_hba_inst, cport)));
17828 				continue;
17829 			}
17830 
17831 			mutex_enter(&pmportinfo->pmport_mutex);
17832 
17833 			/* Mark all pmport to unknow state. */
17834 			pmportinfo->pmport_state = SATA_STATE_UNKNOWN;
17835 			/* Mark all pmports with link events. */
17836 			pmportinfo->pmport_event_flags =
17837 			    (SATA_EVNT_LINK_ESTABLISHED|SATA_EVNT_LINK_LOST);
17838 			mutex_exit(&pmportinfo->pmport_mutex);
17839 		}
17840 
17841 	} else if (event_flags & SATA_EVNT_PMULT_LINK_CHANGED) {
17842 		/*
17843 		 * We need probe the port multiplier to know what has
17844 		 * happened.
17845 		 */
17846 		bzero(&sata_device, sizeof (sata_device_t));
17847 		sata_device.satadev_rev = SATA_DEVICE_REV;
17848 		sata_device.satadev_addr.cport = cport;
17849 		sata_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
17850 		sata_device.satadev_addr.qual = SATA_ADDR_PMULT;
17851 
17852 		mutex_exit(&cportinfo->cport_mutex);
17853 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17854 		    (SATA_DIP(sata_hba_inst), &sata_device);
17855 		mutex_enter(&cportinfo->cport_mutex);
17856 		if (rval != SATA_SUCCESS) {
17857 			/* Something went wrong? Fail the port */
17858 			cportinfo->cport_state = SATA_PSTATE_FAILED;
17859 			mutex_exit(&cportinfo->cport_mutex);
17860 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17861 			    "SATA port %d probing failed", cport));
17862 
17863 			/* PMult structure must be released.  */
17864 			sata_free_pmult(sata_hba_inst, &sata_device);
17865 			return;
17866 		}
17867 
17868 		sata_update_port_info(sata_hba_inst, &sata_device);
17869 
17870 		/*
17871 		 * Sanity check - Port is active? Is the link active?
17872 		 * The device is still a port multiplier?
17873 		 */
17874 		if ((cportinfo->cport_state &
17875 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
17876 		    ((cportinfo->cport_scr.sstatus &
17877 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) ||
17878 		    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
17879 			mutex_exit(&cportinfo->cport_mutex);
17880 
17881 			/* PMult structure must be released.  */
17882 			sata_free_pmult(sata_hba_inst, &sata_device);
17883 			return;
17884 		}
17885 
17886 		/* Probed succeed, set port ready. */
17887 		cportinfo->cport_state |=
17888 		    SATA_STATE_PROBED | SATA_STATE_READY;
17889 	}
17890 
17891 	/* Release port multiplier event flags. */
17892 	pmultinfo->pmult_event_flags &=
17893 	    ~(SATA_EVNT_DEVICE_RESET|SATA_EVNT_PMULT_LINK_CHANGED);
17894 	mutex_exit(&cportinfo->cport_mutex);
17895 
17896 	/*
17897 	 * Check all sub-links.
17898 	 */
17899 	for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst, cport);
17900 	    npmport ++) {
17901 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
17902 		mutex_enter(&pmportinfo->pmport_mutex);
17903 		event_flags = pmportinfo->pmport_event_flags;
17904 		mutex_exit(&pmportinfo->pmport_mutex);
17905 		saddr = &pmportinfo->pmport_addr;
17906 
17907 		if ((event_flags &
17908 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17909 			/*
17910 			 * Got port multiplier port event.
17911 			 * We need some hierarchy of event processing as they
17912 			 * are affecting each other:
17913 			 * 1. device detached/attached
17914 			 * 2. link events - link events may trigger device
17915 			 *    detached or device attached events in some
17916 			 *    circumstances.
17917 			 */
17918 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17919 				sata_process_pmdevice_detached(sata_hba_inst,
17920 				    saddr);
17921 			}
17922 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17923 				sata_process_pmdevice_attached(sata_hba_inst,
17924 				    saddr);
17925 			}
17926 			if (event_flags & SATA_EVNT_LINK_ESTABLISHED ||
17927 			    event_flags & SATA_EVNT_LINK_LOST) {
17928 				sata_process_pmport_link_events(sata_hba_inst,
17929 				    saddr);
17930 			}
17931 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17932 				sata_process_target_node_cleanup(
17933 				    sata_hba_inst, saddr);
17934 			}
17935 		}
17936 
17937 		/* Checking drive event(s). */
17938 		mutex_enter(&pmportinfo->pmport_mutex);
17939 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
17940 		    pmportinfo->pmport_sata_drive != NULL) {
17941 			event_flags = pmportinfo->pmport_sata_drive->
17942 			    satadrv_event_flags;
17943 			if (event_flags & (SATA_EVNT_DEVICE_RESET |
17944 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17945 
17946 				/* Have device event */
17947 				sata_process_pmdevice_reset(sata_hba_inst,
17948 				    saddr);
17949 			}
17950 		}
17951 		mutex_exit(&pmportinfo->pmport_mutex);
17952 
17953 		/* Release PORT_BUSY flag */
17954 		mutex_enter(&cportinfo->cport_mutex);
17955 		cportinfo->cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17956 		mutex_exit(&cportinfo->cport_mutex);
17957 	}
17958 
17959 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17960 	    "[DONE] pmult event(s) on cport %d of controller %d",
17961 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17962 }
17963 
17964 /*
17965  * Process HBA power level change reported by HBA driver.
17966  * Not implemented at this time - event is ignored.
17967  */
17968 static void
17969 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
17970 {
17971 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17972 	    "Processing controller power level change", NULL);
17973 
17974 	/* Ignoring it for now */
17975 	mutex_enter(&sata_hba_inst->satahba_mutex);
17976 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17977 	mutex_exit(&sata_hba_inst->satahba_mutex);
17978 }
17979 
17980 /*
17981  * Process port power level change reported by HBA driver.
17982  * Not implemented at this time - event is ignored.
17983  */
17984 static void
17985 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
17986     sata_address_t *saddr)
17987 {
17988 	sata_cport_info_t *cportinfo;
17989 
17990 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17991 	    "Processing port power level change", NULL);
17992 
17993 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17994 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17995 	/* Reset event flag */
17996 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17997 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17998 }
17999 
18000 /*
18001  * Process port failure reported by HBA driver.
18002  * cports support only - no pmports.
18003  */
18004 static void
18005 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
18006     sata_address_t *saddr)
18007 {
18008 	sata_cport_info_t *cportinfo;
18009 
18010 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18011 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18012 	/* Reset event flag first */
18013 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
18014 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
18015 	if ((cportinfo->cport_state &
18016 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
18017 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18018 		    cport_mutex);
18019 		return;
18020 	}
18021 	/* Fail the port */
18022 	cportinfo->cport_state = SATA_PSTATE_FAILED;
18023 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18024 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
18025 }
18026 
18027 /*
18028  * Device Reset Event processing.
18029  * The seqeunce is managed by 3 stage flags:
18030  * - reset event reported,
18031  * - reset event being processed,
18032  * - request to clear device reset state.
18033  *
18034  * NOTE: This function has to be entered with cport mutex held. It exits with
18035  * mutex held as well, but can release mutex during the processing.
18036  */
18037 static void
18038 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
18039     sata_address_t *saddr)
18040 {
18041 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
18042 	sata_drive_info_t *sdinfo;
18043 	sata_cport_info_t *cportinfo;
18044 	sata_device_t sata_device;
18045 	int rval_probe, rval_set;
18046 
18047 	/* We only care about host sata cport for now */
18048 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18049 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18050 	/*
18051 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
18052 	 * state, ignore reset event.
18053 	 */
18054 	if (((cportinfo->cport_state &
18055 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
18056 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
18057 		sdinfo->satadrv_event_flags &=
18058 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
18059 		return;
18060 	}
18061 
18062 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) ==
18063 	    SATA_DTYPE_PMULT)) {
18064 		/*
18065 		 * Should not happened: this is already handled in
18066 		 * sata_hba_event_notify()
18067 		 */
18068 		mutex_exit(&cportinfo->cport_mutex);
18069 		goto done;
18070 	}
18071 
18072 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
18073 	    SATA_VALID_DEV_TYPE) == 0) {
18074 		/*
18075 		 * This should not happen - coding error.
18076 		 * But we can recover, so do not panic, just clean up
18077 		 * and if in debug mode, log the message.
18078 		 */
18079 #ifdef SATA_DEBUG
18080 		sata_log(sata_hba_inst, CE_WARN,
18081 		    "sata_process_device_reset: "
18082 		    "Invalid device type with sdinfo!", NULL);
18083 #endif
18084 		sdinfo->satadrv_event_flags = 0;
18085 		return;
18086 	}
18087 
18088 #ifdef SATA_DEBUG
18089 	if ((sdinfo->satadrv_event_flags &
18090 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
18091 		/* Nothing to do */
18092 		/* Something is weird - why we are processing dev reset? */
18093 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18094 		    "No device reset event!!!!", NULL);
18095 
18096 		return;
18097 	}
18098 	if ((sdinfo->satadrv_event_flags &
18099 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
18100 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
18101 		/* Something is weird - new device reset event */
18102 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18103 		    "Overlapping device reset events!", NULL);
18104 	}
18105 #endif
18106 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18107 	    "Processing port %d device reset", saddr->cport);
18108 
18109 	/* Clear event flag */
18110 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
18111 
18112 	/* It seems that we always need to check the port state first */
18113 	sata_device.satadev_rev = SATA_DEVICE_REV;
18114 	sata_device.satadev_addr = *saddr;
18115 	/*
18116 	 * We have to exit mutex, because the HBA probe port function may
18117 	 * block on its own mutex.
18118 	 */
18119 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18120 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18121 	    (SATA_DIP(sata_hba_inst), &sata_device);
18122 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18123 	sata_update_port_info(sata_hba_inst, &sata_device);
18124 	if (rval_probe != SATA_SUCCESS) {
18125 		/* Something went wrong? Fail the port */
18126 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18127 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18128 		if (sdinfo != NULL)
18129 			sdinfo->satadrv_event_flags = 0;
18130 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18131 		    cport_mutex);
18132 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18133 		    "SATA port %d probing failed",
18134 		    saddr->cport));
18135 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
18136 		    saddr->cport)->cport_mutex);
18137 		return;
18138 	}
18139 	if ((sata_device.satadev_scr.sstatus  &
18140 	    SATA_PORT_DEVLINK_UP_MASK) !=
18141 	    SATA_PORT_DEVLINK_UP ||
18142 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18143 		/*
18144 		 * No device to process, anymore. Some other event processing
18145 		 * would or have already performed port info cleanup.
18146 		 * To be safe (HBA may need it), request clearing device
18147 		 * reset condition.
18148 		 */
18149 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18150 		if (sdinfo != NULL) {
18151 			sdinfo->satadrv_event_flags &=
18152 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18153 			sdinfo->satadrv_event_flags |=
18154 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18155 		}
18156 		return;
18157 	}
18158 
18159 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
18160 	if (sdinfo == NULL) {
18161 		return;
18162 	}
18163 	if ((sdinfo->satadrv_event_flags &
18164 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18165 		/*
18166 		 * Start tracking time for device feature restoration and
18167 		 * identification. Save current time (lbolt value).
18168 		 */
18169 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18170 	}
18171 	/* Mark device reset processing as active */
18172 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18173 
18174 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18175 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18176 
18177 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
18178 
18179 	if (rval_set  != SATA_SUCCESS) {
18180 		/*
18181 		 * Restoring drive setting failed.
18182 		 * Probe the port first, to check if the port state has changed
18183 		 */
18184 		sata_device.satadev_rev = SATA_DEVICE_REV;
18185 		sata_device.satadev_addr = *saddr;
18186 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
18187 		/* probe port */
18188 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18189 		    (SATA_DIP(sata_hba_inst), &sata_device);
18190 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18191 		    cport_mutex);
18192 		if (rval_probe == SATA_SUCCESS &&
18193 		    (sata_device.satadev_state &
18194 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18195 		    (sata_device.satadev_scr.sstatus  &
18196 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18197 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18198 			/*
18199 			 * We may retry this a bit later - in-process reset
18200 			 * condition should be already set.
18201 			 * Track retry time for device identification.
18202 			 */
18203 			if ((cportinfo->cport_dev_type &
18204 			    SATA_VALID_DEV_TYPE) != 0 &&
18205 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
18206 			    sdinfo->satadrv_reset_time != 0) {
18207 				clock_t cur_time = ddi_get_lbolt();
18208 				/*
18209 				 * If the retry time limit was not
18210 				 * exceeded, retry.
18211 				 */
18212 				if ((cur_time - sdinfo->satadrv_reset_time) <
18213 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18214 					mutex_enter(
18215 					    &sata_hba_inst->satahba_mutex);
18216 					sata_hba_inst->satahba_event_flags |=
18217 					    SATA_EVNT_MAIN;
18218 					mutex_exit(
18219 					    &sata_hba_inst->satahba_mutex);
18220 					mutex_enter(&sata_mutex);
18221 					sata_event_pending |= SATA_EVNT_MAIN;
18222 					mutex_exit(&sata_mutex);
18223 					return;
18224 				}
18225 				if (rval_set == SATA_RETRY) {
18226 					/*
18227 					 * Setting drive features failed, but
18228 					 * the drive is still accessible,
18229 					 * so emit a warning message before
18230 					 * return.
18231 					 */
18232 					mutex_exit(&SATA_CPORT_INFO(
18233 					    sata_hba_inst,
18234 					    saddr->cport)->cport_mutex);
18235 					goto done;
18236 				}
18237 			}
18238 			/* Fail the drive */
18239 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18240 
18241 			sata_log(sata_hba_inst, CE_WARN,
18242 			    "SATA device at port %d - device failed",
18243 			    saddr->cport);
18244 		}
18245 		/*
18246 		 * No point of retrying - device failed or some other event
18247 		 * processing or already did or will do port info cleanup.
18248 		 * To be safe (HBA may need it),
18249 		 * request clearing device reset condition.
18250 		 */
18251 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
18252 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18253 		sdinfo->satadrv_reset_time = 0;
18254 		return;
18255 	}
18256 done:
18257 	/*
18258 	 * If setting of drive features failed, but the drive is still
18259 	 * accessible, emit a warning message.
18260 	 */
18261 	if (rval_set == SATA_RETRY) {
18262 		sata_log(sata_hba_inst, CE_WARN,
18263 		    "SATA device at port %d - desired setting could not be "
18264 		    "restored after reset. Device may not operate as expected.",
18265 		    saddr->cport);
18266 	}
18267 	/*
18268 	 * Raise the flag indicating that the next sata command could
18269 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18270 	 * reset is reported.
18271 	 */
18272 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18273 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18274 		sdinfo->satadrv_reset_time = 0;
18275 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
18276 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18277 			sdinfo->satadrv_event_flags &=
18278 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18279 			sdinfo->satadrv_event_flags |=
18280 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18281 		}
18282 	}
18283 }
18284 
18285 
18286 /*
18287  * Port Multiplier Port Device Reset Event processing.
18288  *
18289  * NOTE: This function has to be entered with pmport mutex held. It exits with
18290  * mutex held as well, but can release mutex during the processing.
18291  */
18292 static void
18293 sata_process_pmdevice_reset(sata_hba_inst_t *sata_hba_inst,
18294     sata_address_t *saddr)
18295 {
18296 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
18297 	sata_drive_info_t *sdinfo = NULL;
18298 	sata_cport_info_t *cportinfo = NULL;
18299 	sata_pmport_info_t *pmportinfo = NULL;
18300 	sata_pmult_info_t *pminfo = NULL;
18301 	sata_device_t sata_device;
18302 	uint8_t cport = saddr->cport;
18303 	uint8_t pmport = saddr->pmport;
18304 	int rval;
18305 
18306 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18307 	    "Processing drive reset at port %d:%d", cport, pmport);
18308 
18309 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
18310 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18311 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport);
18312 
18313 	/*
18314 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
18315 	 * state, ignore reset event.
18316 	 */
18317 	if (((cportinfo->cport_state &
18318 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
18319 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
18320 		sdinfo->satadrv_event_flags &=
18321 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
18322 		return;
18323 	}
18324 
18325 	if ((pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
18326 		/*
18327 		 * This should not happen - coding error.
18328 		 * But we can recover, so do not panic, just clean up
18329 		 * and if in debug mode, log the message.
18330 		 */
18331 #ifdef SATA_DEBUG
18332 		sata_log(sata_hba_inst, CE_WARN,
18333 		    "sata_process_pmdevice_reset: "
18334 		    "Invalid device type with sdinfo!", NULL);
18335 #endif
18336 		sdinfo->satadrv_event_flags = 0;
18337 		return;
18338 	}
18339 
18340 #ifdef SATA_DEBUG
18341 	if ((sdinfo->satadrv_event_flags &
18342 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
18343 		/* Nothing to do */
18344 		/* Something is weird - why we are processing dev reset? */
18345 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18346 		    "No device reset event!!!!", NULL);
18347 
18348 		return;
18349 	}
18350 	if ((sdinfo->satadrv_event_flags &
18351 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
18352 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
18353 		/* Something is weird - new device reset event */
18354 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18355 		    "Overlapping device reset events!", NULL);
18356 	}
18357 #endif
18358 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18359 	    "Processing port %d:%d device reset", cport, pmport);
18360 
18361 	/* Clear event flag */
18362 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
18363 
18364 	/* It seems that we always need to check the port state first */
18365 	sata_device.satadev_rev = SATA_DEVICE_REV;
18366 	sata_device.satadev_addr = *saddr;
18367 	/*
18368 	 * We have to exit mutex, because the HBA probe port function may
18369 	 * block on its own mutex.
18370 	 */
18371 	mutex_exit(&pmportinfo->pmport_mutex);
18372 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18373 	    (SATA_DIP(sata_hba_inst), &sata_device);
18374 	mutex_enter(&pmportinfo->pmport_mutex);
18375 
18376 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18377 	if (rval != SATA_SUCCESS) {
18378 		/* Something went wrong? Fail the port */
18379 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18380 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18381 		    saddr->pmport);
18382 		if (sdinfo != NULL)
18383 			sdinfo->satadrv_event_flags = 0;
18384 		mutex_exit(&pmportinfo->pmport_mutex);
18385 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18386 		    "SATA port %d:%d probing failed",
18387 		    saddr->cport, saddr->pmport));
18388 		mutex_enter(&pmportinfo->pmport_mutex);
18389 		return;
18390 	}
18391 	if ((sata_device.satadev_scr.sstatus  &
18392 	    SATA_PORT_DEVLINK_UP_MASK) !=
18393 	    SATA_PORT_DEVLINK_UP ||
18394 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18395 		/*
18396 		 * No device to process, anymore. Some other event processing
18397 		 * would or have already performed port info cleanup.
18398 		 * To be safe (HBA may need it), request clearing device
18399 		 * reset condition.
18400 		 */
18401 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18402 		    saddr->pmport);
18403 		if (sdinfo != NULL) {
18404 			sdinfo->satadrv_event_flags &=
18405 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18406 			/* must clear flags on cport */
18407 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18408 			    saddr->cport);
18409 			pminfo->pmult_event_flags |=
18410 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18411 		}
18412 		return;
18413 	}
18414 
18415 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18416 	    saddr->pmport);
18417 	if (sdinfo == NULL) {
18418 		return;
18419 	}
18420 	if ((sdinfo->satadrv_event_flags &
18421 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18422 		/*
18423 		 * Start tracking time for device feature restoration and
18424 		 * identification. Save current time (lbolt value).
18425 		 */
18426 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18427 	}
18428 	/* Mark device reset processing as active */
18429 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18430 
18431 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18432 	mutex_exit(&pmportinfo->pmport_mutex);
18433 
18434 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
18435 	    SATA_FAILURE) {
18436 		/*
18437 		 * Restoring drive setting failed.
18438 		 * Probe the port first, to check if the port state has changed
18439 		 */
18440 		sata_device.satadev_rev = SATA_DEVICE_REV;
18441 		sata_device.satadev_addr = *saddr;
18442 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
18443 
18444 		/* probe port */
18445 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18446 		    (SATA_DIP(sata_hba_inst), &sata_device);
18447 		mutex_enter(&pmportinfo->pmport_mutex);
18448 		if (rval == SATA_SUCCESS &&
18449 		    (sata_device.satadev_state &
18450 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18451 		    (sata_device.satadev_scr.sstatus  &
18452 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18453 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18454 			/*
18455 			 * We may retry this a bit later - in-process reset
18456 			 * condition should be already set.
18457 			 * Track retry time for device identification.
18458 			 */
18459 			if ((pmportinfo->pmport_dev_type &
18460 			    SATA_VALID_DEV_TYPE) != 0 &&
18461 			    SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL &&
18462 			    sdinfo->satadrv_reset_time != 0) {
18463 				clock_t cur_time = ddi_get_lbolt();
18464 				/*
18465 				 * If the retry time limit was not
18466 				 * exceeded, retry.
18467 				 */
18468 				if ((cur_time - sdinfo->satadrv_reset_time) <
18469 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18470 					mutex_enter(
18471 					    &sata_hba_inst->satahba_mutex);
18472 					sata_hba_inst->satahba_event_flags |=
18473 					    SATA_EVNT_MAIN;
18474 					mutex_exit(
18475 					    &sata_hba_inst->satahba_mutex);
18476 					mutex_enter(&sata_mutex);
18477 					sata_event_pending |= SATA_EVNT_MAIN;
18478 					mutex_exit(&sata_mutex);
18479 					return;
18480 				}
18481 			}
18482 			/* Fail the drive */
18483 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18484 
18485 			sata_log(sata_hba_inst, CE_WARN,
18486 			    "SATA device at port %d:%d - device failed",
18487 			    saddr->cport, saddr->pmport);
18488 		} else {
18489 			/*
18490 			 * No point of retrying - some other event processing
18491 			 * would or already did port info cleanup.
18492 			 * To be safe (HBA may need it),
18493 			 * request clearing device reset condition.
18494 			 */
18495 			sdinfo->satadrv_event_flags |=
18496 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18497 		}
18498 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18499 		sdinfo->satadrv_reset_time = 0;
18500 		return;
18501 	}
18502 	/*
18503 	 * Raise the flag indicating that the next sata command could
18504 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18505 	 * reset is reported.
18506 	 */
18507 	mutex_enter(&pmportinfo->pmport_mutex);
18508 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18509 		sdinfo->satadrv_reset_time = 0;
18510 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
18511 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18512 			sdinfo->satadrv_event_flags &=
18513 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18514 			/* must clear flags on cport */
18515 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18516 			    saddr->cport);
18517 			pminfo->pmult_event_flags |=
18518 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18519 		}
18520 	}
18521 }
18522 
18523 /*
18524  * Port Link Events processing.
18525  * Every link established event may involve device reset (due to
18526  * COMRESET signal, equivalent of the hard reset) so arbitrarily
18527  * set device reset event for an attached device (if any).
18528  * If the port is in SHUTDOWN or FAILED state, ignore link events.
18529  *
18530  * The link established event processing varies, depending on the state
18531  * of the target node, HBA hotplugging capabilities, state of the port.
18532  * If the link is not active, the link established event is ignored.
18533  * If HBA cannot detect device attachment and there is no target node,
18534  * the link established event triggers device attach event processing.
18535  * Else, link established event triggers device reset event processing.
18536  *
18537  * The link lost event processing varies, depending on a HBA hotplugging
18538  * capability and the state of the port (link active or not active).
18539  * If the link is active, the lost link event is ignored.
18540  * If HBA cannot detect device removal, the lost link event triggers
18541  * device detached event processing after link lost timeout.
18542  * Else, the event is ignored.
18543  *
18544  * NOTE: Port multiplier ports events are handled by
18545  * sata_process_pmport_link_events();
18546  */
18547 static void
18548 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
18549     sata_address_t *saddr)
18550 {
18551 	sata_device_t sata_device;
18552 	sata_cport_info_t *cportinfo;
18553 	sata_drive_info_t *sdinfo;
18554 	uint32_t event_flags;
18555 	int rval;
18556 
18557 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18558 	    "Processing port %d link event(s)", saddr->cport);
18559 
18560 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18561 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18562 	event_flags = cportinfo->cport_event_flags;
18563 
18564 	/* Reset event flags first */
18565 	cportinfo->cport_event_flags &=
18566 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18567 
18568 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18569 	if ((cportinfo->cport_state &
18570 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18571 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18572 		    cport_mutex);
18573 		return;
18574 	}
18575 
18576 	/*
18577 	 * For the sanity sake get current port state.
18578 	 * Set device address only. Other sata_device fields should be
18579 	 * set by HBA driver.
18580 	 */
18581 	sata_device.satadev_rev = SATA_DEVICE_REV;
18582 	sata_device.satadev_addr = *saddr;
18583 	/*
18584 	 * We have to exit mutex, because the HBA probe port function may
18585 	 * block on its own mutex.
18586 	 */
18587 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18588 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18589 	    (SATA_DIP(sata_hba_inst), &sata_device);
18590 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18591 	sata_update_port_info(sata_hba_inst, &sata_device);
18592 	if (rval != SATA_SUCCESS) {
18593 		/* Something went wrong? Fail the port */
18594 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18595 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18596 		    cport_mutex);
18597 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18598 		    "SATA port %d probing failed",
18599 		    saddr->cport));
18600 		/*
18601 		 * We may want to release device info structure, but
18602 		 * it is not necessary.
18603 		 */
18604 		return;
18605 	} else {
18606 		/* port probed successfully */
18607 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18608 	}
18609 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18610 
18611 		if ((sata_device.satadev_scr.sstatus &
18612 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18613 			/* Ignore event */
18614 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18615 			    "Ignoring port %d link established event - "
18616 			    "link down",
18617 			    saddr->cport);
18618 			goto linklost;
18619 		}
18620 
18621 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18622 		    "Processing port %d link established event",
18623 		    saddr->cport);
18624 
18625 		/*
18626 		 * For the sanity sake check if a device is attached - check
18627 		 * return state of a port probing.
18628 		 */
18629 		if (sata_device.satadev_type != SATA_DTYPE_NONE) {
18630 			/*
18631 			 * HBA port probe indicated that there is a device
18632 			 * attached. Check if the framework had device info
18633 			 * structure attached for this device.
18634 			 */
18635 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
18636 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
18637 				    NULL);
18638 
18639 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18640 				if ((sdinfo->satadrv_type &
18641 				    SATA_VALID_DEV_TYPE) != 0) {
18642 					/*
18643 					 * Dev info structure is present.
18644 					 * If dev_type is set to known type in
18645 					 * the framework's drive info struct
18646 					 * then the device existed before and
18647 					 * the link was probably lost
18648 					 * momentarily - in such case
18649 					 * we may want to check device
18650 					 * identity.
18651 					 * Identity check is not supported now.
18652 					 *
18653 					 * Link established event
18654 					 * triggers device reset event.
18655 					 */
18656 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
18657 					    satadrv_event_flags |=
18658 					    SATA_EVNT_DEVICE_RESET;
18659 				}
18660 			} else if (cportinfo->cport_dev_type ==
18661 			    SATA_DTYPE_NONE) {
18662 				/*
18663 				 * We got new device attached! If HBA does not
18664 				 * generate device attached events, trigger it
18665 				 * here.
18666 				 */
18667 				if (!(SATA_FEATURES(sata_hba_inst) &
18668 				    SATA_CTLF_HOTPLUG)) {
18669 					cportinfo->cport_event_flags |=
18670 					    SATA_EVNT_DEVICE_ATTACHED;
18671 				}
18672 			}
18673 			/* Reset link lost timeout */
18674 			cportinfo->cport_link_lost_time = 0;
18675 		}
18676 	}
18677 linklost:
18678 	if (event_flags & SATA_EVNT_LINK_LOST) {
18679 		if ((sata_device.satadev_scr.sstatus &
18680 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18681 			/* Ignore event */
18682 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18683 			    "Ignoring port %d link lost event - link is up",
18684 			    saddr->cport);
18685 			goto done;
18686 		}
18687 #ifdef SATA_DEBUG
18688 		if (cportinfo->cport_link_lost_time == 0) {
18689 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18690 			    "Processing port %d link lost event",
18691 			    saddr->cport);
18692 		}
18693 #endif
18694 		/*
18695 		 * When HBA cannot generate device attached/detached events,
18696 		 * we need to track link lost time and eventually generate
18697 		 * device detach event.
18698 		 */
18699 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18700 			/* We are tracking link lost time */
18701 			if (cportinfo->cport_link_lost_time == 0) {
18702 				/* save current time (lbolt value) */
18703 				cportinfo->cport_link_lost_time =
18704 				    ddi_get_lbolt();
18705 				/* just keep link lost event */
18706 				cportinfo->cport_event_flags |=
18707 				    SATA_EVNT_LINK_LOST;
18708 			} else {
18709 				clock_t cur_time = ddi_get_lbolt();
18710 				if ((cur_time -
18711 				    cportinfo->cport_link_lost_time) >=
18712 				    drv_usectohz(
18713 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18714 					/* trigger device detach event */
18715 					cportinfo->cport_event_flags |=
18716 					    SATA_EVNT_DEVICE_DETACHED;
18717 					cportinfo->cport_link_lost_time = 0;
18718 					SATADBG1(SATA_DBG_EVENTS,
18719 					    sata_hba_inst,
18720 					    "Triggering port %d "
18721 					    "device detached event",
18722 					    saddr->cport);
18723 				} else {
18724 					/* keep link lost event */
18725 					cportinfo->cport_event_flags |=
18726 					    SATA_EVNT_LINK_LOST;
18727 				}
18728 			}
18729 		}
18730 		/*
18731 		 * We could change port state to disable/delay access to
18732 		 * the attached device until the link is recovered.
18733 		 */
18734 	}
18735 done:
18736 	event_flags = cportinfo->cport_event_flags;
18737 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18738 	if (event_flags != 0) {
18739 		mutex_enter(&sata_hba_inst->satahba_mutex);
18740 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18741 		mutex_exit(&sata_hba_inst->satahba_mutex);
18742 		mutex_enter(&sata_mutex);
18743 		sata_event_pending |= SATA_EVNT_MAIN;
18744 		mutex_exit(&sata_mutex);
18745 	}
18746 }
18747 
18748 /*
18749  * Port Multiplier Port Link Events processing.
18750  */
18751 static void
18752 sata_process_pmport_link_events(sata_hba_inst_t *sata_hba_inst,
18753     sata_address_t *saddr)
18754 {
18755 	sata_device_t sata_device;
18756 	sata_pmport_info_t *pmportinfo = NULL;
18757 	sata_drive_info_t *sdinfo = NULL;
18758 	uint32_t event_flags;
18759 	uint8_t cport = saddr->cport;
18760 	uint8_t pmport = saddr->pmport;
18761 	int rval;
18762 
18763 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18764 	    "Processing port %d:%d link event(s)",
18765 	    cport, pmport);
18766 
18767 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18768 	mutex_enter(&pmportinfo->pmport_mutex);
18769 	event_flags = pmportinfo->pmport_event_flags;
18770 
18771 	/* Reset event flags first */
18772 	pmportinfo->pmport_event_flags &=
18773 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18774 
18775 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18776 	if ((pmportinfo->pmport_state &
18777 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18778 		mutex_exit(&pmportinfo->pmport_mutex);
18779 		return;
18780 	}
18781 
18782 	/*
18783 	 * For the sanity sake get current port state.
18784 	 * Set device address only. Other sata_device fields should be
18785 	 * set by HBA driver.
18786 	 */
18787 	sata_device.satadev_rev = SATA_DEVICE_REV;
18788 	sata_device.satadev_addr = *saddr;
18789 	/*
18790 	 * We have to exit mutex, because the HBA probe port function may
18791 	 * block on its own mutex.
18792 	 */
18793 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18794 	    saddr->pmport));
18795 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18796 	    (SATA_DIP(sata_hba_inst), &sata_device);
18797 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18798 	    saddr->pmport));
18799 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18800 	if (rval != SATA_SUCCESS) {
18801 		/* Something went wrong? Fail the port */
18802 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18803 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18804 		    saddr->pmport));
18805 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18806 		    "SATA port %d:%d probing failed",
18807 		    saddr->cport, saddr->pmport));
18808 		/*
18809 		 * We may want to release device info structure, but
18810 		 * it is not necessary.
18811 		 */
18812 		return;
18813 	} else {
18814 		/* port probed successfully */
18815 		pmportinfo->pmport_state |=
18816 		    SATA_STATE_PROBED | SATA_STATE_READY;
18817 	}
18818 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
18819 	    saddr->cport, saddr->pmport));
18820 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
18821 	    saddr->cport, saddr->pmport));
18822 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18823 
18824 		if ((sata_device.satadev_scr.sstatus &
18825 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18826 			/* Ignore event */
18827 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18828 			    "Ignoring port %d:%d link established event - "
18829 			    "link down",
18830 			    saddr->cport, saddr->pmport);
18831 			goto linklost;
18832 		}
18833 
18834 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18835 		    "Processing port %d:%d link established event",
18836 		    cport, pmport);
18837 
18838 		/*
18839 		 * For the sanity sake check if a device is attached - check
18840 		 * return state of a port probing.
18841 		 */
18842 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
18843 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
18844 			/*
18845 			 * HBA port probe indicated that there is a device
18846 			 * attached. Check if the framework had device info
18847 			 * structure attached for this device.
18848 			 */
18849 			if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
18850 				ASSERT(SATA_PMPORTINFO_DRV_INFO(pmportinfo) !=
18851 				    NULL);
18852 
18853 				sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18854 				if ((sdinfo->satadrv_type &
18855 				    SATA_VALID_DEV_TYPE) != 0) {
18856 					/*
18857 					 * Dev info structure is present.
18858 					 * If dev_type is set to known type in
18859 					 * the framework's drive info struct
18860 					 * then the device existed before and
18861 					 * the link was probably lost
18862 					 * momentarily - in such case
18863 					 * we may want to check device
18864 					 * identity.
18865 					 * Identity check is not supported now.
18866 					 *
18867 					 * Link established event
18868 					 * triggers device reset event.
18869 					 */
18870 					(SATA_PMPORTINFO_DRV_INFO(pmportinfo))->
18871 					    satadrv_event_flags |=
18872 					    SATA_EVNT_DEVICE_RESET;
18873 				}
18874 			} else if (pmportinfo->pmport_dev_type ==
18875 			    SATA_DTYPE_NONE) {
18876 				/*
18877 				 * We got new device attached! If HBA does not
18878 				 * generate device attached events, trigger it
18879 				 * here.
18880 				 */
18881 				if (!(SATA_FEATURES(sata_hba_inst) &
18882 				    SATA_CTLF_HOTPLUG)) {
18883 					pmportinfo->pmport_event_flags |=
18884 					    SATA_EVNT_DEVICE_ATTACHED;
18885 				}
18886 			}
18887 			/* Reset link lost timeout */
18888 			pmportinfo->pmport_link_lost_time = 0;
18889 		}
18890 	}
18891 linklost:
18892 	if (event_flags & SATA_EVNT_LINK_LOST) {
18893 #ifdef SATA_DEBUG
18894 		if (pmportinfo->pmport_link_lost_time == 0) {
18895 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18896 			    "Processing port %d:%d link lost event",
18897 			    saddr->cport, saddr->pmport);
18898 		}
18899 #endif
18900 		if ((sata_device.satadev_scr.sstatus &
18901 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18902 			/* Ignore event */
18903 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18904 			    "Ignoring port %d:%d link lost event - link is up",
18905 			    saddr->cport, saddr->pmport);
18906 			goto done;
18907 		}
18908 		/*
18909 		 * When HBA cannot generate device attached/detached events,
18910 		 * we need to track link lost time and eventually generate
18911 		 * device detach event.
18912 		 */
18913 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18914 			/* We are tracking link lost time */
18915 			if (pmportinfo->pmport_link_lost_time == 0) {
18916 				/* save current time (lbolt value) */
18917 				pmportinfo->pmport_link_lost_time =
18918 				    ddi_get_lbolt();
18919 				/* just keep link lost event */
18920 				pmportinfo->pmport_event_flags |=
18921 				    SATA_EVNT_LINK_LOST;
18922 			} else {
18923 				clock_t cur_time = ddi_get_lbolt();
18924 				if ((cur_time -
18925 				    pmportinfo->pmport_link_lost_time) >=
18926 				    drv_usectohz(
18927 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18928 					/* trigger device detach event */
18929 					pmportinfo->pmport_event_flags |=
18930 					    SATA_EVNT_DEVICE_DETACHED;
18931 					pmportinfo->pmport_link_lost_time = 0;
18932 					SATADBG2(SATA_DBG_EVENTS,
18933 					    sata_hba_inst,
18934 					    "Triggering port %d:%d "
18935 					    "device detached event",
18936 					    saddr->cport, saddr->pmport);
18937 				} else {
18938 					/* keep link lost event */
18939 					pmportinfo->pmport_event_flags |=
18940 					    SATA_EVNT_LINK_LOST;
18941 				}
18942 			}
18943 		}
18944 		/*
18945 		 * We could change port state to disable/delay access to
18946 		 * the attached device until the link is recovered.
18947 		 */
18948 	}
18949 done:
18950 	event_flags = pmportinfo->pmport_event_flags;
18951 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18952 	    saddr->pmport));
18953 	if (event_flags != 0) {
18954 		mutex_enter(&sata_hba_inst->satahba_mutex);
18955 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18956 		mutex_exit(&sata_hba_inst->satahba_mutex);
18957 		mutex_enter(&sata_mutex);
18958 		sata_event_pending |= SATA_EVNT_MAIN;
18959 		mutex_exit(&sata_mutex);
18960 	}
18961 }
18962 
18963 /*
18964  * Device Detached Event processing.
18965  * Port is probed to find if a device is really gone. If so,
18966  * the device info structure is detached from the SATA port info structure
18967  * and released.
18968  * Port status is updated.
18969  *
18970  * NOTE: Port multiplier ports events are handled by
18971  * sata_process_pmdevice_detached()
18972  */
18973 static void
18974 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
18975     sata_address_t *saddr)
18976 {
18977 	sata_cport_info_t *cportinfo;
18978 	sata_pmport_info_t *pmportinfo;
18979 	sata_drive_info_t *sdevinfo;
18980 	sata_device_t sata_device;
18981 	sata_address_t pmport_addr;
18982 	char name[16];
18983 	uint8_t cport = saddr->cport;
18984 	int npmport;
18985 	int rval;
18986 
18987 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18988 	    "Processing port %d device detached", saddr->cport);
18989 
18990 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18991 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18992 	/* Clear event flag */
18993 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18994 
18995 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18996 	if ((cportinfo->cport_state &
18997 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18998 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18999 		    cport_mutex);
19000 		return;
19001 	}
19002 	/* For sanity, re-probe the port */
19003 	sata_device.satadev_rev = SATA_DEVICE_REV;
19004 	sata_device.satadev_addr = *saddr;
19005 
19006 	/*
19007 	 * We have to exit mutex, because the HBA probe port function may
19008 	 * block on its own mutex.
19009 	 */
19010 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19011 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19012 	    (SATA_DIP(sata_hba_inst), &sata_device);
19013 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19014 	sata_update_port_info(sata_hba_inst, &sata_device);
19015 	if (rval != SATA_SUCCESS) {
19016 		/* Something went wrong? Fail the port */
19017 		cportinfo->cport_state = SATA_PSTATE_FAILED;
19018 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19019 		    cport_mutex);
19020 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19021 		    "SATA port %d probing failed",
19022 		    saddr->cport));
19023 		/*
19024 		 * We may want to release device info structure, but
19025 		 * it is not necessary.
19026 		 */
19027 		return;
19028 	} else {
19029 		/* port probed successfully */
19030 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
19031 	}
19032 	/*
19033 	 * Check if a device is still attached. For sanity, check also
19034 	 * link status - if no link, there is no device.
19035 	 */
19036 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
19037 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
19038 	    SATA_DTYPE_NONE) {
19039 		/*
19040 		 * Device is still attached - ignore detach event.
19041 		 */
19042 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19043 		    cport_mutex);
19044 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19045 		    "Ignoring detach - device still attached to port %d",
19046 		    sata_device.satadev_addr.cport);
19047 		return;
19048 	}
19049 	/*
19050 	 * We need to detach and release device info structure here
19051 	 */
19052 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19053 		/*
19054 		 * A port-multiplier is removed.
19055 		 *
19056 		 * Calling sata_process_pmdevice_detached() does not work
19057 		 * here. The port multiplier is gone, so we cannot probe
19058 		 * sub-port any more and all pmult-related data structure must
19059 		 * be de-allocated immediately. Following structure of every
19060 		 * implemented sub-port behind the pmult are required to
19061 		 * released.
19062 		 *
19063 		 *   - attachment point
19064 		 *   - target node
19065 		 *   - sata_drive_info
19066 		 *   - sata_pmport_info
19067 		 */
19068 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst,
19069 		    cport); npmport ++) {
19070 			SATADBG2(SATA_DBG_PMULT|SATA_DBG_EVENTS_PROC,
19071 			    sata_hba_inst,
19072 			    "Detaching target node at port %d:%d",
19073 			    cport, npmport);
19074 
19075 			mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
19076 
19077 			/* Remove attachment point. */
19078 			name[0] = '\0';
19079 			(void) sprintf(name, "%d.%d", cport, npmport);
19080 			ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
19081 			sata_log(sata_hba_inst, CE_NOTE,
19082 			    "Remove attachment point of port %d:%d",
19083 			    cport, npmport);
19084 
19085 			/* Remove target node */
19086 			pmport_addr.cport = cport;
19087 			pmport_addr.pmport = (uint8_t)npmport;
19088 			pmport_addr.qual = SATA_ADDR_PMPORT;
19089 			sata_remove_target_node(sata_hba_inst, &pmport_addr);
19090 
19091 			mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
19092 
19093 			/* Release sata_pmport_info & sata_drive_info. */
19094 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19095 			    cport, npmport);
19096 			ASSERT(pmportinfo != NULL);
19097 
19098 			sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19099 			if (sdevinfo != NULL) {
19100 				(void) kmem_free((void *) sdevinfo,
19101 				    sizeof (sata_drive_info_t));
19102 			}
19103 
19104 			/* Release sata_pmport_info at last */
19105 			(void) kmem_free((void *) pmportinfo,
19106 			    sizeof (sata_pmport_info_t));
19107 		}
19108 
19109 		/* Finally, release sata_pmult_info */
19110 		(void) kmem_free((void *)
19111 		    SATA_CPORTINFO_PMULT_INFO(cportinfo),
19112 		    sizeof (sata_pmult_info_t));
19113 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
19114 
19115 		sata_log(sata_hba_inst, CE_WARN,
19116 		    "SATA port-multiplier detached at port %d", cport);
19117 
19118 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19119 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19120 		    saddr->cport)->cport_mutex);
19121 	} else {
19122 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19123 			sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
19124 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
19125 			(void) kmem_free((void *)sdevinfo,
19126 			    sizeof (sata_drive_info_t));
19127 		}
19128 		sata_log(sata_hba_inst, CE_WARN,
19129 		    "SATA device detached at port %d", cport);
19130 
19131 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19132 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19133 		    saddr->cport)->cport_mutex);
19134 
19135 		/*
19136 		 * Try to offline a device and remove target node
19137 		 * if it still exists
19138 		 */
19139 		sata_remove_target_node(sata_hba_inst, saddr);
19140 	}
19141 
19142 
19143 	/*
19144 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19145 	 * with the hint: SE_HINT_REMOVE
19146 	 */
19147 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
19148 }
19149 
19150 /*
19151  * Port Multiplier Port Device Deattached Event processing.
19152  *
19153  * NOTE: No Mutex should be hold.
19154  */
19155 static void
19156 sata_process_pmdevice_detached(sata_hba_inst_t *sata_hba_inst,
19157     sata_address_t *saddr)
19158 {
19159 	sata_pmport_info_t *pmportinfo;
19160 	sata_drive_info_t *sdevinfo;
19161 	sata_device_t sata_device;
19162 	int rval;
19163 	uint8_t cport, pmport;
19164 
19165 	cport = saddr->cport;
19166 	pmport = saddr->pmport;
19167 
19168 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19169 	    "Processing port %d:%d device detached",
19170 	    cport, pmport);
19171 
19172 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19173 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19174 
19175 	/* Clear event flag */
19176 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
19177 
19178 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
19179 	if ((pmportinfo->pmport_state &
19180 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19181 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19182 		return;
19183 	}
19184 	/* For sanity, re-probe the port */
19185 	sata_device.satadev_rev = SATA_DEVICE_REV;
19186 	sata_device.satadev_addr = *saddr;
19187 
19188 	/*
19189 	 * We have to exit mutex, because the HBA probe port function may
19190 	 * block on its own mutex.
19191 	 */
19192 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19193 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19194 	    (SATA_DIP(sata_hba_inst), &sata_device);
19195 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19196 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19197 	if (rval != SATA_SUCCESS) {
19198 		/* Something went wrong? Fail the port */
19199 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19200 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19201 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19202 		    "SATA port %d:%d probing failed",
19203 		    saddr->pmport));
19204 		/*
19205 		 * We may want to release device info structure, but
19206 		 * it is not necessary.
19207 		 */
19208 		return;
19209 	} else {
19210 		/* port probed successfully */
19211 		pmportinfo->pmport_state |=
19212 		    SATA_STATE_PROBED | SATA_STATE_READY;
19213 	}
19214 	/*
19215 	 * Check if a device is still attached. For sanity, check also
19216 	 * link status - if no link, there is no device.
19217 	 */
19218 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
19219 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
19220 	    SATA_DTYPE_NONE) {
19221 		/*
19222 		 * Device is still attached - ignore detach event.
19223 		 */
19224 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19225 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19226 		    "Ignoring detach - device still attached to port %d",
19227 		    sata_device.satadev_addr.pmport);
19228 		return;
19229 	}
19230 	/*
19231 	 * We need to detach and release device info structure here
19232 	 */
19233 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19234 		sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19235 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19236 		(void) kmem_free((void *)sdevinfo,
19237 		    sizeof (sata_drive_info_t));
19238 	}
19239 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19240 	/*
19241 	 * Device cannot be reached anymore, even if the target node may be
19242 	 * still present.
19243 	 */
19244 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
19245 
19246 	/*
19247 	 * Try to offline a device and remove target node if it still exists
19248 	 */
19249 	sata_remove_target_node(sata_hba_inst, saddr);
19250 
19251 	/*
19252 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19253 	 * with the hint: SE_HINT_REMOVE
19254 	 */
19255 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
19256 }
19257 
19258 
19259 /*
19260  * Device Attached Event processing.
19261  * Port state is checked to verify that a device is really attached. If so,
19262  * the device info structure is created and attached to the SATA port info
19263  * structure.
19264  *
19265  * If attached device cannot be identified or set-up, the retry for the
19266  * attach processing is set-up. Subsequent daemon run would try again to
19267  * identify the device, until the time limit is reached
19268  * (SATA_DEV_IDENTIFY_TIMEOUT).
19269  *
19270  * This function cannot be called in interrupt context (it may sleep).
19271  *
19272  * NOTE: Port multiplier ports events are handled by
19273  * sata_process_pmdevice_attached()
19274  */
19275 static void
19276 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
19277     sata_address_t *saddr)
19278 {
19279 	sata_cport_info_t *cportinfo = NULL;
19280 	sata_drive_info_t *sdevinfo = NULL;
19281 	sata_pmult_info_t *pmultinfo = NULL;
19282 	sata_pmport_info_t *pmportinfo = NULL;
19283 	sata_device_t sata_device;
19284 	dev_info_t *tdip;
19285 	uint32_t event_flags = 0, pmult_event_flags = 0;
19286 	int rval;
19287 	int npmport;
19288 
19289 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19290 	    "Processing port %d device attached", saddr->cport);
19291 
19292 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19293 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19294 
19295 	/* Clear attach event flag first */
19296 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19297 
19298 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19299 	if ((cportinfo->cport_state &
19300 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19301 		cportinfo->cport_dev_attach_time = 0;
19302 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19303 		    cport_mutex);
19304 		return;
19305 	}
19306 
19307 	/*
19308 	 * If the sata_drive_info structure is found attached to the port info,
19309 	 * despite the fact the device was removed and now it is re-attached,
19310 	 * the old drive info structure was not removed.
19311 	 * Arbitrarily release device info structure.
19312 	 */
19313 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19314 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
19315 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
19316 		(void) kmem_free((void *)sdevinfo,
19317 		    sizeof (sata_drive_info_t));
19318 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19319 		    "Arbitrarily detaching old device info.", NULL);
19320 	}
19321 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
19322 
19323 	/* For sanity, re-probe the port */
19324 	sata_device.satadev_rev = SATA_DEVICE_REV;
19325 	sata_device.satadev_addr = *saddr;
19326 
19327 	/*
19328 	 * We have to exit mutex, because the HBA probe port function may
19329 	 * block on its own mutex.
19330 	 */
19331 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19332 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19333 	    (SATA_DIP(sata_hba_inst), &sata_device);
19334 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19335 	sata_update_port_info(sata_hba_inst, &sata_device);
19336 	if (rval != SATA_SUCCESS) {
19337 		/* Something went wrong? Fail the port */
19338 		cportinfo->cport_state = SATA_PSTATE_FAILED;
19339 		cportinfo->cport_dev_attach_time = 0;
19340 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19341 		    cport_mutex);
19342 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19343 		    "SATA port %d probing failed",
19344 		    saddr->cport));
19345 		return;
19346 	} else {
19347 		/* port probed successfully */
19348 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
19349 	}
19350 	/*
19351 	 * Check if a device is still attached. For sanity, check also
19352 	 * link status - if no link, there is no device.
19353 	 */
19354 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19355 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19356 	    SATA_DTYPE_NONE) {
19357 		/*
19358 		 * No device - ignore attach event.
19359 		 */
19360 		cportinfo->cport_dev_attach_time = 0;
19361 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19362 		    cport_mutex);
19363 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19364 		    "Ignoring attach - no device connected to port %d",
19365 		    sata_device.satadev_addr.cport);
19366 		return;
19367 	}
19368 
19369 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19370 	/*
19371 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19372 	 * with the hint: SE_HINT_INSERT
19373 	 */
19374 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19375 
19376 	/*
19377 	 * Port reprobing will take care of the creation of the device
19378 	 * info structure and determination of the device type.
19379 	 */
19380 	sata_device.satadev_addr = *saddr;
19381 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19382 	    SATA_DEV_IDENTIFY_NORETRY);
19383 
19384 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19385 	    cport_mutex);
19386 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
19387 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
19388 		/* Some device is attached to the port */
19389 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
19390 			/*
19391 			 * A device was not successfully attached.
19392 			 * Track retry time for device identification.
19393 			 */
19394 			if (cportinfo->cport_dev_attach_time != 0) {
19395 				clock_t cur_time = ddi_get_lbolt();
19396 				/*
19397 				 * If the retry time limit was not exceeded,
19398 				 * reinstate attach event.
19399 				 */
19400 				if ((cur_time -
19401 				    cportinfo->cport_dev_attach_time) <
19402 				    drv_usectohz(
19403 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19404 					/* OK, restore attach event */
19405 					cportinfo->cport_event_flags |=
19406 					    SATA_EVNT_DEVICE_ATTACHED;
19407 				} else {
19408 					/* Timeout - cannot identify device */
19409 					cportinfo->cport_dev_attach_time = 0;
19410 					sata_log(sata_hba_inst,
19411 					    CE_WARN,
19412 					    "Could not identify SATA device "
19413 					    "at port %d",
19414 					    saddr->cport);
19415 				}
19416 			} else {
19417 				/*
19418 				 * Start tracking time for device
19419 				 * identification.
19420 				 * Save current time (lbolt value).
19421 				 */
19422 				cportinfo->cport_dev_attach_time =
19423 				    ddi_get_lbolt();
19424 				/* Restore attach event */
19425 				cportinfo->cport_event_flags |=
19426 				    SATA_EVNT_DEVICE_ATTACHED;
19427 			}
19428 		} else if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19429 			cportinfo->cport_dev_attach_time = 0;
19430 			sata_log(sata_hba_inst, CE_NOTE,
19431 			    "SATA port-multiplier detected at port %d",
19432 			    saddr->cport);
19433 
19434 			if (SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL) {
19435 				/* Log the info of new port multiplier */
19436 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19437 				    saddr->cport)->cport_mutex);
19438 				sata_show_pmult_info(sata_hba_inst,
19439 				    &sata_device);
19440 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19441 				    saddr->cport)->cport_mutex);
19442 			}
19443 
19444 			ASSERT(SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL);
19445 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
19446 			for (npmport = 0; npmport <
19447 			    pmultinfo->pmult_num_dev_ports; npmport++) {
19448 				pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19449 				    saddr->cport, npmport);
19450 				ASSERT(pmportinfo != NULL);
19451 
19452 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19453 				    saddr->cport)->cport_mutex);
19454 				mutex_enter(&pmportinfo->pmport_mutex);
19455 				/* Marked all pmports with link events. */
19456 				pmportinfo->pmport_event_flags =
19457 				    SATA_EVNT_LINK_ESTABLISHED;
19458 				pmult_event_flags |=
19459 				    pmportinfo->pmport_event_flags;
19460 				mutex_exit(&pmportinfo->pmport_mutex);
19461 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19462 				    saddr->cport)->cport_mutex);
19463 			}
19464 			/* Auto-online is not available for PMult now. */
19465 
19466 		} else {
19467 			/*
19468 			 * If device was successfully attached, the subsequent
19469 			 * action depends on a state of the
19470 			 * sata_auto_online variable. If it is set to zero.
19471 			 * an explicit 'configure' command will be needed to
19472 			 * configure it. If its value is non-zero, we will
19473 			 * attempt to online (configure) the device.
19474 			 * First, log the message indicating that a device
19475 			 * was attached.
19476 			 */
19477 			cportinfo->cport_dev_attach_time = 0;
19478 			sata_log(sata_hba_inst, CE_WARN,
19479 			    "SATA device detected at port %d", saddr->cport);
19480 
19481 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19482 				sata_drive_info_t new_sdinfo;
19483 
19484 				/* Log device info data */
19485 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
19486 				    cportinfo));
19487 				sata_show_drive_info(sata_hba_inst,
19488 				    &new_sdinfo);
19489 			}
19490 
19491 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19492 			    saddr->cport)->cport_mutex);
19493 
19494 			/*
19495 			 * Make sure that there is no target node for that
19496 			 * device. If so, release it. It should not happen,
19497 			 * unless we had problem removing the node when
19498 			 * device was detached.
19499 			 */
19500 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19501 			    saddr->cport, saddr->pmport);
19502 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19503 			    saddr->cport)->cport_mutex);
19504 			if (tdip != NULL) {
19505 
19506 #ifdef SATA_DEBUG
19507 				if ((cportinfo->cport_event_flags &
19508 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19509 					sata_log(sata_hba_inst, CE_WARN,
19510 					    "sata_process_device_attached: "
19511 					    "old device target node exists!");
19512 #endif
19513 				/*
19514 				 * target node exists - try to unconfigure
19515 				 * device and remove the node.
19516 				 */
19517 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19518 				    saddr->cport)->cport_mutex);
19519 				rval = ndi_devi_offline(tdip,
19520 				    NDI_DEVI_REMOVE);
19521 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19522 				    saddr->cport)->cport_mutex);
19523 
19524 				if (rval == NDI_SUCCESS) {
19525 					cportinfo->cport_event_flags &=
19526 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19527 					cportinfo->cport_tgtnode_clean = B_TRUE;
19528 				} else {
19529 					/*
19530 					 * PROBLEM - the target node remained
19531 					 * and it belongs to a previously
19532 					 * attached device.
19533 					 * This happens when the file was open
19534 					 * or the node was waiting for
19535 					 * resources at the time the
19536 					 * associated device was removed.
19537 					 * Instruct event daemon to retry the
19538 					 * cleanup later.
19539 					 */
19540 					sata_log(sata_hba_inst,
19541 					    CE_WARN,
19542 					    "Application(s) accessing "
19543 					    "previously attached SATA "
19544 					    "device have to release "
19545 					    "it before newly inserted "
19546 					    "device can be made accessible.",
19547 					    saddr->cport);
19548 					cportinfo->cport_event_flags |=
19549 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19550 					cportinfo->cport_tgtnode_clean =
19551 					    B_FALSE;
19552 				}
19553 			}
19554 			if (sata_auto_online != 0) {
19555 				cportinfo->cport_event_flags |=
19556 				    SATA_EVNT_AUTOONLINE_DEVICE;
19557 			}
19558 
19559 		}
19560 	} else {
19561 		cportinfo->cport_dev_attach_time = 0;
19562 	}
19563 
19564 	event_flags = cportinfo->cport_event_flags;
19565 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19566 	if (event_flags != 0 || pmult_event_flags != 0) {
19567 		mutex_enter(&sata_hba_inst->satahba_mutex);
19568 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19569 		mutex_exit(&sata_hba_inst->satahba_mutex);
19570 		mutex_enter(&sata_mutex);
19571 		sata_event_pending |= SATA_EVNT_MAIN;
19572 		mutex_exit(&sata_mutex);
19573 	}
19574 }
19575 
19576 /*
19577  * Port Multiplier Port Device Attached Event processing.
19578  *
19579  * NOTE: No Mutex should be hold.
19580  */
19581 static void
19582 sata_process_pmdevice_attached(sata_hba_inst_t *sata_hba_inst,
19583     sata_address_t *saddr)
19584 {
19585 	sata_pmport_info_t *pmportinfo;
19586 	sata_drive_info_t *sdinfo;
19587 	sata_device_t sata_device;
19588 	dev_info_t *tdip;
19589 	uint32_t event_flags;
19590 	uint8_t cport = saddr->cport;
19591 	uint8_t pmport = saddr->pmport;
19592 	int rval;
19593 
19594 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19595 	    "Processing port %d:%d device attached", cport, pmport);
19596 
19597 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19598 
19599 	mutex_enter(&pmportinfo->pmport_mutex);
19600 
19601 	/* Clear attach event flag first */
19602 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19603 
19604 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19605 	if ((pmportinfo->pmport_state &
19606 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19607 		pmportinfo->pmport_dev_attach_time = 0;
19608 		mutex_exit(&pmportinfo->pmport_mutex);
19609 		return;
19610 	}
19611 
19612 	/*
19613 	 * If the sata_drive_info structure is found attached to the port info,
19614 	 * despite the fact the device was removed and now it is re-attached,
19615 	 * the old drive info structure was not removed.
19616 	 * Arbitrarily release device info structure.
19617 	 */
19618 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19619 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19620 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19621 		(void) kmem_free((void *)sdinfo,
19622 		    sizeof (sata_drive_info_t));
19623 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19624 		    "Arbitrarily detaching old device info.", NULL);
19625 	}
19626 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19627 
19628 	/* For sanity, re-probe the port */
19629 	sata_device.satadev_rev = SATA_DEVICE_REV;
19630 	sata_device.satadev_addr = *saddr;
19631 
19632 	/*
19633 	 * We have to exit mutex, because the HBA probe port function may
19634 	 * block on its own mutex.
19635 	 */
19636 	mutex_exit(&pmportinfo->pmport_mutex);
19637 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19638 	    (SATA_DIP(sata_hba_inst), &sata_device);
19639 	mutex_enter(&pmportinfo->pmport_mutex);
19640 
19641 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19642 	if (rval != SATA_SUCCESS) {
19643 		/* Something went wrong? Fail the port */
19644 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19645 		pmportinfo->pmport_dev_attach_time = 0;
19646 		mutex_exit(&pmportinfo->pmport_mutex);
19647 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19648 		    "SATA port %d:%d probing failed", cport, pmport));
19649 		return;
19650 	} else {
19651 		/* pmport probed successfully */
19652 		pmportinfo->pmport_state |=
19653 		    SATA_STATE_PROBED | SATA_STATE_READY;
19654 	}
19655 	/*
19656 	 * Check if a device is still attached. For sanity, check also
19657 	 * link status - if no link, there is no device.
19658 	 */
19659 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19660 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19661 	    SATA_DTYPE_NONE) {
19662 		/*
19663 		 * No device - ignore attach event.
19664 		 */
19665 		pmportinfo->pmport_dev_attach_time = 0;
19666 		mutex_exit(&pmportinfo->pmport_mutex);
19667 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19668 		    "Ignoring attach - no device connected to port %d:%d",
19669 		    cport, pmport);
19670 		return;
19671 	}
19672 
19673 	mutex_exit(&pmportinfo->pmport_mutex);
19674 	/*
19675 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19676 	 * with the hint: SE_HINT_INSERT
19677 	 */
19678 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19679 
19680 	/*
19681 	 * Port reprobing will take care of the creation of the device
19682 	 * info structure and determination of the device type.
19683 	 */
19684 	sata_device.satadev_addr = *saddr;
19685 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19686 	    SATA_DEV_IDENTIFY_NORETRY);
19687 
19688 	mutex_enter(&pmportinfo->pmport_mutex);
19689 	if ((pmportinfo->pmport_state & SATA_STATE_READY) &&
19690 	    (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE)) {
19691 		/* Some device is attached to the port */
19692 		if (pmportinfo->pmport_dev_type == SATA_DTYPE_UNKNOWN) {
19693 			/*
19694 			 * A device was not successfully attached.
19695 			 * Track retry time for device identification.
19696 			 */
19697 			if (pmportinfo->pmport_dev_attach_time != 0) {
19698 				clock_t cur_time = ddi_get_lbolt();
19699 				/*
19700 				 * If the retry time limit was not exceeded,
19701 				 * reinstate attach event.
19702 				 */
19703 				if ((cur_time -
19704 				    pmportinfo->pmport_dev_attach_time) <
19705 				    drv_usectohz(
19706 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19707 					/* OK, restore attach event */
19708 					pmportinfo->pmport_event_flags |=
19709 					    SATA_EVNT_DEVICE_ATTACHED;
19710 				} else {
19711 					/* Timeout - cannot identify device */
19712 					pmportinfo->pmport_dev_attach_time = 0;
19713 					sata_log(sata_hba_inst, CE_WARN,
19714 					    "Could not identify SATA device "
19715 					    "at port %d:%d",
19716 					    cport, pmport);
19717 				}
19718 			} else {
19719 				/*
19720 				 * Start tracking time for device
19721 				 * identification.
19722 				 * Save current time (lbolt value).
19723 				 */
19724 				pmportinfo->pmport_dev_attach_time =
19725 				    ddi_get_lbolt();
19726 				/* Restore attach event */
19727 				pmportinfo->pmport_event_flags |=
19728 				    SATA_EVNT_DEVICE_ATTACHED;
19729 			}
19730 		} else {
19731 			/*
19732 			 * If device was successfully attached, the subsequent
19733 			 * action depends on a state of the
19734 			 * sata_auto_online variable. If it is set to zero.
19735 			 * an explicit 'configure' command will be needed to
19736 			 * configure it. If its value is non-zero, we will
19737 			 * attempt to online (configure) the device.
19738 			 * First, log the message indicating that a device
19739 			 * was attached.
19740 			 */
19741 			pmportinfo->pmport_dev_attach_time = 0;
19742 			sata_log(sata_hba_inst, CE_WARN,
19743 			    "SATA device detected at port %d:%d",
19744 			    cport, pmport);
19745 
19746 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19747 				sata_drive_info_t new_sdinfo;
19748 
19749 				/* Log device info data */
19750 				new_sdinfo = *(SATA_PMPORTINFO_DRV_INFO(
19751 				    pmportinfo));
19752 				sata_show_drive_info(sata_hba_inst,
19753 				    &new_sdinfo);
19754 			}
19755 
19756 			mutex_exit(&pmportinfo->pmport_mutex);
19757 
19758 			/*
19759 			 * Make sure that there is no target node for that
19760 			 * device. If so, release it. It should not happen,
19761 			 * unless we had problem removing the node when
19762 			 * device was detached.
19763 			 */
19764 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19765 			    saddr->cport, saddr->pmport);
19766 			mutex_enter(&pmportinfo->pmport_mutex);
19767 			if (tdip != NULL) {
19768 
19769 #ifdef SATA_DEBUG
19770 				if ((pmportinfo->pmport_event_flags &
19771 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19772 					sata_log(sata_hba_inst, CE_WARN,
19773 					    "sata_process_device_attached: "
19774 					    "old device target node exists!");
19775 #endif
19776 				/*
19777 				 * target node exists - try to unconfigure
19778 				 * device and remove the node.
19779 				 */
19780 				mutex_exit(&pmportinfo->pmport_mutex);
19781 				rval = ndi_devi_offline(tdip,
19782 				    NDI_DEVI_REMOVE);
19783 				mutex_enter(&pmportinfo->pmport_mutex);
19784 
19785 				if (rval == NDI_SUCCESS) {
19786 					pmportinfo->pmport_event_flags &=
19787 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19788 					pmportinfo->pmport_tgtnode_clean =
19789 					    B_TRUE;
19790 				} else {
19791 					/*
19792 					 * PROBLEM - the target node remained
19793 					 * and it belongs to a previously
19794 					 * attached device.
19795 					 * This happens when the file was open
19796 					 * or the node was waiting for
19797 					 * resources at the time the
19798 					 * associated device was removed.
19799 					 * Instruct event daemon to retry the
19800 					 * cleanup later.
19801 					 */
19802 					sata_log(sata_hba_inst,
19803 					    CE_WARN,
19804 					    "Application(s) accessing "
19805 					    "previously attached SATA "
19806 					    "device have to release "
19807 					    "it before newly inserted "
19808 					    "device can be made accessible."
19809 					    "at port %d:%d",
19810 					    cport, pmport);
19811 					pmportinfo->pmport_event_flags |=
19812 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19813 					pmportinfo->pmport_tgtnode_clean =
19814 					    B_FALSE;
19815 				}
19816 			}
19817 			if (sata_auto_online != 0) {
19818 				pmportinfo->pmport_event_flags |=
19819 				    SATA_EVNT_AUTOONLINE_DEVICE;
19820 			}
19821 
19822 		}
19823 	} else {
19824 		pmportinfo->pmport_dev_attach_time = 0;
19825 	}
19826 
19827 	event_flags = pmportinfo->pmport_event_flags;
19828 	mutex_exit(&pmportinfo->pmport_mutex);
19829 	if (event_flags != 0) {
19830 		mutex_enter(&sata_hba_inst->satahba_mutex);
19831 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19832 		mutex_exit(&sata_hba_inst->satahba_mutex);
19833 		mutex_enter(&sata_mutex);
19834 		sata_event_pending |= SATA_EVNT_MAIN;
19835 		mutex_exit(&sata_mutex);
19836 	}
19837 
19838 	/* clear the reset_in_progress events */
19839 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19840 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
19841 			/* must clear flags on cport */
19842 			sata_pmult_info_t *pminfo =
19843 			    SATA_PMULT_INFO(sata_hba_inst,
19844 			    saddr->cport);
19845 			pminfo->pmult_event_flags |=
19846 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19847 		}
19848 	}
19849 }
19850 
19851 /*
19852  * Device Target Node Cleanup Event processing.
19853  * If the target node associated with a sata port device is in
19854  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
19855  * If the target node cannot be removed, the event flag is left intact,
19856  * so that event daemon may re-run this function later.
19857  *
19858  * This function cannot be called in interrupt context (it may sleep).
19859  *
19860  * NOTE: Processes cport events only, not port multiplier ports.
19861  */
19862 static void
19863 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19864     sata_address_t *saddr)
19865 {
19866 	sata_cport_info_t *cportinfo;
19867 	dev_info_t *tdip;
19868 
19869 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19870 	    "Processing port %d device target node cleanup", saddr->cport);
19871 
19872 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19873 
19874 	/*
19875 	 * Check if there is target node for that device and it is in the
19876 	 * DEVI_DEVICE_REMOVED state. If so, release it.
19877 	 */
19878 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19879 	    saddr->pmport);
19880 	if (tdip != NULL) {
19881 		/*
19882 		 * target node exists - check if it is target node of
19883 		 * a removed device.
19884 		 */
19885 		if (sata_check_device_removed(tdip) == B_TRUE) {
19886 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19887 			    "sata_process_target_node_cleanup: "
19888 			    "old device target node exists!", NULL);
19889 			/*
19890 			 * Unconfigure and remove the target node
19891 			 */
19892 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
19893 			    NDI_SUCCESS) {
19894 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19895 				    saddr->cport)->cport_mutex);
19896 				cportinfo->cport_event_flags &=
19897 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19898 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19899 				    saddr->cport)->cport_mutex);
19900 				return;
19901 			}
19902 			/*
19903 			 * Event daemon will retry the cleanup later.
19904 			 */
19905 			mutex_enter(&sata_hba_inst->satahba_mutex);
19906 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19907 			mutex_exit(&sata_hba_inst->satahba_mutex);
19908 			mutex_enter(&sata_mutex);
19909 			sata_event_pending |= SATA_EVNT_MAIN;
19910 			mutex_exit(&sata_mutex);
19911 		}
19912 	} else {
19913 		if (saddr->qual == SATA_ADDR_CPORT ||
19914 		    saddr->qual == SATA_ADDR_DCPORT) {
19915 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19916 			    saddr->cport)->cport_mutex);
19917 			cportinfo->cport_event_flags &=
19918 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19919 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19920 			    saddr->cport)->cport_mutex);
19921 		} else {
19922 			/* sanity check */
19923 			if (SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) !=
19924 			    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
19925 			    saddr->cport) == NULL)
19926 				return;
19927 			if (SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19928 			    saddr->pmport) == NULL)
19929 				return;
19930 
19931 			mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19932 			    saddr->cport, saddr->pmport)->pmport_mutex);
19933 			SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19934 			    saddr->pmport)->pmport_event_flags &=
19935 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19936 			mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19937 			    saddr->cport, saddr->pmport)->pmport_mutex);
19938 		}
19939 	}
19940 }
19941 
19942 /*
19943  * Device AutoOnline Event processing.
19944  * If attached device is to be onlined, an attempt is made to online this
19945  * device, but only if there is no lingering (old) target node present.
19946  * If the device cannot be onlined, the event flag is left intact,
19947  * so that event daemon may re-run this function later.
19948  *
19949  * This function cannot be called in interrupt context (it may sleep).
19950  *
19951  * NOTE: Processes cport events only, not port multiplier ports.
19952  */
19953 static void
19954 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
19955     sata_address_t *saddr)
19956 {
19957 	sata_cport_info_t *cportinfo;
19958 	sata_drive_info_t *sdinfo;
19959 	sata_device_t sata_device;
19960 	dev_info_t *tdip;
19961 
19962 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19963 	    "Processing port %d attached device auto-onlining", saddr->cport);
19964 
19965 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19966 
19967 	/*
19968 	 * Check if device is present and recognized. If not, reset event.
19969 	 */
19970 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19971 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
19972 		/* Nothing to online */
19973 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19974 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19975 		    saddr->cport)->cport_mutex);
19976 		return;
19977 	}
19978 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19979 
19980 	/*
19981 	 * Check if there is target node for this device and if it is in the
19982 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
19983 	 * the event for later processing.
19984 	 */
19985 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19986 	    saddr->pmport);
19987 	if (tdip != NULL) {
19988 		/*
19989 		 * target node exists - check if it is target node of
19990 		 * a removed device.
19991 		 */
19992 		if (sata_check_device_removed(tdip) == B_TRUE) {
19993 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19994 			    "sata_process_device_autoonline: "
19995 			    "old device target node exists!", NULL);
19996 			/*
19997 			 * Event daemon will retry device onlining later.
19998 			 */
19999 			mutex_enter(&sata_hba_inst->satahba_mutex);
20000 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20001 			mutex_exit(&sata_hba_inst->satahba_mutex);
20002 			mutex_enter(&sata_mutex);
20003 			sata_event_pending |= SATA_EVNT_MAIN;
20004 			mutex_exit(&sata_mutex);
20005 			return;
20006 		}
20007 		/*
20008 		 * If the target node is not in the 'removed" state, assume
20009 		 * that it belongs to this device. There is nothing more to do,
20010 		 * but reset the event.
20011 		 */
20012 	} else {
20013 
20014 		/*
20015 		 * Try to online the device
20016 		 * If there is any reset-related event, remove it. We are
20017 		 * configuring the device and no state restoring is needed.
20018 		 */
20019 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20020 		    saddr->cport)->cport_mutex);
20021 		sata_device.satadev_addr = *saddr;
20022 		if (saddr->qual == SATA_ADDR_CPORT)
20023 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
20024 		else
20025 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
20026 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
20027 		if (sdinfo != NULL) {
20028 			if (sdinfo->satadrv_event_flags &
20029 			    (SATA_EVNT_DEVICE_RESET |
20030 			    SATA_EVNT_INPROC_DEVICE_RESET))
20031 				sdinfo->satadrv_event_flags = 0;
20032 			sdinfo->satadrv_event_flags |=
20033 			    SATA_EVNT_CLEAR_DEVICE_RESET;
20034 
20035 			/* Need to create a new target node. */
20036 			cportinfo->cport_tgtnode_clean = B_TRUE;
20037 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20038 			    saddr->cport)->cport_mutex);
20039 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
20040 			    sata_hba_inst, &sata_device.satadev_addr);
20041 			if (tdip == NULL) {
20042 				/*
20043 				 * Configure (onlining) failed.
20044 				 * We will NOT retry
20045 				 */
20046 				SATA_LOG_D((sata_hba_inst, CE_WARN,
20047 				    "sata_process_device_autoonline: "
20048 				    "configuring SATA device at port %d failed",
20049 				    saddr->cport));
20050 			}
20051 		} else {
20052 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20053 			    saddr->cport)->cport_mutex);
20054 		}
20055 
20056 	}
20057 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
20058 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
20059 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20060 	    saddr->cport)->cport_mutex);
20061 }
20062 
20063 
20064 static void
20065 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
20066     int hint)
20067 {
20068 	char ap[MAXPATHLEN];
20069 	nvlist_t *ev_attr_list = NULL;
20070 	int err;
20071 
20072 	/* Allocate and build sysevent attribute list */
20073 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
20074 	if (err != 0) {
20075 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20076 		    "sata_gen_sysevent: "
20077 		    "cannot allocate memory for sysevent attributes\n"));
20078 		return;
20079 	}
20080 	/* Add hint attribute */
20081 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
20082 	if (err != 0) {
20083 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20084 		    "sata_gen_sysevent: "
20085 		    "failed to add DR_HINT attr for sysevent"));
20086 		nvlist_free(ev_attr_list);
20087 		return;
20088 	}
20089 	/*
20090 	 * Add AP attribute.
20091 	 * Get controller pathname and convert it into AP pathname by adding
20092 	 * a target number.
20093 	 */
20094 	(void) snprintf(ap, MAXPATHLEN, "/devices");
20095 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
20096 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
20097 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
20098 
20099 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
20100 	if (err != 0) {
20101 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20102 		    "sata_gen_sysevent: "
20103 		    "failed to add DR_AP_ID attr for sysevent"));
20104 		nvlist_free(ev_attr_list);
20105 		return;
20106 	}
20107 
20108 	/* Generate/log sysevent */
20109 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
20110 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
20111 	if (err != DDI_SUCCESS) {
20112 		SATA_LOG_D((sata_hba_inst, CE_WARN,
20113 		    "sata_gen_sysevent: "
20114 		    "cannot log sysevent, err code %x\n", err));
20115 	}
20116 
20117 	nvlist_free(ev_attr_list);
20118 }
20119 
20120 
20121 
20122 
20123 /*
20124  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
20125  */
20126 static void
20127 sata_set_device_removed(dev_info_t *tdip)
20128 {
20129 	int circ;
20130 
20131 	ASSERT(tdip != NULL);
20132 
20133 	ndi_devi_enter(tdip, &circ);
20134 	mutex_enter(&DEVI(tdip)->devi_lock);
20135 	DEVI_SET_DEVICE_REMOVED(tdip);
20136 	mutex_exit(&DEVI(tdip)->devi_lock);
20137 	ndi_devi_exit(tdip, circ);
20138 }
20139 
20140 
20141 /*
20142  * Set internal event instructing event daemon to try
20143  * to perform the target node cleanup.
20144  */
20145 static void
20146 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
20147     sata_address_t *saddr)
20148 {
20149 	if (saddr->qual == SATA_ADDR_CPORT ||
20150 	    saddr->qual == SATA_ADDR_DCPORT) {
20151 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
20152 		    saddr->cport)->cport_mutex);
20153 		SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
20154 		    SATA_EVNT_TARGET_NODE_CLEANUP;
20155 		SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
20156 		    cport_tgtnode_clean = B_FALSE;
20157 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
20158 		    saddr->cport)->cport_mutex);
20159 	} else {
20160 		mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
20161 		    saddr->cport, saddr->pmport)->pmport_mutex);
20162 		SATA_PMPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport,
20163 		    saddr->pmport) |= SATA_EVNT_TARGET_NODE_CLEANUP;
20164 		SATA_PMPORT_INFO(sata_hba_inst, saddr->cport, saddr->pmport)->
20165 		    pmport_tgtnode_clean = B_FALSE;
20166 		mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
20167 		    saddr->cport, saddr->pmport)->pmport_mutex);
20168 	}
20169 	mutex_enter(&sata_hba_inst->satahba_mutex);
20170 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
20171 	mutex_exit(&sata_hba_inst->satahba_mutex);
20172 	mutex_enter(&sata_mutex);
20173 	sata_event_pending |= SATA_EVNT_MAIN;
20174 	mutex_exit(&sata_mutex);
20175 }
20176 
20177 
20178 /*
20179  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
20180  * i.e. check if the target node state indicates that it belongs to a removed
20181  * device.
20182  *
20183  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
20184  * B_FALSE otherwise.
20185  */
20186 static boolean_t
20187 sata_check_device_removed(dev_info_t *tdip)
20188 {
20189 	ASSERT(tdip != NULL);
20190 
20191 	if (DEVI_IS_DEVICE_REMOVED(tdip))
20192 		return (B_TRUE);
20193 	else
20194 		return (B_FALSE);
20195 }
20196 
20197 /* ************************ FAULT INJECTTION **************************** */
20198 
20199 #ifdef SATA_INJECT_FAULTS
20200 
20201 static	uint32_t sata_fault_count = 0;
20202 static	uint32_t sata_fault_suspend_count = 0;
20203 
20204 /*
20205  * Inject sata pkt fault
20206  * It modifies returned values of the sata packet.
20207  * It returns immediately if:
20208  * pkt fault injection is not enabled (via sata_inject_fault,
20209  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
20210  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
20211  * pkt is not directed to specified fault controller/device
20212  * (sata_fault_ctrl_dev and sata_fault_device).
20213  * If fault controller is not specified, fault injection applies to all
20214  * controllers and devices.
20215  *
20216  * First argument is the pointer to the executed sata packet.
20217  * Second argument is a pointer to a value returned by the HBA tran_start
20218  * function.
20219  * Third argument specifies injected error. Injected sata packet faults
20220  * are the satapkt_reason values.
20221  * SATA_PKT_BUSY		-1	Not completed, busy
20222  * SATA_PKT_DEV_ERROR		1	Device reported error
20223  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
20224  * SATA_PKT_PORT_ERROR		3	Not completed, port error
20225  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
20226  * SATA_PKT_ABORTED		5	Aborted by request
20227  * SATA_PKT_TIMEOUT		6	Operation timeut
20228  * SATA_PKT_RESET		7	Aborted by reset request
20229  *
20230  * Additional global variables affecting the execution:
20231  *
20232  * sata_inject_fault_count variable specifies number of times in row the
20233  * error is injected. Value of -1 specifies permanent fault, ie. every time
20234  * the fault injection point is reached, the fault is injected and a pause
20235  * between fault injection specified by sata_inject_fault_pause_count is
20236  * ignored). Fault injection routine decrements sata_inject_fault_count
20237  * (if greater than zero) until it reaches 0. No fault is injected when
20238  * sata_inject_fault_count is 0 (zero).
20239  *
20240  * sata_inject_fault_pause_count variable specifies number of times a fault
20241  * injection is bypassed (pause between fault injections).
20242  * If set to 0, a fault is injected only a number of times specified by
20243  * sata_inject_fault_count.
20244  *
20245  * The fault counts are static, so for periodic errors they have to be manually
20246  * reset to start repetition sequence from scratch.
20247  * If the original value returned by the HBA tran_start function is not
20248  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
20249  * is injected (to avoid masking real problems);
20250  *
20251  * NOTE: In its current incarnation, this function should be invoked only for
20252  * commands executed in SYNCHRONOUS mode.
20253  */
20254 
20255 
20256 static void
20257 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
20258 {
20259 
20260 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
20261 		return;
20262 
20263 	if (sata_inject_fault_count == 0)
20264 		return;
20265 
20266 	if (fault == 0)
20267 		return;
20268 
20269 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
20270 		return;
20271 
20272 	if (sata_fault_ctrl != NULL) {
20273 		sata_pkt_txlate_t *spx =
20274 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
20275 
20276 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
20277 		    spx->txlt_sata_hba_inst->satahba_dip)
20278 			return;
20279 
20280 		if (sata_fault_device.satadev_addr.cport !=
20281 		    spkt->satapkt_device.satadev_addr.cport ||
20282 		    sata_fault_device.satadev_addr.pmport !=
20283 		    spkt->satapkt_device.satadev_addr.pmport ||
20284 		    sata_fault_device.satadev_addr.qual !=
20285 		    spkt->satapkt_device.satadev_addr.qual)
20286 			return;
20287 	}
20288 
20289 	/* Modify pkt return parameters */
20290 	if (*rval != SATA_TRAN_ACCEPTED ||
20291 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
20292 		sata_fault_count = 0;
20293 		sata_fault_suspend_count = 0;
20294 		return;
20295 	}
20296 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
20297 		/* Pause in the injection */
20298 		sata_fault_suspend_count -= 1;
20299 		return;
20300 	}
20301 
20302 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
20303 		/*
20304 		 * Init inject fault cycle. If fault count is set to -1,
20305 		 * it is a permanent fault.
20306 		 */
20307 		if (sata_inject_fault_count != -1) {
20308 			sata_fault_count = sata_inject_fault_count;
20309 			sata_fault_suspend_count =
20310 			    sata_inject_fault_pause_count;
20311 			if (sata_fault_suspend_count == 0)
20312 				sata_inject_fault_count = 0;
20313 		}
20314 	}
20315 
20316 	if (sata_fault_count != 0)
20317 		sata_fault_count -= 1;
20318 
20319 	switch (fault) {
20320 	case SATA_PKT_BUSY:
20321 		*rval = SATA_TRAN_BUSY;
20322 		spkt->satapkt_reason = SATA_PKT_BUSY;
20323 		break;
20324 
20325 	case SATA_PKT_QUEUE_FULL:
20326 		*rval = SATA_TRAN_QUEUE_FULL;
20327 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
20328 		break;
20329 
20330 	case SATA_PKT_CMD_UNSUPPORTED:
20331 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
20332 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
20333 		break;
20334 
20335 	case SATA_PKT_PORT_ERROR:
20336 		/* This is "rejected" command */
20337 		*rval = SATA_TRAN_PORT_ERROR;
20338 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
20339 		/* Additional error setup could be done here - port state */
20340 		break;
20341 
20342 	case SATA_PKT_DEV_ERROR:
20343 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
20344 		/*
20345 		 * Additional error setup could be done here
20346 		 */
20347 		break;
20348 
20349 	case SATA_PKT_ABORTED:
20350 		spkt->satapkt_reason = SATA_PKT_ABORTED;
20351 		break;
20352 
20353 	case SATA_PKT_TIMEOUT:
20354 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
20355 		/* Additional error setup could be done here */
20356 		break;
20357 
20358 	case SATA_PKT_RESET:
20359 		spkt->satapkt_reason = SATA_PKT_RESET;
20360 		/*
20361 		 * Additional error setup could be done here - device reset
20362 		 */
20363 		break;
20364 
20365 	default:
20366 		break;
20367 	}
20368 }
20369 
20370 #endif
20371 
20372 /*
20373  * SATA Trace Ring Buffer
20374  * ----------------------
20375  *
20376  * Overview
20377  *
20378  * The SATA trace ring buffer is a ring buffer created and managed by
20379  * the SATA framework module that can be used by any module or driver
20380  * within the SATA framework to store debug messages.
20381  *
20382  * Ring Buffer Interfaces:
20383  *
20384  *	sata_vtrace_debug()	<-- Adds debug message to ring buffer
20385  *	sata_trace_debug()	<-- Wraps varargs into sata_vtrace_debug()
20386  *
20387  *	Note that the sata_trace_debug() interface was created to give
20388  *	consumers the flexibilty of sending debug messages to ring buffer
20389  *	as variable arguments.  Consumers can send type va_list debug
20390  *	messages directly to sata_vtrace_debug(). The sata_trace_debug()
20391  *	and sata_vtrace_debug() relationship is similar to that of
20392  *	cmn_err(9F) and vcmn_err(9F).
20393  *
20394  * Below is a diagram of the SATA trace ring buffer interfaces and
20395  * sample consumers:
20396  *
20397  * +---------------------------------+
20398  * |    o  o  SATA Framework Module  |
20399  * | o  SATA  o     +------------------+      +------------------+
20400  * |o   Trace  o <--|sata_vtrace_debug/|<-----|SATA HBA Driver #1|
20401  * |o   R-Buf  o    |sata_trace_debug  |<--+  +------------------+
20402  * | o        o     +------------------+   |  +------------------+
20403  * |    o  o                ^        |     +--|SATA HBA Driver #2|
20404  * |                        |        |        +------------------+
20405  * |           +------------------+  |
20406  * |           |SATA Debug Message|  |
20407  * |           +------------------+  |
20408  * +---------------------------------+
20409  *
20410  * Supporting Routines:
20411  *
20412  *	sata_trace_rbuf_alloc()	<-- Initializes ring buffer
20413  *	sata_trace_rbuf_free()	<-- Destroys ring buffer
20414  *	sata_trace_dmsg_alloc() <-- Creates or reuses buffer in ring buffer
20415  *	sata_trace_dmsg_free()	<-- Destroys content of ring buffer
20416  *
20417  * The default SATA trace ring buffer size is defined by DMSG_RING_SIZE.
20418  * The ring buffer size can be adjusted by setting dmsg_ring_size in
20419  * /etc/system to desired size in unit of bytes.
20420  *
20421  * The individual debug message size in the ring buffer is restricted
20422  * to DMSG_BUF_SIZE.
20423  */
20424 void
20425 sata_vtrace_debug(dev_info_t *dip, const char *fmt, va_list ap)
20426 {
20427 	sata_trace_dmsg_t *dmsg;
20428 
20429 	if (sata_debug_rbuf == NULL) {
20430 		return;
20431 	}
20432 
20433 	/*
20434 	 * If max size of ring buffer is smaller than size
20435 	 * required for one debug message then just return
20436 	 * since we have no room for the debug message.
20437 	 */
20438 	if (sata_debug_rbuf->maxsize < (sizeof (sata_trace_dmsg_t))) {
20439 		return;
20440 	}
20441 
20442 	mutex_enter(&sata_debug_rbuf->lock);
20443 
20444 	/* alloc or reuse on ring buffer */
20445 	dmsg = sata_trace_dmsg_alloc();
20446 
20447 	if (dmsg == NULL) {
20448 		/* resource allocation failed */
20449 		mutex_exit(&sata_debug_rbuf->lock);
20450 		return;
20451 	}
20452 
20453 	dmsg->dip = dip;
20454 	gethrestime(&dmsg->timestamp);
20455 
20456 	(void) vsnprintf(dmsg->buf, sizeof (dmsg->buf), fmt, ap);
20457 
20458 	mutex_exit(&sata_debug_rbuf->lock);
20459 }
20460 
20461 void
20462 sata_trace_debug(dev_info_t *dip, const char *fmt, ...)
20463 {
20464 	va_list ap;
20465 
20466 	va_start(ap, fmt);
20467 	sata_vtrace_debug(dip, fmt, ap);
20468 	va_end(ap);
20469 }
20470 
20471 /*
20472  * This routine is used to manage debug messages
20473  * on ring buffer.
20474  */
20475 static sata_trace_dmsg_t *
20476 sata_trace_dmsg_alloc(void)
20477 {
20478 	sata_trace_dmsg_t *dmsg_alloc, *dmsg = sata_debug_rbuf->dmsgp;
20479 
20480 	if (sata_debug_rbuf->looped == TRUE) {
20481 		sata_debug_rbuf->dmsgp = dmsg->next;
20482 		return (sata_debug_rbuf->dmsgp);
20483 	}
20484 
20485 	/*
20486 	 * If we're looping for the first time,
20487 	 * connect the ring.
20488 	 */
20489 	if (((sata_debug_rbuf->size + (sizeof (sata_trace_dmsg_t))) >
20490 	    sata_debug_rbuf->maxsize) && (sata_debug_rbuf->dmsgh != NULL)) {
20491 		dmsg->next = sata_debug_rbuf->dmsgh;
20492 		sata_debug_rbuf->dmsgp = sata_debug_rbuf->dmsgh;
20493 		sata_debug_rbuf->looped = TRUE;
20494 		return (sata_debug_rbuf->dmsgp);
20495 	}
20496 
20497 	/* If we've gotten this far then memory allocation is needed */
20498 	dmsg_alloc = kmem_zalloc(sizeof (sata_trace_dmsg_t), KM_NOSLEEP);
20499 	if (dmsg_alloc == NULL) {
20500 		sata_debug_rbuf->allocfailed++;
20501 		return (dmsg_alloc);
20502 	} else {
20503 		sata_debug_rbuf->size += sizeof (sata_trace_dmsg_t);
20504 	}
20505 
20506 	if (sata_debug_rbuf->dmsgp != NULL) {
20507 		dmsg->next = dmsg_alloc;
20508 		sata_debug_rbuf->dmsgp = dmsg->next;
20509 		return (sata_debug_rbuf->dmsgp);
20510 	} else {
20511 		/*
20512 		 * We should only be here if we're initializing
20513 		 * the ring buffer.
20514 		 */
20515 		if (sata_debug_rbuf->dmsgh == NULL) {
20516 			sata_debug_rbuf->dmsgh = dmsg_alloc;
20517 		} else {
20518 			/* Something is wrong */
20519 			kmem_free(dmsg_alloc, sizeof (sata_trace_dmsg_t));
20520 			return (NULL);
20521 		}
20522 
20523 		sata_debug_rbuf->dmsgp = dmsg_alloc;
20524 		return (sata_debug_rbuf->dmsgp);
20525 	}
20526 }
20527 
20528 
20529 /*
20530  * Free all messages on debug ring buffer.
20531  */
20532 static void
20533 sata_trace_dmsg_free(void)
20534 {
20535 	sata_trace_dmsg_t *dmsg_next, *dmsg = sata_debug_rbuf->dmsgh;
20536 
20537 	while (dmsg != NULL) {
20538 		dmsg_next = dmsg->next;
20539 		kmem_free(dmsg, sizeof (sata_trace_dmsg_t));
20540 
20541 		/*
20542 		 * If we've looped around the ring than we're done.
20543 		 */
20544 		if (dmsg_next == sata_debug_rbuf->dmsgh) {
20545 			break;
20546 		} else {
20547 			dmsg = dmsg_next;
20548 		}
20549 	}
20550 }
20551 
20552 
20553 /*
20554  * This function can block
20555  */
20556 static void
20557 sata_trace_rbuf_alloc(void)
20558 {
20559 	sata_debug_rbuf = kmem_zalloc(sizeof (sata_trace_rbuf_t), KM_SLEEP);
20560 
20561 	mutex_init(&sata_debug_rbuf->lock, NULL, MUTEX_DRIVER, NULL);
20562 
20563 	if (dmsg_ring_size > 0) {
20564 		sata_debug_rbuf->maxsize = (size_t)dmsg_ring_size;
20565 	}
20566 }
20567 
20568 
20569 static void
20570 sata_trace_rbuf_free(void)
20571 {
20572 	sata_trace_dmsg_free();
20573 	mutex_destroy(&sata_debug_rbuf->lock);
20574 	kmem_free(sata_debug_rbuf, sizeof (sata_trace_rbuf_t));
20575 }
20576 
20577 /*
20578  * If SATA_DEBUG is not defined then this routine is called instead
20579  * of sata_log() via the SATA_LOG_D macro.
20580  */
20581 static void
20582 sata_trace_log(sata_hba_inst_t *sata_hba_inst, uint_t level,
20583     const char *fmt, ...)
20584 {
20585 #ifndef __lock_lint
20586 	_NOTE(ARGUNUSED(level))
20587 #endif
20588 
20589 	dev_info_t *dip = NULL;
20590 	va_list ap;
20591 
20592 	if (sata_hba_inst != NULL) {
20593 		dip = SATA_DIP(sata_hba_inst);
20594 	}
20595 
20596 	va_start(ap, fmt);
20597 	sata_vtrace_debug(dip, fmt, ap);
20598 	va_end(ap);
20599 }
20600