xref: /titanic_52/usr/src/uts/common/io/sata/impl/sata.c (revision 1e6f4912c04ba197d638cc6eb5b35eeae672df40)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 
28 /*
29  * SATA Framework
30  * Generic SATA Host Adapter Implementation
31  */
32 
33 #include <sys/conf.h>
34 #include <sys/file.h>
35 #include <sys/ddi.h>
36 #include <sys/sunddi.h>
37 #include <sys/modctl.h>
38 #include <sys/cmn_err.h>
39 #include <sys/errno.h>
40 #include <sys/thread.h>
41 #include <sys/kstat.h>
42 #include <sys/note.h>
43 #include <sys/sysevent.h>
44 #include <sys/sysevent/eventdefs.h>
45 #include <sys/sysevent/dr.h>
46 #include <sys/taskq.h>
47 #include <sys/disp.h>
48 
49 #include <sys/sata/impl/sata.h>
50 #include <sys/sata/sata_hba.h>
51 #include <sys/sata/sata_defs.h>
52 #include <sys/sata/sata_cfgadm.h>
53 #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_request_sense(sata_pkt_txlate_t *);
205 static	int sata_txlt_read(sata_pkt_txlate_t *);
206 static	int sata_txlt_write(sata_pkt_txlate_t *);
207 static	int sata_txlt_log_sense(sata_pkt_txlate_t *);
208 static	int sata_txlt_log_select(sata_pkt_txlate_t *);
209 static	int sata_txlt_mode_sense(sata_pkt_txlate_t *);
210 static	int sata_txlt_mode_select(sata_pkt_txlate_t *);
211 static	int sata_txlt_ata_pass_thru(sata_pkt_txlate_t *);
212 static	int sata_txlt_synchronize_cache(sata_pkt_txlate_t *);
213 static	int sata_txlt_write_buffer(sata_pkt_txlate_t *);
214 static	int sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *);
215 
216 static	int sata_hba_start(sata_pkt_txlate_t *, int *);
217 static	int sata_txlt_invalid_command(sata_pkt_txlate_t *);
218 static	int sata_txlt_check_condition(sata_pkt_txlate_t *, uchar_t, uchar_t);
219 static	int sata_txlt_lba_out_of_range(sata_pkt_txlate_t *);
220 static	int sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *);
221 static	void sata_txlt_rw_completion(sata_pkt_t *);
222 static	void sata_txlt_nodata_cmd_completion(sata_pkt_t *);
223 static	void sata_txlt_apt_completion(sata_pkt_t *sata_pkt);
224 static	void sata_txlt_download_mcode_cmd_completion(sata_pkt_t *);
225 static	int sata_emul_rw_completion(sata_pkt_txlate_t *);
226 static	void sata_fill_ata_return_desc(sata_pkt_t *, uint8_t, uint8_t,
227     uint8_t);
228 static	struct scsi_extended_sense *sata_immediate_error_response(
229     sata_pkt_txlate_t *, int);
230 static	struct scsi_extended_sense *sata_arq_sense(sata_pkt_txlate_t *);
231 
232 static	int sata_txlt_atapi(sata_pkt_txlate_t *);
233 static	void sata_txlt_atapi_completion(sata_pkt_t *);
234 
235 /*
236  * Local functions for ioctl
237  */
238 static	int32_t sata_get_port_num(sata_hba_inst_t *,  struct devctl_iocdata *);
239 static	void sata_cfgadm_state(sata_hba_inst_t *, int32_t,
240     devctl_ap_state_t *);
241 static	dev_info_t *sata_get_target_dip(dev_info_t *, uint8_t, uint8_t);
242 static	dev_info_t *sata_get_scsi_target_dip(dev_info_t *, sata_address_t *);
243 static	dev_info_t *sata_devt_to_devinfo(dev_t);
244 static	int sata_ioctl_connect(sata_hba_inst_t *, sata_device_t *);
245 static	int sata_ioctl_disconnect(sata_hba_inst_t *, sata_device_t *);
246 static	int sata_ioctl_configure(sata_hba_inst_t *, sata_device_t *);
247 static	int sata_ioctl_unconfigure(sata_hba_inst_t *, sata_device_t *);
248 static	int sata_ioctl_activate(sata_hba_inst_t *, sata_device_t *);
249 static	int sata_ioctl_deactivate(sata_hba_inst_t *, sata_device_t *);
250 static	int sata_ioctl_reset_port(sata_hba_inst_t *, sata_device_t *);
251 static	int sata_ioctl_reset_device(sata_hba_inst_t *, sata_device_t *);
252 static	int sata_ioctl_reset_all(sata_hba_inst_t *);
253 static	int sata_ioctl_port_self_test(sata_hba_inst_t *, sata_device_t *);
254 static	int sata_ioctl_get_device_path(sata_hba_inst_t *, sata_device_t *,
255     sata_ioctl_data_t *, int mode);
256 static	int sata_ioctl_get_ap_type(sata_hba_inst_t *, sata_device_t *,
257     sata_ioctl_data_t *, int mode);
258 static	int sata_ioctl_get_model_info(sata_hba_inst_t *, sata_device_t *,
259     sata_ioctl_data_t *, int mode);
260 static	int sata_ioctl_get_revfirmware_info(sata_hba_inst_t *, sata_device_t *,
261     sata_ioctl_data_t *, int mode);
262 static	int sata_ioctl_get_serialnumber_info(sata_hba_inst_t *,
263     sata_device_t *, sata_ioctl_data_t *, int mode);
264 
265 /*
266  * Local functions
267  */
268 static 	void sata_remove_hba_instance(dev_info_t *);
269 static 	int sata_validate_sata_hba_tran(dev_info_t *, sata_hba_tran_t *);
270 static 	void sata_probe_ports(sata_hba_inst_t *);
271 static	void sata_probe_pmports(sata_hba_inst_t *, uint8_t);
272 static 	int sata_reprobe_port(sata_hba_inst_t *, sata_device_t *, int);
273 static 	int sata_reprobe_pmult(sata_hba_inst_t *, sata_device_t *, int);
274 static 	int sata_reprobe_pmport(sata_hba_inst_t *, sata_device_t *, int);
275 static	int sata_alloc_pmult(sata_hba_inst_t *, sata_device_t *);
276 static	void sata_free_pmult(sata_hba_inst_t *, sata_device_t *);
277 static 	int sata_add_device(dev_info_t *, sata_hba_inst_t *, sata_device_t *);
278 static	int sata_offline_device(sata_hba_inst_t *, sata_device_t *,
279     sata_drive_info_t *);
280 static 	dev_info_t *sata_create_target_node(dev_info_t *, sata_hba_inst_t *,
281     sata_address_t *);
282 static 	void sata_remove_target_node(sata_hba_inst_t *,
283     sata_address_t *);
284 static 	int sata_validate_scsi_address(sata_hba_inst_t *,
285     struct scsi_address *, sata_device_t *);
286 static 	int sata_validate_sata_address(sata_hba_inst_t *, int, int, int);
287 static	sata_pkt_t *sata_pkt_alloc(sata_pkt_txlate_t *, int (*)(caddr_t));
288 static	void sata_pkt_free(sata_pkt_txlate_t *);
289 static	int sata_dma_buf_setup(sata_pkt_txlate_t *, int, int (*)(caddr_t),
290     caddr_t, ddi_dma_attr_t *);
291 static	void sata_common_free_dma_rsrcs(sata_pkt_txlate_t *);
292 static	int sata_probe_device(sata_hba_inst_t *, sata_device_t *);
293 static	sata_drive_info_t *sata_get_device_info(sata_hba_inst_t *,
294     sata_device_t *);
295 static 	int sata_identify_device(sata_hba_inst_t *, sata_drive_info_t *);
296 static	void sata_reidentify_device(sata_pkt_txlate_t *);
297 static	struct buf *sata_alloc_local_buffer(sata_pkt_txlate_t *, int);
298 static 	void sata_free_local_buffer(sata_pkt_txlate_t *);
299 static 	uint64_t sata_check_capacity(sata_drive_info_t *);
300 void 	sata_adjust_dma_attr(sata_drive_info_t *, ddi_dma_attr_t *,
301     ddi_dma_attr_t *);
302 static 	int sata_fetch_device_identify_data(sata_hba_inst_t *,
303     sata_drive_info_t *);
304 static	void sata_update_port_info(sata_hba_inst_t *, sata_device_t *);
305 static	void sata_update_pmport_info(sata_hba_inst_t *, sata_device_t *);
306 static	void sata_update_port_scr(sata_port_scr_t *, sata_device_t *);
307 static	int sata_set_dma_mode(sata_hba_inst_t *, sata_drive_info_t *);
308 static	int sata_set_cache_mode(sata_hba_inst_t *, sata_drive_info_t *, int);
309 static	int sata_set_rmsn(sata_hba_inst_t *, sata_drive_info_t *, int);
310 static	int sata_set_drive_features(sata_hba_inst_t *,
311     sata_drive_info_t *, int flag);
312 static	void sata_init_write_cache_mode(sata_drive_info_t *sdinfo);
313 static	int sata_initialize_device(sata_hba_inst_t *, sata_drive_info_t *);
314 static	void sata_identdev_to_inquiry(sata_hba_inst_t *, sata_drive_info_t *,
315     uint8_t *);
316 static	int sata_get_atapi_inquiry_data(sata_hba_inst_t *, sata_address_t *,
317     struct scsi_inquiry *);
318 static	int sata_build_msense_page_1(sata_drive_info_t *, int, uint8_t *);
319 static	int sata_build_msense_page_8(sata_drive_info_t *, int, uint8_t *);
320 static	int sata_build_msense_page_1a(sata_drive_info_t *, int, uint8_t *);
321 static	int sata_build_msense_page_1c(sata_drive_info_t *, int, uint8_t *);
322 static	int sata_build_msense_page_30(sata_drive_info_t *, int, uint8_t *);
323 static	int sata_mode_select_page_8(sata_pkt_txlate_t *,
324     struct mode_cache_scsi3 *, int, int *, int *, int *);
325 static	int sata_mode_select_page_1a(sata_pkt_txlate_t *,
326     struct mode_info_power_cond *, int, int *, int *, int *);
327 static	int sata_mode_select_page_1c(sata_pkt_txlate_t *,
328     struct mode_info_excpt_page *, int, int *, int *, int *);
329 static	int sata_mode_select_page_30(sata_pkt_txlate_t *,
330     struct mode_acoustic_management *, int, int *, int *, int *);
331 
332 static	int sata_build_lsense_page_0(sata_drive_info_t *, uint8_t *);
333 static	int sata_build_lsense_page_10(sata_drive_info_t *, uint8_t *,
334     sata_hba_inst_t *);
335 static	int sata_build_lsense_page_2f(sata_drive_info_t *, uint8_t *,
336     sata_hba_inst_t *);
337 static	int sata_build_lsense_page_30(sata_drive_info_t *, uint8_t *,
338     sata_hba_inst_t *);
339 static	int sata_build_lsense_page_0e(sata_drive_info_t *, uint8_t *,
340     sata_pkt_txlate_t *);
341 
342 static	void sata_set_arq_data(sata_pkt_t *);
343 static	void sata_build_read_verify_cmd(sata_cmd_t *, uint16_t, uint64_t);
344 static	void sata_build_generic_cmd(sata_cmd_t *, uint8_t);
345 static	uint8_t sata_get_standby_timer(uint8_t *timer);
346 
347 static	void sata_save_drive_settings(sata_drive_info_t *);
348 static	void sata_show_drive_info(sata_hba_inst_t *, sata_drive_info_t *);
349 static	void sata_show_pmult_info(sata_hba_inst_t *, sata_device_t *);
350 static	void sata_log(sata_hba_inst_t *, uint_t, char *fmt, ...);
351 static	void sata_trace_log(sata_hba_inst_t *, uint_t, const char *fmt, ...);
352 static	int sata_fetch_smart_return_status(sata_hba_inst_t *,
353     sata_drive_info_t *);
354 static	int sata_fetch_smart_data(sata_hba_inst_t *, sata_drive_info_t *,
355     struct smart_data *);
356 static	int sata_smart_selftest_log(sata_hba_inst_t *,
357     sata_drive_info_t *,
358     struct smart_selftest_log *);
359 static	int sata_ext_smart_selftest_read_log(sata_hba_inst_t *,
360     sata_drive_info_t *, struct smart_ext_selftest_log *, uint16_t);
361 static	int sata_smart_read_log(sata_hba_inst_t *, sata_drive_info_t *,
362     uint8_t *, uint8_t, uint8_t);
363 static	int sata_read_log_ext_directory(sata_hba_inst_t *, sata_drive_info_t *,
364     struct read_log_ext_directory *);
365 static	void sata_gen_sysevent(sata_hba_inst_t *, sata_address_t *, int);
366 static	void sata_xlate_errors(sata_pkt_txlate_t *);
367 static	void sata_decode_device_error(sata_pkt_txlate_t *,
368     struct scsi_extended_sense *);
369 static	void sata_set_device_removed(dev_info_t *);
370 static	boolean_t sata_check_device_removed(dev_info_t *);
371 static	void sata_set_target_node_cleanup(sata_hba_inst_t *, sata_address_t *);
372 static	int sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *,
373     sata_drive_info_t *);
374 static	int sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *,
375     sata_drive_info_t *);
376 static	void sata_atapi_packet_cmd_setup(sata_cmd_t *, sata_drive_info_t *);
377 static	void sata_fixed_sense_data_preset(struct scsi_extended_sense *);
378 static  void sata_target_devid_register(dev_info_t *, sata_drive_info_t *);
379 static  int sata_check_modser(char *, int);
380 
381 
382 
383 /*
384  * SATA Framework will ignore SATA HBA driver cb_ops structure and
385  * register following one with SCSA framework.
386  * Open & close are provided, so scsi framework will not use its own
387  */
388 static struct cb_ops sata_cb_ops = {
389 	sata_hba_open,			/* open */
390 	sata_hba_close,			/* close */
391 	nodev,				/* strategy */
392 	nodev,				/* print */
393 	nodev,				/* dump */
394 	nodev,				/* read */
395 	nodev,				/* write */
396 	sata_hba_ioctl,			/* ioctl */
397 	nodev,				/* devmap */
398 	nodev,				/* mmap */
399 	nodev,				/* segmap */
400 	nochpoll,			/* chpoll */
401 	ddi_prop_op,			/* cb_prop_op */
402 	0,				/* streamtab */
403 	D_NEW | D_MP,			/* cb_flag */
404 	CB_REV,				/* rev */
405 	nodev,				/* aread */
406 	nodev				/* awrite */
407 };
408 
409 
410 extern struct mod_ops mod_miscops;
411 extern uchar_t	scsi_cdb_size[];
412 
413 static struct modlmisc modlmisc = {
414 	&mod_miscops,			/* Type of module */
415 	"SATA Module"			/* module name */
416 };
417 
418 
419 static struct modlinkage modlinkage = {
420 	MODREV_1,
421 	(void *)&modlmisc,
422 	NULL
423 };
424 
425 /*
426  * Default sata pkt timeout. Used when a target driver scsi_pkt time is zero,
427  * i.e. when scsi_pkt has not timeout specified.
428  */
429 static int sata_default_pkt_time = 60;	/* 60 seconds */
430 
431 /*
432  * Intermediate buffer device access attributes - they are required,
433  * but not necessarily used.
434  */
435 static ddi_device_acc_attr_t sata_acc_attr = {
436 	DDI_DEVICE_ATTR_V0,
437 	DDI_STRUCTURE_LE_ACC,
438 	DDI_STRICTORDER_ACC
439 };
440 
441 
442 /*
443  * Mutexes protecting structures in multithreaded operations.
444  * Because events are relatively rare, a single global mutex protecting
445  * data structures should be sufficient. To increase performance, add
446  * separate mutex per each sata port and use global mutex only to protect
447  * common data structures.
448  */
449 static	kmutex_t sata_mutex;		/* protects sata_hba_list */
450 static	kmutex_t sata_log_mutex;	/* protects log */
451 
452 static 	char sata_log_buf[256];
453 
454 /*
455  * sata trace debug
456  */
457 static	sata_trace_rbuf_t *sata_debug_rbuf;
458 static	sata_trace_dmsg_t *sata_trace_dmsg_alloc(void);
459 static	void sata_trace_dmsg_free(void);
460 static	void sata_trace_rbuf_alloc(void);
461 static	void sata_trace_rbuf_free(void);
462 
463 int	dmsg_ring_size = DMSG_RING_SIZE;
464 
465 /* Default write cache setting for SATA hard disks */
466 int	sata_write_cache = 1;		/* enabled */
467 
468 /* Default write cache setting for SATA ATAPI CD/DVD */
469 int	sata_atapicdvd_write_cache = 1; /* enabled */
470 
471 /* Default write cache setting for SATA ATAPI tape */
472 int	sata_atapitape_write_cache = 1; /* enabled */
473 
474 /* Default write cache setting for SATA ATAPI disk */
475 int	sata_atapidisk_write_cache = 1;	/* enabled */
476 
477 /*
478  * Linked list of HBA instances
479  */
480 static 	sata_hba_inst_t *sata_hba_list = NULL;
481 static 	sata_hba_inst_t *sata_hba_list_tail = NULL;
482 /*
483  * Pointer to per-instance SATA HBA soft structure is stored in sata_hba_tran
484  * structure and in sata soft state.
485  */
486 
487 /*
488  * Event daemon related variables
489  */
490 static 	kmutex_t sata_event_mutex;
491 static 	kcondvar_t sata_event_cv;
492 static 	kthread_t *sata_event_thread = NULL;
493 static 	int sata_event_thread_terminate = 0;
494 static 	int sata_event_pending = 0;
495 static 	int sata_event_thread_active = 0;
496 extern 	pri_t minclsyspri;
497 
498 /*
499  * NCQ error recovery command
500  */
501 static const sata_cmd_t sata_rle_cmd = {
502 	SATA_CMD_REV,
503 	NULL,
504 	{
505 		SATA_DIR_READ
506 	},
507 	ATA_ADDR_LBA48,
508 	0,
509 	0,
510 	0,
511 	0,
512 	0,
513 	1,
514 	READ_LOG_EXT_NCQ_ERROR_RECOVERY,
515 	0,
516 	0,
517 	0,
518 	SATAC_READ_LOG_EXT,
519 	0,
520 	0,
521 	0,
522 };
523 
524 /*
525  * ATAPI error recovery CDB
526  */
527 static const uint8_t sata_rqsense_cdb[SATA_ATAPI_RQSENSE_CDB_LEN] = {
528 	SCMD_REQUEST_SENSE,
529 	0,			/* Only fixed RQ format is supported */
530 	0,
531 	0,
532 	SATA_ATAPI_MIN_RQSENSE_LEN, /* Less data may be returned */
533 	0
534 };
535 
536 
537 /* Warlock directives */
538 
539 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_hba_tran))
540 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_device))
541 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_ops))
542 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_extended_sense))
543 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", scsi_arq_status))
544 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_attr))
545 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", ddi_dma_cookie_t))
546 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", devctl_ap_state))
547 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", dev_info::devi_state))
548 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_list))
549 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_list))
550 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_next))
551 _NOTE(MUTEX_PROTECTS_DATA(sata_mutex, sata_hba_inst::satahba_prev))
552 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", \
553     sata_hba_inst::satahba_scsi_tran))
554 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_tran))
555 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_hba_inst::satahba_dip))
556 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_hba_inst::satahba_attached))
557 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_hba_inst::satahba_dev_port))
558 _NOTE(MUTEX_PROTECTS_DATA(sata_hba_inst::satahba_mutex,
559     sata_hba_inst::satahba_event_flags))
560 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
561     sata_cport_info::cport_devp))
562 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_devp))
563 _NOTE(SCHEME_PROTECTS_DATA("Scheme", sata_cport_info::cport_addr))
564 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
565     sata_cport_info::cport_dev_type))
566 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_dev_type))
567 _NOTE(MUTEX_PROTECTS_DATA(sata_cport_info::cport_mutex, \
568     sata_cport_info::cport_state))
569 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_cport_info::cport_state))
570 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
571     sata_pmport_info::pmport_state))
572 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_state))
573 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
574     sata_pmport_info::pmport_dev_type))
575 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_dev_type))
576 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
577     sata_pmport_info::pmport_sata_drive))
578 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
579     sata_pmport_info::pmport_tgtnode_clean))
580 _NOTE(MUTEX_PROTECTS_DATA(sata_pmport_info::pmport_mutex, \
581     sata_pmport_info::pmport_event_flags))
582 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmport_info::pmport_sata_drive))
583 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_dev_port))
584 _NOTE(DATA_READABLE_WITHOUT_LOCK(sata_pmult_info::pmult_num_dev_ports))
585 #ifdef SATA_DEBUG
586 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuf_count))
587 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", mbuffail_count))
588 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace))
589 _NOTE(SCHEME_PROTECTS_DATA("No Mutex Needed", sata_atapi_trace_index))
590 #endif
591 
592 /* End of warlock directives */
593 
594 /* ************** loadable module configuration functions ************** */
595 
596 int
597 _init()
598 {
599 	int rval;
600 
601 	mutex_init(&sata_mutex, NULL, MUTEX_DRIVER, NULL);
602 	mutex_init(&sata_event_mutex, NULL, MUTEX_DRIVER, NULL);
603 	mutex_init(&sata_log_mutex, NULL, MUTEX_DRIVER, NULL);
604 	cv_init(&sata_event_cv, NULL, CV_DRIVER, NULL);
605 	sata_trace_rbuf_alloc();
606 	if ((rval = mod_install(&modlinkage)) != 0) {
607 #ifdef SATA_DEBUG
608 		cmn_err(CE_WARN, "sata: _init: mod_install failed\n");
609 #endif
610 		sata_trace_rbuf_free();
611 		mutex_destroy(&sata_log_mutex);
612 		cv_destroy(&sata_event_cv);
613 		mutex_destroy(&sata_event_mutex);
614 		mutex_destroy(&sata_mutex);
615 	}
616 	return (rval);
617 }
618 
619 int
620 _fini()
621 {
622 	int rval;
623 
624 	if ((rval = mod_remove(&modlinkage)) != 0)
625 		return (rval);
626 
627 	sata_trace_rbuf_free();
628 	mutex_destroy(&sata_log_mutex);
629 	cv_destroy(&sata_event_cv);
630 	mutex_destroy(&sata_event_mutex);
631 	mutex_destroy(&sata_mutex);
632 	return (rval);
633 }
634 
635 int
636 _info(struct modinfo *modinfop)
637 {
638 	return (mod_info(&modlinkage, modinfop));
639 }
640 
641 
642 
643 /* ********************* SATA HBA entry points ********************* */
644 
645 
646 /*
647  * Called by SATA HBA from _init().
648  * Registers HBA driver instance/sata framework pair with scsi framework, by
649  * calling scsi_hba_init().
650  *
651  * SATA HBA driver cb_ops are ignored - SATA HBA framework cb_ops are used
652  * instead. SATA HBA framework cb_ops pointer overwrites SATA HBA driver
653  * cb_ops pointer in SATA HBA driver dev_ops structure.
654  * SATA HBA framework cb_ops supplies cb_open cb_close and cb_ioctl vectors.
655  *
656  * Return status of the scsi_hba_init() is returned to a calling SATA HBA
657  * driver.
658  */
659 int
660 sata_hba_init(struct modlinkage *modlp)
661 {
662 	int rval;
663 	struct dev_ops *hba_ops;
664 
665 	SATADBG1(SATA_DBG_HBA_IF, NULL,
666 	    "sata_hba_init: name %s \n",
667 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
668 	/*
669 	 * Fill-up cb_ops and dev_ops when necessary
670 	 */
671 	hba_ops = ((struct modldrv *)(modlp->ml_linkage[0]))->drv_dev_ops;
672 	/*
673 	 * Provide pointer to SATA dev_ops
674 	 */
675 	hba_ops->devo_cb_ops = &sata_cb_ops;
676 
677 	/*
678 	 * Register SATA HBA with SCSI framework
679 	 */
680 	if ((rval = scsi_hba_init(modlp)) != 0) {
681 		SATADBG1(SATA_DBG_HBA_IF, NULL,
682 		    "sata_hba_init: scsi hba init failed\n", NULL);
683 		return (rval);
684 	}
685 
686 	return (0);
687 }
688 
689 
690 /* HBA attach stages */
691 #define	HBA_ATTACH_STAGE_SATA_HBA_INST	1
692 #define	HBA_ATTACH_STAGE_SCSI_ATTACHED	2
693 #define	HBA_ATTACH_STAGE_SETUP		4
694 #define	HBA_ATTACH_STAGE_LINKED		8
695 
696 
697 /*
698  *
699  * Called from SATA HBA driver's attach routine to attach an instance of
700  * the HBA.
701  *
702  * For DDI_ATTACH command:
703  * sata_hba_inst structure is allocated here and initialized with pointers to
704  * SATA framework implementation of required scsi tran functions.
705  * The scsi_tran's tran_hba_private field is used by SATA Framework to point
706  * to the soft structure (sata_hba_inst) allocated by SATA framework for
707  * SATA HBA instance related data.
708  * The scsi_tran's tran_hba_private field is used by SATA framework to
709  * store a pointer to per-HBA-instance of sata_hba_inst structure.
710  * The sata_hba_inst structure is cross-linked to scsi tran structure.
711  * Among other info, a pointer to sata_hba_tran structure is stored in
712  * sata_hba_inst. The sata_hba_inst structures for different HBA instances are
713  * linked together into the list, pointed to by sata_hba_list.
714  * On the first HBA instance attach the sata event thread is initialized.
715  * Attachment points are created for all SATA ports of the HBA being attached.
716  * All HBA instance's SATA ports are probed and type of plugged devices is
717  * determined. For each device of a supported type, a target node is created.
718  *
719  * DDI_SUCCESS is returned when attachment process is successful,
720  * DDI_FAILURE is returned otherwise.
721  *
722  * For DDI_RESUME command:
723  * Not implemented at this time (postponed until phase 2 of the development).
724  */
725 int
726 sata_hba_attach(dev_info_t *dip, sata_hba_tran_t *sata_tran,
727     ddi_attach_cmd_t cmd)
728 {
729 	sata_hba_inst_t	*sata_hba_inst;
730 	scsi_hba_tran_t *scsi_tran = NULL;
731 	int hba_attach_state = 0;
732 	char taskq_name[MAXPATHLEN];
733 
734 	SATADBG3(SATA_DBG_HBA_IF, NULL,
735 	    "sata_hba_attach: node %s (%s%d)\n",
736 	    ddi_node_name(dip), ddi_driver_name(dip),
737 	    ddi_get_instance(dip));
738 
739 	if (cmd == DDI_RESUME) {
740 		/*
741 		 * Postponed until phase 2 of the development
742 		 */
743 		return (DDI_FAILURE);
744 	}
745 
746 	if (cmd != DDI_ATTACH) {
747 		return (DDI_FAILURE);
748 	}
749 
750 	/* cmd == DDI_ATTACH */
751 
752 	if (sata_validate_sata_hba_tran(dip, sata_tran) != SATA_SUCCESS) {
753 		SATA_LOG_D((NULL, CE_WARN,
754 		    "sata_hba_attach: invalid sata_hba_tran"));
755 		return (DDI_FAILURE);
756 	}
757 	/*
758 	 * Allocate and initialize SCSI tran structure.
759 	 * SATA copy of tran_bus_config is provided to create port nodes.
760 	 */
761 	scsi_tran = scsi_hba_tran_alloc(dip, SCSI_HBA_CANSLEEP);
762 	if (scsi_tran == NULL)
763 		return (DDI_FAILURE);
764 	/*
765 	 * Allocate soft structure for SATA HBA instance.
766 	 * There is a separate softstate for each HBA instance.
767 	 */
768 	sata_hba_inst = kmem_zalloc(sizeof (struct sata_hba_inst), KM_SLEEP);
769 	ASSERT(sata_hba_inst != NULL); /* this should not fail */
770 	mutex_init(&sata_hba_inst->satahba_mutex, NULL, MUTEX_DRIVER, NULL);
771 	hba_attach_state |= HBA_ATTACH_STAGE_SATA_HBA_INST;
772 
773 	/*
774 	 * scsi_trans's tran_hba_private is used by SATA Framework to point to
775 	 * soft structure allocated by SATA framework for
776 	 * SATA HBA instance related data.
777 	 */
778 	scsi_tran->tran_hba_private	= sata_hba_inst;
779 	scsi_tran->tran_tgt_private	= NULL;
780 
781 	scsi_tran->tran_tgt_init	= sata_scsi_tgt_init;
782 	scsi_tran->tran_tgt_probe	= sata_scsi_tgt_probe;
783 	scsi_tran->tran_tgt_free	= sata_scsi_tgt_free;
784 
785 	scsi_tran->tran_start		= sata_scsi_start;
786 	scsi_tran->tran_reset		= sata_scsi_reset;
787 	scsi_tran->tran_abort		= sata_scsi_abort;
788 	scsi_tran->tran_getcap		= sata_scsi_getcap;
789 	scsi_tran->tran_setcap		= sata_scsi_setcap;
790 	scsi_tran->tran_init_pkt	= sata_scsi_init_pkt;
791 	scsi_tran->tran_destroy_pkt	= sata_scsi_destroy_pkt;
792 
793 	scsi_tran->tran_dmafree		= sata_scsi_dmafree;
794 	scsi_tran->tran_sync_pkt	= sata_scsi_sync_pkt;
795 
796 	scsi_tran->tran_reset_notify	= NULL;
797 	scsi_tran->tran_get_bus_addr	= NULL;
798 	scsi_tran->tran_quiesce		= NULL;
799 	scsi_tran->tran_unquiesce	= NULL;
800 	scsi_tran->tran_bus_reset	= NULL;
801 
802 	if (scsi_hba_attach_setup(dip, sata_tran->sata_tran_hba_dma_attr,
803 	    scsi_tran, 0) != DDI_SUCCESS) {
804 #ifdef SATA_DEBUG
805 		cmn_err(CE_WARN, "?SATA: %s%d hba scsi attach failed",
806 		    ddi_driver_name(dip), ddi_get_instance(dip));
807 #endif
808 		goto fail;
809 	}
810 	hba_attach_state |= HBA_ATTACH_STAGE_SCSI_ATTACHED;
811 
812 	if (!ddi_prop_exists(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "sata")) {
813 		if (ddi_prop_update_int(DDI_DEV_T_NONE, dip,
814 		    "sata", 1) != DDI_PROP_SUCCESS) {
815 			SATA_LOG_D((NULL, CE_WARN, "sata_hba_attach: "
816 			    "failed to create hba sata prop"));
817 			goto fail;
818 		}
819 	}
820 
821 	/*
822 	 * Save pointers in hba instance soft state.
823 	 */
824 	sata_hba_inst->satahba_scsi_tran = scsi_tran;
825 	sata_hba_inst->satahba_tran = sata_tran;
826 	sata_hba_inst->satahba_dip = dip;
827 
828 	/*
829 	 * Create a task queue to handle emulated commands completion
830 	 * Use node name, dash, instance number as the queue name.
831 	 */
832 	taskq_name[0] = '\0';
833 	(void) strlcat(taskq_name, DEVI(dip)->devi_node_name,
834 	    sizeof (taskq_name));
835 	(void) snprintf(taskq_name + strlen(taskq_name),
836 	    sizeof (taskq_name) - strlen(taskq_name),
837 	    "-%d", DEVI(dip)->devi_instance);
838 	sata_hba_inst->satahba_taskq = taskq_create(taskq_name, 1,
839 	    minclsyspri, 1, sata_tran->sata_tran_hba_num_cports * 4,
840 	    TASKQ_DYNAMIC);
841 
842 	hba_attach_state |= HBA_ATTACH_STAGE_SETUP;
843 
844 	/*
845 	 * Create events thread if not created yet.
846 	 */
847 	sata_event_thread_control(1);
848 
849 	/*
850 	 * Link this hba instance into the list.
851 	 */
852 	mutex_enter(&sata_mutex);
853 
854 	if (sata_hba_list == NULL) {
855 		/*
856 		 * The first instance of HBA is attached.
857 		 * Set current/active default maximum NCQ/TCQ queue depth for
858 		 * all SATA devices. It is done here and now, to eliminate the
859 		 * possibility of the dynamic, programatic modification of the
860 		 * queue depth via global (and public) sata_max_queue_depth
861 		 * variable (this would require special handling in HBA drivers)
862 		 */
863 		sata_current_max_qdepth = sata_max_queue_depth;
864 		if (sata_current_max_qdepth > 32)
865 			sata_current_max_qdepth = 32;
866 		else if (sata_current_max_qdepth < 1)
867 			sata_current_max_qdepth = 1;
868 	}
869 
870 	sata_hba_inst->satahba_next = NULL;
871 	sata_hba_inst->satahba_prev = sata_hba_list_tail;
872 	if (sata_hba_list == NULL) {
873 		sata_hba_list = sata_hba_inst;
874 	}
875 	if (sata_hba_list_tail != NULL) {
876 		sata_hba_list_tail->satahba_next = sata_hba_inst;
877 	}
878 	sata_hba_list_tail = sata_hba_inst;
879 	mutex_exit(&sata_mutex);
880 	hba_attach_state |= HBA_ATTACH_STAGE_LINKED;
881 
882 	/*
883 	 * Create SATA HBA devctl minor node for sata_hba_open, close, ioctl
884 	 * SATA HBA driver should not use its own open/close entry points.
885 	 *
886 	 * Make sure that instance number doesn't overflow
887 	 * when forming minor numbers.
888 	 */
889 	ASSERT(ddi_get_instance(dip) <= (L_MAXMIN >> INST_MINOR_SHIFT));
890 	if (ddi_create_minor_node(dip, "devctl", S_IFCHR,
891 	    INST2DEVCTL(ddi_get_instance(dip)),
892 	    DDI_NT_SATA_NEXUS, 0) != DDI_SUCCESS) {
893 #ifdef SATA_DEBUG
894 		cmn_err(CE_WARN, "sata_hba_attach: "
895 		    "cannot create devctl minor node");
896 #endif
897 		goto fail;
898 	}
899 
900 
901 	/*
902 	 * Set-up kstats here, if necessary.
903 	 * (postponed until future phase of the development).
904 	 */
905 
906 	/*
907 	 * Indicate that HBA is attached. This will enable events processing
908 	 * for this HBA.
909 	 */
910 	sata_hba_inst->satahba_attached = 1;
911 	/*
912 	 * Probe controller ports. This operation will describe a current
913 	 * controller/port/multipliers/device configuration and will create
914 	 * attachment points.
915 	 * We may end-up with just a controller with no devices attached.
916 	 * For the ports with a supported device attached, device target nodes
917 	 * are created and devices are initialized.
918 	 */
919 	sata_probe_ports(sata_hba_inst);
920 
921 	return (DDI_SUCCESS);
922 
923 fail:
924 	if (hba_attach_state & HBA_ATTACH_STAGE_LINKED) {
925 		(void) sata_remove_hba_instance(dip);
926 		if (sata_hba_list == NULL)
927 			sata_event_thread_control(0);
928 	}
929 
930 	if (hba_attach_state & HBA_ATTACH_STAGE_SETUP) {
931 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
932 		taskq_destroy(sata_hba_inst->satahba_taskq);
933 	}
934 
935 	if (hba_attach_state & HBA_ATTACH_STAGE_SCSI_ATTACHED)
936 		(void) scsi_hba_detach(dip);
937 
938 	if (hba_attach_state & HBA_ATTACH_STAGE_SATA_HBA_INST) {
939 		mutex_destroy(&sata_hba_inst->satahba_mutex);
940 		kmem_free((void *)sata_hba_inst,
941 		    sizeof (struct sata_hba_inst));
942 		scsi_hba_tran_free(scsi_tran);
943 	}
944 
945 	sata_log(NULL, CE_WARN, "?SATA: %s%d hba attach failed",
946 	    ddi_driver_name(dip), ddi_get_instance(dip));
947 
948 	return (DDI_FAILURE);
949 }
950 
951 
952 /*
953  * Called by SATA HBA from to detach an instance of the driver.
954  *
955  * For DDI_DETACH command:
956  * Free local structures allocated for SATA HBA instance during
957  * sata_hba_attach processing.
958  *
959  * Returns DDI_SUCCESS when HBA was detached, DDI_FAILURE otherwise.
960  *
961  * For DDI_SUSPEND command:
962  * Not implemented at this time (postponed until phase 2 of the development)
963  * Returnd DDI_SUCCESS.
964  *
965  * When the last HBA instance is detached, the event daemon is terminated.
966  *
967  * NOTE: Port multiplier is supported.
968  */
969 int
970 sata_hba_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
971 {
972 	dev_info_t	*tdip;
973 	sata_hba_inst_t	*sata_hba_inst;
974 	scsi_hba_tran_t *scsi_hba_tran;
975 	sata_cport_info_t *cportinfo;
976 	sata_pmult_info_t *pminfo;
977 	sata_drive_info_t *sdinfo;
978 	sata_device_t	sdevice;
979 	int ncport, npmport;
980 
981 	SATADBG3(SATA_DBG_HBA_IF, NULL, "sata_hba_detach: node %s (%s%d)\n",
982 	    ddi_node_name(dip), ddi_driver_name(dip), ddi_get_instance(dip));
983 
984 	switch (cmd) {
985 	case DDI_DETACH:
986 
987 		if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
988 			return (DDI_FAILURE);
989 
990 		sata_hba_inst = scsi_hba_tran->tran_hba_private;
991 		if (sata_hba_inst == NULL)
992 			return (DDI_FAILURE);
993 
994 		if (scsi_hba_detach(dip) == DDI_FAILURE) {
995 			sata_hba_inst->satahba_attached = 1;
996 			return (DDI_FAILURE);
997 		}
998 
999 		/*
1000 		 * Free all target nodes - at this point
1001 		 * devices should be at least offlined
1002 		 * otherwise scsi_hba_detach() should not be called.
1003 		 */
1004 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
1005 		    ncport++) {
1006 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
1007 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1008 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
1009 				if (sdinfo != NULL) {
1010 					tdip = sata_get_target_dip(dip,
1011 					    ncport, 0);
1012 					if (tdip != NULL) {
1013 						if (ndi_devi_offline(tdip,
1014 						    NDI_DEVI_REMOVE) !=
1015 						    NDI_SUCCESS) {
1016 							SATA_LOG_D((
1017 							    sata_hba_inst,
1018 							    CE_WARN,
1019 							    "sata_hba_detach: "
1020 							    "Target node not "
1021 							    "removed !"));
1022 							return (DDI_FAILURE);
1023 						}
1024 					}
1025 				}
1026 			} else { /* SATA_DTYPE_PMULT */
1027 				mutex_enter(&cportinfo->cport_mutex);
1028 				pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
1029 
1030 				if (pminfo == NULL) {
1031 					SATA_LOG_D((sata_hba_inst, CE_WARN,
1032 					    "sata_hba_detach: Port multiplier "
1033 					    "not ready yet!"));
1034 					mutex_exit(&cportinfo->cport_mutex);
1035 					return (DDI_FAILURE);
1036 				}
1037 
1038 				/*
1039 				 * Detach would fail if removal of any of the
1040 				 * target nodes is failed - albeit in that
1041 				 * case some of them may have been removed.
1042 				 */
1043 				for (npmport = 0; npmport < SATA_NUM_PMPORTS(
1044 				    sata_hba_inst, ncport); npmport++) {
1045 					tdip = sata_get_target_dip(dip, ncport,
1046 					    npmport);
1047 					if (tdip != NULL) {
1048 						if (ndi_devi_offline(tdip,
1049 						    NDI_DEVI_REMOVE) !=
1050 						    NDI_SUCCESS) {
1051 							SATA_LOG_D((
1052 							    sata_hba_inst,
1053 							    CE_WARN,
1054 							    "sata_hba_detach: "
1055 							    "Target node not "
1056 							    "removed !"));
1057 							mutex_exit(&cportinfo->
1058 							    cport_mutex);
1059 							return (DDI_FAILURE);
1060 						}
1061 					}
1062 				}
1063 				mutex_exit(&cportinfo->cport_mutex);
1064 			}
1065 		}
1066 		/*
1067 		 * Disable sata event daemon processing for this HBA
1068 		 */
1069 		sata_hba_inst->satahba_attached = 0;
1070 
1071 		/*
1072 		 * Remove event daemon thread, if it is last HBA instance.
1073 		 */
1074 
1075 		mutex_enter(&sata_mutex);
1076 		if (sata_hba_list->satahba_next == NULL) {
1077 			mutex_exit(&sata_mutex);
1078 			sata_event_thread_control(0);
1079 			mutex_enter(&sata_mutex);
1080 		}
1081 		mutex_exit(&sata_mutex);
1082 
1083 		/* Remove this HBA instance from the HBA list */
1084 		sata_remove_hba_instance(dip);
1085 
1086 		/*
1087 		 * At this point there should be no target nodes attached.
1088 		 * Detach and destroy device and port info structures.
1089 		 */
1090 		for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst);
1091 		    ncport++) {
1092 			cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
1093 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
1094 				sdinfo =
1095 				    cportinfo->cport_devp.cport_sata_drive;
1096 				if (sdinfo != NULL) {
1097 					/* Release device structure */
1098 					kmem_free(sdinfo,
1099 					    sizeof (sata_drive_info_t));
1100 				}
1101 				/* Release cport info */
1102 				mutex_destroy(&cportinfo->cport_mutex);
1103 				kmem_free(cportinfo,
1104 				    sizeof (sata_cport_info_t));
1105 			} else { /* SATA_DTYPE_PMULT */
1106 				sdevice.satadev_addr.cport = (uint8_t)ncport;
1107 				sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
1108 				sata_free_pmult(sata_hba_inst, &sdevice);
1109 			}
1110 		}
1111 
1112 		scsi_hba_tran_free(sata_hba_inst->satahba_scsi_tran);
1113 
1114 		(void) ddi_prop_remove(DDI_DEV_T_ANY, dip, "sata");
1115 
1116 		taskq_destroy(sata_hba_inst->satahba_taskq);
1117 
1118 		mutex_destroy(&sata_hba_inst->satahba_mutex);
1119 		kmem_free((void *)sata_hba_inst,
1120 		    sizeof (struct sata_hba_inst));
1121 
1122 		return (DDI_SUCCESS);
1123 
1124 	case DDI_SUSPEND:
1125 		/*
1126 		 * Postponed until phase 2
1127 		 */
1128 		return (DDI_FAILURE);
1129 
1130 	default:
1131 		return (DDI_FAILURE);
1132 	}
1133 }
1134 
1135 
1136 /*
1137  * Called by an HBA drive from _fini() routine.
1138  * Unregisters SATA HBA instance/SATA framework pair from the scsi framework.
1139  */
1140 void
1141 sata_hba_fini(struct modlinkage *modlp)
1142 {
1143 	SATADBG1(SATA_DBG_HBA_IF, NULL,
1144 	    "sata_hba_fini: name %s\n",
1145 	    ((struct modldrv *)(modlp->ml_linkage[0]))->drv_linkinfo);
1146 
1147 	scsi_hba_fini(modlp);
1148 }
1149 
1150 
1151 /*
1152  * Default open and close routine for sata_hba framework.
1153  *
1154  */
1155 /*
1156  * Open devctl node.
1157  *
1158  * Returns:
1159  * 0 if node was open successfully, error code otherwise.
1160  *
1161  *
1162  */
1163 
1164 static int
1165 sata_hba_open(dev_t *devp, int flags, int otyp, cred_t *credp)
1166 {
1167 #ifndef __lock_lint
1168 	_NOTE(ARGUNUSED(credp))
1169 #endif
1170 	int rv = 0;
1171 	dev_info_t *dip;
1172 	scsi_hba_tran_t *scsi_hba_tran;
1173 	sata_hba_inst_t	*sata_hba_inst;
1174 
1175 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_open: entered", NULL);
1176 
1177 	if (otyp != OTYP_CHR)
1178 		return (EINVAL);
1179 
1180 	dip = sata_devt_to_devinfo(*devp);
1181 	if (dip == NULL)
1182 		return (ENXIO);
1183 
1184 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1185 		return (ENXIO);
1186 
1187 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1188 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1189 		return (ENXIO);
1190 
1191 	mutex_enter(&sata_mutex);
1192 	if (flags & FEXCL) {
1193 		if (sata_hba_inst->satahba_open_flag != 0) {
1194 			rv = EBUSY;
1195 		} else {
1196 			sata_hba_inst->satahba_open_flag =
1197 			    SATA_DEVCTL_EXOPENED;
1198 		}
1199 	} else {
1200 		if (sata_hba_inst->satahba_open_flag == SATA_DEVCTL_EXOPENED) {
1201 			rv = EBUSY;
1202 		} else {
1203 			sata_hba_inst->satahba_open_flag =
1204 			    SATA_DEVCTL_SOPENED;
1205 		}
1206 	}
1207 	mutex_exit(&sata_mutex);
1208 
1209 	return (rv);
1210 }
1211 
1212 
1213 /*
1214  * Close devctl node.
1215  * Returns:
1216  * 0 if node was closed successfully, error code otherwise.
1217  *
1218  */
1219 
1220 static int
1221 sata_hba_close(dev_t dev, int flag, int otyp, cred_t *credp)
1222 {
1223 #ifndef __lock_lint
1224 	_NOTE(ARGUNUSED(credp))
1225 	_NOTE(ARGUNUSED(flag))
1226 #endif
1227 	dev_info_t *dip;
1228 	scsi_hba_tran_t *scsi_hba_tran;
1229 	sata_hba_inst_t	*sata_hba_inst;
1230 
1231 	SATADBG1(SATA_DBG_IOCTL_IF, NULL, "sata_hba_close: entered", NULL);
1232 
1233 	if (otyp != OTYP_CHR)
1234 		return (EINVAL);
1235 
1236 	dip = sata_devt_to_devinfo(dev);
1237 	if (dip == NULL)
1238 		return (ENXIO);
1239 
1240 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1241 		return (ENXIO);
1242 
1243 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1244 	if (sata_hba_inst == NULL || sata_hba_inst->satahba_attached == 0)
1245 		return (ENXIO);
1246 
1247 	mutex_enter(&sata_mutex);
1248 	sata_hba_inst->satahba_open_flag = 0;
1249 	mutex_exit(&sata_mutex);
1250 	return (0);
1251 }
1252 
1253 
1254 
1255 /*
1256  * Standard IOCTL commands for SATA hotplugging.
1257  * Implemented DEVCTL_AP commands:
1258  * DEVCTL_AP_CONNECT
1259  * DEVCTL_AP_DISCONNECT
1260  * DEVCTL_AP_CONFIGURE
1261  * DEVCTL_UNCONFIGURE
1262  * DEVCTL_AP_CONTROL
1263  *
1264  * Commands passed to default ndi ioctl handler:
1265  * DEVCTL_DEVICE_GETSTATE
1266  * DEVCTL_DEVICE_ONLINE
1267  * DEVCTL_DEVICE_OFFLINE
1268  * DEVCTL_DEVICE_REMOVE
1269  * DEVCTL_DEVICE_INSERT
1270  * DEVCTL_BUS_GETSTATE
1271  *
1272  * All other cmds are passed to HBA if it provide ioctl handler, or failed
1273  * if not.
1274  *
1275  * Returns:
1276  * 0 if successful,
1277  * error code if operation failed.
1278  *
1279  * Port Multiplier support is supported now.
1280  *
1281  * NOTE: qual should be SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT
1282  */
1283 
1284 static int
1285 sata_hba_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
1286     int *rvalp)
1287 {
1288 #ifndef __lock_lint
1289 	_NOTE(ARGUNUSED(credp))
1290 	_NOTE(ARGUNUSED(rvalp))
1291 #endif
1292 	int rv = 0;
1293 	int32_t	comp_port = -1;
1294 	dev_info_t *dip;
1295 	devctl_ap_state_t ap_state;
1296 	struct devctl_iocdata *dcp = NULL;
1297 	scsi_hba_tran_t *scsi_hba_tran;
1298 	sata_hba_inst_t *sata_hba_inst;
1299 	sata_device_t sata_device;
1300 	sata_cport_info_t *cportinfo;
1301 	int cport, pmport, qual;
1302 	int rval = SATA_SUCCESS;
1303 
1304 	dip = sata_devt_to_devinfo(dev);
1305 	if (dip == NULL)
1306 		return (ENXIO);
1307 
1308 	if ((scsi_hba_tran = ddi_get_driver_private(dip)) == NULL)
1309 		return (ENXIO);
1310 
1311 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
1312 	if (sata_hba_inst == NULL)
1313 		return (ENXIO);
1314 
1315 	if (sata_hba_inst->satahba_tran == NULL)
1316 		return (ENXIO);
1317 
1318 	switch (cmd) {
1319 
1320 	case DEVCTL_DEVICE_GETSTATE:
1321 	case DEVCTL_DEVICE_ONLINE:
1322 	case DEVCTL_DEVICE_OFFLINE:
1323 	case DEVCTL_DEVICE_REMOVE:
1324 	case DEVCTL_BUS_GETSTATE:
1325 		/*
1326 		 * There may be more cases that we want to pass to default
1327 		 * handler rather than fail them.
1328 		 */
1329 		return (ndi_devctl_ioctl(dip, cmd, arg, mode, 0));
1330 	}
1331 
1332 	/* read devctl ioctl data */
1333 	if (cmd != DEVCTL_AP_CONTROL) {
1334 		if (ndi_dc_allochdl((void *)arg, &dcp) != NDI_SUCCESS)
1335 			return (EFAULT);
1336 
1337 		if ((comp_port = sata_get_port_num(sata_hba_inst, dcp)) ==
1338 		    -1) {
1339 			if (dcp)
1340 				ndi_dc_freehdl(dcp);
1341 			return (EINVAL);
1342 		}
1343 
1344 		/*
1345 		 * According to SCSI_TO_SATA_ADDR_QUAL, qual should be either
1346 		 * SATA_ADDR_DCPORT or SATA_ADDR_DPMPORT.
1347 		 */
1348 		cport = SCSI_TO_SATA_CPORT(comp_port);
1349 		pmport = SCSI_TO_SATA_PMPORT(comp_port);
1350 		qual = SCSI_TO_SATA_ADDR_QUAL(comp_port);
1351 
1352 		if (sata_validate_sata_address(sata_hba_inst, cport, pmport,
1353 		    qual) != 0) {
1354 			ndi_dc_freehdl(dcp);
1355 			return (EINVAL);
1356 		}
1357 
1358 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1359 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1360 		    cport_mutex);
1361 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1362 			/*
1363 			 * Cannot process ioctl request now. Come back later.
1364 			 */
1365 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1366 			    cport_mutex);
1367 			ndi_dc_freehdl(dcp);
1368 			return (EBUSY);
1369 		}
1370 		/* Block event processing for this port */
1371 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1372 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1373 
1374 		sata_device.satadev_addr.cport = cport;
1375 		sata_device.satadev_addr.pmport = pmport;
1376 		sata_device.satadev_addr.qual = qual;
1377 		sata_device.satadev_rev = SATA_DEVICE_REV;
1378 	}
1379 
1380 	switch (cmd) {
1381 
1382 	case DEVCTL_AP_DISCONNECT:
1383 
1384 		/*
1385 		 * Normally, cfgadm sata plugin will try to offline
1386 		 * (unconfigure) device before this request. Nevertheless,
1387 		 * if a device is still configured, we need to
1388 		 * attempt to offline and unconfigure device first, and we will
1389 		 * deactivate the port regardless of the unconfigure
1390 		 * operation results.
1391 		 *
1392 		 */
1393 		rv = sata_ioctl_disconnect(sata_hba_inst, &sata_device);
1394 
1395 		break;
1396 
1397 	case DEVCTL_AP_UNCONFIGURE:
1398 
1399 		/*
1400 		 * The unconfigure operation uses generic nexus operation to
1401 		 * offline a device. It leaves a target device node attached.
1402 		 * and obviously sata_drive_info attached as well, because
1403 		 * from the hardware point of view nothing has changed.
1404 		 */
1405 		rv = sata_ioctl_unconfigure(sata_hba_inst, &sata_device);
1406 		break;
1407 
1408 	case DEVCTL_AP_CONNECT:
1409 	{
1410 		/*
1411 		 * The sata cfgadm pluging will invoke this operation only if
1412 		 * port was found in the disconnect state (failed state
1413 		 * is also treated as the disconnected state).
1414 		 * If port activation is successful and a device is found
1415 		 * attached to the port, the initialization sequence is
1416 		 * executed to probe the port and attach
1417 		 * a device structure to a port structure. The device is not
1418 		 * set in configured state (system-wise) by this operation.
1419 		 */
1420 
1421 		rv = sata_ioctl_connect(sata_hba_inst, &sata_device);
1422 
1423 		break;
1424 	}
1425 
1426 	case DEVCTL_AP_CONFIGURE:
1427 	{
1428 		/*
1429 		 * A port may be in an active or shutdown state.
1430 		 * If port is in a failed state, operation is aborted.
1431 		 * If a port is in a shutdown state, sata_tran_port_activate()
1432 		 * is invoked prior to any other operation.
1433 		 *
1434 		 * Onlining the device involves creating a new target node.
1435 		 * If there is an old target node present (belonging to
1436 		 * previously removed device), the operation is aborted - the
1437 		 * old node has to be released and removed before configure
1438 		 * operation is attempted.
1439 		 */
1440 
1441 		rv = sata_ioctl_configure(sata_hba_inst, &sata_device);
1442 
1443 		break;
1444 	}
1445 
1446 	case DEVCTL_AP_GETSTATE:
1447 
1448 		sata_cfgadm_state(sata_hba_inst, comp_port, &ap_state);
1449 
1450 		ap_state.ap_last_change = (time_t)-1;
1451 		ap_state.ap_error_code = 0;
1452 		ap_state.ap_in_transition = 0;
1453 
1454 		/* Copy the return AP-state information to the user space */
1455 		if (ndi_dc_return_ap_state(&ap_state, dcp) != NDI_SUCCESS) {
1456 			rv = EFAULT;
1457 		}
1458 		break;
1459 
1460 	case DEVCTL_AP_CONTROL:
1461 	{
1462 		/*
1463 		 * Generic devctl for hardware specific functionality
1464 		 */
1465 		sata_ioctl_data_t	ioc;
1466 
1467 		ASSERT(dcp == NULL);
1468 
1469 		/* Copy in user ioctl data first */
1470 #ifdef _MULTI_DATAMODEL
1471 		if (ddi_model_convert_from(mode & FMODELS) ==
1472 		    DDI_MODEL_ILP32) {
1473 
1474 			sata_ioctl_data_32_t	ioc32;
1475 
1476 			if (ddi_copyin((void *)arg, (void *)&ioc32,
1477 			    sizeof (ioc32), mode) != 0) {
1478 				rv = EFAULT;
1479 				break;
1480 			}
1481 			ioc.cmd 	= (uint_t)ioc32.cmd;
1482 			ioc.port	= (uint_t)ioc32.port;
1483 			ioc.get_size	= (uint_t)ioc32.get_size;
1484 			ioc.buf		= (caddr_t)(uintptr_t)ioc32.buf;
1485 			ioc.bufsiz	= (uint_t)ioc32.bufsiz;
1486 			ioc.misc_arg	= (uint_t)ioc32.misc_arg;
1487 		} else
1488 #endif /* _MULTI_DATAMODEL */
1489 		if (ddi_copyin((void *)arg, (void *)&ioc, sizeof (ioc),
1490 		    mode) != 0) {
1491 			return (EFAULT);
1492 		}
1493 
1494 		SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
1495 		    "sata_hba_ioctl: DEVCTL_AP_CONTROL "
1496 		    "cmd 0x%x, port 0x%x", ioc.cmd, ioc.port);
1497 
1498 		/*
1499 		 * To avoid BE/LE and 32/64 issues, a get_size always returns
1500 		 * a 32-bit number.
1501 		 */
1502 		if (ioc.get_size != 0 && ioc.bufsiz != (sizeof (uint32_t))) {
1503 			return (EINVAL);
1504 		}
1505 		/* validate address */
1506 		cport = SCSI_TO_SATA_CPORT(ioc.port);
1507 		pmport = SCSI_TO_SATA_PMPORT(ioc.port);
1508 		qual = SCSI_TO_SATA_ADDR_QUAL(ioc.port);
1509 
1510 		SATADBG3(SATA_DBG_IOCTL_IF, sata_hba_inst,
1511 		    "sata_hba_ioctl: target port is %d:%d (%d)",
1512 		    cport, pmport, qual);
1513 
1514 		if (sata_validate_sata_address(sata_hba_inst, cport,
1515 		    pmport, qual) != 0)
1516 			return (EINVAL);
1517 
1518 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
1519 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1520 		    cport_mutex);
1521 		/* Is the port locked by event processing daemon ? */
1522 		if (cportinfo->cport_event_flags & SATA_EVNT_LOCK_PORT_BUSY) {
1523 			/*
1524 			 * Cannot process ioctl request now. Come back later
1525 			 */
1526 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
1527 			    cport_mutex);
1528 			return (EBUSY);
1529 		}
1530 		/* Block event processing for this port */
1531 		cportinfo->cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
1532 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1533 
1534 
1535 		sata_device.satadev_addr.cport = cport;
1536 		sata_device.satadev_addr.pmport = pmport;
1537 		sata_device.satadev_addr.qual = qual;
1538 		sata_device.satadev_rev = SATA_DEVICE_REV;
1539 
1540 		switch (ioc.cmd) {
1541 
1542 		case SATA_CFGA_RESET_PORT:
1543 			/*
1544 			 * There is no protection for configured device.
1545 			 */
1546 			rv = sata_ioctl_reset_port(sata_hba_inst, &sata_device);
1547 			break;
1548 
1549 		case SATA_CFGA_RESET_DEVICE:
1550 			/*
1551 			 * There is no protection for configured device.
1552 			 */
1553 			rv = sata_ioctl_reset_device(sata_hba_inst,
1554 			    &sata_device);
1555 			break;
1556 
1557 		case SATA_CFGA_RESET_ALL:
1558 			/*
1559 			 * There is no protection for configured devices.
1560 			 */
1561 			rv = sata_ioctl_reset_all(sata_hba_inst);
1562 			/*
1563 			 * We return here, because common return is for
1564 			 * a single port operation - we have already unlocked
1565 			 * all ports and no dc handle was allocated.
1566 			 */
1567 			return (rv);
1568 
1569 		case SATA_CFGA_PORT_DEACTIVATE:
1570 			/*
1571 			 * Arbitrarily unconfigure attached device, if any.
1572 			 * Even if the unconfigure fails, proceed with the
1573 			 * port deactivation.
1574 			 */
1575 			rv = sata_ioctl_deactivate(sata_hba_inst, &sata_device);
1576 
1577 			break;
1578 
1579 		case SATA_CFGA_PORT_ACTIVATE:
1580 
1581 			rv = sata_ioctl_activate(sata_hba_inst, &sata_device);
1582 			break;
1583 
1584 		case SATA_CFGA_PORT_SELF_TEST:
1585 
1586 			rv = sata_ioctl_port_self_test(sata_hba_inst,
1587 			    &sata_device);
1588 			break;
1589 
1590 		case SATA_CFGA_GET_DEVICE_PATH:
1591 
1592 			rv = sata_ioctl_get_device_path(sata_hba_inst,
1593 			    &sata_device, &ioc, mode);
1594 			break;
1595 
1596 		case SATA_CFGA_GET_AP_TYPE:
1597 
1598 			rv = sata_ioctl_get_ap_type(sata_hba_inst,
1599 			    &sata_device, &ioc, mode);
1600 			break;
1601 
1602 		case SATA_CFGA_GET_MODEL_INFO:
1603 
1604 			rv = sata_ioctl_get_model_info(sata_hba_inst,
1605 			    &sata_device, &ioc, mode);
1606 			break;
1607 
1608 		case SATA_CFGA_GET_REVFIRMWARE_INFO:
1609 
1610 			rv = sata_ioctl_get_revfirmware_info(sata_hba_inst,
1611 			    &sata_device, &ioc, mode);
1612 			break;
1613 
1614 		case SATA_CFGA_GET_SERIALNUMBER_INFO:
1615 
1616 			rv = sata_ioctl_get_serialnumber_info(sata_hba_inst,
1617 			    &sata_device, &ioc, mode);
1618 			break;
1619 
1620 		default:
1621 			rv = EINVAL;
1622 			break;
1623 
1624 		} /* End of DEVCTL_AP_CONTROL cmd switch */
1625 
1626 		break;
1627 	}
1628 
1629 	default:
1630 	{
1631 		/*
1632 		 * If we got here, we got an IOCTL that SATA HBA Framework
1633 		 * does not recognize. Pass ioctl to HBA driver, in case
1634 		 * it could process it.
1635 		 */
1636 		sata_hba_tran_t *sata_tran = sata_hba_inst->satahba_tran;
1637 		dev_info_t	*mydip = SATA_DIP(sata_hba_inst);
1638 
1639 		SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1640 		    "IOCTL 0x%2x not supported in SATA framework, "
1641 		    "passthrough to HBA", cmd);
1642 
1643 		if (sata_tran->sata_tran_ioctl == NULL) {
1644 			rv = EINVAL;
1645 			break;
1646 		}
1647 		rval = (*sata_tran->sata_tran_ioctl)(mydip, cmd, arg);
1648 		if (rval != 0) {
1649 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
1650 			    "IOCTL 0x%2x failed in HBA", cmd);
1651 			rv = rval;
1652 		}
1653 		break;
1654 	}
1655 
1656 	} /* End of main IOCTL switch */
1657 
1658 	if (dcp) {
1659 		ndi_dc_freehdl(dcp);
1660 	}
1661 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1662 	cportinfo->cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
1663 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
1664 
1665 	return (rv);
1666 }
1667 
1668 
1669 /*
1670  * Create error retrieval sata packet
1671  *
1672  * A sata packet is allocated and set-up to contain specified error retrieval
1673  * command and appropriate dma-able data buffer.
1674  * No association with any scsi packet is made and no callback routine is
1675  * specified.
1676  *
1677  * Returns a pointer to sata packet upon successfull packet creation.
1678  * Returns NULL, if packet cannot be created.
1679  */
1680 sata_pkt_t *
1681 sata_get_error_retrieval_pkt(dev_info_t *dip, sata_device_t *sata_device,
1682     int pkt_type)
1683 {
1684 	sata_hba_inst_t	*sata_hba_inst;
1685 	sata_pkt_txlate_t *spx;
1686 	sata_pkt_t *spkt;
1687 	sata_drive_info_t *sdinfo;
1688 
1689 	mutex_enter(&sata_mutex);
1690 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1691 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1692 		if (SATA_DIP(sata_hba_inst) == dip)
1693 			break;
1694 	}
1695 	mutex_exit(&sata_mutex);
1696 	ASSERT(sata_hba_inst != NULL);
1697 
1698 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
1699 	if (sdinfo == NULL) {
1700 		sata_log(sata_hba_inst, CE_WARN,
1701 		    "sata: error recovery request for non-attached device at "
1702 		    "cport %d", sata_device->satadev_addr.cport);
1703 		return (NULL);
1704 	}
1705 
1706 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1707 	spx->txlt_sata_hba_inst = sata_hba_inst;
1708 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
1709 	spkt = sata_pkt_alloc(spx, NULL);
1710 	if (spkt == NULL) {
1711 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1712 		return (NULL);
1713 	}
1714 	/* address is needed now */
1715 	spkt->satapkt_device.satadev_addr = sata_device->satadev_addr;
1716 
1717 	switch (pkt_type) {
1718 	case SATA_ERR_RETR_PKT_TYPE_NCQ:
1719 		if (sata_ncq_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1720 			return (spkt);
1721 		break;
1722 
1723 	case SATA_ERR_RETR_PKT_TYPE_ATAPI:
1724 		if (sata_atapi_err_ret_cmd_setup(spx, sdinfo) == SATA_SUCCESS)
1725 			return (spkt);
1726 		break;
1727 
1728 	default:
1729 		break;
1730 	}
1731 
1732 	sata_pkt_free(spx);
1733 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1734 	return (NULL);
1735 
1736 }
1737 
1738 
1739 /*
1740  * Free error retrieval sata packet
1741  *
1742  * Free sata packet and any associated resources allocated previously by
1743  * sata_get_error_retrieval_pkt().
1744  *
1745  * Void return.
1746  */
1747 void
1748 sata_free_error_retrieval_pkt(sata_pkt_t *sata_pkt)
1749 {
1750 	sata_pkt_txlate_t *spx =
1751 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1752 
1753 	ASSERT(sata_pkt != NULL);
1754 
1755 	sata_free_local_buffer(spx);
1756 	sata_pkt_free(spx);
1757 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1758 
1759 }
1760 
1761 /*
1762  * Create READ PORT MULTIPLIER and WRITE PORT MULTIPLIER sata packet
1763  *
1764  * No association with any scsi packet is made and no callback routine is
1765  * specified.
1766  *
1767  * Returns a pointer to sata packet upon successfull packet creation.
1768  * Returns NULL, if packet cannot be created.
1769  *
1770  * NOTE: Input/Output value includes 64 bits accoring to SATA Spec 2.6,
1771  * only lower 32 bits are available currently.
1772  */
1773 sata_pkt_t *
1774 sata_get_rdwr_pmult_pkt(dev_info_t *dip, sata_device_t *sd,
1775     uint8_t regn, uint32_t regv, uint32_t type)
1776 {
1777 	sata_hba_inst_t	*sata_hba_inst;
1778 	sata_pkt_txlate_t *spx;
1779 	sata_pkt_t *spkt;
1780 	sata_cmd_t *scmd;
1781 
1782 	/* Only READ/WRITE commands are accepted. */
1783 	ASSERT(type == SATA_RDWR_PMULT_PKT_TYPE_READ ||
1784 	    type == SATA_RDWR_PMULT_PKT_TYPE_WRITE);
1785 
1786 	mutex_enter(&sata_mutex);
1787 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1788 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1789 		if (SATA_DIP(sata_hba_inst) == dip)
1790 			break;
1791 	}
1792 	mutex_exit(&sata_mutex);
1793 	ASSERT(sata_hba_inst != NULL);
1794 
1795 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
1796 	spx->txlt_sata_hba_inst = sata_hba_inst;
1797 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
1798 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
1799 	if (spkt == NULL) {
1800 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
1801 		return (NULL);
1802 	}
1803 
1804 	/*
1805 	 * NOTE: We need to send this command to the port multiplier,
1806 	 * that means send to SATA_PMULT_HOSTPORT(0xf) pmport
1807 	 *
1808 	 * sata_device contains the address of actual target device, and the
1809 	 * pmport number in the command comes from the sata_device structure.
1810 	 */
1811 	spkt->satapkt_device.satadev_addr = sd->satadev_addr;
1812 	spkt->satapkt_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
1813 	spkt->satapkt_device.satadev_addr.qual = SATA_ADDR_PMULT;
1814 
1815 	/* Fill sata_pkt */
1816 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_POLLING;
1817 	spkt->satapkt_comp = NULL; /* Synchronous mode, no callback */
1818 	spkt->satapkt_time = 10; /* Timeout 10s */
1819 
1820 	/* Build READ PORT MULTIPLIER cmd in the sata_pkt */
1821 	scmd = &spkt->satapkt_cmd;
1822 	scmd->satacmd_features_reg = regn & 0xff;
1823 	scmd->satacmd_features_reg_ext = (regn >> 8) & 0xff;
1824 	scmd->satacmd_device_reg = sd->satadev_addr.pmport;
1825 	scmd->satacmd_addr_type = 0;		/* N/A */
1826 
1827 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
1828 
1829 	if (type == SATA_RDWR_PMULT_PKT_TYPE_READ) {
1830 		scmd->satacmd_cmd_reg = SATAC_READ_PORTMULT;
1831 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
1832 		scmd->satacmd_flags.sata_special_regs = 1;
1833 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
1834 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
1835 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
1836 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
1837 	} else if (type == SATA_RDWR_PMULT_PKT_TYPE_WRITE) {
1838 		scmd->satacmd_cmd_reg = SATAC_WRITE_PORTMULT;
1839 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
1840 		scmd->satacmd_sec_count_lsb = regv & 0xff;
1841 		scmd->satacmd_lba_low_lsb = regv >> 8 & 0xff;
1842 		scmd->satacmd_lba_mid_lsb = regv >> 16 & 0xff;
1843 		scmd->satacmd_lba_high_lsb = regv >> 24 & 0xff;
1844 	}
1845 
1846 	return (spkt);
1847 }
1848 
1849 /*
1850  * Free sata packet and any associated resources allocated previously by
1851  * sata_get_rdwr_pmult_pkt().
1852  *
1853  * Void return.
1854  */
1855 void
1856 sata_free_rdwr_pmult_pkt(sata_pkt_t *sata_pkt)
1857 {
1858 	sata_pkt_txlate_t *spx =
1859 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
1860 
1861 	/* Free allocated resources */
1862 	sata_pkt_free(spx);
1863 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
1864 }
1865 
1866 /*
1867  * Register a port multiplier to framework.
1868  * 1) Store the GSCR values in the previous allocated pmult_info strctures.
1869  * 2) Search in the blacklist and update the number of the device ports of the
1870  * port multiplier.
1871  *
1872  * Void return.
1873  */
1874 void
1875 sata_register_pmult(dev_info_t *dip, sata_device_t *sd, sata_pmult_gscr_t *sg)
1876 {
1877 	sata_hba_inst_t *sata_hba_inst = NULL;
1878 	sata_pmult_info_t *pmultinfo;
1879 	sata_pmult_bl_t *blp;
1880 	int cport = sd->satadev_addr.cport;
1881 
1882 	mutex_enter(&sata_mutex);
1883 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
1884 	    sata_hba_inst = sata_hba_inst->satahba_next) {
1885 		if (SATA_DIP(sata_hba_inst) == dip)
1886 			if (sata_hba_inst->satahba_attached == 1)
1887 				break;
1888 	}
1889 	mutex_exit(&sata_mutex);
1890 	/* HBA not attached? */
1891 	if (sata_hba_inst == NULL)
1892 		return;
1893 
1894 	/* Number of pmports */
1895 	sd->satadev_add_info = sg->gscr2 & SATA_PMULT_PORTNUM_MASK;
1896 
1897 	/* Check the blacklist */
1898 	for (blp = sata_pmult_blacklist; blp->bl_gscr0; blp++) {
1899 		if (sg->gscr0 != blp->bl_gscr0 && blp->bl_gscr0)
1900 			continue;
1901 		if (sg->gscr1 != blp->bl_gscr1 && blp->bl_gscr1)
1902 			continue;
1903 		if (sg->gscr2 != blp->bl_gscr2 && blp->bl_gscr2)
1904 			continue;
1905 
1906 		cmn_err(CE_WARN, "!Port multiplier is on the blacklist.");
1907 		sd->satadev_add_info = blp->bl_flags;
1908 		break;
1909 	}
1910 
1911 	/* Register the port multiplier GSCR */
1912 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
1913 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
1914 	if (pmultinfo != NULL) {
1915 		pmultinfo->pmult_gscr = *sg;
1916 		pmultinfo->pmult_num_dev_ports =
1917 		    sd->satadev_add_info & SATA_PMULT_PORTNUM_MASK;
1918 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
1919 		    "Port multiplier registered at port %d", cport);
1920 	}
1921 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
1922 }
1923 
1924 /*
1925  * sata_name_child is for composing the name of the node
1926  * the format of the name is "target,0".
1927  */
1928 static int
1929 sata_name_child(dev_info_t *dip, char *name, int namelen)
1930 {
1931 	int target;
1932 
1933 	target = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1934 	    DDI_PROP_DONTPASS, "target", -1);
1935 	if (target == -1)
1936 		return (DDI_FAILURE);
1937 	(void) snprintf(name, namelen, "%x,0", target);
1938 	return (DDI_SUCCESS);
1939 }
1940 
1941 
1942 
1943 /* ****************** SCSA required entry points *********************** */
1944 
1945 /*
1946  * Implementation of scsi tran_tgt_init.
1947  * sata_scsi_tgt_init() initializes scsi_device structure
1948  *
1949  * If successful, DDI_SUCCESS is returned.
1950  * DDI_FAILURE is returned if addressed device does not exist
1951  */
1952 
1953 static int
1954 sata_scsi_tgt_init(dev_info_t *hba_dip, dev_info_t *tgt_dip,
1955     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
1956 {
1957 #ifndef __lock_lint
1958 	_NOTE(ARGUNUSED(hba_dip))
1959 	_NOTE(ARGUNUSED(tgt_dip))
1960 #endif
1961 	sata_device_t		sata_device;
1962 	sata_drive_info_t	*sdinfo;
1963 	struct sata_id		*sid;
1964 	sata_hba_inst_t		*sata_hba_inst;
1965 	char			model[SATA_ID_MODEL_LEN + 1];
1966 	char			fw[SATA_ID_FW_LEN + 1];
1967 	char			*vid, *pid;
1968 	int			i;
1969 
1970 	/*
1971 	 * Fail tran_tgt_init for .conf stub node
1972 	 */
1973 	if (ndi_dev_is_persistent_node(tgt_dip) == 0) {
1974 		(void) ndi_merge_node(tgt_dip, sata_name_child);
1975 		ddi_set_name_addr(tgt_dip, NULL);
1976 		return (DDI_FAILURE);
1977 	}
1978 
1979 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
1980 
1981 	/* Validate scsi device address */
1982 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
1983 	    &sata_device) != 0)
1984 		return (DDI_FAILURE);
1985 
1986 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
1987 	    sata_device.satadev_addr.cport)));
1988 
1989 	/* sata_device now contains a valid sata address */
1990 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
1991 	if (sdinfo == NULL) {
1992 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1993 		    sata_device.satadev_addr.cport)));
1994 		return (DDI_FAILURE);
1995 	}
1996 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
1997 	    sata_device.satadev_addr.cport)));
1998 
1999 	/*
2000 	 * Check if we need to create a legacy devid (i.e cmdk style) for
2001 	 * the target disks.
2002 	 *
2003 	 * HBA devinfo node will have the property "use-cmdk-devid-format"
2004 	 * if we need to create cmdk-style devid for all the disk devices
2005 	 * attached to this controller. This property may have been set
2006 	 * from HBA driver's .conf file or by the HBA driver in its
2007 	 * attach(9F) function.
2008 	 */
2009 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
2010 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
2011 	    "use-cmdk-devid-format", 0) == 1)) {
2012 		/* register a legacy devid for this target node */
2013 		sata_target_devid_register(tgt_dip, sdinfo);
2014 	}
2015 
2016 
2017 	/*
2018 	 * 'Identify Device Data' does not always fit in standard SCSI
2019 	 * INQUIRY data, so establish INQUIRY_* properties with full-form
2020 	 * of information.
2021 	 */
2022 	sid = &sdinfo->satadrv_id;
2023 #ifdef	_LITTLE_ENDIAN
2024 	swab(sid->ai_model, model, SATA_ID_MODEL_LEN);
2025 	swab(sid->ai_fw, fw, SATA_ID_FW_LEN);
2026 #else	/* _LITTLE_ENDIAN */
2027 	bcopy(sid->ai_model, model, SATA_ID_MODEL_LEN);
2028 	bcopy(sid->ai_fw, fw, SATA_ID_FW_LEN);
2029 #endif	/* _LITTLE_ENDIAN */
2030 	model[SATA_ID_MODEL_LEN] = 0;
2031 	fw[SATA_ID_FW_LEN] = 0;
2032 
2033 	/* split model into into vid/pid */
2034 	for (i = 0, pid = model; i < SATA_ID_MODEL_LEN; i++, pid++)
2035 		if ((*pid == ' ') || (*pid == '\t'))
2036 			break;
2037 	if (i < SATA_ID_MODEL_LEN) {
2038 		vid = model;
2039 		*pid++ = 0;		/* terminate vid, establish pid */
2040 	} else {
2041 		vid = NULL;		/* vid will stay "ATA     " */
2042 		pid = model;		/* model is all pid */
2043 	}
2044 
2045 	if (vid)
2046 		(void) scsi_device_prop_update_inqstring(sd, INQUIRY_VENDOR_ID,
2047 		    vid, strlen(vid));
2048 	if (pid)
2049 		(void) scsi_device_prop_update_inqstring(sd, INQUIRY_PRODUCT_ID,
2050 		    pid, strlen(pid));
2051 	(void) scsi_device_prop_update_inqstring(sd, INQUIRY_REVISION_ID,
2052 	    fw, strlen(fw));
2053 
2054 	return (DDI_SUCCESS);
2055 }
2056 
2057 /*
2058  * Implementation of scsi tran_tgt_probe.
2059  * Probe target, by calling default scsi routine scsi_hba_probe()
2060  */
2061 static int
2062 sata_scsi_tgt_probe(struct scsi_device *sd, int (*callback)(void))
2063 {
2064 	sata_hba_inst_t *sata_hba_inst =
2065 	    (sata_hba_inst_t *)(sd->sd_address.a_hba_tran->tran_hba_private);
2066 	int rval;
2067 	uint32_t pm_cap;
2068 
2069 	rval = scsi_hba_probe(sd, callback);
2070 	pm_cap = SATA_CAP_POWER_CONDITON | SATA_CAP_SMART_PAGE |
2071 	    SATA_CAP_LOG_SENSE;
2072 
2073 	if (rval == SCSIPROBE_EXISTS) {
2074 		/*
2075 		 * Set property "pm-capable" on the target device node, so that
2076 		 * the target driver will not try to fetch scsi cycle counters
2077 		 * before enabling device power-management.
2078 		 */
2079 		if ((ddi_prop_update_int(DDI_DEV_T_NONE, sd->sd_dev,
2080 		    "pm-capable", pm_cap)) != DDI_PROP_SUCCESS) {
2081 			sata_log(sata_hba_inst, CE_WARN,
2082 			    "SATA device at port %d: "
2083 			    "will not be power-managed ",
2084 			    SCSI_TO_SATA_CPORT(sd->sd_address.a_target));
2085 			SATA_LOG_D((sata_hba_inst, CE_WARN,
2086 			    "failure updating pm-capable property"));
2087 		}
2088 	}
2089 	return (rval);
2090 }
2091 
2092 /*
2093  * Implementation of scsi tran_tgt_free.
2094  * Release all resources allocated for scsi_device
2095  */
2096 static void
2097 sata_scsi_tgt_free(dev_info_t *hba_dip, dev_info_t *tgt_dip,
2098     scsi_hba_tran_t *hba_tran, struct scsi_device *sd)
2099 {
2100 #ifndef __lock_lint
2101 	_NOTE(ARGUNUSED(hba_dip))
2102 #endif
2103 	sata_device_t		sata_device;
2104 	sata_drive_info_t	*sdinfo;
2105 	sata_hba_inst_t		*sata_hba_inst;
2106 	ddi_devid_t		devid;
2107 
2108 	sata_hba_inst = (sata_hba_inst_t *)(hba_tran->tran_hba_private);
2109 
2110 	/* Validate scsi device address */
2111 	/*
2112 	 * Note: tgt_free relates to the SCSA view of a device. If called, there
2113 	 * was a device at this address, so even if the sata framework internal
2114 	 * resources were alredy released because a device was detached,
2115 	 * this function should be executed as long as its actions do
2116 	 * not require the internal sata view of a device and the address
2117 	 * refers to a valid sata address.
2118 	 * Validating the address here means that we do not trust SCSA...
2119 	 */
2120 	if (sata_validate_scsi_address(sata_hba_inst, &sd->sd_address,
2121 	    &sata_device) == -1)
2122 		return;
2123 
2124 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2125 	    sata_device.satadev_addr.cport)));
2126 
2127 	/* sata_device now should contain a valid sata address */
2128 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
2129 	if (sdinfo == NULL) {
2130 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2131 		    sata_device.satadev_addr.cport)));
2132 		return;
2133 	}
2134 	/*
2135 	 * We did not allocate any resources in sata_scsi_tgt_init()
2136 	 * other than few properties.
2137 	 * Free them.
2138 	 */
2139 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2140 	    sata_device.satadev_addr.cport)));
2141 	(void) ndi_prop_remove(DDI_DEV_T_NONE, tgt_dip, "pm-capable");
2142 
2143 	/*
2144 	 * If devid was previously created but not freed up from
2145 	 * sd(7D) driver (i.e during detach(9F)) then do it here.
2146 	 */
2147 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
2148 	    (ddi_getprop(DDI_DEV_T_ANY, hba_dip, DDI_PROP_DONTPASS,
2149 	    "use-cmdk-devid-format", 0) == 1) &&
2150 	    (ddi_devid_get(tgt_dip, &devid) == DDI_SUCCESS)) {
2151 		ddi_devid_unregister(tgt_dip);
2152 		ddi_devid_free(devid);
2153 	}
2154 }
2155 
2156 /*
2157  * Implementation of scsi tran_init_pkt
2158  * Upon successful return, scsi pkt buffer has DMA resources allocated.
2159  *
2160  * It seems that we should always allocate pkt, even if the address is
2161  * for non-existing device - just use some default for dma_attr.
2162  * The reason is that there is no way to communicate this to a caller here.
2163  * Subsequent call to sata_scsi_start may fail appropriately.
2164  * Simply returning NULL does not seem to discourage a target driver...
2165  *
2166  * Returns a pointer to initialized scsi_pkt, or NULL otherwise.
2167  */
2168 static struct scsi_pkt *
2169 sata_scsi_init_pkt(struct scsi_address *ap, struct scsi_pkt *pkt,
2170     struct buf *bp, int cmdlen, int statuslen, int tgtlen, int flags,
2171     int (*callback)(caddr_t), caddr_t arg)
2172 {
2173 	sata_hba_inst_t *sata_hba_inst =
2174 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2175 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
2176 	sata_device_t sata_device;
2177 	sata_drive_info_t *sdinfo;
2178 	sata_pkt_txlate_t *spx;
2179 	ddi_dma_attr_t cur_dma_attr;
2180 	int rval;
2181 	boolean_t new_pkt = TRUE;
2182 
2183 	ASSERT(ap->a_hba_tran->tran_hba_dip == dip);
2184 
2185 	/*
2186 	 * We need to translate the address, even if it could be
2187 	 * a bogus one, for a non-existing device
2188 	 */
2189 	sata_device.satadev_addr.qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
2190 	sata_device.satadev_addr.cport = SCSI_TO_SATA_CPORT(ap->a_target);
2191 	sata_device.satadev_addr.pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2192 	sata_device.satadev_rev = SATA_DEVICE_REV;
2193 
2194 	if (pkt == NULL) {
2195 		/*
2196 		 * Have to allocate a brand new scsi packet.
2197 		 * We need to operate with auto request sense enabled.
2198 		 */
2199 		pkt = scsi_hba_pkt_alloc(dip, ap, cmdlen,
2200 		    MAX(statuslen, SATA_MAX_SENSE_LEN),
2201 		    tgtlen, sizeof (sata_pkt_txlate_t), callback, arg);
2202 
2203 		if (pkt == NULL)
2204 			return (NULL);
2205 
2206 		/* Fill scsi packet structure */
2207 		pkt->pkt_comp		= (void (*)())NULL;
2208 		pkt->pkt_time		= 0;
2209 		pkt->pkt_resid		= 0;
2210 		pkt->pkt_statistics	= 0;
2211 		pkt->pkt_reason		= 0;
2212 
2213 		/*
2214 		 * pkt_hba_private will point to sata pkt txlate structure
2215 		 */
2216 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2217 		bzero(spx, sizeof (sata_pkt_txlate_t));
2218 
2219 		spx->txlt_scsi_pkt = pkt;
2220 		spx->txlt_sata_hba_inst = sata_hba_inst;
2221 
2222 		/* Allocate sata_pkt */
2223 		spx->txlt_sata_pkt = sata_pkt_alloc(spx, callback);
2224 		if (spx->txlt_sata_pkt == NULL) {
2225 			/* Could not allocate sata pkt */
2226 			scsi_hba_pkt_free(ap, pkt);
2227 			return (NULL);
2228 		}
2229 		/* Set sata address */
2230 		spx->txlt_sata_pkt->satapkt_device.satadev_addr =
2231 		    sata_device.satadev_addr;
2232 		spx->txlt_sata_pkt->satapkt_device.satadev_rev =
2233 		    sata_device.satadev_rev;
2234 
2235 		if ((bp == NULL) || (bp->b_bcount == 0))
2236 			return (pkt);
2237 
2238 		spx->txlt_total_residue = bp->b_bcount;
2239 	} else {
2240 		new_pkt = FALSE;
2241 		/*
2242 		 * Packet was preallocated/initialized by previous call
2243 		 */
2244 		spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2245 
2246 		if ((bp == NULL) || (bp->b_bcount == 0)) {
2247 			return (pkt);
2248 		}
2249 
2250 		/* Pkt is available already: spx->txlt_scsi_pkt == pkt; */
2251 	}
2252 
2253 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
2254 
2255 	/*
2256 	 * We use an adjusted version of the dma_attr, to account
2257 	 * for device addressing limitations.
2258 	 * sata_adjust_dma_attr() will handle sdinfo == NULL which may
2259 	 * happen when a device is not yet configured.
2260 	 */
2261 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2262 	    sata_device.satadev_addr.cport)));
2263 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
2264 	    &spx->txlt_sata_pkt->satapkt_device);
2265 	/* NULL sdinfo may be passsed to sata_adjust_dma_attr() */
2266 	sata_adjust_dma_attr(sdinfo,
2267 	    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
2268 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2269 	    sata_device.satadev_addr.cport)));
2270 	/*
2271 	 * Allocate necessary DMA resources for the packet's data buffer
2272 	 * NOTE:
2273 	 * In case of read/write commands, DMA resource allocation here is
2274 	 * based on the premise that the transfer length specified in
2275 	 * the read/write scsi cdb will match exactly DMA resources -
2276 	 * returning correct packet residue is crucial.
2277 	 */
2278 	if ((rval = sata_dma_buf_setup(spx, flags, callback, arg,
2279 	    &cur_dma_attr)) != DDI_SUCCESS) {
2280 		/*
2281 		 * If a DMA allocation request fails with
2282 		 * DDI_DMA_NOMAPPING, indicate the error by calling
2283 		 * bioerror(9F) with bp and an error code of EFAULT.
2284 		 * If a DMA allocation request fails with
2285 		 * DDI_DMA_TOOBIG, indicate the error by calling
2286 		 * bioerror(9F) with bp and an error code of EINVAL.
2287 		 * For DDI_DMA_NORESOURCES, we may have some of them allocated.
2288 		 * Request may be repeated later - there is no real error.
2289 		 */
2290 		switch (rval) {
2291 		case DDI_DMA_NORESOURCES:
2292 			bioerror(bp, 0);
2293 			break;
2294 		case DDI_DMA_NOMAPPING:
2295 		case DDI_DMA_BADATTR:
2296 			bioerror(bp, EFAULT);
2297 			break;
2298 		case DDI_DMA_TOOBIG:
2299 		default:
2300 			bioerror(bp, EINVAL);
2301 			break;
2302 		}
2303 		if (new_pkt == TRUE) {
2304 			/*
2305 			 * Since this is a new packet, we can clean-up
2306 			 * everything
2307 			 */
2308 			sata_scsi_destroy_pkt(ap, pkt);
2309 		} else {
2310 			/*
2311 			 * This is a re-used packet. It will be target driver's
2312 			 * responsibility to eventually destroy it (which
2313 			 * will free allocated resources).
2314 			 * Here, we just "complete" the request, leaving
2315 			 * allocated resources intact, so the request may
2316 			 * be retried.
2317 			 */
2318 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2319 			sata_pkt_free(spx);
2320 		}
2321 		return (NULL);
2322 	}
2323 	/* Set number of bytes that are not yet accounted for */
2324 	pkt->pkt_resid = spx->txlt_total_residue;
2325 	ASSERT(pkt->pkt_resid >= 0);
2326 
2327 	return (pkt);
2328 }
2329 
2330 /*
2331  * Implementation of scsi tran_start.
2332  * Translate scsi cmd into sata operation and return status.
2333  * ATAPI CDBs are passed to ATAPI devices - the device determines what commands
2334  * are supported.
2335  * For SATA hard disks, supported scsi commands:
2336  * SCMD_INQUIRY
2337  * SCMD_TEST_UNIT_READY
2338  * SCMD_START_STOP
2339  * SCMD_READ_CAPACITY
2340  * SCMD_REQUEST_SENSE
2341  * SCMD_LOG_SENSE_G1
2342  * SCMD_LOG_SELECT_G1
2343  * SCMD_MODE_SENSE	(specific pages)
2344  * SCMD_MODE_SENSE_G1	(specific pages)
2345  * SCMD_MODE_SELECT	(specific pages)
2346  * SCMD_MODE_SELECT_G1	(specific pages)
2347  * SCMD_SYNCHRONIZE_CACHE
2348  * SCMD_SYNCHRONIZE_CACHE_G1
2349  * SCMD_READ
2350  * SCMD_READ_G1
2351  * SCMD_READ_G4
2352  * SCMD_READ_G5
2353  * SCMD_WRITE
2354  * SCMD_WRITE_BUFFER
2355  * SCMD_WRITE_G1
2356  * SCMD_WRITE_G4
2357  * SCMD_WRITE_G5
2358  * SCMD_SEEK		(noop)
2359  * SCMD_SDIAG
2360  *
2361  * All other commands are rejected as unsupported.
2362  *
2363  * Returns:
2364  * TRAN_ACCEPT if command was executed successfully or accepted by HBA driver
2365  * for execution. TRAN_ACCEPT may be returned also if device was removed but
2366  * a callback could be scheduled.
2367  * TRAN_BADPKT if cmd was directed to invalid address.
2368  * TRAN_FATAL_ERROR is command was rejected due to hardware error, including
2369  * some unspecified error. TRAN_FATAL_ERROR may be also returned if a device
2370  * was removed and there was no callback specified in scsi pkt.
2371  * TRAN_BUSY if command could not be executed becasue HBA driver or SATA
2372  * framework was busy performing some other operation(s).
2373  *
2374  */
2375 static int
2376 sata_scsi_start(struct scsi_address *ap, struct scsi_pkt *pkt)
2377 {
2378 	sata_hba_inst_t *sata_hba_inst =
2379 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2380 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2381 	sata_device_t *sdevice = &spx->txlt_sata_pkt->satapkt_device;
2382 	sata_drive_info_t *sdinfo;
2383 	struct buf *bp;
2384 	uint8_t cport, pmport;
2385 	boolean_t dev_gone = B_FALSE;
2386 	int rval;
2387 
2388 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2389 	    "sata_scsi_start: cmd 0x%02x\n", pkt->pkt_cdbp[0]);
2390 
2391 	ASSERT(spx != NULL &&
2392 	    spx->txlt_scsi_pkt == pkt && spx->txlt_sata_pkt != NULL);
2393 
2394 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
2395 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
2396 
2397 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2398 
2399 	if (sdevice->satadev_addr.qual == SATA_ADDR_DCPORT) {
2400 		sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2401 		if (sdinfo == NULL ||
2402 		    SATA_CPORT_INFO(sata_hba_inst, cport)->
2403 		    cport_tgtnode_clean == B_FALSE ||
2404 		    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2405 			dev_gone = B_TRUE;
2406 		}
2407 	} else if (sdevice->satadev_addr.qual == SATA_ADDR_DPMPORT) {
2408 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
2409 		    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
2410 		    cport) == NULL) {
2411 			dev_gone = B_TRUE;
2412 		} else if (SATA_PMPORT_INFO(sata_hba_inst, cport,
2413 		    pmport) == NULL) {
2414 			dev_gone = B_TRUE;
2415 		} else {
2416 			mutex_enter(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2417 			    cport, pmport)));
2418 			sdinfo = sata_get_device_info(sata_hba_inst, sdevice);
2419 			if (sdinfo == NULL ||
2420 			    SATA_PMPORT_INFO(sata_hba_inst, cport, pmport)->
2421 			    pmport_tgtnode_clean == B_FALSE ||
2422 			    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
2423 				dev_gone = B_TRUE;
2424 			}
2425 			mutex_exit(&(SATA_PMPORT_MUTEX(sata_hba_inst,
2426 			    cport, pmport)));
2427 		}
2428 	}
2429 
2430 	if (dev_gone == B_TRUE) {
2431 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2432 		pkt->pkt_reason = CMD_DEV_GONE;
2433 		/*
2434 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
2435 		 * only in callback function (for normal requests) and
2436 		 * in the dump code path.
2437 		 * So, if the callback is available, we need to do
2438 		 * the callback rather than returning TRAN_FATAL_ERROR here.
2439 		 */
2440 		if (pkt->pkt_comp != NULL) {
2441 			/* scsi callback required */
2442 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
2443 			    (task_func_t *)pkt->pkt_comp,
2444 			    (void *)pkt, TQ_NOSLEEP) == NULL)
2445 				/* Scheduling the callback failed */
2446 				return (TRAN_BUSY);
2447 			return (TRAN_ACCEPT);
2448 		}
2449 		/* No callback available */
2450 		return (TRAN_FATAL_ERROR);
2451 	}
2452 
2453 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
2454 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2455 		rval = sata_txlt_atapi(spx);
2456 		SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2457 		    "sata_scsi_start atapi: rval %d\n", rval);
2458 		return (rval);
2459 	}
2460 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
2461 
2462 	/*
2463 	 * Checking for power state, if it was on
2464 	 * STOPPED state, then the drive is not capable
2465 	 * of processing media access command.  And
2466 	 * TEST_UNIT_READY, REQUEST_SENSE has special handling
2467 	 * in the function for different power state.
2468 	 */
2469 	if (((sdinfo->satadrv_power_level == SATA_POWER_STANDBY) ||
2470 	    (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)) &&
2471 	    (SATA_IS_MEDIUM_ACCESS_CMD(pkt->pkt_cdbp[0]))) {
2472 		return (sata_txlt_check_condition(spx, KEY_NOT_READY,
2473 		    SD_SCSI_ASC_LU_NOT_READY));
2474 	}
2475 
2476 	/* ATA Disk commands processing starts here */
2477 
2478 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
2479 
2480 	switch (pkt->pkt_cdbp[0]) {
2481 
2482 	case SCMD_INQUIRY:
2483 		/* Mapped to identify device */
2484 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2485 			bp_mapin(bp);
2486 		rval = sata_txlt_inquiry(spx);
2487 		break;
2488 
2489 	case SCMD_TEST_UNIT_READY:
2490 		/*
2491 		 * SAT "SATA to ATA Translation" doc specifies translation
2492 		 * to ATA CHECK POWER MODE.
2493 		 */
2494 		rval = sata_txlt_test_unit_ready(spx);
2495 		break;
2496 
2497 	case SCMD_START_STOP:
2498 		/* Mapping depends on the command */
2499 		rval = sata_txlt_start_stop_unit(spx);
2500 		break;
2501 
2502 	case SCMD_READ_CAPACITY:
2503 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2504 			bp_mapin(bp);
2505 		rval = sata_txlt_read_capacity(spx);
2506 		break;
2507 
2508 	case SCMD_REQUEST_SENSE:
2509 		/*
2510 		 * Always No Sense, since we force ARQ
2511 		 */
2512 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2513 			bp_mapin(bp);
2514 		rval = sata_txlt_request_sense(spx);
2515 		break;
2516 
2517 	case SCMD_LOG_SENSE_G1:
2518 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2519 			bp_mapin(bp);
2520 		rval = sata_txlt_log_sense(spx);
2521 		break;
2522 
2523 	case SCMD_LOG_SELECT_G1:
2524 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2525 			bp_mapin(bp);
2526 		rval = sata_txlt_log_select(spx);
2527 		break;
2528 
2529 	case SCMD_MODE_SENSE:
2530 	case SCMD_MODE_SENSE_G1:
2531 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2532 			bp_mapin(bp);
2533 		rval = sata_txlt_mode_sense(spx);
2534 		break;
2535 
2536 
2537 	case SCMD_MODE_SELECT:
2538 	case SCMD_MODE_SELECT_G1:
2539 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2540 			bp_mapin(bp);
2541 		rval = sata_txlt_mode_select(spx);
2542 		break;
2543 
2544 	case SCMD_SYNCHRONIZE_CACHE:
2545 	case SCMD_SYNCHRONIZE_CACHE_G1:
2546 		rval = sata_txlt_synchronize_cache(spx);
2547 		break;
2548 
2549 	case SCMD_READ:
2550 	case SCMD_READ_G1:
2551 	case SCMD_READ_G4:
2552 	case SCMD_READ_G5:
2553 		rval = sata_txlt_read(spx);
2554 		break;
2555 	case SCMD_WRITE_BUFFER:
2556 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2557 			bp_mapin(bp);
2558 		rval = sata_txlt_write_buffer(spx);
2559 		break;
2560 
2561 	case SCMD_WRITE:
2562 	case SCMD_WRITE_G1:
2563 	case SCMD_WRITE_G4:
2564 	case SCMD_WRITE_G5:
2565 		rval = sata_txlt_write(spx);
2566 		break;
2567 
2568 	case SCMD_SEEK:
2569 		rval = sata_txlt_nodata_cmd_immediate(spx);
2570 		break;
2571 
2572 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
2573 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
2574 		if (bp != NULL && (bp->b_flags & (B_PHYS | B_PAGEIO)))
2575 			bp_mapin(bp);
2576 		rval = sata_txlt_ata_pass_thru(spx);
2577 		break;
2578 
2579 		/* Other cases will be filed later */
2580 		/* postponed until phase 2 of the development */
2581 	default:
2582 		rval = sata_txlt_invalid_command(spx);
2583 		break;
2584 	}
2585 
2586 	SATADBG1(SATA_DBG_SCSI_IF, sata_hba_inst,
2587 	    "sata_scsi_start: rval %d\n", rval);
2588 
2589 	return (rval);
2590 }
2591 
2592 /*
2593  * Implementation of scsi tran_abort.
2594  * Abort specific pkt or all packets.
2595  *
2596  * Returns 1 if one or more packets were aborted, returns 0 otherwise
2597  *
2598  * May be called from an interrupt level.
2599  */
2600 static int
2601 sata_scsi_abort(struct scsi_address *ap, struct scsi_pkt *scsi_pkt)
2602 {
2603 	sata_hba_inst_t *sata_hba_inst =
2604 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2605 	sata_device_t	sata_device;
2606 	sata_pkt_t	*sata_pkt;
2607 
2608 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2609 	    "sata_scsi_abort: %s at target: 0x%x\n",
2610 	    scsi_pkt == NULL ? "all packets" : "one pkt", ap->a_target);
2611 
2612 	/* Validate address */
2613 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0)
2614 		/* Invalid address */
2615 		return (0);
2616 
2617 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2618 	    sata_device.satadev_addr.cport)));
2619 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2620 		/* invalid address */
2621 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2622 		    sata_device.satadev_addr.cport)));
2623 		return (0);
2624 	}
2625 	if (scsi_pkt == NULL) {
2626 		/*
2627 		 * Abort all packets.
2628 		 * Although we do not have specific packet, we still need
2629 		 * dummy packet structure to pass device address to HBA.
2630 		 * Allocate one, without sleeping. Fail if pkt cannot be
2631 		 * allocated.
2632 		 */
2633 		sata_pkt = kmem_zalloc(sizeof (sata_pkt_t), KM_NOSLEEP);
2634 		if (sata_pkt == NULL) {
2635 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2636 			    sata_device.satadev_addr.cport)));
2637 			SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_pkt_abort: "
2638 			    "could not allocate sata_pkt"));
2639 			return (0);
2640 		}
2641 		sata_pkt->satapkt_rev = SATA_PKT_REV;
2642 		sata_pkt->satapkt_device = sata_device;
2643 		sata_pkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
2644 	} else {
2645 		if (scsi_pkt->pkt_ha_private == NULL) {
2646 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2647 			    sata_device.satadev_addr.cport)));
2648 			return (0); /* Bad scsi pkt */
2649 		}
2650 		/* extract pointer to sata pkt */
2651 		sata_pkt = ((sata_pkt_txlate_t *)scsi_pkt->pkt_ha_private)->
2652 		    txlt_sata_pkt;
2653 	}
2654 
2655 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2656 	    sata_device.satadev_addr.cport)));
2657 	/* Send abort request to HBA */
2658 	if ((*SATA_ABORT_FUNC(sata_hba_inst))
2659 	    (SATA_DIP(sata_hba_inst), sata_pkt,
2660 	    scsi_pkt == NULL ? SATA_ABORT_ALL_PACKETS : SATA_ABORT_PACKET) ==
2661 	    SATA_SUCCESS) {
2662 		if (scsi_pkt == NULL)
2663 			kmem_free(sata_pkt, sizeof (sata_pkt_t));
2664 		/* Success */
2665 		return (1);
2666 	}
2667 	/* Else, something did not go right */
2668 	if (scsi_pkt == NULL)
2669 		kmem_free(sata_pkt, sizeof (sata_pkt_t));
2670 	/* Failure */
2671 	return (0);
2672 }
2673 
2674 
2675 /*
2676  * Implementation of scsi tran_reset.
2677  * RESET_ALL request is translated into port reset.
2678  * RESET_TARGET requests is translated into a device reset,
2679  * RESET_LUN request is accepted only for LUN 0 and translated into
2680  * device reset.
2681  * The target reset should cause all HBA active and queued packets to
2682  * be terminated and returned with pkt reason SATA_PKT_RESET prior to
2683  * the return. HBA should report reset event for the device.
2684  *
2685  * Returns 1 upon success, 0 upon failure.
2686  */
2687 static int
2688 sata_scsi_reset(struct scsi_address *ap, int level)
2689 {
2690 	sata_hba_inst_t	*sata_hba_inst =
2691 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2692 	sata_device_t	sata_device;
2693 	int		val;
2694 
2695 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2696 	    "sata_scsi_reset: level %d target: 0x%x\n",
2697 	    level, ap->a_target);
2698 
2699 	/* Validate address */
2700 	val = sata_validate_scsi_address(sata_hba_inst, ap, &sata_device);
2701 	if (val == -1)
2702 		/* Invalid address */
2703 		return (0);
2704 
2705 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2706 	    sata_device.satadev_addr.cport)));
2707 	if (sata_get_device_info(sata_hba_inst, &sata_device) == NULL) {
2708 		/* invalid address */
2709 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2710 		    sata_device.satadev_addr.cport)));
2711 		return (0);
2712 	}
2713 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2714 	    sata_device.satadev_addr.cport)));
2715 	if (level == RESET_ALL) {
2716 		/* port reset */
2717 		if (sata_device.satadev_addr.qual == SATA_ADDR_DCPORT)
2718 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
2719 		else
2720 			sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
2721 
2722 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2723 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2724 			return (1);
2725 		else
2726 			return (0);
2727 
2728 	} else if (val == 0 &&
2729 	    (level == RESET_TARGET || level == RESET_LUN)) {
2730 		/* reset device (device attached) */
2731 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
2732 		    (SATA_DIP(sata_hba_inst), &sata_device) == SATA_SUCCESS)
2733 			return (1);
2734 		else
2735 			return (0);
2736 	}
2737 	return (0);
2738 }
2739 
2740 
2741 /*
2742  * Implementation of scsi tran_getcap (get transport/device capabilities).
2743  * Supported capabilities for SATA hard disks:
2744  * auto-rqsense		(always supported)
2745  * tagged-qing		(supported if HBA supports it)
2746  * untagged-qing	(could be supported if disk supports it, but because
2747  *			 caching behavior allowing untagged queuing actually
2748  *			 results in reduced performance.  sd tries to throttle
2749  *			 back to only 3 outstanding commands, which may
2750  *			 work for real SCSI disks, but with read ahead
2751  *			 caching, having more than 1 outstanding command
2752  *			 results in cache thrashing.)
2753  * sector_size
2754  * dma_max
2755  * interconnect-type	(INTERCONNECT_SATA)
2756  *
2757  * Supported capabilities for ATAPI CD/DVD devices:
2758  * auto-rqsense		(always supported)
2759  * sector_size
2760  * dma_max
2761  * max-cdb-length
2762  * interconnect-type	(INTERCONNECT_SATA)
2763  *
2764  * Supported capabilities for ATAPI TAPE devices:
2765  * auto-rqsense		(always supported)
2766  * dma_max
2767  * max-cdb-length
2768  *
2769  * Supported capabilities for SATA ATAPI hard disks:
2770  * auto-rqsense		(always supported)
2771  * interconnect-type	(INTERCONNECT_SATA)
2772  * max-cdb-length
2773  *
2774  * Request for other capabilities is rejected as unsupported.
2775  *
2776  * Returns supported capability value, or -1 if capability is unsuppported or
2777  * the address is invalid - no device.
2778  */
2779 
2780 static int
2781 sata_scsi_getcap(struct scsi_address *ap, char *cap, int whom)
2782 {
2783 
2784 	sata_hba_inst_t 	*sata_hba_inst =
2785 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2786 	sata_device_t		sata_device;
2787 	sata_drive_info_t	*sdinfo;
2788 	ddi_dma_attr_t		adj_dma_attr;
2789 	int 			rval;
2790 
2791 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2792 	    "sata_scsi_getcap: target: 0x%x, cap: %s\n",
2793 	    ap->a_target, cap);
2794 
2795 	/*
2796 	 * We want to process the capabilities on per port granularity.
2797 	 * So, we are specifically restricting ourselves to whom != 0
2798 	 * to exclude the controller wide handling.
2799 	 */
2800 	if (cap == NULL || whom == 0)
2801 		return (-1);
2802 
2803 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2804 		/* Invalid address */
2805 		return (-1);
2806 	}
2807 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2808 	    sata_device.satadev_addr.cport)));
2809 	if ((sdinfo = sata_get_device_info(sata_hba_inst, &sata_device)) ==
2810 	    NULL) {
2811 		/* invalid address */
2812 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2813 		    sata_device.satadev_addr.cport)));
2814 		return (-1);
2815 	}
2816 
2817 	switch (scsi_hba_lookup_capstr(cap)) {
2818 	case SCSI_CAP_ARQ:
2819 		rval = 1;		/* ARQ supported, turned on */
2820 		break;
2821 
2822 	case SCSI_CAP_SECTOR_SIZE:
2823 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK)
2824 			rval = SATA_DISK_SECTOR_SIZE;	/* fixed size */
2825 		else if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD)
2826 			rval = SATA_ATAPI_SECTOR_SIZE;
2827 		else rval = -1;
2828 		break;
2829 
2830 	/*
2831 	 * untagged queuing cause a performance inversion because of
2832 	 * the way sd operates.  Because of this reason we do not
2833 	 * use it when available.
2834 	 */
2835 	case SCSI_CAP_UNTAGGED_QING:
2836 		if (sdinfo->satadrv_features_enabled &
2837 		    SATA_DEV_F_E_UNTAGGED_QING)
2838 			rval = 1;	/* Untagged queuing available */
2839 		else
2840 			rval = -1;	/* Untagged queuing not available */
2841 		break;
2842 
2843 	case SCSI_CAP_TAGGED_QING:
2844 		if ((sdinfo->satadrv_features_enabled &
2845 		    SATA_DEV_F_E_TAGGED_QING) &&
2846 		    (sdinfo->satadrv_max_queue_depth > 1))
2847 			rval = 1;	/* Tagged queuing available */
2848 		else
2849 			rval = -1;	/* Tagged queuing not available */
2850 		break;
2851 
2852 	case SCSI_CAP_DMA_MAX:
2853 		sata_adjust_dma_attr(sdinfo, SATA_DMA_ATTR(sata_hba_inst),
2854 		    &adj_dma_attr);
2855 		rval = (int)adj_dma_attr.dma_attr_maxxfer;
2856 		/* We rely on the fact that dma_attr_maxxfer < 0x80000000 */
2857 		break;
2858 
2859 	case SCSI_CAP_INTERCONNECT_TYPE:
2860 		rval = INTERCONNECT_SATA;	/* SATA interconnect type */
2861 		break;
2862 
2863 	case SCSI_CAP_CDB_LEN:
2864 		if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI)
2865 			rval = sdinfo->satadrv_atapi_cdb_len;
2866 		else
2867 			rval = -1;
2868 		break;
2869 
2870 	default:
2871 		rval = -1;
2872 		break;
2873 	}
2874 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2875 	    sata_device.satadev_addr.cport)));
2876 	return (rval);
2877 }
2878 
2879 /*
2880  * Implementation of scsi tran_setcap
2881  *
2882  * Only SCSI_CAP_UNTAGGED_QING and  SCSI_CAP_TAGGED_QING are changeable.
2883  *
2884  */
2885 static int
2886 sata_scsi_setcap(struct scsi_address *ap, char *cap, int value, int whom)
2887 {
2888 	sata_hba_inst_t	*sata_hba_inst =
2889 	    (sata_hba_inst_t *)(ap->a_hba_tran->tran_hba_private);
2890 	sata_device_t	sata_device;
2891 	sata_drive_info_t	*sdinfo;
2892 	int		rval;
2893 
2894 	SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
2895 	    "sata_scsi_setcap: target: 0x%x, cap: %s\n", ap->a_target, cap);
2896 
2897 	/*
2898 	 * We want to process the capabilities on per port granularity.
2899 	 * So, we are specifically restricting ourselves to whom != 0
2900 	 * to exclude the controller wide handling.
2901 	 */
2902 	if (cap == NULL || whom == 0) {
2903 		return (-1);
2904 	}
2905 
2906 	if (sata_validate_scsi_address(sata_hba_inst, ap, &sata_device) != 0) {
2907 		/* Invalid address */
2908 		return (-1);
2909 	}
2910 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
2911 	    sata_device.satadev_addr.cport)));
2912 	if ((sdinfo = sata_get_device_info(sata_hba_inst,
2913 	    &sata_device)) == NULL) {
2914 		/* invalid address */
2915 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2916 		    sata_device.satadev_addr.cport)));
2917 		return (-1);
2918 	}
2919 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
2920 	    sata_device.satadev_addr.cport)));
2921 
2922 	switch (scsi_hba_lookup_capstr(cap)) {
2923 	case SCSI_CAP_ARQ:
2924 	case SCSI_CAP_SECTOR_SIZE:
2925 	case SCSI_CAP_DMA_MAX:
2926 	case SCSI_CAP_INTERCONNECT_TYPE:
2927 		rval = 0;
2928 		break;
2929 	case SCSI_CAP_UNTAGGED_QING:
2930 		if (SATA_QDEPTH(sata_hba_inst) > 1) {
2931 			rval = 1;
2932 			if (value == 1) {
2933 				sdinfo->satadrv_features_enabled |=
2934 				    SATA_DEV_F_E_UNTAGGED_QING;
2935 			} else if (value == 0) {
2936 				sdinfo->satadrv_features_enabled &=
2937 				    ~SATA_DEV_F_E_UNTAGGED_QING;
2938 			} else {
2939 				rval = -1;
2940 			}
2941 		} else {
2942 			rval = 0;
2943 		}
2944 		break;
2945 	case SCSI_CAP_TAGGED_QING:
2946 		/* This can TCQ or NCQ */
2947 		if (sata_func_enable & SATA_ENABLE_QUEUING &&
2948 		    ((sdinfo->satadrv_features_support & SATA_DEV_F_TCQ &&
2949 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_QCMD) ||
2950 		    (sata_func_enable & SATA_ENABLE_NCQ &&
2951 		    sdinfo->satadrv_features_support & SATA_DEV_F_NCQ &&
2952 		    SATA_FEATURES(sata_hba_inst) & SATA_CTLF_NCQ)) &&
2953 		    (sdinfo->satadrv_max_queue_depth > 1)) {
2954 			rval = 1;
2955 			if (value == 1) {
2956 				sdinfo->satadrv_features_enabled |=
2957 				    SATA_DEV_F_E_TAGGED_QING;
2958 			} else if (value == 0) {
2959 				sdinfo->satadrv_features_enabled &=
2960 				    ~SATA_DEV_F_E_TAGGED_QING;
2961 			} else {
2962 				rval = -1;
2963 			}
2964 		} else {
2965 			rval = 0;
2966 		}
2967 		break;
2968 	default:
2969 		rval = -1;
2970 		break;
2971 	}
2972 	return (rval);
2973 }
2974 
2975 /*
2976  * Implementations of scsi tran_destroy_pkt.
2977  * Free resources allocated by sata_scsi_init_pkt()
2978  */
2979 static void
2980 sata_scsi_destroy_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
2981 {
2982 	sata_pkt_txlate_t *spx;
2983 
2984 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
2985 
2986 	sata_common_free_dma_rsrcs(spx);
2987 
2988 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
2989 	sata_pkt_free(spx);
2990 
2991 	scsi_hba_pkt_free(ap, pkt);
2992 }
2993 
2994 /*
2995  * Implementation of scsi tran_dmafree.
2996  * Free DMA resources allocated by sata_scsi_init_pkt()
2997  */
2998 
2999 static void
3000 sata_scsi_dmafree(struct scsi_address *ap, struct scsi_pkt *pkt)
3001 {
3002 #ifndef __lock_lint
3003 	_NOTE(ARGUNUSED(ap))
3004 #endif
3005 	sata_pkt_txlate_t *spx;
3006 
3007 	ASSERT(pkt != NULL);
3008 	spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3009 
3010 	sata_common_free_dma_rsrcs(spx);
3011 }
3012 
3013 /*
3014  * Implementation of scsi tran_sync_pkt.
3015  *
3016  * The assumption below is that pkt is unique - there is no need to check ap
3017  *
3018  * Synchronize DMA buffer and, if the intermediate buffer is used, copy data
3019  * into/from the real buffer.
3020  */
3021 static void
3022 sata_scsi_sync_pkt(struct scsi_address *ap, struct scsi_pkt *pkt)
3023 {
3024 #ifndef __lock_lint
3025 	_NOTE(ARGUNUSED(ap))
3026 #endif
3027 	int rval;
3028 	sata_pkt_txlate_t *spx = (sata_pkt_txlate_t *)pkt->pkt_ha_private;
3029 	struct buf *bp;
3030 	int direction;
3031 
3032 	ASSERT(spx != NULL);
3033 	if (spx->txlt_buf_dma_handle != NULL) {
3034 		direction = spx->txlt_sata_pkt->
3035 		    satapkt_cmd.satacmd_flags.sata_data_direction;
3036 		if (spx->txlt_sata_pkt != NULL &&
3037 		    direction != SATA_DIR_NODATA_XFER) {
3038 			if (spx->txlt_tmp_buf != NULL) {
3039 				/* Intermediate DMA buffer used */
3040 				bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3041 
3042 				if (direction & SATA_DIR_WRITE) {
3043 					bcopy(bp->b_un.b_addr,
3044 					    spx->txlt_tmp_buf, bp->b_bcount);
3045 				}
3046 			}
3047 			/* Sync the buffer for device or for CPU */
3048 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle,   0, 0,
3049 			    (direction & SATA_DIR_WRITE) ?
3050 			    DDI_DMA_SYNC_FORDEV :  DDI_DMA_SYNC_FORCPU);
3051 			ASSERT(rval == DDI_SUCCESS);
3052 			if (spx->txlt_tmp_buf != NULL &&
3053 			    !(direction & SATA_DIR_WRITE)) {
3054 				/* Intermediate DMA buffer used for read */
3055 				bcopy(spx->txlt_tmp_buf,
3056 				    bp->b_un.b_addr, bp->b_bcount);
3057 			}
3058 
3059 		}
3060 	}
3061 }
3062 
3063 
3064 
3065 /* *******************  SATA - SCSI Translation functions **************** */
3066 /*
3067  * SCSI to SATA pkt and command translation and SATA to SCSI status/error
3068  * translation.
3069  */
3070 
3071 /*
3072  * Checks if a device exists and can be access and translates common
3073  * scsi_pkt data to sata_pkt data.
3074  *
3075  * Flag argument indicates that ATA command may be sent to HBA to execute
3076  * this packet.
3077  *
3078  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_CMPLT if device exists and
3079  * sata_pkt was set-up.
3080  * Returns TRAN_ACCEPT and scsi pkt_reason CMD_DEV_GONE if device does not
3081  * exist and pkt_comp callback was scheduled.
3082  * Returns other TRAN_XXXXX values when error occured and command should be
3083  * rejected with the returned TRAN_XXXXX value.
3084  *
3085  * This function should be called with port mutex held.
3086  */
3087 static int
3088 sata_txlt_generic_pkt_info(sata_pkt_txlate_t *spx, int *reason, int flag)
3089 {
3090 	sata_drive_info_t *sdinfo;
3091 	sata_device_t sata_device;
3092 	const struct sata_cmd_flags sata_initial_cmd_flags = {
3093 		SATA_DIR_NODATA_XFER,
3094 		/* all other values to 0/FALSE */
3095 	};
3096 	/*
3097 	 * Pkt_reason has to be set if the pkt_comp callback is invoked,
3098 	 * and that implies TRAN_ACCEPT return value. Any other returned value
3099 	 * indicates that the scsi packet was not accepted (the reason will not
3100 	 * be checked by the scsi target driver).
3101 	 * To make debugging easier, we set pkt_reason to know value here.
3102 	 * It may be changed later when different completion reason is
3103 	 * determined.
3104 	 */
3105 	spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
3106 	*reason = CMD_TRAN_ERR;
3107 
3108 	/* Validate address */
3109 	switch (sata_validate_scsi_address(spx->txlt_sata_hba_inst,
3110 	    &spx->txlt_scsi_pkt->pkt_address, &sata_device)) {
3111 
3112 	case -1:
3113 		/* Invalid address or invalid device type */
3114 		return (TRAN_BADPKT);
3115 	case 2:
3116 		/*
3117 		 * Valid address but device type is unknown - Chack if it is
3118 		 * in the reset state and therefore in an indeterminate state.
3119 		 */
3120 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3121 		    &spx->txlt_sata_pkt->satapkt_device);
3122 		if (sdinfo != NULL && (sdinfo->satadrv_event_flags &
3123 		    (SATA_EVNT_DEVICE_RESET |
3124 		    SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3125 			if (!ddi_in_panic()) {
3126 				spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3127 				*reason = CMD_INCOMPLETE;
3128 				SATADBG1(SATA_DBG_SCSI_IF,
3129 				    spx->txlt_sata_hba_inst,
3130 				    "sata_scsi_start: rejecting command "
3131 				    "because of device reset state\n", NULL);
3132 				return (TRAN_BUSY);
3133 			}
3134 		}
3135 		/* FALLTHROUGH */
3136 	case 1:
3137 		/* valid address but no valid device - it has disappeared */
3138 		spx->txlt_scsi_pkt->pkt_reason = CMD_DEV_GONE;
3139 		*reason = CMD_DEV_GONE;
3140 		/*
3141 		 * The sd target driver is checking CMD_DEV_GONE pkt_reason
3142 		 * only in callback function (for normal requests) and
3143 		 * in the dump code path.
3144 		 * So, if the callback is available, we need to do
3145 		 * the callback rather than returning TRAN_FATAL_ERROR here.
3146 		 */
3147 		if (spx->txlt_scsi_pkt->pkt_comp != NULL) {
3148 			/* scsi callback required */
3149 			if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3150 			    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3151 			    (void *)spx->txlt_scsi_pkt,
3152 			    TQ_SLEEP) == NULL)
3153 				/* Scheduling the callback failed */
3154 				return (TRAN_BUSY);
3155 
3156 			return (TRAN_ACCEPT);
3157 		}
3158 		return (TRAN_FATAL_ERROR);
3159 	default:
3160 		/* all OK; pkt reason will be overwritten later */
3161 		break;
3162 	}
3163 	/*
3164 	 * If pkt is to be executed in polling mode and a command will not be
3165 	 * emulated in SATA module (requires sending ATA command to HBA
3166 	 * driver) and we are in the interrupt contex and not in panic dump,
3167 	 * then reject the packet to avoid a possible interrupt stack overrun.
3168 	 */
3169 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0 && flag != 0 &&
3170 	    servicing_interrupt() && !ddi_in_panic()) {
3171 		SATADBG1(SATA_DBG_INTR_CTX, spx->txlt_sata_hba_inst,
3172 		    "sata_scsi_start: rejecting synchronous command because "
3173 		    "of interrupt context\n", NULL);
3174 		return (TRAN_BUSY);
3175 	}
3176 
3177 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3178 	    &spx->txlt_sata_pkt->satapkt_device);
3179 
3180 	/*
3181 	 * If device is in reset condition, reject the packet with
3182 	 * TRAN_BUSY, unless:
3183 	 * 1. system is panicking (dumping)
3184 	 * In such case only one thread is running and there is no way to
3185 	 * process reset.
3186 	 * 2. cfgadm operation is is progress (internal APCTL lock is set)
3187 	 * Some cfgadm operations involve drive commands, so reset condition
3188 	 * needs to be ignored for IOCTL operations.
3189 	 */
3190 	if ((sdinfo->satadrv_event_flags &
3191 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) != 0) {
3192 
3193 		if (!ddi_in_panic() &&
3194 		    ((SATA_CPORT_EVENT_FLAGS(spx->txlt_sata_hba_inst,
3195 		    sata_device.satadev_addr.cport) &
3196 		    SATA_APCTL_LOCK_PORT_BUSY) == 0)) {
3197 			spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
3198 			*reason = CMD_INCOMPLETE;
3199 			SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3200 			    "sata_scsi_start: rejecting command because "
3201 			    "of device reset state\n", NULL);
3202 			return (TRAN_BUSY);
3203 		}
3204 	}
3205 
3206 	/*
3207 	 * Fix the dev_type in the sata_pkt->satapkt_device. It was not set by
3208 	 * sata_scsi_pkt_init() because pkt init had to work also with
3209 	 * non-existing devices.
3210 	 * Now we know that the packet was set-up for a real device, so its
3211 	 * type is known.
3212 	 */
3213 	spx->txlt_sata_pkt->satapkt_device.satadev_type = sdinfo->satadrv_type;
3214 
3215 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags = sata_initial_cmd_flags;
3216 	if ((SATA_CPORT_INFO(spx->txlt_sata_hba_inst,
3217 	    sata_device.satadev_addr.cport)->cport_event_flags &
3218 	    SATA_APCTL_LOCK_PORT_BUSY) != 0) {
3219 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3220 		    sata_ignore_dev_reset = B_TRUE;
3221 	}
3222 	/*
3223 	 * At this point the generic translation routine determined that the
3224 	 * scsi packet should be accepted. Packet completion reason may be
3225 	 * changed later when a different completion reason is determined.
3226 	 */
3227 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3228 	*reason = CMD_CMPLT;
3229 
3230 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) != 0) {
3231 		/* Synchronous execution */
3232 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH |
3233 		    SATA_OPMODE_POLLING;
3234 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
3235 		    sata_ignore_dev_reset = ddi_in_panic();
3236 	} else {
3237 		/* Asynchronous execution */
3238 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_ASYNCH |
3239 		    SATA_OPMODE_INTERRUPTS;
3240 	}
3241 	/* Convert queuing information */
3242 	if (spx->txlt_scsi_pkt->pkt_flags & FLAG_STAG)
3243 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_stag =
3244 		    B_TRUE;
3245 	else if (spx->txlt_scsi_pkt->pkt_flags &
3246 	    (FLAG_OTAG | FLAG_HTAG | FLAG_HEAD))
3247 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.sata_queue_otag =
3248 		    B_TRUE;
3249 
3250 	/* Always limit pkt time */
3251 	if (spx->txlt_scsi_pkt->pkt_time == 0)
3252 		spx->txlt_sata_pkt->satapkt_time = sata_default_pkt_time;
3253 	else
3254 		/* Pass on scsi_pkt time */
3255 		spx->txlt_sata_pkt->satapkt_time =
3256 		    spx->txlt_scsi_pkt->pkt_time;
3257 
3258 	return (TRAN_ACCEPT);
3259 }
3260 
3261 
3262 /*
3263  * Translate ATA Identify Device data to SCSI Inquiry data.
3264  * This function may be called only for ATA devices.
3265  * This function should not be called for ATAPI devices - they
3266  * respond directly to SCSI Inquiry command.
3267  *
3268  * SATA Identify Device data has to be valid in sata_drive_info.
3269  * Buffer has to accomodate the inquiry length (36 bytes).
3270  *
3271  * This function should be called with a port mutex held.
3272  */
3273 static	void
3274 sata_identdev_to_inquiry(sata_hba_inst_t *sata_hba_inst,
3275     sata_drive_info_t *sdinfo, uint8_t *buf)
3276 {
3277 
3278 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
3279 	struct sata_id *sid = &sdinfo->satadrv_id;
3280 
3281 	/* Start with a nice clean slate */
3282 	bzero((void *)inq, sizeof (struct scsi_inquiry));
3283 
3284 	/*
3285 	 * Rely on the dev_type for setting paripheral qualifier.
3286 	 * Assume that  DTYPE_RODIRECT applies to CD/DVD R/W devices.
3287 	 * It could be that DTYPE_OPTICAL could also qualify in the future.
3288 	 * ATAPI Inquiry may provide more data to the target driver.
3289 	 */
3290 	inq->inq_dtype = sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3291 	    DTYPE_DIRECT : DTYPE_RODIRECT; /* DTYPE_UNKNOWN; */
3292 
3293 	/* CFA type device is not a removable media device */
3294 	inq->inq_rmb = ((sid->ai_config != SATA_CFA_TYPE) &&
3295 	    (sid->ai_config & SATA_REM_MEDIA)) ? 1 : 0;
3296 	inq->inq_qual = 0;	/* Device type qualifier (obsolete in SCSI3? */
3297 	inq->inq_iso = 0;	/* ISO version */
3298 	inq->inq_ecma = 0;	/* ECMA version */
3299 	inq->inq_ansi = 3;	/* ANSI version - SCSI 3 */
3300 	inq->inq_aenc = 0;	/* Async event notification cap. */
3301 	inq->inq_trmiop = 0;	/* Supports TERMINATE I/O PROC msg - NO */
3302 	inq->inq_normaca = 0;	/* setting NACA bit supported - NO */
3303 	inq->inq_rdf = RDF_SCSI2; /* Response data format- SPC-3 */
3304 	inq->inq_len = 31;	/* Additional length */
3305 	inq->inq_dualp = 0;	/* dual port device - NO */
3306 	inq->inq_reladdr = 0;	/* Supports relative addressing - NO */
3307 	inq->inq_sync = 0;	/* Supports synchronous data xfers - NO */
3308 	inq->inq_linked = 0;	/* Supports linked commands - NO */
3309 				/*
3310 				 * Queuing support - controller has to
3311 				 * support some sort of command queuing.
3312 				 */
3313 	if (SATA_QDEPTH(sata_hba_inst) > 1)
3314 		inq->inq_cmdque = 1; /* Supports command queueing - YES */
3315 	else
3316 		inq->inq_cmdque = 0; /* Supports command queueing - NO */
3317 	inq->inq_sftre = 0;	/* Supports Soft Reset option - NO ??? */
3318 	inq->inq_wbus32 = 0;	/* Supports 32 bit wide data xfers - NO */
3319 	inq->inq_wbus16 = 0;	/* Supports 16 bit wide data xfers - NO */
3320 
3321 #ifdef	_LITTLE_ENDIAN
3322 	/* Swap text fields to match SCSI format */
3323 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3324 	swab(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3325 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3326 		swab(sid->ai_fw, inq->inq_revision, 4);	/* Revision level */
3327 	else
3328 		swab(&sid->ai_fw[4], inq->inq_revision, 4);	/* Rev. level */
3329 #else	/* _LITTLE_ENDIAN */
3330 	bcopy("ATA     ", inq->inq_vid, 8);		/* Vendor ID */
3331 	bcopy(sid->ai_model, inq->inq_pid, 16);		/* Product ID */
3332 	if (strncmp(&sid->ai_fw[4], "    ", 4) == 0)
3333 		bcopy(sid->ai_fw, inq->inq_revision, 4); /* Revision level */
3334 	else
3335 		bcopy(&sid->ai_fw[4], inq->inq_revision, 4); /* Rev. level */
3336 #endif	/* _LITTLE_ENDIAN */
3337 }
3338 
3339 
3340 /*
3341  * Scsi response set up for invalid command (command not supported)
3342  *
3343  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3344  */
3345 static int
3346 sata_txlt_invalid_command(sata_pkt_txlate_t *spx)
3347 {
3348 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3349 	struct scsi_extended_sense *sense;
3350 
3351 	scsipkt->pkt_reason = CMD_CMPLT;
3352 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3353 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3354 
3355 	*scsipkt->pkt_scbp = STATUS_CHECK;
3356 
3357 	sense = sata_arq_sense(spx);
3358 	sense->es_key = KEY_ILLEGAL_REQUEST;
3359 	sense->es_add_code = SD_SCSI_ASC_INVALID_COMMAND_CODE;
3360 
3361 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3362 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3363 
3364 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3365 	    scsipkt->pkt_comp != NULL)
3366 		/* scsi callback required */
3367 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3368 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3369 		    (void *)spx->txlt_scsi_pkt,
3370 		    TQ_SLEEP) == NULL)
3371 			/* Scheduling the callback failed */
3372 			return (TRAN_BUSY);
3373 	return (TRAN_ACCEPT);
3374 }
3375 
3376 /*
3377  * Scsi response set up for check condition with special sense key
3378  * and additional sense code.
3379  *
3380  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3381  */
3382 static int
3383 sata_txlt_check_condition(sata_pkt_txlate_t *spx, uchar_t key, uchar_t code)
3384 {
3385 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3386 	int cport = SATA_TXLT_CPORT(spx);
3387 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3388 	struct scsi_extended_sense *sense;
3389 
3390 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3391 	scsipkt->pkt_reason = CMD_CMPLT;
3392 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3393 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3394 
3395 	*scsipkt->pkt_scbp = STATUS_CHECK;
3396 
3397 	sense = sata_arq_sense(spx);
3398 	sense->es_key = key;
3399 	sense->es_add_code = code;
3400 
3401 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3402 
3403 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3404 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3405 
3406 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3407 		/* scsi callback required */
3408 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3409 		    (task_func_t *)scsi_hba_pkt_comp,
3410 		    (void *)spx->txlt_scsi_pkt,
3411 		    TQ_SLEEP) == NULL)
3412 			/* Scheduling the callback failed */
3413 			return (TRAN_BUSY);
3414 	return (TRAN_ACCEPT);
3415 }
3416 
3417 /*
3418  * Scsi response setup for
3419  * emulated non-data command that requires no action/return data
3420  *
3421  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3422  */
3423 static	int
3424 sata_txlt_nodata_cmd_immediate(sata_pkt_txlate_t *spx)
3425 {
3426 	int rval;
3427 	int reason;
3428 
3429 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3430 
3431 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3432 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3433 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3434 		return (rval);
3435 	}
3436 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3437 
3438 	spx->txlt_scsi_pkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3439 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3440 	spx->txlt_scsi_pkt->pkt_reason = CMD_CMPLT;
3441 	*(spx->txlt_scsi_pkt->pkt_scbp) = STATUS_GOOD;
3442 
3443 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3444 	    "Scsi_pkt completion reason %x\n",
3445 	    spx->txlt_scsi_pkt->pkt_reason);
3446 
3447 	if ((spx->txlt_scsi_pkt->pkt_flags & FLAG_NOINTR) == 0 &&
3448 	    spx->txlt_scsi_pkt->pkt_comp != NULL)
3449 		/* scsi callback required */
3450 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3451 		    (task_func_t *)spx->txlt_scsi_pkt->pkt_comp,
3452 		    (void *)spx->txlt_scsi_pkt,
3453 		    TQ_SLEEP) == NULL)
3454 			/* Scheduling the callback failed */
3455 			return (TRAN_BUSY);
3456 	return (TRAN_ACCEPT);
3457 }
3458 
3459 
3460 /*
3461  * SATA translate command: Inquiry / Identify Device
3462  * Use cached Identify Device data for now, rather than issuing actual
3463  * Device Identify cmd request. If device is detached and re-attached,
3464  * asynchronous event processing should fetch and refresh Identify Device
3465  * data.
3466  * Two VPD pages are supported now:
3467  * Vital Product Data page
3468  * Unit Serial Number page
3469  *
3470  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3471  */
3472 
3473 #define	EVPD			1	/* Extended Vital Product Data flag */
3474 #define	CMDDT			2	/* Command Support Data - Obsolete */
3475 #define	INQUIRY_SUP_VPD_PAGE	0	/* Supported VDP Pages Page COde */
3476 #define	INQUIRY_USN_PAGE	0x80	/* Unit Serial Number Page Code */
3477 #define	INQUIRY_DEV_IDENTIFICATION_PAGE 0x83 /* Not needed yet */
3478 
3479 static int
3480 sata_txlt_inquiry(sata_pkt_txlate_t *spx)
3481 {
3482 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3483 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3484 	sata_drive_info_t *sdinfo;
3485 	struct scsi_extended_sense *sense;
3486 	int count;
3487 	uint8_t *p;
3488 	int i, j;
3489 	uint8_t page_buf[0xff]; /* Max length */
3490 	int rval, reason;
3491 
3492 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3493 
3494 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
3495 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3496 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3497 		return (rval);
3498 	}
3499 
3500 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3501 	    &spx->txlt_sata_pkt->satapkt_device);
3502 
3503 	ASSERT(sdinfo != NULL);
3504 
3505 	scsipkt->pkt_reason = CMD_CMPLT;
3506 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3507 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3508 
3509 	/* Reject not supported request */
3510 	if (scsipkt->pkt_cdbp[1] & CMDDT) { /* No support for this bit */
3511 		*scsipkt->pkt_scbp = STATUS_CHECK;
3512 		sense = sata_arq_sense(spx);
3513 		sense->es_key = KEY_ILLEGAL_REQUEST;
3514 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3515 		goto done;
3516 	}
3517 
3518 	/* Valid Inquiry request */
3519 	*scsipkt->pkt_scbp = STATUS_GOOD;
3520 
3521 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3522 
3523 		/*
3524 		 * Because it is fully emulated command storing data
3525 		 * programatically in the specified buffer, release
3526 		 * preallocated DMA resources before storing data in the buffer,
3527 		 * so no unwanted DMA sync would take place.
3528 		 */
3529 		sata_scsi_dmafree(NULL, scsipkt);
3530 
3531 		if (!(scsipkt->pkt_cdbp[1] & EVPD)) {
3532 			/* Standard Inquiry Data request */
3533 			struct scsi_inquiry inq;
3534 			unsigned int bufsize;
3535 
3536 			sata_identdev_to_inquiry(spx->txlt_sata_hba_inst,
3537 			    sdinfo, (uint8_t *)&inq);
3538 			/* Copy no more than requested */
3539 			count = MIN(bp->b_bcount,
3540 			    sizeof (struct scsi_inquiry));
3541 			bufsize = scsipkt->pkt_cdbp[4];
3542 			bufsize |= scsipkt->pkt_cdbp[3] << 8;
3543 			count = MIN(count, bufsize);
3544 			bcopy(&inq, bp->b_un.b_addr, count);
3545 
3546 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
3547 			scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3548 			    bufsize - count : 0;
3549 		} else {
3550 			/*
3551 			 * peripheral_qualifier = 0;
3552 			 *
3553 			 * We are dealing only with HD and will be
3554 			 * dealing with CD/DVD devices soon
3555 			 */
3556 			uint8_t peripheral_device_type =
3557 			    sdinfo->satadrv_type == SATA_DTYPE_ATADISK ?
3558 			    DTYPE_DIRECT : DTYPE_RODIRECT;
3559 
3560 			switch ((uint_t)scsipkt->pkt_cdbp[2]) {
3561 			case INQUIRY_SUP_VPD_PAGE:
3562 				/*
3563 				 * Request for suported Vital Product Data
3564 				 * pages - assuming only 2 page codes
3565 				 * supported.
3566 				 */
3567 				page_buf[0] = peripheral_device_type;
3568 				page_buf[1] = INQUIRY_SUP_VPD_PAGE;
3569 				page_buf[2] = 0;
3570 				page_buf[3] = 2; /* page length */
3571 				page_buf[4] = INQUIRY_SUP_VPD_PAGE;
3572 				page_buf[5] = INQUIRY_USN_PAGE;
3573 				/* Copy no more than requested */
3574 				count = MIN(bp->b_bcount, 6);
3575 				bcopy(page_buf, bp->b_un.b_addr, count);
3576 				break;
3577 
3578 			case INQUIRY_USN_PAGE:
3579 				/*
3580 				 * Request for Unit Serial Number page.
3581 				 * Set-up the page.
3582 				 */
3583 				page_buf[0] = peripheral_device_type;
3584 				page_buf[1] = INQUIRY_USN_PAGE;
3585 				page_buf[2] = 0;
3586 				/* remaining page length */
3587 				page_buf[3] = SATA_ID_SERIAL_LEN;
3588 
3589 				/*
3590 				 * Copy serial number from Identify Device data
3591 				 * words into the inquiry page and swap bytes
3592 				 * when necessary.
3593 				 */
3594 				p = (uint8_t *)(sdinfo->satadrv_id.ai_drvser);
3595 #ifdef	_LITTLE_ENDIAN
3596 				swab(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3597 #else
3598 				bcopy(p, &page_buf[4], SATA_ID_SERIAL_LEN);
3599 #endif
3600 				/*
3601 				 * Least significant character of the serial
3602 				 * number shall appear as the last byte,
3603 				 * according to SBC-3 spec.
3604 				 * Count trailing spaces to determine the
3605 				 * necessary shift length.
3606 				 */
3607 				p = &page_buf[SATA_ID_SERIAL_LEN + 4 - 1];
3608 				for (j = 0; j < SATA_ID_SERIAL_LEN; j++) {
3609 					if (*(p - j) != '\0' &&
3610 					    *(p - j) != '\040')
3611 						break;
3612 				}
3613 
3614 				/*
3615 				 * Shift SN string right, so that the last
3616 				 * non-blank character would appear in last
3617 				 * byte of SN field in the page.
3618 				 * 'j' is the shift length.
3619 				 */
3620 				for (i = 0;
3621 				    i < (SATA_ID_SERIAL_LEN - j) && j != 0;
3622 				    i++, p--)
3623 					*p = *(p - j);
3624 
3625 				/*
3626 				 * Add leading spaces - same number as the
3627 				 * shift size
3628 				 */
3629 				for (; j > 0; j--)
3630 					page_buf[4 + j - 1] = '\040';
3631 
3632 				count = MIN(bp->b_bcount,
3633 				    SATA_ID_SERIAL_LEN + 4);
3634 				bcopy(page_buf, bp->b_un.b_addr, count);
3635 				break;
3636 
3637 			case INQUIRY_DEV_IDENTIFICATION_PAGE:
3638 				/*
3639 				 * We may want to implement this page, when
3640 				 * identifiers are common for SATA devices
3641 				 * But not now.
3642 				 */
3643 				/*FALLTHROUGH*/
3644 
3645 			default:
3646 				/* Request for unsupported VPD page */
3647 				*scsipkt->pkt_scbp = STATUS_CHECK;
3648 				sense = sata_arq_sense(spx);
3649 				sense->es_key = KEY_ILLEGAL_REQUEST;
3650 				sense->es_add_code =
3651 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
3652 				goto done;
3653 			}
3654 		}
3655 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3656 		scsipkt->pkt_resid = scsipkt->pkt_cdbp[4] > count ?
3657 		    scsipkt->pkt_cdbp[4] - count : 0;
3658 	}
3659 done:
3660 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3661 
3662 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3663 	    "Scsi_pkt completion reason %x\n",
3664 	    scsipkt->pkt_reason);
3665 
3666 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
3667 	    scsipkt->pkt_comp != NULL) {
3668 		/* scsi callback required */
3669 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3670 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
3671 		    TQ_SLEEP) == NULL)
3672 			/* Scheduling the callback failed */
3673 			return (TRAN_BUSY);
3674 	}
3675 	return (TRAN_ACCEPT);
3676 }
3677 
3678 /*
3679  * SATA translate command: Request Sense.
3680  *
3681  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3682  * At the moment this is an emulated command (ATA version for SATA hard disks).
3683  * May be translated into Check Power Mode command in the future.
3684  *
3685  * Note: There is a mismatch between already implemented Informational
3686  * Exception Mode Select page 0x1C and this function.
3687  * When MRIE bit is set in page 0x1C, Request Sense is supposed to return
3688  * NO SENSE and set additional sense code to the exception code - this is not
3689  * implemented here.
3690  */
3691 static int
3692 sata_txlt_request_sense(sata_pkt_txlate_t *spx)
3693 {
3694 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3695 	struct scsi_extended_sense sense;
3696 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
3697 	sata_drive_info_t *sdinfo;
3698 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3699 	int rval, reason, power_state = 0;
3700 
3701 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3702 
3703 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3704 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3705 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3706 		return (rval);
3707 	}
3708 
3709 	scsipkt->pkt_reason = CMD_CMPLT;
3710 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3711 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3712 	*scsipkt->pkt_scbp = STATUS_GOOD;
3713 
3714 	/*
3715 	 * when CONTROL field's NACA bit == 1
3716 	 * return ILLEGAL_REQUEST
3717 	 */
3718 	if (scsipkt->pkt_cdbp[5] & CTL_BYTE_NACA_MASK) {
3719 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3720 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3721 		    SD_SCSI_ASC_CMD_SEQUENCE_ERR));
3722 	}
3723 
3724 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3725 	    &spx->txlt_sata_pkt->satapkt_device);
3726 	ASSERT(sdinfo != NULL);
3727 
3728 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3729 
3730 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3731 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3732 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3733 	if (sata_hba_start(spx, &rval) != 0) {
3734 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3735 		return (rval);
3736 	} else {
3737 		if (scmd->satacmd_error_reg != 0) {
3738 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3739 			return (sata_txlt_check_condition(spx, KEY_NO_SENSE,
3740 			    SD_SCSI_ASC_NO_ADD_SENSE));
3741 		}
3742 	}
3743 
3744 	switch (scmd->satacmd_sec_count_lsb) {
3745 	case SATA_PWRMODE_STANDBY: /* device in standby mode */
3746 		if (sdinfo->satadrv_power_level == SATA_POWER_STOPPED)
3747 			power_state = SATA_POWER_STOPPED;
3748 		else {
3749 			power_state = SATA_POWER_STANDBY;
3750 			sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
3751 		}
3752 		break;
3753 	case SATA_PWRMODE_IDLE: /* device in idle mode */
3754 		power_state = SATA_POWER_IDLE;
3755 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
3756 		break;
3757 	case SATA_PWRMODE_ACTIVE: /* device in active or idle mode */
3758 	default:		  /* 0x40, 0x41 active mode */
3759 		if (sdinfo->satadrv_power_level == SATA_POWER_IDLE)
3760 			power_state = SATA_POWER_IDLE;
3761 		else {
3762 			power_state = SATA_POWER_ACTIVE;
3763 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3764 		}
3765 		break;
3766 	}
3767 
3768 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3769 
3770 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
3771 		/*
3772 		 * Because it is fully emulated command storing data
3773 		 * programatically in the specified buffer, release
3774 		 * preallocated DMA resources before storing data in the buffer,
3775 		 * so no unwanted DMA sync would take place.
3776 		 */
3777 		int count = MIN(bp->b_bcount,
3778 		    sizeof (struct scsi_extended_sense));
3779 		sata_scsi_dmafree(NULL, scsipkt);
3780 		bzero(&sense, sizeof (struct scsi_extended_sense));
3781 		sense.es_valid = 0;	/* Valid LBA */
3782 		sense.es_class = 7;	/* Response code 0x70 - current err */
3783 		sense.es_key = KEY_NO_SENSE;
3784 		sense.es_add_len = 6;	/* Additional length */
3785 		/* Copy no more than requested */
3786 		bcopy(&sense, bp->b_un.b_addr, count);
3787 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
3788 		scsipkt->pkt_resid = 0;
3789 		switch (power_state) {
3790 		case SATA_POWER_IDLE:
3791 		case SATA_POWER_STANDBY:
3792 			sense.es_add_code =
3793 			    SD_SCSI_ASC_LOW_POWER_CONDITION_ON;
3794 			break;
3795 		case SATA_POWER_STOPPED:
3796 			sense.es_add_code = SD_SCSI_ASC_NO_ADD_SENSE;
3797 			break;
3798 		case SATA_POWER_ACTIVE:
3799 		default:
3800 			break;
3801 		}
3802 	}
3803 
3804 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3805 	    "Scsi_pkt completion reason %x\n",
3806 	    scsipkt->pkt_reason);
3807 
3808 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3809 		/* scsi callback required */
3810 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3811 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
3812 		    TQ_SLEEP) == NULL)
3813 			/* Scheduling the callback failed */
3814 			return (TRAN_BUSY);
3815 	return (TRAN_ACCEPT);
3816 }
3817 
3818 /*
3819  * SATA translate command: Test Unit Ready
3820  * (ATA version for SATA hard disks).
3821  * It is translated into the Check Power Mode command.
3822  *
3823  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
3824  */
3825 static int
3826 sata_txlt_test_unit_ready(sata_pkt_txlate_t *spx)
3827 {
3828 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3829 	struct scsi_extended_sense *sense;
3830 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3831 	sata_drive_info_t *sdinfo;
3832 	int power_state;
3833 	int rval, reason;
3834 
3835 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
3836 
3837 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3838 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3839 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3840 		return (rval);
3841 	}
3842 
3843 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3844 	    &spx->txlt_sata_pkt->satapkt_device);
3845 	ASSERT(sdinfo != NULL);
3846 
3847 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3848 
3849 	/* send CHECK POWER MODE command */
3850 	sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
3851 	scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
3852 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3853 	if (sata_hba_start(spx, &rval) != 0) {
3854 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3855 		return (rval);
3856 	} else {
3857 		if (scmd->satacmd_error_reg != 0) {
3858 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3859 			return (sata_txlt_check_condition(spx, KEY_NOT_READY,
3860 			    SD_SCSI_ASC_LU_NOT_RESPONSE));
3861 		}
3862 	}
3863 
3864 	power_state = scmd->satacmd_sec_count_lsb;
3865 
3866 	/*
3867 	 * return NOT READY when device in STOPPED mode
3868 	 */
3869 	if (power_state == SATA_PWRMODE_STANDBY &&
3870 	    sdinfo->satadrv_power_level == SATA_POWER_STOPPED) {
3871 		*scsipkt->pkt_scbp = STATUS_CHECK;
3872 		sense = sata_arq_sense(spx);
3873 		sense->es_key = KEY_NOT_READY;
3874 		sense->es_add_code = SD_SCSI_ASC_LU_NOT_READY;
3875 	} else {
3876 		/*
3877 		 * For other power mode, return GOOD status
3878 		 */
3879 		*scsipkt->pkt_scbp = STATUS_GOOD;
3880 	}
3881 
3882 	scsipkt->pkt_reason = CMD_CMPLT;
3883 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
3884 	    STATE_SENT_CMD | STATE_GOT_STATUS;
3885 
3886 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3887 
3888 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3889 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
3890 
3891 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
3892 		/* scsi callback required */
3893 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
3894 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
3895 		    TQ_SLEEP) == NULL)
3896 			/* Scheduling the callback failed */
3897 			return (TRAN_BUSY);
3898 
3899 	return (TRAN_ACCEPT);
3900 }
3901 
3902 /*
3903  * SATA translate command: Start Stop Unit
3904  * Translation depends on a command:
3905  *
3906  * Power condition bits will be supported
3907  * and the power level should be maintained by SATL,
3908  * When SATL received a command, it will check the
3909  * power level firstly, and return the status according
3910  * to SAT2 v2.6 and SAT-2 Standby Modifications
3911  *
3912  * SPC-4/SBC-3      SATL    ATA power condition  SATL      SPC/SBC
3913  * -----------------------------------------------------------------------
3914  * SSU_PC1 Active   <==>     ATA  Active         <==>     SSU:start_bit =1
3915  * SSU_PC2 Idle     <==>     ATA  Idle           <==>     N/A
3916  * SSU_PC3 Standby  <==>     ATA  Standby        <==>     N/A
3917  * SSU_PC4 Stopped  <==>     ATA  Standby        <==>     SSU:start_bit = 0
3918  *
3919  *	Unload Media / NOT SUPPORTED YET
3920  *	Load Media / NOT SUPPROTED YET
3921  *	Immediate bit / NOT SUPPORTED YET (deferred error)
3922  *
3923  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
3924  * appropriate values in scsi_pkt fields.
3925  */
3926 static int
3927 sata_txlt_start_stop_unit(sata_pkt_txlate_t *spx)
3928 {
3929 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
3930 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
3931 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
3932 	int cport = SATA_TXLT_CPORT(spx);
3933 	int rval, reason;
3934 	sata_drive_info_t *sdinfo;
3935 	sata_id_t *sata_id;
3936 
3937 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
3938 	    "sata_txlt_start_stop_unit: %d\n", scsipkt->pkt_scbp[4] & 1);
3939 
3940 	mutex_enter(&SATA_CPORT_MUTEX(shi, cport));
3941 
3942 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
3943 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
3944 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
3945 		return (rval);
3946 	}
3947 
3948 	if (scsipkt->pkt_cdbp[1] & START_STOP_IMMED_MASK) {
3949 		/* IMMED bit - not supported */
3950 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3951 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
3952 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
3953 	}
3954 
3955 	spx->txlt_sata_pkt->satapkt_op_mode |= SATA_OPMODE_SYNCH;
3956 	spx->txlt_sata_pkt->satapkt_comp = NULL;
3957 
3958 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
3959 	    &spx->txlt_sata_pkt->satapkt_device);
3960 	ASSERT(sdinfo != NULL);
3961 	sata_id = &sdinfo->satadrv_id;
3962 
3963 	switch ((scsipkt->pkt_cdbp[4] & START_STOP_POWER_COND_MASK) >> 4) {
3964 	case 0:
3965 		if (scsipkt->pkt_cdbp[4] & START_STOP_LOEJ_MASK) {
3966 			/* Load/Unload Media - invalid request */
3967 			goto err_out;
3968 		}
3969 		if (scsipkt->pkt_cdbp[4] & START_STOP_START_MASK) {
3970 			/* Start Unit */
3971 			sata_build_read_verify_cmd(scmd, 1, 5);
3972 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3973 			/* Transfer command to HBA */
3974 			if (sata_hba_start(spx, &rval) != 0) {
3975 				/* Pkt not accepted for execution */
3976 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3977 				return (rval);
3978 			} else {
3979 				if (scmd->satacmd_error_reg != 0) {
3980 					goto err_out;
3981 				}
3982 			}
3983 			sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
3984 		} else {
3985 			/* Stop Unit */
3986 			sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
3987 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3988 			if (sata_hba_start(spx, &rval) != 0) {
3989 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
3990 				return (rval);
3991 			} else {
3992 				if (scmd->satacmd_error_reg != 0) {
3993 					goto err_out;
3994 				}
3995 			}
3996 			/* ata standby immediate command */
3997 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
3998 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
3999 			if (sata_hba_start(spx, &rval) != 0) {
4000 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4001 				return (rval);
4002 			} else {
4003 				if (scmd->satacmd_error_reg != 0) {
4004 					goto err_out;
4005 				}
4006 			}
4007 			sdinfo->satadrv_power_level = SATA_POWER_STOPPED;
4008 		}
4009 		break;
4010 	case 0x1:
4011 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4012 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4013 		if (sata_hba_start(spx, &rval) != 0) {
4014 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4015 			return (rval);
4016 		} else {
4017 			if (scmd->satacmd_error_reg != 0) {
4018 				goto err_out;
4019 			}
4020 		}
4021 		sata_build_read_verify_cmd(scmd, 1, 5);
4022 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4023 		/* Transfer command to HBA */
4024 		if (sata_hba_start(spx, &rval) != 0) {
4025 			/* Pkt not accepted for execution */
4026 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4027 			return (rval);
4028 		} else {
4029 			if (scmd->satacmd_error_reg != 0) {
4030 				goto err_out;
4031 			}
4032 		}
4033 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
4034 		break;
4035 	case 0x2:
4036 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4037 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4038 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4039 			if (sata_hba_start(spx, &rval) != 0) {
4040 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4041 				return (rval);
4042 			} else {
4043 				if (scmd->satacmd_error_reg != 0) {
4044 					goto err_out;
4045 				}
4046 			}
4047 		}
4048 		sata_build_generic_cmd(scmd, SATAC_IDLE);
4049 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4050 		if (sata_hba_start(spx, &rval) != 0) {
4051 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4052 			return (rval);
4053 		} else {
4054 			if (scmd->satacmd_error_reg != 0) {
4055 				goto err_out;
4056 			}
4057 		}
4058 		if ((scsipkt->pkt_cdbp[3] & START_STOP_MODIFIER_MASK)) {
4059 			/*
4060 			 *  POWER CONDITION MODIFIER bit set
4061 			 *  to 0x1 or larger it will be handled
4062 			 *  on the same way as bit = 0x1
4063 			 */
4064 			if (!(sata_id->ai_cmdset84 &
4065 			    SATA_IDLE_UNLOAD_SUPPORTED)) {
4066 				sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4067 				break;
4068 			}
4069 			sata_build_generic_cmd(scmd, SATAC_IDLE_IM);
4070 			scmd->satacmd_features_reg = 0x44;
4071 			scmd->satacmd_lba_low_lsb = 0x4c;
4072 			scmd->satacmd_lba_mid_lsb = 0x4e;
4073 			scmd->satacmd_lba_high_lsb = 0x55;
4074 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4075 			if (sata_hba_start(spx, &rval) != 0) {
4076 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4077 				return (rval);
4078 			} else {
4079 				if (scmd->satacmd_error_reg != 0) {
4080 					goto err_out;
4081 				}
4082 			}
4083 		}
4084 		sdinfo->satadrv_power_level = SATA_POWER_IDLE;
4085 		break;
4086 	case 0x3:
4087 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4088 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4089 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4090 			if (sata_hba_start(spx, &rval) != 0) {
4091 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4092 				return (rval);
4093 			} else {
4094 				if (scmd->satacmd_error_reg != 0) {
4095 					goto err_out;
4096 				}
4097 			}
4098 		}
4099 		sata_build_generic_cmd(scmd, SATAC_STANDBY);
4100 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4101 		if (sata_hba_start(spx, &rval) != 0) {
4102 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4103 			return (rval);
4104 		} else {
4105 			if (scmd->satacmd_error_reg != 0) {
4106 				goto err_out;
4107 			}
4108 		}
4109 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
4110 		break;
4111 	case 0x7:
4112 		sata_build_generic_cmd(scmd, SATAC_CHECK_POWER_MODE);
4113 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = B_TRUE;
4114 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4115 		if (sata_hba_start(spx, &rval) != 0) {
4116 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4117 			return (rval);
4118 		} else {
4119 			if (scmd->satacmd_error_reg != 0) {
4120 				goto err_out;
4121 			}
4122 		}
4123 		switch (scmd->satacmd_sec_count_lsb) {
4124 		case SATA_PWRMODE_STANDBY:
4125 			sata_build_generic_cmd(scmd, SATAC_STANDBY);
4126 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4127 			    sdinfo->satadrv_standby_timer);
4128 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4129 			if (sata_hba_start(spx, &rval) != 0) {
4130 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4131 				return (rval);
4132 			} else {
4133 				if (scmd->satacmd_error_reg != 0) {
4134 					goto err_out;
4135 				}
4136 			}
4137 			break;
4138 		case SATA_PWRMODE_IDLE:
4139 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4140 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4141 			    sdinfo->satadrv_standby_timer);
4142 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4143 			if (sata_hba_start(spx, &rval) != 0) {
4144 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4145 				return (rval);
4146 			} else {
4147 				if (scmd->satacmd_error_reg != 0) {
4148 					goto err_out;
4149 				}
4150 			}
4151 			break;
4152 		case SATA_PWRMODE_ACTIVE_SPINDOWN:
4153 		case SATA_PWRMODE_ACTIVE_SPINUP:
4154 		case SATA_PWRMODE_ACTIVE:
4155 			sata_build_generic_cmd(scmd, SATAC_IDLE);
4156 			scmd->satacmd_sec_count_msb = sata_get_standby_timer(
4157 			    sdinfo->satadrv_standby_timer);
4158 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4159 			if (sata_hba_start(spx, &rval) != 0) {
4160 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4161 				return (rval);
4162 			} else {
4163 				if (scmd->satacmd_error_reg != 0) {
4164 					goto err_out;
4165 				}
4166 			}
4167 			sata_build_read_verify_cmd(scmd, 1, 5);
4168 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4169 			if (sata_hba_start(spx, &rval) != 0) {
4170 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4171 				return (rval);
4172 			} else {
4173 				if (scmd->satacmd_error_reg != 0) {
4174 					goto err_out;
4175 				}
4176 			}
4177 			break;
4178 		default:
4179 			goto err_out;
4180 		}
4181 		break;
4182 	case 0xb:
4183 		if ((sata_get_standby_timer(sdinfo->satadrv_standby_timer) ==
4184 		    0) || (!(sata_id->ai_cap & SATA_STANDBYTIMER))) {
4185 			mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4186 			return (sata_txlt_check_condition(spx,
4187 			    KEY_ILLEGAL_REQUEST,
4188 			    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4189 		}
4190 		sata_build_generic_cmd(scmd, SATAC_FLUSH_CACHE);
4191 		scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4192 		if (!(scsipkt->pkt_cdbp[4] & START_STOP_NOFLUSH_MASK)) {
4193 			if (sata_hba_start(spx, &rval) != 0) {
4194 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4195 				return (rval);
4196 			} else {
4197 				if (scmd->satacmd_error_reg != 0) {
4198 					goto err_out;
4199 				}
4200 			}
4201 			sata_build_generic_cmd(scmd, SATAC_STANDBY_IM);
4202 			scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
4203 			if (sata_hba_start(spx, &rval) != 0) {
4204 				mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4205 				return (rval);
4206 			} else {
4207 				if (scmd->satacmd_error_reg != 0) {
4208 					goto err_out;
4209 				}
4210 			}
4211 		}
4212 		bzero(sdinfo->satadrv_standby_timer, sizeof (uchar_t) * 4);
4213 		break;
4214 	default:
4215 err_out:
4216 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4217 		return (sata_txlt_check_condition(spx, KEY_ILLEGAL_REQUEST,
4218 		    SD_SCSI_ASC_INVALID_FIELD_IN_CDB));
4219 	}
4220 
4221 	/*
4222 	 * Since it was a synchronous command,
4223 	 * a callback function will be called directly.
4224 	 */
4225 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
4226 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4227 	    "synchronous execution status %x\n",
4228 	    spx->txlt_sata_pkt->satapkt_reason);
4229 
4230 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0) {
4231 		sata_set_arq_data(spx->txlt_sata_pkt);
4232 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4233 		    (task_func_t *)scsi_hba_pkt_comp, (void *) scsipkt,
4234 		    TQ_SLEEP) == 0) {
4235 			return (TRAN_BUSY);
4236 		}
4237 	}
4238 	else
4239 
4240 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
4241 
4242 	return (TRAN_ACCEPT);
4243 
4244 }
4245 
4246 /*
4247  * SATA translate command:  Read Capacity.
4248  * Emulated command for SATA disks.
4249  * Capacity is retrieved from cached Idenifty Device data.
4250  * Identify Device data shows effective disk capacity, not the native
4251  * capacity, which may be limitted by Set Max Address command.
4252  * This is ATA version for SATA hard disks.
4253  *
4254  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4255  */
4256 static int
4257 sata_txlt_read_capacity(sata_pkt_txlate_t *spx)
4258 {
4259 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4260 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4261 	sata_drive_info_t *sdinfo;
4262 	uint64_t val;
4263 	uchar_t *rbuf;
4264 	int rval, reason;
4265 
4266 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4267 	    "sata_txlt_read_capacity: ", NULL);
4268 
4269 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4270 
4271 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4272 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4273 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4274 		return (rval);
4275 	}
4276 
4277 	scsipkt->pkt_reason = CMD_CMPLT;
4278 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4279 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4280 	*scsipkt->pkt_scbp = STATUS_GOOD;
4281 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4282 		/*
4283 		 * Because it is fully emulated command storing data
4284 		 * programatically in the specified buffer, release
4285 		 * preallocated DMA resources before storing data in the buffer,
4286 		 * so no unwanted DMA sync would take place.
4287 		 */
4288 		sata_scsi_dmafree(NULL, scsipkt);
4289 
4290 		sdinfo = sata_get_device_info(
4291 		    spx->txlt_sata_hba_inst,
4292 		    &spx->txlt_sata_pkt->satapkt_device);
4293 		/* Last logical block address */
4294 		val = sdinfo->satadrv_capacity - 1;
4295 		rbuf = (uchar_t *)bp->b_un.b_addr;
4296 		/* Need to swap endians to match scsi format */
4297 		rbuf[0] = (val >> 24) & 0xff;
4298 		rbuf[1] = (val >> 16) & 0xff;
4299 		rbuf[2] = (val >> 8) & 0xff;
4300 		rbuf[3] = val & 0xff;
4301 		/* block size - always 512 bytes, for now */
4302 		rbuf[4] = 0;
4303 		rbuf[5] = 0;
4304 		rbuf[6] = 0x02;
4305 		rbuf[7] = 0;
4306 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4307 		scsipkt->pkt_resid = 0;
4308 
4309 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst, "%d\n",
4310 		    sdinfo->satadrv_capacity -1);
4311 	}
4312 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4313 	/*
4314 	 * If a callback was requested, do it now.
4315 	 */
4316 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4317 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4318 
4319 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4320 	    scsipkt->pkt_comp != NULL)
4321 		/* scsi callback required */
4322 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4323 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4324 		    TQ_SLEEP) == NULL)
4325 			/* Scheduling the callback failed */
4326 			return (TRAN_BUSY);
4327 
4328 	return (TRAN_ACCEPT);
4329 }
4330 
4331 /*
4332  * SATA translate command: Mode Sense.
4333  * Translated into appropriate SATA command or emulated.
4334  * Saved Values Page Control (03) are not supported.
4335  *
4336  * NOTE: only caching mode sense page is currently implemented.
4337  *
4338  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
4339  */
4340 
4341 #define	LLBAA	0x10	/* Long LBA Accepted */
4342 
4343 static int
4344 sata_txlt_mode_sense(sata_pkt_txlate_t *spx)
4345 {
4346 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
4347 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4348 	sata_drive_info_t *sdinfo;
4349 	sata_id_t *sata_id;
4350 	struct scsi_extended_sense *sense;
4351 	int 		len, bdlen, count, alc_len;
4352 	int		pc;	/* Page Control code */
4353 	uint8_t		*buf;	/* mode sense buffer */
4354 	int		rval, reason;
4355 
4356 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4357 	    "sata_txlt_mode_sense, pc %x page code 0x%02x\n",
4358 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
4359 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
4360 
4361 	buf = kmem_zalloc(1024, KM_SLEEP);
4362 
4363 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4364 
4365 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 0)) !=
4366 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4367 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4368 		kmem_free(buf, 1024);
4369 		return (rval);
4370 	}
4371 
4372 	scsipkt->pkt_reason = CMD_CMPLT;
4373 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4374 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4375 
4376 	pc = scsipkt->pkt_cdbp[2] >> 6;
4377 
4378 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
4379 		/*
4380 		 * Because it is fully emulated command storing data
4381 		 * programatically in the specified buffer, release
4382 		 * preallocated DMA resources before storing data in the buffer,
4383 		 * so no unwanted DMA sync would take place.
4384 		 */
4385 		sata_scsi_dmafree(NULL, scsipkt);
4386 
4387 		len = 0;
4388 		bdlen = 0;
4389 		if (!(scsipkt->pkt_cdbp[1] & 8)) {
4390 			if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE_G1 &&
4391 			    (scsipkt->pkt_cdbp[1] & LLBAA))
4392 				bdlen = 16;
4393 			else
4394 				bdlen = 8;
4395 		}
4396 		/* Build mode parameter header */
4397 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4398 			/* 4-byte mode parameter header */
4399 			buf[len++] = 0;		/* mode data length */
4400 			buf[len++] = 0;		/* medium type */
4401 			buf[len++] = 0;		/* dev-specific param */
4402 			buf[len++] = bdlen;	/* Block Descriptor length */
4403 		} else {
4404 			/* 8-byte mode parameter header */
4405 			buf[len++] = 0;		/* mode data length */
4406 			buf[len++] = 0;
4407 			buf[len++] = 0;		/* medium type */
4408 			buf[len++] = 0;		/* dev-specific param */
4409 			if (bdlen == 16)
4410 				buf[len++] = 1;	/* long lba descriptor */
4411 			else
4412 				buf[len++] = 0;
4413 			buf[len++] = 0;
4414 			buf[len++] = 0;		/* Block Descriptor length */
4415 			buf[len++] = bdlen;
4416 		}
4417 
4418 		sdinfo = sata_get_device_info(
4419 		    spx->txlt_sata_hba_inst,
4420 		    &spx->txlt_sata_pkt->satapkt_device);
4421 
4422 		/* Build block descriptor only if not disabled (DBD) */
4423 		if ((scsipkt->pkt_cdbp[1] & 0x08) == 0) {
4424 			/* Block descriptor - direct-access device format */
4425 			if (bdlen == 8) {
4426 				/* build regular block descriptor */
4427 				buf[len++] =
4428 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4429 				buf[len++] =
4430 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4431 				buf[len++] =
4432 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4433 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4434 				buf[len++] = 0; /* density code */
4435 				buf[len++] = 0;
4436 				if (sdinfo->satadrv_type ==
4437 				    SATA_DTYPE_ATADISK)
4438 					buf[len++] = 2;
4439 				else
4440 					/* ATAPI */
4441 					buf[len++] = 8;
4442 				buf[len++] = 0;
4443 			} else if (bdlen == 16) {
4444 				/* Long LBA Accepted */
4445 				/* build long lba block descriptor */
4446 #ifndef __lock_lint
4447 				buf[len++] =
4448 				    (sdinfo->satadrv_capacity >> 56) & 0xff;
4449 				buf[len++] =
4450 				    (sdinfo->satadrv_capacity >> 48) & 0xff;
4451 				buf[len++] =
4452 				    (sdinfo->satadrv_capacity >> 40) & 0xff;
4453 				buf[len++] =
4454 				    (sdinfo->satadrv_capacity >> 32) & 0xff;
4455 #endif
4456 				buf[len++] =
4457 				    (sdinfo->satadrv_capacity >> 24) & 0xff;
4458 				buf[len++] =
4459 				    (sdinfo->satadrv_capacity >> 16) & 0xff;
4460 				buf[len++] =
4461 				    (sdinfo->satadrv_capacity >> 8) & 0xff;
4462 				buf[len++] = sdinfo->satadrv_capacity & 0xff;
4463 				buf[len++] = 0;
4464 				buf[len++] = 0; /* density code */
4465 				buf[len++] = 0;
4466 				buf[len++] = 0;
4467 				if (sdinfo->satadrv_type ==
4468 				    SATA_DTYPE_ATADISK)
4469 					buf[len++] = 2;
4470 				else
4471 					/* ATAPI */
4472 					buf[len++] = 8;
4473 				buf[len++] = 0;
4474 			}
4475 		}
4476 
4477 		sata_id = &sdinfo->satadrv_id;
4478 
4479 		/*
4480 		 * Add requested pages.
4481 		 * Page 3 and 4 are obsolete and we are not supporting them.
4482 		 * We deal now with:
4483 		 * caching (read/write cache control).
4484 		 * We should eventually deal with following mode pages:
4485 		 * error recovery  (0x01),
4486 		 * power condition (0x1a),
4487 		 * exception control page (enables SMART) (0x1c),
4488 		 * enclosure management (ses),
4489 		 * protocol-specific port mode (port control).
4490 		 */
4491 		switch (scsipkt->pkt_cdbp[2] & 0x3f) {
4492 		case MODEPAGE_RW_ERRRECOV:
4493 			/* DAD_MODE_ERR_RECOV */
4494 			/* R/W recovery */
4495 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4496 			break;
4497 		case MODEPAGE_CACHING:
4498 			/* DAD_MODE_CACHE */
4499 			/* Reject not supported request for saved parameters */
4500 			if (pc == 3) {
4501 				*scsipkt->pkt_scbp = STATUS_CHECK;
4502 				sense = sata_arq_sense(spx);
4503 				sense->es_key = KEY_ILLEGAL_REQUEST;
4504 				sense->es_add_code =
4505 				    SD_SCSI_ASC_SAVING_PARAMS_NOT_SUPPORTED;
4506 				goto done;
4507 			}
4508 
4509 			/* caching */
4510 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4511 			break;
4512 		case MODEPAGE_INFO_EXCPT:
4513 			/* exception cntrl */
4514 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4515 				len += sata_build_msense_page_1c(sdinfo, pc,
4516 				    buf+len);
4517 			}
4518 			else
4519 				goto err;
4520 			break;
4521 		case MODEPAGE_POWER_COND:
4522 			/* DAD_MODE_POWER_COND */
4523 			/* power condition */
4524 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4525 			break;
4526 
4527 		case MODEPAGE_ACOUSTIC_MANAG:
4528 			/* acoustic management */
4529 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4530 			break;
4531 		case MODEPAGE_ALLPAGES:
4532 			/* all pages */
4533 			len += sata_build_msense_page_1(sdinfo, pc, buf+len);
4534 			len += sata_build_msense_page_8(sdinfo, pc, buf+len);
4535 			len += sata_build_msense_page_1a(sdinfo, pc, buf+len);
4536 			if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
4537 				len += sata_build_msense_page_1c(sdinfo, pc,
4538 				    buf+len);
4539 			}
4540 			len += sata_build_msense_page_30(sdinfo, pc, buf+len);
4541 			break;
4542 		default:
4543 		err:
4544 			/* Invalid request */
4545 			*scsipkt->pkt_scbp = STATUS_CHECK;
4546 			sense = sata_arq_sense(spx);
4547 			sense->es_key = KEY_ILLEGAL_REQUEST;
4548 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4549 			goto done;
4550 		}
4551 
4552 		/* fix total mode data length */
4553 		if (spx->txlt_scsi_pkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4554 			/* 4-byte mode parameter header */
4555 			buf[0] = len - 1;	/* mode data length */
4556 		} else {
4557 			buf[0] = (len -2) >> 8;
4558 			buf[1] = (len -2) & 0xff;
4559 		}
4560 
4561 
4562 		/* Check allocation length */
4563 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SENSE) {
4564 			alc_len = scsipkt->pkt_cdbp[4];
4565 		} else {
4566 			alc_len = scsipkt->pkt_cdbp[7];
4567 			alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
4568 		}
4569 		/*
4570 		 * We do not check for possible parameters truncation
4571 		 * (alc_len < len) assuming that the target driver works
4572 		 * correctly. Just avoiding overrun.
4573 		 * Copy no more than requested and possible, buffer-wise.
4574 		 */
4575 		count = MIN(alc_len, len);
4576 		count = MIN(bp->b_bcount, count);
4577 		bcopy(buf, bp->b_un.b_addr, count);
4578 
4579 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4580 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
4581 	}
4582 	*scsipkt->pkt_scbp = STATUS_GOOD;
4583 done:
4584 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4585 	(void) kmem_free(buf, 1024);
4586 
4587 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4588 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4589 
4590 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4591 	    scsipkt->pkt_comp != NULL)
4592 		/* scsi callback required */
4593 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4594 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4595 		    TQ_SLEEP) == NULL)
4596 			/* Scheduling the callback failed */
4597 			return (TRAN_BUSY);
4598 
4599 	return (TRAN_ACCEPT);
4600 }
4601 
4602 
4603 /*
4604  * SATA translate command: Mode Select.
4605  * Translated into appropriate SATA command or emulated.
4606  * Saving parameters is not supported.
4607  * Changing device capacity is not supported (although theoretically
4608  * possible by executing SET FEATURES/SET MAX ADDRESS)
4609  *
4610  * Assumption is that the target driver is working correctly.
4611  *
4612  * More than one SATA command may be executed to perform operations specified
4613  * by mode select pages. The first error terminates further execution.
4614  * Operations performed successully are not backed-up in such case.
4615  *
4616  * NOTE: Implemented pages:
4617  * - caching page
4618  * - informational exception page
4619  * - acoustic management page
4620  * - power condition page
4621  * Caching setup is remembered so it could be re-stored in case of
4622  * an unexpected device reset.
4623  *
4624  * Returns TRAN_XXXX.
4625  * If TRAN_ACCEPT is returned, appropriate values are set in scsi_pkt fields.
4626  */
4627 
4628 static int
4629 sata_txlt_mode_select(sata_pkt_txlate_t *spx)
4630 {
4631 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4632 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4633 	struct scsi_extended_sense *sense;
4634 	int len, pagelen, count, pllen;
4635 	uint8_t *buf;	/* mode select buffer */
4636 	int rval, stat, reason;
4637 	uint_t nointr_flag;
4638 	int dmod = 0;
4639 
4640 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4641 	    "sata_txlt_mode_select, 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 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4646 
4647 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
4648 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4649 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4650 		return (rval);
4651 	}
4652 
4653 	rval = TRAN_ACCEPT;
4654 
4655 	scsipkt->pkt_reason = CMD_CMPLT;
4656 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
4657 	    STATE_SENT_CMD | STATE_GOT_STATUS;
4658 	nointr_flag = scsipkt->pkt_flags & FLAG_NOINTR;
4659 
4660 	/* Reject not supported request */
4661 	if (! (scsipkt->pkt_cdbp[1] & 0x10)) { /* No support for PF bit = 0 */
4662 		*scsipkt->pkt_scbp = STATUS_CHECK;
4663 		sense = sata_arq_sense(spx);
4664 		sense->es_key = KEY_ILLEGAL_REQUEST;
4665 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4666 		goto done;
4667 	}
4668 
4669 	if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4670 		pllen = scsipkt->pkt_cdbp[4];
4671 	} else {
4672 		pllen = scsipkt->pkt_cdbp[7];
4673 		pllen = (pllen << 8) | scsipkt->pkt_cdbp[7];
4674 	}
4675 
4676 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
4677 
4678 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount && pllen != 0) {
4679 		buf = (uint8_t *)bp->b_un.b_addr;
4680 		count = MIN(bp->b_bcount, pllen);
4681 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
4682 		scsipkt->pkt_resid = 0;
4683 		pllen = count;
4684 
4685 		/*
4686 		 * Check the header to skip the block descriptor(s) - we
4687 		 * do not support setting device capacity.
4688 		 * Existing macros do not recognize long LBA dscriptor,
4689 		 * hence manual calculation.
4690 		 */
4691 		if (scsipkt->pkt_cdbp[0] == SCMD_MODE_SELECT) {
4692 			/* 6-bytes CMD, 4 bytes header */
4693 			if (count <= 4)
4694 				goto done;		/* header only */
4695 			len = buf[3] + 4;
4696 		} else {
4697 			/* 10-bytes CMD, 8 bytes header */
4698 			if (count <= 8)
4699 				goto done;		/* header only */
4700 			len = buf[6];
4701 			len = (len << 8) + buf[7] + 8;
4702 		}
4703 		if (len >= count)
4704 			goto done;	/* header + descriptor(s) only */
4705 
4706 		pllen -= len;		/* remaining data length */
4707 
4708 		/*
4709 		 * We may be executing SATA command and want to execute it
4710 		 * in SYNCH mode, regardless of scsi_pkt setting.
4711 		 * Save scsi_pkt setting and indicate SYNCH mode
4712 		 */
4713 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4714 		    scsipkt->pkt_comp != NULL) {
4715 			scsipkt->pkt_flags |= FLAG_NOINTR;
4716 		}
4717 		spx->txlt_sata_pkt->satapkt_op_mode = SATA_OPMODE_SYNCH;
4718 
4719 		/*
4720 		 * len is now the offset to a first mode select page
4721 		 * Process all pages
4722 		 */
4723 		while (pllen > 0) {
4724 			switch ((int)buf[len]) {
4725 			case MODEPAGE_CACHING:
4726 				/* No support for SP (saving) */
4727 				if (scsipkt->pkt_cdbp[1] & 0x01) {
4728 					*scsipkt->pkt_scbp = STATUS_CHECK;
4729 					sense = sata_arq_sense(spx);
4730 					sense->es_key = KEY_ILLEGAL_REQUEST;
4731 					sense->es_add_code =
4732 					    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
4733 					goto done;
4734 				}
4735 				stat = sata_mode_select_page_8(spx,
4736 				    (struct mode_cache_scsi3 *)&buf[len],
4737 				    pllen, &pagelen, &rval, &dmod);
4738 				/*
4739 				 * The pagelen value indicates the number of
4740 				 * parameter bytes already processed.
4741 				 * The rval is the return value from
4742 				 * sata_tran_start().
4743 				 * The stat indicates the overall status of
4744 				 * the operation(s).
4745 				 */
4746 				if (stat != SATA_SUCCESS)
4747 					/*
4748 					 * Page processing did not succeed -
4749 					 * all error info is already set-up,
4750 					 * just return
4751 					 */
4752 					pllen = 0; /* this breaks the loop */
4753 				else {
4754 					len += pagelen;
4755 					pllen -= pagelen;
4756 				}
4757 				break;
4758 
4759 			case MODEPAGE_INFO_EXCPT:
4760 				stat = sata_mode_select_page_1c(spx,
4761 				    (struct mode_info_excpt_page *)&buf[len],
4762 				    pllen, &pagelen, &rval, &dmod);
4763 				/*
4764 				 * The pagelen value indicates the number of
4765 				 * parameter bytes already processed.
4766 				 * The rval is the return value from
4767 				 * sata_tran_start().
4768 				 * The stat indicates the overall status of
4769 				 * the operation(s).
4770 				 */
4771 				if (stat != SATA_SUCCESS)
4772 					/*
4773 					 * Page processing did not succeed -
4774 					 * all error info is already set-up,
4775 					 * just return
4776 					 */
4777 					pllen = 0; /* this breaks the loop */
4778 				else {
4779 					len += pagelen;
4780 					pllen -= pagelen;
4781 				}
4782 				break;
4783 
4784 			case MODEPAGE_ACOUSTIC_MANAG:
4785 				stat = sata_mode_select_page_30(spx,
4786 				    (struct mode_acoustic_management *)
4787 				    &buf[len], pllen, &pagelen, &rval, &dmod);
4788 				/*
4789 				 * The pagelen value indicates the number of
4790 				 * parameter bytes already processed.
4791 				 * The rval is the return value from
4792 				 * sata_tran_start().
4793 				 * The stat indicates the overall status of
4794 				 * the operation(s).
4795 				 */
4796 				if (stat != SATA_SUCCESS)
4797 					/*
4798 					 * Page processing did not succeed -
4799 					 * all error info is already set-up,
4800 					 * just return
4801 					 */
4802 					pllen = 0; /* this breaks the loop */
4803 				else {
4804 					len += pagelen;
4805 					pllen -= pagelen;
4806 				}
4807 
4808 				break;
4809 			case MODEPAGE_POWER_COND:
4810 				stat = sata_mode_select_page_1a(spx,
4811 				    (struct mode_info_power_cond *)&buf[len],
4812 				    pllen, &pagelen, &rval, &dmod);
4813 				/*
4814 				 * The pagelen value indicates the number of
4815 				 * parameter bytes already processed.
4816 				 * The rval is the return value from
4817 				 * sata_tran_start().
4818 				 * The stat indicates the overall status of
4819 				 * the operation(s).
4820 				 */
4821 				if (stat != SATA_SUCCESS)
4822 					/*
4823 					 * Page processing did not succeed -
4824 					 * all error info is already set-up,
4825 					 * just return
4826 					 */
4827 					pllen = 0; /* this breaks the loop */
4828 				else {
4829 					len += pagelen;
4830 					pllen -= pagelen;
4831 				}
4832 				break;
4833 			default:
4834 				*scsipkt->pkt_scbp = STATUS_CHECK;
4835 				sense = sata_arq_sense(spx);
4836 				sense->es_key = KEY_ILLEGAL_REQUEST;
4837 				sense->es_add_code =
4838 				    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
4839 				goto done;
4840 			}
4841 		}
4842 	}
4843 done:
4844 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4845 	/*
4846 	 * If device parameters were modified, fetch and store the new
4847 	 * Identify Device data. Since port mutex could have been released
4848 	 * for accessing HBA driver, we need to re-check device existence.
4849 	 */
4850 	if (dmod != 0) {
4851 		sata_drive_info_t new_sdinfo, *sdinfo;
4852 		int rv = 0;
4853 
4854 		/*
4855 		 * Following statement has to be changed if this function is
4856 		 * used for devices other than SATA hard disks.
4857 		 */
4858 		new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
4859 
4860 		new_sdinfo.satadrv_addr =
4861 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr;
4862 		rv = sata_fetch_device_identify_data(spx->txlt_sata_hba_inst,
4863 		    &new_sdinfo);
4864 
4865 		mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4866 		/*
4867 		 * Since port mutex could have been released when
4868 		 * accessing HBA driver, we need to re-check that the
4869 		 * framework still holds the device info structure.
4870 		 */
4871 		sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
4872 		    &spx->txlt_sata_pkt->satapkt_device);
4873 		if (sdinfo != NULL) {
4874 			/*
4875 			 * Device still has info structure in the
4876 			 * sata framework. Copy newly fetched info
4877 			 */
4878 			if (rv == 0) {
4879 				sdinfo->satadrv_id = new_sdinfo.satadrv_id;
4880 				sata_save_drive_settings(sdinfo);
4881 			} else {
4882 				/*
4883 				 * Could not fetch new data - invalidate
4884 				 * sata_drive_info. That makes device
4885 				 * unusable.
4886 				 */
4887 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
4888 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
4889 			}
4890 		}
4891 		if (rv != 0 || sdinfo == NULL) {
4892 			/*
4893 			 * This changes the overall mode select completion
4894 			 * reason to a failed one !!!!!
4895 			 */
4896 			*scsipkt->pkt_scbp = STATUS_CHECK;
4897 			sense = sata_arq_sense(spx);
4898 			scsipkt->pkt_reason = CMD_INCOMPLETE;
4899 			rval = TRAN_ACCEPT;
4900 		}
4901 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4902 	}
4903 	/* Restore the scsi pkt flags */
4904 	scsipkt->pkt_flags &= ~FLAG_NOINTR;
4905 	scsipkt->pkt_flags |= nointr_flag;
4906 
4907 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
4908 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
4909 
4910 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
4911 	    scsipkt->pkt_comp != NULL)
4912 		/* scsi callback required */
4913 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
4914 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
4915 		    TQ_SLEEP) == NULL)
4916 			/* Scheduling the callback failed */
4917 			return (TRAN_BUSY);
4918 
4919 	return (rval);
4920 }
4921 
4922 /*
4923  * Translate command: ATA Pass Through
4924  * Incomplete implementation.  Only supports No-Data, PIO Data-In, and
4925  * PIO Data-Out protocols.  Also supports CK_COND bit.
4926  *
4927  * Mapping of the incoming CDB bytes to the outgoing satacmd bytes is
4928  * described in Table 111 of SAT-2 (Draft 9).
4929  */
4930 static  int
4931 sata_txlt_ata_pass_thru(sata_pkt_txlate_t *spx)
4932 {
4933 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
4934 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
4935 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
4936 	int extend;
4937 	uint64_t lba;
4938 	uint16_t feature, sec_count;
4939 	int t_len, synch;
4940 	int rval, reason;
4941 
4942 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
4943 
4944 	rval = sata_txlt_generic_pkt_info(spx, &reason, 1);
4945 	if ((rval != TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
4946 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4947 		return (rval);
4948 	}
4949 
4950 	/* T_DIR bit */
4951 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_T_DIR)
4952 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
4953 	else
4954 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
4955 
4956 	/* MULTIPLE_COUNT field.  If non-zero, invalid command (for now). */
4957 	if (((scsipkt->pkt_cdbp[1] >> 5) & 0x7) != 0) {
4958 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4959 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4960 	}
4961 
4962 	/* OFFLINE field. If non-zero, invalid command (for now). */
4963 	if (((scsipkt->pkt_cdbp[2] >> 6) & 0x3) != 0) {
4964 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4965 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4966 	}
4967 
4968 	/* PROTOCOL field */
4969 	switch ((scsipkt->pkt_cdbp[1] >> 1) & 0xf) {
4970 	case SATL_APT_P_HW_RESET:
4971 	case SATL_APT_P_SRST:
4972 	case SATL_APT_P_DMA:
4973 	case SATL_APT_P_DMA_QUEUED:
4974 	case SATL_APT_P_DEV_DIAG:
4975 	case SATL_APT_P_DEV_RESET:
4976 	case SATL_APT_P_UDMA_IN:
4977 	case SATL_APT_P_UDMA_OUT:
4978 	case SATL_APT_P_FPDMA:
4979 	case SATL_APT_P_RET_RESP:
4980 		/* Not yet implemented */
4981 	default:
4982 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4983 		return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4984 
4985 	case SATL_APT_P_NON_DATA:
4986 		scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
4987 		break;
4988 
4989 	case SATL_APT_P_PIO_DATA_IN:
4990 		/* If PROTOCOL disagrees with T_DIR, invalid command */
4991 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_WRITE) {
4992 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
4993 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
4994 		}
4995 
4996 		/* if there is a buffer, release its DMA resources */
4997 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
4998 			sata_scsi_dmafree(NULL, scsipkt);
4999 		} else {
5000 			/* if there is no buffer, how do you PIO in? */
5001 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5002 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5003 		}
5004 
5005 		break;
5006 
5007 	case SATL_APT_P_PIO_DATA_OUT:
5008 		/* If PROTOCOL disagrees with T_DIR, invalid command */
5009 		if (scmd->satacmd_flags.sata_data_direction == SATA_DIR_READ) {
5010 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5011 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5012 		}
5013 
5014 		/* if there is a buffer, release its DMA resources */
5015 		if ((bp != NULL) && bp->b_un.b_addr && bp->b_bcount) {
5016 			sata_scsi_dmafree(NULL, scsipkt);
5017 		} else {
5018 			/* if there is no buffer, how do you PIO out? */
5019 			mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5020 			return (sata_txlt_ata_pass_thru_illegal_cmd(spx));
5021 		}
5022 
5023 		break;
5024 	}
5025 
5026 	/* Parse the ATA cmd fields, transfer some straight to the satacmd */
5027 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5028 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH12:
5029 		feature = scsipkt->pkt_cdbp[3];
5030 
5031 		sec_count = scsipkt->pkt_cdbp[4];
5032 
5033 		lba = scsipkt->pkt_cdbp[8] & 0xf;
5034 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5035 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5036 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5037 
5038 		scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] & 0xf0;
5039 		scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[9];
5040 
5041 		break;
5042 
5043 	case SPC3_CMD_ATA_COMMAND_PASS_THROUGH16:
5044 		if (scsipkt->pkt_cdbp[1] & SATL_APT_BM_EXTEND) {
5045 			extend = 1;
5046 
5047 			feature = scsipkt->pkt_cdbp[3];
5048 			feature = (feature << 8) | scsipkt->pkt_cdbp[4];
5049 
5050 			sec_count = scsipkt->pkt_cdbp[5];
5051 			sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[6];
5052 
5053 			lba = scsipkt->pkt_cdbp[11];
5054 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5055 			lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5056 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5057 			lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5058 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5059 
5060 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13];
5061 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5062 		} else {
5063 			feature = scsipkt->pkt_cdbp[3];
5064 
5065 			sec_count = scsipkt->pkt_cdbp[5];
5066 
5067 			lba = scsipkt->pkt_cdbp[13] & 0xf;
5068 			lba = (lba << 8) | scsipkt->pkt_cdbp[12];
5069 			lba = (lba << 8) | scsipkt->pkt_cdbp[10];
5070 			lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5071 
5072 			scmd->satacmd_device_reg = scsipkt->pkt_cdbp[13] &
5073 			    0xf0;
5074 			scmd->satacmd_cmd_reg = scsipkt->pkt_cdbp[14];
5075 		}
5076 
5077 		break;
5078 	}
5079 
5080 	/* CK_COND bit */
5081 	if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
5082 		if (extend) {
5083 			scmd->satacmd_flags.sata_copy_out_sec_count_msb = 1;
5084 			scmd->satacmd_flags.sata_copy_out_lba_low_msb = 1;
5085 			scmd->satacmd_flags.sata_copy_out_lba_mid_msb = 1;
5086 			scmd->satacmd_flags.sata_copy_out_lba_high_msb = 1;
5087 		}
5088 
5089 		scmd->satacmd_flags.sata_copy_out_sec_count_lsb = 1;
5090 		scmd->satacmd_flags.sata_copy_out_lba_low_lsb = 1;
5091 		scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = 1;
5092 		scmd->satacmd_flags.sata_copy_out_lba_high_lsb = 1;
5093 		scmd->satacmd_flags.sata_copy_out_device_reg = 1;
5094 		scmd->satacmd_flags.sata_copy_out_error_reg = 1;
5095 	}
5096 
5097 	/* Transfer remaining parsed ATA cmd values to the satacmd */
5098 	if (extend) {
5099 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5100 
5101 		scmd->satacmd_features_reg_ext = (feature >> 8) & 0xff;
5102 		scmd->satacmd_sec_count_msb = (sec_count >> 8) & 0xff;
5103 		scmd->satacmd_lba_low_msb = (lba >> 8) & 0xff;
5104 		scmd->satacmd_lba_mid_msb = (lba >> 8) & 0xff;
5105 		scmd->satacmd_lba_high_msb = lba >> 40;
5106 	} else {
5107 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5108 
5109 		scmd->satacmd_features_reg_ext = 0;
5110 		scmd->satacmd_sec_count_msb = 0;
5111 		scmd->satacmd_lba_low_msb = 0;
5112 		scmd->satacmd_lba_mid_msb = 0;
5113 		scmd->satacmd_lba_high_msb = 0;
5114 	}
5115 
5116 	scmd->satacmd_features_reg = feature & 0xff;
5117 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5118 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5119 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5120 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5121 
5122 	/* Determine transfer length */
5123 	switch (scsipkt->pkt_cdbp[2] & 0x3) {		/* T_LENGTH field */
5124 	case 1:
5125 		t_len = feature;
5126 		break;
5127 	case 2:
5128 		t_len = sec_count;
5129 		break;
5130 	default:
5131 		t_len = 0;
5132 		break;
5133 	}
5134 
5135 	/* Adjust transfer length for the Byte Block bit */
5136 	if ((scsipkt->pkt_cdbp[2] >> 2) & 1)
5137 		t_len *= SATA_DISK_SECTOR_SIZE;
5138 
5139 	/* Start processing command */
5140 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5141 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_apt_completion;
5142 		synch = FALSE;
5143 	} else {
5144 		synch = TRUE;
5145 	}
5146 
5147 	if (sata_hba_start(spx, &rval) != 0) {
5148 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5149 		return (rval);
5150 	}
5151 
5152 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5153 
5154 	if (synch) {
5155 		sata_txlt_apt_completion(spx->txlt_sata_pkt);
5156 	}
5157 
5158 	return (TRAN_ACCEPT);
5159 }
5160 
5161 /*
5162  * Translate command: Log Sense
5163  */
5164 static 	int
5165 sata_txlt_log_sense(sata_pkt_txlate_t *spx)
5166 {
5167 	struct scsi_pkt	*scsipkt = spx->txlt_scsi_pkt;
5168 	struct buf	*bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5169 	sata_drive_info_t *sdinfo;
5170 	struct scsi_extended_sense *sense;
5171 	int 		len, count, alc_len;
5172 	int		pc;	/* Page Control code */
5173 	int		page_code;	/* Page code */
5174 	uint8_t		*buf;	/* log sense buffer */
5175 	int		rval, reason;
5176 #define	MAX_LOG_SENSE_PAGE_SIZE	512
5177 
5178 	SATADBG2(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5179 	    "sata_txlt_log_sense, pc 0x%x, page code 0x%x\n",
5180 	    spx->txlt_scsi_pkt->pkt_cdbp[2] >> 6,
5181 	    spx->txlt_scsi_pkt->pkt_cdbp[2] & 0x3f);
5182 
5183 	buf = kmem_zalloc(MAX_LOG_SENSE_PAGE_SIZE, KM_SLEEP);
5184 
5185 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5186 
5187 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5188 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5189 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5190 		kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5191 		return (rval);
5192 	}
5193 
5194 	scsipkt->pkt_reason = CMD_CMPLT;
5195 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5196 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5197 
5198 	pc = scsipkt->pkt_cdbp[2] >> 6;
5199 	page_code = scsipkt->pkt_cdbp[2] & 0x3f;
5200 
5201 	/* Reject not supported request for all but cumulative values */
5202 	switch (pc) {
5203 	case PC_CUMULATIVE_VALUES:
5204 		break;
5205 	default:
5206 		*scsipkt->pkt_scbp = STATUS_CHECK;
5207 		sense = sata_arq_sense(spx);
5208 		sense->es_key = KEY_ILLEGAL_REQUEST;
5209 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5210 		goto done;
5211 	}
5212 
5213 	switch (page_code) {
5214 	case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5215 	case PAGE_CODE_SELF_TEST_RESULTS:
5216 	case PAGE_CODE_INFORMATION_EXCEPTIONS:
5217 	case PAGE_CODE_SMART_READ_DATA:
5218 	case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5219 		break;
5220 	default:
5221 		*scsipkt->pkt_scbp = STATUS_CHECK;
5222 		sense = sata_arq_sense(spx);
5223 		sense->es_key = KEY_ILLEGAL_REQUEST;
5224 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5225 		goto done;
5226 	}
5227 
5228 	if (bp != NULL && bp->b_un.b_addr && bp->b_bcount) {
5229 		/*
5230 		 * Because log sense uses local buffers for data retrieval from
5231 		 * the devices and sets the data programatically in the
5232 		 * original specified buffer, release preallocated DMA
5233 		 * resources before storing data in the original buffer,
5234 		 * so no unwanted DMA sync would take place.
5235 		 */
5236 		sata_id_t *sata_id;
5237 
5238 		sata_scsi_dmafree(NULL, scsipkt);
5239 
5240 		len = 0;
5241 
5242 		/* Build log parameter header */
5243 		buf[len++] = page_code;	/* page code as in the CDB */
5244 		buf[len++] = 0;		/* reserved */
5245 		buf[len++] = 0;		/* Zero out page length for now (MSB) */
5246 		buf[len++] = 0;		/* (LSB) */
5247 
5248 		sdinfo = sata_get_device_info(
5249 		    spx->txlt_sata_hba_inst,
5250 		    &spx->txlt_sata_pkt->satapkt_device);
5251 
5252 		/*
5253 		 * Add requested pages.
5254 		 */
5255 		switch (page_code) {
5256 		case PAGE_CODE_GET_SUPPORTED_LOG_PAGES:
5257 			len = sata_build_lsense_page_0(sdinfo, buf + len);
5258 			break;
5259 		case PAGE_CODE_SELF_TEST_RESULTS:
5260 			sata_id = &sdinfo->satadrv_id;
5261 			if ((! (sata_id->ai_cmdset84 &
5262 			    SATA_SMART_SELF_TEST_SUPPORTED)) ||
5263 			    (! (sata_id->ai_features87 &
5264 			    SATA_SMART_SELF_TEST_SUPPORTED))) {
5265 				*scsipkt->pkt_scbp = STATUS_CHECK;
5266 				sense = sata_arq_sense(spx);
5267 				sense->es_key = KEY_ILLEGAL_REQUEST;
5268 				sense->es_add_code =
5269 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5270 
5271 				goto done;
5272 			}
5273 			len = sata_build_lsense_page_10(sdinfo, buf + len,
5274 			    spx->txlt_sata_hba_inst);
5275 			break;
5276 		case PAGE_CODE_INFORMATION_EXCEPTIONS:
5277 			sata_id = &sdinfo->satadrv_id;
5278 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5279 				*scsipkt->pkt_scbp = STATUS_CHECK;
5280 				sense = sata_arq_sense(spx);
5281 				sense->es_key = KEY_ILLEGAL_REQUEST;
5282 				sense->es_add_code =
5283 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5284 
5285 				goto done;
5286 			}
5287 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5288 				*scsipkt->pkt_scbp = STATUS_CHECK;
5289 				sense = sata_arq_sense(spx);
5290 				sense->es_key = KEY_ABORTED_COMMAND;
5291 				sense->es_add_code =
5292 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5293 				sense->es_qual_code =
5294 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5295 
5296 				goto done;
5297 			}
5298 
5299 			len = sata_build_lsense_page_2f(sdinfo, buf + len,
5300 			    spx->txlt_sata_hba_inst);
5301 			break;
5302 		case PAGE_CODE_SMART_READ_DATA:
5303 			sata_id = &sdinfo->satadrv_id;
5304 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5305 				*scsipkt->pkt_scbp = STATUS_CHECK;
5306 				sense = sata_arq_sense(spx);
5307 				sense->es_key = KEY_ILLEGAL_REQUEST;
5308 				sense->es_add_code =
5309 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5310 
5311 				goto done;
5312 			}
5313 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5314 				*scsipkt->pkt_scbp = STATUS_CHECK;
5315 				sense = sata_arq_sense(spx);
5316 				sense->es_key = KEY_ABORTED_COMMAND;
5317 				sense->es_add_code =
5318 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5319 				sense->es_qual_code =
5320 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5321 
5322 				goto done;
5323 			}
5324 
5325 			/* This page doesn't include a page header */
5326 			len = sata_build_lsense_page_30(sdinfo, buf,
5327 			    spx->txlt_sata_hba_inst);
5328 			goto no_header;
5329 		case PAGE_CODE_START_STOP_CYCLE_COUNTER:
5330 			sata_id = &sdinfo->satadrv_id;
5331 			if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
5332 				*scsipkt->pkt_scbp = STATUS_CHECK;
5333 				sense = sata_arq_sense(spx);
5334 				sense->es_key = KEY_ILLEGAL_REQUEST;
5335 				sense->es_add_code =
5336 				    SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5337 
5338 				goto done;
5339 			}
5340 			if (! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
5341 				*scsipkt->pkt_scbp = STATUS_CHECK;
5342 				sense = sata_arq_sense(spx);
5343 				sense->es_key = KEY_ABORTED_COMMAND;
5344 				sense->es_add_code =
5345 				    SCSI_ASC_ATA_DEV_FEAT_NOT_ENABLED;
5346 				sense->es_qual_code =
5347 				    SCSI_ASCQ_ATA_DEV_FEAT_NOT_ENABLED;
5348 
5349 				goto done;
5350 			}
5351 			len = sata_build_lsense_page_0e(sdinfo, buf, spx);
5352 			goto no_header;
5353 		default:
5354 			/* Invalid request */
5355 			*scsipkt->pkt_scbp = STATUS_CHECK;
5356 			sense = sata_arq_sense(spx);
5357 			sense->es_key = KEY_ILLEGAL_REQUEST;
5358 			sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
5359 			goto done;
5360 		}
5361 
5362 		/* set parameter log sense data length */
5363 		buf[2] = len >> 8;	/* log sense length (MSB) */
5364 		buf[3] = len & 0xff;	/* log sense length (LSB) */
5365 
5366 		len += SCSI_LOG_PAGE_HDR_LEN;
5367 		ASSERT(len <= MAX_LOG_SENSE_PAGE_SIZE);
5368 
5369 no_header:
5370 		/* Check allocation length */
5371 		alc_len = scsipkt->pkt_cdbp[7];
5372 		alc_len = (len << 8) | scsipkt->pkt_cdbp[8];
5373 
5374 		/*
5375 		 * We do not check for possible parameters truncation
5376 		 * (alc_len < len) assuming that the target driver works
5377 		 * correctly. Just avoiding overrun.
5378 		 * Copy no more than requested and possible, buffer-wise.
5379 		 */
5380 		count = MIN(alc_len, len);
5381 		count = MIN(bp->b_bcount, count);
5382 		bcopy(buf, bp->b_un.b_addr, count);
5383 
5384 		scsipkt->pkt_state |= STATE_XFERRED_DATA;
5385 		scsipkt->pkt_resid = alc_len > count ? alc_len - count : 0;
5386 	}
5387 	*scsipkt->pkt_scbp = STATUS_GOOD;
5388 done:
5389 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5390 	(void) kmem_free(buf, MAX_LOG_SENSE_PAGE_SIZE);
5391 
5392 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5393 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
5394 
5395 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
5396 	    scsipkt->pkt_comp != NULL)
5397 		/* scsi callback required */
5398 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
5399 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
5400 		    TQ_SLEEP) == NULL)
5401 			/* Scheduling the callback failed */
5402 			return (TRAN_BUSY);
5403 
5404 	return (TRAN_ACCEPT);
5405 }
5406 
5407 /*
5408  * Translate command: Log Select
5409  * Not implemented at this time - returns invalid command response.
5410  */
5411 static	int
5412 sata_txlt_log_select(sata_pkt_txlate_t *spx)
5413 {
5414 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5415 	    "sata_txlt_log_select\n", NULL);
5416 
5417 	return (sata_txlt_invalid_command(spx));
5418 }
5419 
5420 
5421 /*
5422  * Translate command: Read (various types).
5423  * Translated into appropriate type of ATA READ command
5424  * for SATA hard disks.
5425  * Both the device capabilities and requested operation mode are
5426  * considered.
5427  *
5428  * Following scsi cdb fields are ignored:
5429  * rdprotect, dpo, fua, fua_nv, group_number.
5430  *
5431  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5432  * enable variable sata_func_enable), the capability of the controller and
5433  * capability of a device are checked and if both support queueing, read
5434  * request will be translated to READ_DMA_QUEUEING or READ_DMA_QUEUEING_EXT
5435  * command rather than plain READ_XXX command.
5436  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5437  * both the controller and device suport such functionality, the read
5438  * request will be translated to READ_FPDMA_QUEUED command.
5439  * In both cases the maximum queue depth is derived as minimum of:
5440  * HBA capability,device capability and sata_max_queue_depth variable setting.
5441  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5442  * used to pass max queue depth value, and the maximum possible queue depth
5443  * is 32.
5444  *
5445  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5446  * appropriate values in scsi_pkt fields.
5447  */
5448 static int
5449 sata_txlt_read(sata_pkt_txlate_t *spx)
5450 {
5451 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5452 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5453 	sata_drive_info_t *sdinfo;
5454 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5455 	int cport = SATA_TXLT_CPORT(spx);
5456 	uint16_t sec_count;
5457 	uint64_t lba;
5458 	int rval, reason;
5459 	int synch;
5460 
5461 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5462 
5463 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5464 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5465 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5466 		return (rval);
5467 	}
5468 
5469 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5470 	    &spx->txlt_sata_pkt->satapkt_device);
5471 
5472 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
5473 	/*
5474 	 * Extract LBA and sector count from scsi CDB.
5475 	 */
5476 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5477 	case SCMD_READ:
5478 		/* 6-byte scsi read cmd : 0x08 */
5479 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5480 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5481 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5482 		sec_count = scsipkt->pkt_cdbp[4];
5483 		/* sec_count 0 will be interpreted as 256 by a device */
5484 		break;
5485 	case SCMD_READ_G1:
5486 		/* 10-bytes scsi read command : 0x28 */
5487 		lba = scsipkt->pkt_cdbp[2];
5488 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5489 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5490 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5491 		sec_count = scsipkt->pkt_cdbp[7];
5492 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5493 		break;
5494 	case SCMD_READ_G5:
5495 		/* 12-bytes scsi read command : 0xA8 */
5496 		lba = scsipkt->pkt_cdbp[2];
5497 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5498 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5499 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5500 		sec_count = scsipkt->pkt_cdbp[6];
5501 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5502 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5503 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5504 		break;
5505 	case SCMD_READ_G4:
5506 		/* 16-bytes scsi read command : 0x88 */
5507 		lba = scsipkt->pkt_cdbp[2];
5508 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5509 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5510 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5511 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5512 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5513 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5514 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5515 		sec_count = scsipkt->pkt_cdbp[10];
5516 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5517 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5518 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5519 		break;
5520 	default:
5521 		/* Unsupported command */
5522 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5523 		return (sata_txlt_invalid_command(spx));
5524 	}
5525 
5526 	/*
5527 	 * Check if specified address exceeds device capacity
5528 	 */
5529 	if ((lba >= sdinfo->satadrv_capacity) ||
5530 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5531 		/* LBA out of range */
5532 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5533 		return (sata_txlt_lba_out_of_range(spx));
5534 	}
5535 
5536 	/*
5537 	 * For zero-length transfer, emulate good completion of the command
5538 	 * (reasons for rejecting the command were already checked).
5539 	 * No DMA resources were allocated.
5540 	 */
5541 	if (spx->txlt_dma_cookie_list == NULL) {
5542 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5543 		return (sata_emul_rw_completion(spx));
5544 	}
5545 
5546 	/*
5547 	 * Build cmd block depending on the device capability and
5548 	 * requested operation mode.
5549 	 * Do not bother with non-dma mode - we are working only with
5550 	 * devices supporting DMA.
5551 	 */
5552 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5553 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5554 	scmd->satacmd_cmd_reg = SATAC_READ_DMA;
5555 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5556 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5557 		scmd->satacmd_cmd_reg = SATAC_READ_DMA_EXT;
5558 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5559 #ifndef __lock_lint
5560 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5561 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5562 		scmd->satacmd_lba_high_msb = lba >> 40;
5563 #endif
5564 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5565 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5566 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5567 	}
5568 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5569 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5570 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5571 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5572 	scmd->satacmd_features_reg = 0;
5573 	scmd->satacmd_status_reg = 0;
5574 	scmd->satacmd_error_reg = 0;
5575 
5576 	/*
5577 	 * Check if queueing commands should be used and switch
5578 	 * to appropriate command if possible
5579 	 */
5580 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5581 		boolean_t using_queuing;
5582 
5583 		/* Queuing supported by controller and device? */
5584 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5585 		    (sdinfo->satadrv_features_support &
5586 		    SATA_DEV_F_NCQ) &&
5587 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5588 		    SATA_CTLF_NCQ)) {
5589 			using_queuing = B_TRUE;
5590 
5591 			/* NCQ supported - use FPDMA READ */
5592 			scmd->satacmd_cmd_reg =
5593 			    SATAC_READ_FPDMA_QUEUED;
5594 			scmd->satacmd_features_reg_ext =
5595 			    scmd->satacmd_sec_count_msb;
5596 			scmd->satacmd_sec_count_msb = 0;
5597 		} else if ((sdinfo->satadrv_features_support &
5598 		    SATA_DEV_F_TCQ) &&
5599 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5600 		    SATA_CTLF_QCMD)) {
5601 			using_queuing = B_TRUE;
5602 
5603 			/* Legacy queueing */
5604 			if (sdinfo->satadrv_features_support &
5605 			    SATA_DEV_F_LBA48) {
5606 				scmd->satacmd_cmd_reg =
5607 				    SATAC_READ_DMA_QUEUED_EXT;
5608 				scmd->satacmd_features_reg_ext =
5609 				    scmd->satacmd_sec_count_msb;
5610 				scmd->satacmd_sec_count_msb = 0;
5611 			} else {
5612 				scmd->satacmd_cmd_reg =
5613 				    SATAC_READ_DMA_QUEUED;
5614 			}
5615 		} else	/* NCQ nor legacy queuing not supported */
5616 			using_queuing = B_FALSE;
5617 
5618 		/*
5619 		 * If queuing, the sector count goes in the features register
5620 		 * and the secount count will contain the tag.
5621 		 */
5622 		if (using_queuing) {
5623 			scmd->satacmd_features_reg =
5624 			    scmd->satacmd_sec_count_lsb;
5625 			scmd->satacmd_sec_count_lsb = 0;
5626 			scmd->satacmd_flags.sata_queued = B_TRUE;
5627 
5628 			/* Set-up maximum queue depth */
5629 			scmd->satacmd_flags.sata_max_queue_depth =
5630 			    sdinfo->satadrv_max_queue_depth - 1;
5631 		} else if (sdinfo->satadrv_features_enabled &
5632 		    SATA_DEV_F_E_UNTAGGED_QING) {
5633 			/*
5634 			 * Although NCQ/TCQ is not enabled, untagged queuing
5635 			 * may be still used.
5636 			 * Set-up the maximum untagged queue depth.
5637 			 * Use controller's queue depth from sata_hba_tran.
5638 			 * SATA HBA drivers may ignore this value and rely on
5639 			 * the internal limits.For drivers that do not
5640 			 * ignore untaged queue depth, limit the value to
5641 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5642 			 * largest value that can be passed via
5643 			 * satacmd_flags.sata_max_queue_depth.
5644 			 */
5645 			scmd->satacmd_flags.sata_max_queue_depth =
5646 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5647 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5648 
5649 		} else {
5650 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5651 		}
5652 	} else
5653 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5654 
5655 	SATADBG3(SATA_DBG_HBA_IF, spx->txlt_sata_hba_inst,
5656 	    "sata_txlt_read cmd 0x%2x, lba %llx, sec count %x\n",
5657 	    scmd->satacmd_cmd_reg, lba, sec_count);
5658 
5659 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5660 		/* Need callback function */
5661 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5662 		synch = FALSE;
5663 	} else
5664 		synch = TRUE;
5665 
5666 	/* Transfer command to HBA */
5667 	if (sata_hba_start(spx, &rval) != 0) {
5668 		/* Pkt not accepted for execution */
5669 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5670 		return (rval);
5671 	}
5672 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5673 	/*
5674 	 * If execution is non-synchronous,
5675 	 * a callback function will handle potential errors, translate
5676 	 * the response and will do a callback to a target driver.
5677 	 * If it was synchronous, check execution status using the same
5678 	 * framework callback.
5679 	 */
5680 	if (synch) {
5681 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5682 		    "synchronous execution status %x\n",
5683 		    spx->txlt_sata_pkt->satapkt_reason);
5684 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5685 	}
5686 	return (TRAN_ACCEPT);
5687 }
5688 
5689 
5690 /*
5691  * SATA translate command: Write (various types)
5692  * Translated into appropriate type of ATA WRITE command
5693  * for SATA hard disks.
5694  * Both the device capabilities and requested operation mode are
5695  * considered.
5696  *
5697  * Following scsi cdb fields are ignored:
5698  * rwprotect, dpo, fua, fua_nv, group_number.
5699  *
5700  * If SATA_ENABLE_QUEUING flag is set (in the global SATA HBA framework
5701  * enable variable sata_func_enable), the capability of the controller and
5702  * capability of a device are checked and if both support queueing, write
5703  * request will be translated to WRITE_DMA_QUEUEING or WRITE_DMA_QUEUEING_EXT
5704  * command rather than plain WRITE_XXX command.
5705  * If SATA_ENABLE_NCQ flag is set in addition to SATA_ENABLE_QUEUING flag and
5706  * both the controller and device suport such functionality, the write
5707  * request will be translated to WRITE_FPDMA_QUEUED command.
5708  * In both cases the maximum queue depth is derived as minimum of:
5709  * HBA capability,device capability and sata_max_queue_depth variable setting.
5710  * The value passed to HBA driver is decremented by 1, because only 5 bits are
5711  * used to pass max queue depth value, and the maximum possible queue depth
5712  * is 32.
5713  *
5714  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
5715  * appropriate values in scsi_pkt fields.
5716  */
5717 static int
5718 sata_txlt_write(sata_pkt_txlate_t *spx)
5719 {
5720 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5721 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5722 	sata_drive_info_t *sdinfo;
5723 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
5724 	int cport = SATA_TXLT_CPORT(spx);
5725 	uint16_t sec_count;
5726 	uint64_t lba;
5727 	int rval, reason;
5728 	int synch;
5729 
5730 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5731 
5732 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5733 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
5734 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5735 		return (rval);
5736 	}
5737 
5738 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
5739 	    &spx->txlt_sata_pkt->satapkt_device);
5740 
5741 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5742 	/*
5743 	 * Extract LBA and sector count from scsi CDB
5744 	 */
5745 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
5746 	case SCMD_WRITE:
5747 		/* 6-byte scsi read cmd : 0x0A */
5748 		lba = (scsipkt->pkt_cdbp[1] & 0x1f);
5749 		lba = (lba << 8) | scsipkt->pkt_cdbp[2];
5750 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5751 		sec_count = scsipkt->pkt_cdbp[4];
5752 		/* sec_count 0 will be interpreted as 256 by a device */
5753 		break;
5754 	case SCMD_WRITE_G1:
5755 		/* 10-bytes scsi write command : 0x2A */
5756 		lba = scsipkt->pkt_cdbp[2];
5757 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5758 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5759 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5760 		sec_count = scsipkt->pkt_cdbp[7];
5761 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5762 		break;
5763 	case SCMD_WRITE_G5:
5764 		/* 12-bytes scsi read command : 0xAA */
5765 		lba = scsipkt->pkt_cdbp[2];
5766 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5767 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5768 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5769 		sec_count = scsipkt->pkt_cdbp[6];
5770 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[7];
5771 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[8];
5772 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[9];
5773 		break;
5774 	case SCMD_WRITE_G4:
5775 		/* 16-bytes scsi write command : 0x8A */
5776 		lba = scsipkt->pkt_cdbp[2];
5777 		lba = (lba << 8) | scsipkt->pkt_cdbp[3];
5778 		lba = (lba << 8) | scsipkt->pkt_cdbp[4];
5779 		lba = (lba << 8) | scsipkt->pkt_cdbp[5];
5780 		lba = (lba << 8) | scsipkt->pkt_cdbp[6];
5781 		lba = (lba << 8) | scsipkt->pkt_cdbp[7];
5782 		lba = (lba << 8) | scsipkt->pkt_cdbp[8];
5783 		lba = (lba << 8) | scsipkt->pkt_cdbp[9];
5784 		sec_count = scsipkt->pkt_cdbp[10];
5785 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[11];
5786 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[12];
5787 		sec_count = (sec_count << 8) | scsipkt->pkt_cdbp[13];
5788 		break;
5789 	default:
5790 		/* Unsupported command */
5791 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5792 		return (sata_txlt_invalid_command(spx));
5793 	}
5794 
5795 	/*
5796 	 * Check if specified address and length exceeds device capacity
5797 	 */
5798 	if ((lba >= sdinfo->satadrv_capacity) ||
5799 	    ((lba + sec_count) > sdinfo->satadrv_capacity)) {
5800 		/* LBA out of range */
5801 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5802 		return (sata_txlt_lba_out_of_range(spx));
5803 	}
5804 
5805 	/*
5806 	 * For zero-length transfer, emulate good completion of the command
5807 	 * (reasons for rejecting the command were already checked).
5808 	 * No DMA resources were allocated.
5809 	 */
5810 	if (spx->txlt_dma_cookie_list == NULL) {
5811 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5812 		return (sata_emul_rw_completion(spx));
5813 	}
5814 
5815 	/*
5816 	 * Build cmd block depending on the device capability and
5817 	 * requested operation mode.
5818 	 * Do not bother with non-dma mode- we are working only with
5819 	 * devices supporting DMA.
5820 	 */
5821 	scmd->satacmd_addr_type = ATA_ADDR_LBA;
5822 	scmd->satacmd_device_reg = SATA_ADH_LBA;
5823 	scmd->satacmd_cmd_reg = SATAC_WRITE_DMA;
5824 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
5825 		scmd->satacmd_addr_type = ATA_ADDR_LBA48;
5826 		scmd->satacmd_cmd_reg = SATAC_WRITE_DMA_EXT;
5827 		scmd->satacmd_sec_count_msb = sec_count >> 8;
5828 		scmd->satacmd_lba_low_msb = (lba >> 24) & 0xff;
5829 #ifndef __lock_lint
5830 		scmd->satacmd_lba_mid_msb = (lba >> 32) & 0xff;
5831 		scmd->satacmd_lba_high_msb = lba >> 40;
5832 #endif
5833 	} else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28) {
5834 		scmd->satacmd_addr_type = ATA_ADDR_LBA28;
5835 		scmd->satacmd_device_reg = SATA_ADH_LBA | ((lba >> 24) & 0xf);
5836 	}
5837 	scmd->satacmd_sec_count_lsb = sec_count & 0xff;
5838 	scmd->satacmd_lba_low_lsb = lba & 0xff;
5839 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
5840 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
5841 	scmd->satacmd_features_reg = 0;
5842 	scmd->satacmd_status_reg = 0;
5843 	scmd->satacmd_error_reg = 0;
5844 
5845 	/*
5846 	 * Check if queueing commands should be used and switch
5847 	 * to appropriate command if possible
5848 	 */
5849 	if (sata_func_enable & SATA_ENABLE_QUEUING) {
5850 		boolean_t using_queuing;
5851 
5852 		/* Queuing supported by controller and device? */
5853 		if ((sata_func_enable & SATA_ENABLE_NCQ) &&
5854 		    (sdinfo->satadrv_features_support &
5855 		    SATA_DEV_F_NCQ) &&
5856 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5857 		    SATA_CTLF_NCQ)) {
5858 			using_queuing = B_TRUE;
5859 
5860 			/* NCQ supported - use FPDMA WRITE */
5861 			scmd->satacmd_cmd_reg =
5862 			    SATAC_WRITE_FPDMA_QUEUED;
5863 			scmd->satacmd_features_reg_ext =
5864 			    scmd->satacmd_sec_count_msb;
5865 			scmd->satacmd_sec_count_msb = 0;
5866 		} else if ((sdinfo->satadrv_features_support &
5867 		    SATA_DEV_F_TCQ) &&
5868 		    (SATA_FEATURES(spx->txlt_sata_hba_inst) &
5869 		    SATA_CTLF_QCMD)) {
5870 			using_queuing = B_TRUE;
5871 
5872 			/* Legacy queueing */
5873 			if (sdinfo->satadrv_features_support &
5874 			    SATA_DEV_F_LBA48) {
5875 				scmd->satacmd_cmd_reg =
5876 				    SATAC_WRITE_DMA_QUEUED_EXT;
5877 				scmd->satacmd_features_reg_ext =
5878 				    scmd->satacmd_sec_count_msb;
5879 				scmd->satacmd_sec_count_msb = 0;
5880 			} else {
5881 				scmd->satacmd_cmd_reg =
5882 				    SATAC_WRITE_DMA_QUEUED;
5883 			}
5884 		} else	/*  NCQ nor legacy queuing not supported */
5885 			using_queuing = B_FALSE;
5886 
5887 		if (using_queuing) {
5888 			scmd->satacmd_features_reg =
5889 			    scmd->satacmd_sec_count_lsb;
5890 			scmd->satacmd_sec_count_lsb = 0;
5891 			scmd->satacmd_flags.sata_queued = B_TRUE;
5892 			/* Set-up maximum queue depth */
5893 			scmd->satacmd_flags.sata_max_queue_depth =
5894 			    sdinfo->satadrv_max_queue_depth - 1;
5895 		} else if (sdinfo->satadrv_features_enabled &
5896 		    SATA_DEV_F_E_UNTAGGED_QING) {
5897 			/*
5898 			 * Although NCQ/TCQ is not enabled, untagged queuing
5899 			 * may be still used.
5900 			 * Set-up the maximum untagged queue depth.
5901 			 * Use controller's queue depth from sata_hba_tran.
5902 			 * SATA HBA drivers may ignore this value and rely on
5903 			 * the internal limits. For drivera that do not
5904 			 * ignore untaged queue depth, limit the value to
5905 			 * SATA_MAX_QUEUE_DEPTH (32), as this is the
5906 			 * largest value that can be passed via
5907 			 * satacmd_flags.sata_max_queue_depth.
5908 			 */
5909 			scmd->satacmd_flags.sata_max_queue_depth =
5910 			    SATA_QDEPTH(shi) <= SATA_MAX_QUEUE_DEPTH ?
5911 			    SATA_QDEPTH(shi) - 1: SATA_MAX_QUEUE_DEPTH - 1;
5912 
5913 		} else {
5914 			scmd->satacmd_flags.sata_max_queue_depth = 0;
5915 		}
5916 	} else
5917 		scmd->satacmd_flags.sata_max_queue_depth = 0;
5918 
5919 	SATADBG3(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5920 	    "sata_txlt_write cmd 0x%2x, lba %llx, sec count %x\n",
5921 	    scmd->satacmd_cmd_reg, lba, sec_count);
5922 
5923 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
5924 		/* Need callback function */
5925 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_rw_completion;
5926 		synch = FALSE;
5927 	} else
5928 		synch = TRUE;
5929 
5930 	/* Transfer command to HBA */
5931 	if (sata_hba_start(spx, &rval) != 0) {
5932 		/* Pkt not accepted for execution */
5933 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5934 		return (rval);
5935 	}
5936 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
5937 
5938 	/*
5939 	 * If execution is non-synchronous,
5940 	 * a callback function will handle potential errors, translate
5941 	 * the response and will do a callback to a target driver.
5942 	 * If it was synchronous, check execution status using the same
5943 	 * framework callback.
5944 	 */
5945 	if (synch) {
5946 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5947 		    "synchronous execution status %x\n",
5948 		    spx->txlt_sata_pkt->satapkt_reason);
5949 		sata_txlt_rw_completion(spx->txlt_sata_pkt);
5950 	}
5951 	return (TRAN_ACCEPT);
5952 }
5953 
5954 
5955 /*
5956  * Implements SCSI SBC WRITE BUFFER command download microcode option
5957  */
5958 static int
5959 sata_txlt_write_buffer(sata_pkt_txlate_t *spx)
5960 {
5961 #define	WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE			4
5962 #define	WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE			5
5963 
5964 	sata_hba_inst_t *sata_hba_inst = SATA_TXLT_HBA_INST(spx);
5965 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
5966 	struct sata_pkt *sata_pkt = spx->txlt_sata_pkt;
5967 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
5968 
5969 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
5970 	struct scsi_extended_sense *sense;
5971 	int rval, mode, sector_count, reason;
5972 	int cport = SATA_TXLT_CPORT(spx);
5973 
5974 	mode = scsipkt->pkt_cdbp[1] & 0x1f;
5975 
5976 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
5977 	    "sata_txlt_write_buffer, mode 0x%x\n", mode);
5978 
5979 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
5980 
5981 	if ((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
5982 	    TRAN_ACCEPT) {
5983 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
5984 		return (rval);
5985 	}
5986 
5987 	/* Use synchronous mode */
5988 	spx->txlt_sata_pkt->satapkt_op_mode
5989 	    |= SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
5990 
5991 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_WRITE;
5992 
5993 	scsipkt->pkt_reason = CMD_CMPLT;
5994 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
5995 	    STATE_SENT_CMD | STATE_GOT_STATUS;
5996 
5997 	/*
5998 	 * The SCSI to ATA translation specification only calls
5999 	 * for WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE.
6000 	 * WB_DOWNLOAD_MICROC_AND_REVERT_MODE is implemented, but
6001 	 * ATA 8 (draft) got rid of download microcode for temp
6002 	 * and it is even optional for ATA 7, so it may be aborted.
6003 	 * WB_DOWNLOAD_MICROCODE_WITH_OFFSET is not implemented as
6004 	 * it is not specified and the buffer offset for SCSI is a 16-bit
6005 	 * value in bytes, but for ATA it is a 16-bit offset in 512 byte
6006 	 * sectors.  Thus the offset really doesn't buy us anything.
6007 	 * If and when ATA 8 is stabilized and the SCSI to ATA specification
6008 	 * is revised, this can be revisisted.
6009 	 */
6010 	/* Reject not supported request */
6011 	switch (mode) {
6012 	case WB_DOWNLOAD_MICROCODE_AND_REVERT_MODE:
6013 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_TEMP;
6014 		break;
6015 	case WB_DOWNLOAD_MICROCODE_AND_SAVE_MODE:
6016 		scmd->satacmd_features_reg = SATA_DOWNLOAD_MCODE_SAVE;
6017 		break;
6018 	default:
6019 		goto bad_param;
6020 	}
6021 
6022 	*scsipkt->pkt_scbp = STATUS_GOOD;	/* Presumed outcome */
6023 
6024 	scmd->satacmd_cmd_reg = SATAC_DOWNLOAD_MICROCODE;
6025 	if ((bp->b_bcount % SATA_DISK_SECTOR_SIZE) != 0)
6026 		goto bad_param;
6027 	sector_count = bp->b_bcount / SATA_DISK_SECTOR_SIZE;
6028 	scmd->satacmd_sec_count_lsb = (uint8_t)sector_count;
6029 	scmd->satacmd_lba_low_lsb = ((uint16_t)sector_count) >> 8;
6030 	scmd->satacmd_lba_mid_lsb = 0;
6031 	scmd->satacmd_lba_high_lsb = 0;
6032 	scmd->satacmd_device_reg = 0;
6033 	spx->txlt_sata_pkt->satapkt_comp = NULL;
6034 	scmd->satacmd_addr_type = 0;
6035 
6036 	/* Transfer command to HBA */
6037 	if (sata_hba_start(spx, &rval) != 0) {
6038 		/* Pkt not accepted for execution */
6039 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6040 		return (rval);
6041 	}
6042 
6043 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
6044 
6045 	/* Then we need synchronous check the status of the disk */
6046 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6047 	    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6048 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6049 		scsipkt->pkt_reason = CMD_CMPLT;
6050 
6051 		/* Download commmand succeed, so probe and identify device */
6052 		sata_reidentify_device(spx);
6053 	} else {
6054 		/* Something went wrong, microcode download command failed */
6055 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6056 		*scsipkt->pkt_scbp = STATUS_CHECK;
6057 		sense = sata_arq_sense(spx);
6058 		switch (sata_pkt->satapkt_reason) {
6059 		case SATA_PKT_PORT_ERROR:
6060 			/*
6061 			 * We have no device data. Assume no data transfered.
6062 			 */
6063 			sense->es_key = KEY_HARDWARE_ERROR;
6064 			break;
6065 
6066 		case SATA_PKT_DEV_ERROR:
6067 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6068 			    SATA_STATUS_ERR) {
6069 				/*
6070 				 * determine dev error reason from error
6071 				 * reg content
6072 				 */
6073 				sata_decode_device_error(spx, sense);
6074 				break;
6075 			}
6076 			/* No extended sense key - no info available */
6077 			break;
6078 
6079 		case SATA_PKT_TIMEOUT:
6080 			scsipkt->pkt_reason = CMD_TIMEOUT;
6081 			scsipkt->pkt_statistics |=
6082 			    STAT_TIMEOUT | STAT_DEV_RESET;
6083 			/* No extended sense key ? */
6084 			break;
6085 
6086 		case SATA_PKT_ABORTED:
6087 			scsipkt->pkt_reason = CMD_ABORTED;
6088 			scsipkt->pkt_statistics |= STAT_ABORTED;
6089 			/* No extended sense key ? */
6090 			break;
6091 
6092 		case SATA_PKT_RESET:
6093 			/* pkt aborted by an explicit reset from a host */
6094 			scsipkt->pkt_reason = CMD_RESET;
6095 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6096 			break;
6097 
6098 		default:
6099 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6100 			    "sata_txlt_nodata_cmd_completion: "
6101 			    "invalid packet completion reason %d",
6102 			    sata_pkt->satapkt_reason));
6103 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6104 			break;
6105 		}
6106 
6107 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6108 		    "scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6109 
6110 		if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6111 			/* scsi callback required */
6112 			scsi_hba_pkt_comp(scsipkt);
6113 	}
6114 	return (TRAN_ACCEPT);
6115 
6116 bad_param:
6117 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6118 	*scsipkt->pkt_scbp = STATUS_CHECK;
6119 	sense = sata_arq_sense(spx);
6120 	sense->es_key = KEY_ILLEGAL_REQUEST;
6121 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6122 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6123 	    scsipkt->pkt_comp != NULL) {
6124 		/* scsi callback required */
6125 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6126 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
6127 		    TQ_SLEEP) == 0) {
6128 			/* Scheduling the callback failed */
6129 			rval = TRAN_BUSY;
6130 		}
6131 	}
6132 	return (rval);
6133 }
6134 
6135 /*
6136  * Re-identify device after doing a firmware download.
6137  */
6138 static void
6139 sata_reidentify_device(sata_pkt_txlate_t *spx)
6140 {
6141 #define	DOWNLOAD_WAIT_TIME_SECS	60
6142 #define	DOWNLOAD_WAIT_INTERVAL_SECS	1
6143 	int rval;
6144 	int retry_cnt;
6145 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6146 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6147 	sata_device_t sata_device = spx->txlt_sata_pkt->satapkt_device;
6148 	sata_drive_info_t *sdinfo;
6149 
6150 	/*
6151 	 * Before returning good status, probe device.
6152 	 * Device probing will get IDENTIFY DEVICE data, if possible.
6153 	 * The assumption is that the new microcode is applied by the
6154 	 * device. It is a caller responsibility to verify this.
6155 	 */
6156 	for (retry_cnt = 0;
6157 	    retry_cnt < DOWNLOAD_WAIT_TIME_SECS / DOWNLOAD_WAIT_INTERVAL_SECS;
6158 	    retry_cnt++) {
6159 		rval = sata_probe_device(sata_hba_inst, &sata_device);
6160 
6161 		if (rval == SATA_SUCCESS) { /* Set default features */
6162 			sdinfo = sata_get_device_info(sata_hba_inst,
6163 			    &sata_device);
6164 			if (sata_initialize_device(sata_hba_inst, sdinfo) !=
6165 			    SATA_SUCCESS) {
6166 				/* retry */
6167 				rval = sata_initialize_device(sata_hba_inst,
6168 				    sdinfo);
6169 				if (rval == SATA_RETRY)
6170 					sata_log(sata_hba_inst, CE_WARN,
6171 					    "SATA device at port %d pmport %d -"
6172 					    " default device features could not"
6173 					    " be set. Device may not operate "
6174 					    "as expected.",
6175 					    sata_device.satadev_addr.cport,
6176 					    sata_device.satadev_addr.pmport);
6177 			}
6178 			if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6179 				scsi_hba_pkt_comp(scsipkt);
6180 			return;
6181 		} else if (rval == SATA_RETRY) {
6182 			delay(drv_usectohz(1000000 *
6183 			    DOWNLOAD_WAIT_INTERVAL_SECS));
6184 			continue;
6185 		} else	/* failed - no reason to retry */
6186 			break;
6187 	}
6188 
6189 	/*
6190 	 * Something went wrong, device probing failed.
6191 	 */
6192 	SATA_LOG_D((sata_hba_inst, CE_WARN,
6193 	    "Cannot probe device after downloading microcode\n"));
6194 
6195 	/* Reset device to force retrying the probe. */
6196 	(void) (*SATA_RESET_DPORT_FUNC(sata_hba_inst))
6197 	    (SATA_DIP(sata_hba_inst), &sata_device);
6198 
6199 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6200 		scsi_hba_pkt_comp(scsipkt);
6201 }
6202 
6203 
6204 /*
6205  * Translate command: Synchronize Cache.
6206  * Translates into Flush Cache command for SATA hard disks.
6207  *
6208  * Returns TRAN_ACCEPT or code returned by sata_hba_start() and
6209  * appropriate values in scsi_pkt fields.
6210  */
6211 static 	int
6212 sata_txlt_synchronize_cache(sata_pkt_txlate_t *spx)
6213 {
6214 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
6215 	sata_hba_inst_t *shi = SATA_TXLT_HBA_INST(spx);
6216 	int cport = SATA_TXLT_CPORT(spx);
6217 	int rval, reason;
6218 	int synch;
6219 
6220 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
6221 
6222 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
6223 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
6224 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
6225 		return (rval);
6226 	}
6227 
6228 	scmd->satacmd_addr_type = 0;
6229 	scmd->satacmd_cmd_reg = SATAC_FLUSH_CACHE;
6230 	scmd->satacmd_device_reg = 0;
6231 	scmd->satacmd_sec_count_lsb = 0;
6232 	scmd->satacmd_lba_low_lsb = 0;
6233 	scmd->satacmd_lba_mid_lsb = 0;
6234 	scmd->satacmd_lba_high_lsb = 0;
6235 	scmd->satacmd_features_reg = 0;
6236 	scmd->satacmd_status_reg = 0;
6237 	scmd->satacmd_error_reg = 0;
6238 
6239 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6240 	    "sata_txlt_synchronize_cache\n", NULL);
6241 
6242 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6243 		/* Need to set-up a callback function */
6244 		spx->txlt_sata_pkt->satapkt_comp =
6245 		    sata_txlt_nodata_cmd_completion;
6246 		synch = FALSE;
6247 	} else
6248 		synch = TRUE;
6249 
6250 	/* Transfer command to HBA */
6251 	if (sata_hba_start(spx, &rval) != 0) {
6252 		/* Pkt not accepted for execution */
6253 		mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6254 		return (rval);
6255 	}
6256 	mutex_exit(&SATA_CPORT_MUTEX(shi, cport));
6257 
6258 	/*
6259 	 * If execution non-synchronous, it had to be completed
6260 	 * a callback function will handle potential errors, translate
6261 	 * the response and will do a callback to a target driver.
6262 	 * If it was synchronous, check status, using the same
6263 	 * framework callback.
6264 	 */
6265 	if (synch) {
6266 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6267 		    "synchronous execution status %x\n",
6268 		    spx->txlt_sata_pkt->satapkt_reason);
6269 		sata_txlt_nodata_cmd_completion(spx->txlt_sata_pkt);
6270 	}
6271 	return (TRAN_ACCEPT);
6272 }
6273 
6274 
6275 /*
6276  * Send pkt to SATA HBA driver
6277  *
6278  * This function may be called only if the operation is requested by scsi_pkt,
6279  * i.e. scsi_pkt is not NULL.
6280  *
6281  * This function has to be called with cport mutex held. It does release
6282  * the mutex when it calls HBA driver sata_tran_start function and
6283  * re-acquires it afterwards.
6284  *
6285  * If return value is 0, pkt was accepted, -1 otherwise
6286  * rval is set to appropriate sata_scsi_start return value.
6287  *
6288  * Note 1:If HBA driver returns value other than TRAN_ACCEPT, it should not
6289  * have called the sata_pkt callback function for this packet.
6290  *
6291  * The scsi callback has to be performed by the caller of this routine.
6292  */
6293 static int
6294 sata_hba_start(sata_pkt_txlate_t *spx, int *rval)
6295 {
6296 	int stat;
6297 	uint8_t cport = SATA_TXLT_CPORT(spx);
6298 	uint8_t pmport = SATA_TXLT_PMPORT(spx);
6299 	sata_hba_inst_t *sata_hba_inst = spx->txlt_sata_hba_inst;
6300 	sata_drive_info_t *sdinfo;
6301 	sata_pmult_info_t *pminfo;
6302 	sata_pmport_info_t *pmportinfo = NULL;
6303 	sata_device_t *sata_device = NULL;
6304 	uint8_t cmd;
6305 	struct sata_cmd_flags cmd_flags;
6306 
6307 	ASSERT(spx->txlt_sata_pkt != NULL);
6308 
6309 	ASSERT(mutex_owned(&SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6310 
6311 	sdinfo = sata_get_device_info(sata_hba_inst,
6312 	    &spx->txlt_sata_pkt->satapkt_device);
6313 	ASSERT(sdinfo != NULL);
6314 
6315 	/* Clear device reset state? */
6316 	/* qual should be XXX_DPMPORT, but add XXX_PMPORT in case */
6317 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT ||
6318 	    sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT) {
6319 
6320 		/*
6321 		 * Get the pmult_info of the its parent port multiplier, all
6322 		 * sub-devices share a common device reset flags on in
6323 		 * pmult_info.
6324 		 */
6325 		pminfo = SATA_PMULT_INFO(sata_hba_inst, cport);
6326 		pmportinfo = pminfo->pmult_dev_port[pmport];
6327 		ASSERT(pminfo != NULL);
6328 		if (pminfo->pmult_event_flags & SATA_EVNT_CLEAR_DEVICE_RESET) {
6329 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6330 			    sata_clear_dev_reset = B_TRUE;
6331 			pminfo->pmult_event_flags &=
6332 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6333 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6334 			    "sata_hba_start: clearing device reset state"
6335 			    "on pmult.\n", NULL);
6336 		}
6337 	} else {
6338 		if (sdinfo->satadrv_event_flags &
6339 		    SATA_EVNT_CLEAR_DEVICE_RESET) {
6340 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags.
6341 			    sata_clear_dev_reset = B_TRUE;
6342 			sdinfo->satadrv_event_flags &=
6343 			    ~SATA_EVNT_CLEAR_DEVICE_RESET;
6344 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6345 			    "sata_hba_start: clearing device reset state\n",
6346 			    NULL);
6347 		}
6348 	}
6349 
6350 	cmd = spx->txlt_sata_pkt->satapkt_cmd.satacmd_cmd_reg;
6351 	cmd_flags = spx->txlt_sata_pkt->satapkt_cmd.satacmd_flags;
6352 	sata_device = &spx->txlt_sata_pkt->satapkt_device;
6353 
6354 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6355 
6356 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6357 	    "Sata cmd 0x%2x\n", cmd);
6358 
6359 	stat = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
6360 	    spx->txlt_sata_pkt);
6361 
6362 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6363 	/*
6364 	 * If sata pkt was accepted and executed in asynchronous mode, i.e.
6365 	 * with the sata callback, the sata_pkt could be already destroyed
6366 	 * by the time we check ther return status from the hba_start()
6367 	 * function, because sata_scsi_destroy_pkt() could have been already
6368 	 * called (perhaps in the interrupt context). So, in such case, there
6369 	 * should be no references to it. In other cases, sata_pkt still
6370 	 * exists.
6371 	 */
6372 	if (stat == SATA_TRAN_ACCEPTED) {
6373 		/*
6374 		 * pkt accepted for execution.
6375 		 * If it was executed synchronously, it is already completed
6376 		 * and pkt completion_reason indicates completion status.
6377 		 */
6378 		*rval = TRAN_ACCEPT;
6379 		return (0);
6380 	}
6381 
6382 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6383 	switch (stat) {
6384 	case SATA_TRAN_QUEUE_FULL:
6385 		/*
6386 		 * Controller detected queue full condition.
6387 		 */
6388 		SATADBG1(SATA_DBG_HBA_IF, sata_hba_inst,
6389 		    "sata_hba_start: queue full\n", NULL);
6390 
6391 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6392 		*spx->txlt_scsi_pkt->pkt_scbp = STATUS_QFULL;
6393 
6394 		*rval = TRAN_BUSY;
6395 		break;
6396 
6397 	case SATA_TRAN_PORT_ERROR:
6398 		/*
6399 		 * Communication/link with device or general port error
6400 		 * detected before pkt execution begun.
6401 		 */
6402 		if (spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6403 		    SATA_ADDR_CPORT ||
6404 		    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual ==
6405 		    SATA_ADDR_DCPORT)
6406 			sata_log(sata_hba_inst, CE_CONT,
6407 			    "SATA port %d error",
6408 			    sata_device->satadev_addr.cport);
6409 		else
6410 			sata_log(sata_hba_inst, CE_CONT,
6411 			    "SATA port %d:%d error\n",
6412 			    sata_device->satadev_addr.cport,
6413 			    sata_device->satadev_addr.pmport);
6414 
6415 		/*
6416 		 * Update the port/device structure.
6417 		 * sata_pkt should be still valid. Since port error is
6418 		 * returned, sata_device content should reflect port
6419 		 * state - it means, that sata address have been changed,
6420 		 * because original packet's sata address refered to a device
6421 		 * attached to some port.
6422 		 */
6423 		if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT ||
6424 		    sata_device->satadev_addr.qual == SATA_ADDR_PMPORT) {
6425 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6426 			mutex_enter(&pmportinfo->pmport_mutex);
6427 			sata_update_pmport_info(sata_hba_inst, sata_device);
6428 			mutex_exit(&pmportinfo->pmport_mutex);
6429 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6430 		} else {
6431 			sata_update_port_info(sata_hba_inst, sata_device);
6432 		}
6433 
6434 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6435 		*rval = TRAN_FATAL_ERROR;
6436 		break;
6437 
6438 	case SATA_TRAN_CMD_UNSUPPORTED:
6439 		/*
6440 		 * Command rejected by HBA as unsupported. It was HBA driver
6441 		 * that rejected the command, command was not sent to
6442 		 * an attached device.
6443 		 */
6444 		if ((sdinfo != NULL) &&
6445 		    (sdinfo->satadrv_state & SATA_DSTATE_RESET))
6446 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6447 			    "sat_hba_start: cmd 0x%2x rejected "
6448 			    "with SATA_TRAN_CMD_UNSUPPORTED status\n", cmd);
6449 
6450 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6451 		(void) sata_txlt_invalid_command(spx);
6452 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
6453 
6454 		*rval = TRAN_ACCEPT;
6455 		break;
6456 
6457 	case SATA_TRAN_BUSY:
6458 		/*
6459 		 * Command rejected by HBA because other operation prevents
6460 		 * accepting the packet, or device is in RESET condition.
6461 		 */
6462 		if (sdinfo != NULL) {
6463 			sdinfo->satadrv_state =
6464 			    spx->txlt_sata_pkt->satapkt_device.satadev_state;
6465 
6466 			if (sdinfo->satadrv_state & SATA_DSTATE_RESET) {
6467 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6468 				    "sata_hba_start: cmd 0x%2x rejected "
6469 				    "because of device reset condition\n",
6470 				    cmd);
6471 			} else {
6472 				SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
6473 				    "sata_hba_start: cmd 0x%2x rejected "
6474 				    "with SATA_TRAN_BUSY status\n",
6475 				    cmd);
6476 			}
6477 		}
6478 		spx->txlt_scsi_pkt->pkt_reason = CMD_INCOMPLETE;
6479 		*rval = TRAN_BUSY;
6480 		break;
6481 
6482 	default:
6483 		/* Unrecognized HBA response */
6484 		SATA_LOG_D((sata_hba_inst, CE_WARN,
6485 		    "sata_hba_start: unrecognized HBA response "
6486 		    "to cmd : 0x%2x resp 0x%x", cmd, rval));
6487 		spx->txlt_scsi_pkt->pkt_reason = CMD_TRAN_ERR;
6488 		*rval = TRAN_FATAL_ERROR;
6489 		break;
6490 	}
6491 
6492 	/*
6493 	 * If we got here, the packet was rejected.
6494 	 * Check if we need to remember reset state clearing request
6495 	 */
6496 	if (cmd_flags.sata_clear_dev_reset) {
6497 		/*
6498 		 * Check if device is still configured - it may have
6499 		 * disapeared from the configuration
6500 		 */
6501 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
6502 		if (sdinfo != NULL) {
6503 			/*
6504 			 * Restore the flag that requests clearing of
6505 			 * the device reset state,
6506 			 * so the next sata packet may carry it to HBA.
6507 			 */
6508 			if (sdinfo->satadrv_addr.qual == SATA_ADDR_PMPORT ||
6509 			    sdinfo->satadrv_addr.qual == SATA_ADDR_DPMPORT) {
6510 				pminfo->pmult_event_flags |=
6511 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6512 			} else {
6513 				sdinfo->satadrv_event_flags |=
6514 				    SATA_EVNT_CLEAR_DEVICE_RESET;
6515 			}
6516 		}
6517 	}
6518 	return (-1);
6519 }
6520 
6521 /*
6522  * Scsi response setup for invalid LBA
6523  *
6524  * Returns TRAN_ACCEPT and appropriate values in scsi_pkt fields.
6525  */
6526 static int
6527 sata_txlt_lba_out_of_range(sata_pkt_txlate_t *spx)
6528 {
6529 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6530 	struct scsi_extended_sense *sense;
6531 
6532 	scsipkt->pkt_reason = CMD_CMPLT;
6533 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6534 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6535 	*scsipkt->pkt_scbp = STATUS_CHECK;
6536 
6537 	*scsipkt->pkt_scbp = STATUS_CHECK;
6538 	sense = sata_arq_sense(spx);
6539 	sense->es_key = KEY_ILLEGAL_REQUEST;
6540 	sense->es_add_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
6541 
6542 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6543 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6544 
6545 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6546 	    scsipkt->pkt_comp != NULL)
6547 		/* scsi callback required */
6548 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6549 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
6550 		    TQ_SLEEP) == NULL)
6551 			/* Scheduling the callback failed */
6552 			return (TRAN_BUSY);
6553 	return (TRAN_ACCEPT);
6554 }
6555 
6556 
6557 /*
6558  * Analyze device status and error registers and translate them into
6559  * appropriate scsi sense codes.
6560  * NOTE: non-packet commands only for now
6561  */
6562 static void
6563 sata_decode_device_error(sata_pkt_txlate_t *spx,
6564     struct scsi_extended_sense *sense)
6565 {
6566 	uint8_t err_reg = spx->txlt_sata_pkt->satapkt_cmd.satacmd_error_reg;
6567 
6568 	ASSERT(sense != NULL);
6569 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
6570 	    SATA_STATUS_ERR);
6571 
6572 
6573 	if (err_reg & SATA_ERROR_ICRC) {
6574 		sense->es_key = KEY_ABORTED_COMMAND;
6575 		sense->es_add_code = 0x08; /* Communication failure */
6576 		return;
6577 	}
6578 
6579 	if (err_reg & SATA_ERROR_UNC) {
6580 		sense->es_key = KEY_MEDIUM_ERROR;
6581 		/* Information bytes (LBA) need to be set by a caller */
6582 		return;
6583 	}
6584 
6585 	/* ADD HERE: MC error bit handling for ATAPI CD/DVD */
6586 	if (err_reg & (SATA_ERROR_MCR | SATA_ERROR_NM)) {
6587 		sense->es_key = KEY_UNIT_ATTENTION;
6588 		sense->es_add_code = 0x3a; /* No media present */
6589 		return;
6590 	}
6591 
6592 	if (err_reg & SATA_ERROR_IDNF) {
6593 		if (err_reg & SATA_ERROR_ABORT) {
6594 			sense->es_key = KEY_ABORTED_COMMAND;
6595 		} else {
6596 			sense->es_key = KEY_ILLEGAL_REQUEST;
6597 			sense->es_add_code = 0x21; /* LBA out of range */
6598 		}
6599 		return;
6600 	}
6601 
6602 	if (err_reg & SATA_ERROR_ABORT) {
6603 		ASSERT(spx->txlt_sata_pkt != NULL);
6604 		sense->es_key = KEY_ABORTED_COMMAND;
6605 		return;
6606 	}
6607 }
6608 
6609 /*
6610  * Extract error LBA from sata_pkt.satapkt_cmd register fields
6611  */
6612 static void
6613 sata_extract_error_lba(sata_pkt_txlate_t *spx, uint64_t *lba)
6614 {
6615 	sata_cmd_t *sata_cmd = &spx->txlt_sata_pkt->satapkt_cmd;
6616 
6617 	*lba = 0;
6618 	if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA48) {
6619 		*lba = sata_cmd->satacmd_lba_high_msb;
6620 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_msb;
6621 		*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_msb;
6622 	} else if (sata_cmd->satacmd_addr_type == ATA_ADDR_LBA28) {
6623 		*lba = sata_cmd->satacmd_device_reg & 0xf;
6624 	}
6625 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_high_lsb;
6626 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_mid_lsb;
6627 	*lba = (*lba << 8) | sata_cmd->satacmd_lba_low_lsb;
6628 }
6629 
6630 /*
6631  * This is fixed sense format - if LBA exceeds the info field size,
6632  * no valid info will be returned (valid bit in extended sense will
6633  * be set to 0).
6634  */
6635 static struct scsi_extended_sense *
6636 sata_arq_sense(sata_pkt_txlate_t *spx)
6637 {
6638 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6639 	struct scsi_arq_status *arqs;
6640 	struct scsi_extended_sense *sense;
6641 
6642 	/* Fill ARQ sense data */
6643 	scsipkt->pkt_state |= STATE_ARQ_DONE;
6644 	arqs = (struct scsi_arq_status *)scsipkt->pkt_scbp;
6645 	*(uchar_t *)&arqs->sts_status = STATUS_CHECK;
6646 	*(uchar_t *)&arqs->sts_rqpkt_status = STATUS_GOOD;
6647 	arqs->sts_rqpkt_reason = CMD_CMPLT;
6648 	arqs->sts_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6649 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
6650 	arqs->sts_rqpkt_resid = 0;
6651 	sense = &arqs->sts_sensedata;
6652 	bzero(sense, sizeof (struct scsi_extended_sense));
6653 	sata_fixed_sense_data_preset(sense);
6654 	return (sense);
6655 }
6656 
6657 /*
6658  * ATA Pass Through support
6659  * Sets flags indicating that an invalid value was found in some
6660  * field in the command.  It could be something illegal according to
6661  * the SAT-2 spec or it could be a feature that is not (yet?)
6662  * supported.
6663  */
6664 static int
6665 sata_txlt_ata_pass_thru_illegal_cmd(sata_pkt_txlate_t *spx)
6666 {
6667 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6668 	struct scsi_extended_sense *sense = sata_arq_sense(spx);
6669 
6670 	scsipkt->pkt_reason = CMD_CMPLT;
6671 	*scsipkt->pkt_scbp = STATUS_CHECK;
6672 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6673 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6674 
6675 	sense = sata_arq_sense(spx);
6676 	sense->es_key = KEY_ILLEGAL_REQUEST;
6677 	sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
6678 
6679 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
6680 	    scsipkt->pkt_comp != NULL)
6681 		/* scsi callback required */
6682 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6683 		    (task_func_t *)scsipkt->pkt_comp, (void *) scsipkt,
6684 		    TQ_SLEEP) == NULL)
6685 			/* Scheduling the callback failed */
6686 			return (TRAN_BUSY);
6687 
6688 	return (TRAN_ACCEPT);
6689 }
6690 
6691 /*
6692  * Emulated SATA Read/Write command completion for zero-length requests.
6693  * This request always succedes, so in synchronous mode it always returns
6694  * TRAN_ACCEPT, and in non-synchronous mode it may return TRAN_BUSY if the
6695  * callback cannot be scheduled.
6696  */
6697 static int
6698 sata_emul_rw_completion(sata_pkt_txlate_t *spx)
6699 {
6700 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6701 
6702 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6703 	    STATE_SENT_CMD | STATE_GOT_STATUS;
6704 	scsipkt->pkt_reason = CMD_CMPLT;
6705 	*scsipkt->pkt_scbp = STATUS_GOOD;
6706 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
6707 		/* scsi callback required - have to schedule it */
6708 		if (taskq_dispatch(SATA_TXLT_TASKQ(spx),
6709 		    (task_func_t *)scsipkt->pkt_comp,
6710 		    (void *)scsipkt, TQ_SLEEP) == NULL)
6711 			/* Scheduling the callback failed */
6712 			return (TRAN_BUSY);
6713 	}
6714 	return (TRAN_ACCEPT);
6715 }
6716 
6717 
6718 /*
6719  * Translate completion status of SATA read/write commands into scsi response.
6720  * pkt completion_reason is checked to determine the completion status.
6721  * Do scsi callback if necessary.
6722  *
6723  * Note: this function may be called also for synchronously executed
6724  * commands.
6725  * This function may be used only if scsi_pkt is non-NULL.
6726  */
6727 static void
6728 sata_txlt_rw_completion(sata_pkt_t *sata_pkt)
6729 {
6730 	sata_pkt_txlate_t *spx =
6731 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6732 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
6733 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6734 	struct scsi_extended_sense *sense;
6735 	uint64_t lba;
6736 	struct buf *bp;
6737 	int rval;
6738 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6739 		/* Normal completion */
6740 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6741 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6742 		scsipkt->pkt_reason = CMD_CMPLT;
6743 		*scsipkt->pkt_scbp = STATUS_GOOD;
6744 		if (spx->txlt_tmp_buf != NULL) {
6745 			/* Temporary buffer was used */
6746 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6747 			if (bp->b_flags & B_READ) {
6748 				rval = ddi_dma_sync(
6749 				    spx->txlt_buf_dma_handle, 0, 0,
6750 				    DDI_DMA_SYNC_FORCPU);
6751 				ASSERT(rval == DDI_SUCCESS);
6752 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
6753 				    bp->b_bcount);
6754 			}
6755 		}
6756 	} else {
6757 		/*
6758 		 * Something went wrong - analyze return
6759 		 */
6760 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6761 		    STATE_SENT_CMD | STATE_GOT_STATUS;
6762 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6763 		*scsipkt->pkt_scbp = STATUS_CHECK;
6764 		sense = sata_arq_sense(spx);
6765 		ASSERT(sense != NULL);
6766 
6767 		/*
6768 		 * SATA_PKT_DEV_ERROR is the only case where we may be able to
6769 		 * extract from device registers the failing LBA.
6770 		 */
6771 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
6772 			if ((scmd->satacmd_addr_type == ATA_ADDR_LBA48) &&
6773 			    (scmd->satacmd_lba_mid_msb != 0 ||
6774 			    scmd->satacmd_lba_high_msb != 0)) {
6775 				/*
6776 				 * We have problem reporting this cmd LBA
6777 				 * in fixed sense data format, because of
6778 				 * the size of the scsi LBA fields.
6779 				 */
6780 				sense->es_valid = 0;
6781 			} else {
6782 				sata_extract_error_lba(spx, &lba);
6783 				sense->es_info_1 = (lba & 0xFF000000) >> 24;
6784 				sense->es_info_2 = (lba & 0xFF0000) >> 16;
6785 				sense->es_info_3 = (lba & 0xFF00) >> 8;
6786 				sense->es_info_4 = lba & 0xFF;
6787 			}
6788 		} else {
6789 			/* Invalid extended sense info */
6790 			sense->es_valid = 0;
6791 		}
6792 
6793 		switch (sata_pkt->satapkt_reason) {
6794 		case SATA_PKT_PORT_ERROR:
6795 			/* We may want to handle DEV GONE state as well */
6796 			/*
6797 			 * We have no device data. Assume no data transfered.
6798 			 */
6799 			sense->es_key = KEY_HARDWARE_ERROR;
6800 			break;
6801 
6802 		case SATA_PKT_DEV_ERROR:
6803 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
6804 			    SATA_STATUS_ERR) {
6805 				/*
6806 				 * determine dev error reason from error
6807 				 * reg content
6808 				 */
6809 				sata_decode_device_error(spx, sense);
6810 				if (sense->es_key == KEY_MEDIUM_ERROR) {
6811 					switch (scmd->satacmd_cmd_reg) {
6812 					case SATAC_READ_DMA:
6813 					case SATAC_READ_DMA_EXT:
6814 					case SATAC_READ_DMA_QUEUED:
6815 					case SATAC_READ_DMA_QUEUED_EXT:
6816 					case SATAC_READ_FPDMA_QUEUED:
6817 						/* Unrecovered read error */
6818 						sense->es_add_code =
6819 						    SD_SCSI_ASC_UNREC_READ_ERR;
6820 						break;
6821 					case SATAC_WRITE_DMA:
6822 					case SATAC_WRITE_DMA_EXT:
6823 					case SATAC_WRITE_DMA_QUEUED:
6824 					case SATAC_WRITE_DMA_QUEUED_EXT:
6825 					case SATAC_WRITE_FPDMA_QUEUED:
6826 						/* Write error */
6827 						sense->es_add_code =
6828 						    SD_SCSI_ASC_WRITE_ERR;
6829 						break;
6830 					default:
6831 						/* Internal error */
6832 						SATA_LOG_D((
6833 						    spx->txlt_sata_hba_inst,
6834 						    CE_WARN,
6835 						    "sata_txlt_rw_completion :"
6836 						    "internal error - invalid "
6837 						    "command 0x%2x",
6838 						    scmd->satacmd_cmd_reg));
6839 						break;
6840 					}
6841 				}
6842 				break;
6843 			}
6844 			/* No extended sense key - no info available */
6845 			scsipkt->pkt_reason = CMD_INCOMPLETE;
6846 			break;
6847 
6848 		case SATA_PKT_TIMEOUT:
6849 			scsipkt->pkt_reason = CMD_TIMEOUT;
6850 			scsipkt->pkt_statistics |=
6851 			    STAT_TIMEOUT | STAT_DEV_RESET;
6852 			sense->es_key = KEY_ABORTED_COMMAND;
6853 			break;
6854 
6855 		case SATA_PKT_ABORTED:
6856 			scsipkt->pkt_reason = CMD_ABORTED;
6857 			scsipkt->pkt_statistics |= STAT_ABORTED;
6858 			sense->es_key = KEY_ABORTED_COMMAND;
6859 			break;
6860 
6861 		case SATA_PKT_RESET:
6862 			scsipkt->pkt_reason = CMD_RESET;
6863 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
6864 			sense->es_key = KEY_ABORTED_COMMAND;
6865 			break;
6866 
6867 		default:
6868 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
6869 			    "sata_txlt_rw_completion: "
6870 			    "invalid packet completion reason"));
6871 			scsipkt->pkt_reason = CMD_TRAN_ERR;
6872 			break;
6873 		}
6874 	}
6875 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
6876 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
6877 
6878 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6879 		/* scsi callback required */
6880 		scsi_hba_pkt_comp(scsipkt);
6881 }
6882 
6883 
6884 /*
6885  * Translate completion status of non-data commands (i.e. commands returning
6886  * no data).
6887  * pkt completion_reason is checked to determine the completion status.
6888  * Do scsi callback if necessary (FLAG_NOINTR == 0)
6889  *
6890  * Note: this function may be called also for synchronously executed
6891  * commands.
6892  * This function may be used only if scsi_pkt is non-NULL.
6893  */
6894 
6895 static	void
6896 sata_txlt_nodata_cmd_completion(sata_pkt_t *sata_pkt)
6897 {
6898 	sata_pkt_txlate_t *spx =
6899 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6900 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6901 
6902 	sata_set_arq_data(sata_pkt);
6903 
6904 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
6905 		/* scsi callback required */
6906 		scsi_hba_pkt_comp(scsipkt);
6907 }
6908 
6909 /*
6910  * Completion handler for ATA Pass Through command
6911  */
6912 static void
6913 sata_txlt_apt_completion(sata_pkt_t *sata_pkt)
6914 {
6915 	sata_pkt_txlate_t *spx =
6916 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
6917 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
6918 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
6919 	struct buf *bp;
6920 	uint8_t sense_key = 0, addl_sense_code = 0, addl_sense_qual = 0;
6921 
6922 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
6923 		/* Normal completion */
6924 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6925 		    STATE_SENT_CMD | STATE_XFERRED_DATA | STATE_GOT_STATUS;
6926 		scsipkt->pkt_reason = CMD_CMPLT;
6927 		*scsipkt->pkt_scbp = STATUS_GOOD;
6928 
6929 		/*
6930 		 * If the command has CK_COND set
6931 		 */
6932 		if (scsipkt->pkt_cdbp[2] & SATL_APT_BM_CK_COND) {
6933 			*scsipkt->pkt_scbp = STATUS_CHECK;
6934 			sata_fill_ata_return_desc(sata_pkt,
6935 			    KEY_RECOVERABLE_ERROR,
6936 			    SD_SCSI_ASC_ATP_INFO_AVAIL, 0);
6937 		}
6938 
6939 		if (spx->txlt_tmp_buf != NULL) {
6940 			/* Temporary buffer was used */
6941 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
6942 			if (bp->b_flags & B_READ) {
6943 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
6944 				    bp->b_bcount);
6945 			}
6946 		}
6947 	} else {
6948 		scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
6949 		    STATE_SENT_CMD | STATE_GOT_STATUS;
6950 		scsipkt->pkt_reason = CMD_INCOMPLETE;
6951 		*scsipkt->pkt_scbp = STATUS_CHECK;
6952 
6953 		/*
6954 		 * If DF or ERR was set, the HBA should have copied out the
6955 		 * status and error registers to the satacmd structure.
6956 		 */
6957 		if (scmd->satacmd_status_reg & SATA_STATUS_DF) {
6958 			sense_key = KEY_HARDWARE_ERROR;
6959 			addl_sense_code = SD_SCSI_ASC_INTERNAL_TARGET_FAILURE;
6960 			addl_sense_qual = 0;
6961 		} else if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
6962 			if (scmd->satacmd_error_reg & SATA_ERROR_NM) {
6963 				sense_key = KEY_NOT_READY;
6964 				addl_sense_code =
6965 				    SD_SCSI_ASC_MEDIUM_NOT_PRESENT;
6966 				addl_sense_qual = 0;
6967 			} else if (scmd->satacmd_error_reg & SATA_ERROR_UNC) {
6968 				sense_key = KEY_MEDIUM_ERROR;
6969 				addl_sense_code = SD_SCSI_ASC_UNREC_READ_ERR;
6970 				addl_sense_qual = 0;
6971 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ILI) {
6972 				sense_key = KEY_DATA_PROTECT;
6973 				addl_sense_code = SD_SCSI_ASC_WRITE_PROTECTED;
6974 				addl_sense_qual = 0;
6975 			} else if (scmd->satacmd_error_reg & SATA_ERROR_IDNF) {
6976 				sense_key = KEY_ILLEGAL_REQUEST;
6977 				addl_sense_code = SD_SCSI_ASC_LBA_OUT_OF_RANGE;
6978 				addl_sense_qual = 0;
6979 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
6980 				sense_key = KEY_ABORTED_COMMAND;
6981 				addl_sense_code = SD_SCSI_ASC_NO_ADD_SENSE;
6982 				addl_sense_qual = 0;
6983 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MC) {
6984 				sense_key = KEY_UNIT_ATTENTION;
6985 				addl_sense_code =
6986 				    SD_SCSI_ASC_MEDIUM_MAY_HAVE_CHANGED;
6987 				addl_sense_qual = 0;
6988 			} else if (scmd->satacmd_error_reg & SATA_ERROR_MCR) {
6989 				sense_key = KEY_UNIT_ATTENTION;
6990 				addl_sense_code = SD_SCSI_ASC_OP_MEDIUM_REM_REQ;
6991 				addl_sense_qual = 0;
6992 			} else if (scmd->satacmd_error_reg & SATA_ERROR_ICRC) {
6993 				sense_key = KEY_ABORTED_COMMAND;
6994 				addl_sense_code =
6995 				    SD_SCSI_ASC_INFO_UNIT_IUCRC_ERR;
6996 				addl_sense_qual = 0;
6997 			}
6998 		}
6999 
7000 		sata_fill_ata_return_desc(sata_pkt, sense_key, addl_sense_code,
7001 		    addl_sense_qual);
7002 	}
7003 
7004 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0)
7005 		/* scsi callback required */
7006 		scsi_hba_pkt_comp(scsipkt);
7007 }
7008 
7009 /*
7010  * j
7011  */
7012 static void
7013 sata_fill_ata_return_desc(sata_pkt_t *sata_pkt, uint8_t sense_key,
7014     uint8_t addl_sense_code, uint8_t addl_sense_qual)
7015 {
7016 	sata_pkt_txlate_t *spx =
7017 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7018 	sata_cmd_t *scmd = &sata_pkt->satapkt_cmd;
7019 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7020 	struct sata_apt_sense_data *apt_sd =
7021 	    (struct sata_apt_sense_data *)scsipkt->pkt_scbp;
7022 	struct scsi_descr_sense_hdr *sds = &(apt_sd->apt_sd_hdr);
7023 	struct scsi_ata_status_ret_sense_descr *ata_ret_desc =
7024 	    &(apt_sd->apt_sd_sense);
7025 	int extend = 0;
7026 
7027 	if ((scsipkt->pkt_cdbp[0] == SPC3_CMD_ATA_COMMAND_PASS_THROUGH16) &&
7028 	    (scsipkt->pkt_cdbp[2] & SATL_APT_BM_EXTEND))
7029 		extend = 1;
7030 
7031 	scsipkt->pkt_state |= STATE_ARQ_DONE;
7032 
7033 	/* update the residual count */
7034 	*(uchar_t *)&apt_sd->apt_status = STATUS_CHECK;
7035 	*(uchar_t *)&apt_sd->apt_rqpkt_status = STATUS_GOOD;
7036 	apt_sd->apt_rqpkt_reason = CMD_CMPLT;
7037 	apt_sd->apt_rqpkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7038 	    STATE_XFERRED_DATA | STATE_SENT_CMD | STATE_GOT_STATUS;
7039 	apt_sd->apt_rqpkt_resid = scsipkt->pkt_scblen -
7040 	    sizeof (struct sata_apt_sense_data);
7041 
7042 	/*
7043 	 * Fill in the Descriptor sense header
7044 	 */
7045 	bzero(sds, sizeof (struct scsi_descr_sense_hdr));
7046 	sds->ds_code = CODE_FMT_DESCR_CURRENT;
7047 	sds->ds_class = CLASS_EXTENDED_SENSE;
7048 	sds->ds_key = sense_key & 0xf;
7049 	sds->ds_add_code = addl_sense_code;
7050 	sds->ds_qual_code = addl_sense_qual;
7051 	sds->ds_addl_sense_length =
7052 	    sizeof (struct scsi_ata_status_ret_sense_descr);
7053 
7054 	/*
7055 	 * Fill in the ATA Return descriptor sense data
7056 	 */
7057 	bzero(ata_ret_desc, sizeof (struct scsi_ata_status_ret_sense_descr));
7058 	ata_ret_desc->ars_descr_type = DESCR_ATA_STATUS_RETURN;
7059 	ata_ret_desc->ars_addl_length = 0xc;
7060 	ata_ret_desc->ars_error = scmd->satacmd_error_reg;
7061 	ata_ret_desc->ars_sec_count_lsb = scmd->satacmd_sec_count_lsb;
7062 	ata_ret_desc->ars_lba_low_lsb = scmd->satacmd_lba_low_lsb;
7063 	ata_ret_desc->ars_lba_mid_lsb = scmd->satacmd_lba_mid_lsb;
7064 	ata_ret_desc->ars_lba_high_lsb = scmd->satacmd_lba_high_lsb;
7065 	ata_ret_desc->ars_device = scmd->satacmd_device_reg;
7066 	ata_ret_desc->ars_status = scmd->satacmd_status_reg;
7067 
7068 	if (extend == 1) {
7069 		ata_ret_desc->ars_extend = 1;
7070 		ata_ret_desc->ars_sec_count_msb = scmd->satacmd_sec_count_msb;
7071 		ata_ret_desc->ars_lba_low_msb = scmd->satacmd_lba_low_msb;
7072 		ata_ret_desc->ars_lba_mid_msb = scmd->satacmd_lba_mid_msb;
7073 		ata_ret_desc->ars_lba_high_msb = scmd->satacmd_lba_high_msb;
7074 	} else {
7075 		ata_ret_desc->ars_extend = 0;
7076 		ata_ret_desc->ars_sec_count_msb = 0;
7077 		ata_ret_desc->ars_lba_low_msb = 0;
7078 		ata_ret_desc->ars_lba_mid_msb = 0;
7079 		ata_ret_desc->ars_lba_high_msb = 0;
7080 	}
7081 }
7082 
7083 static	void
7084 sata_set_arq_data(sata_pkt_t *sata_pkt)
7085 {
7086 	sata_pkt_txlate_t *spx =
7087 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
7088 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7089 	struct scsi_extended_sense *sense;
7090 
7091 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
7092 	    STATE_SENT_CMD | STATE_GOT_STATUS;
7093 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
7094 		/* Normal completion */
7095 		scsipkt->pkt_reason = CMD_CMPLT;
7096 		*scsipkt->pkt_scbp = STATUS_GOOD;
7097 	} else {
7098 		/* Something went wrong */
7099 		scsipkt->pkt_reason = CMD_INCOMPLETE;
7100 		*scsipkt->pkt_scbp = STATUS_CHECK;
7101 		sense = sata_arq_sense(spx);
7102 		switch (sata_pkt->satapkt_reason) {
7103 		case SATA_PKT_PORT_ERROR:
7104 			/*
7105 			 * We have no device data. Assume no data transfered.
7106 			 */
7107 			sense->es_key = KEY_HARDWARE_ERROR;
7108 			break;
7109 
7110 		case SATA_PKT_DEV_ERROR:
7111 			if (sata_pkt->satapkt_cmd.satacmd_status_reg &
7112 			    SATA_STATUS_ERR) {
7113 				/*
7114 				 * determine dev error reason from error
7115 				 * reg content
7116 				 */
7117 				sata_decode_device_error(spx, sense);
7118 				break;
7119 			}
7120 			/* No extended sense key - no info available */
7121 			break;
7122 
7123 		case SATA_PKT_TIMEOUT:
7124 			scsipkt->pkt_reason = CMD_TIMEOUT;
7125 			scsipkt->pkt_statistics |=
7126 			    STAT_TIMEOUT | STAT_DEV_RESET;
7127 			/* No extended sense key ? */
7128 			break;
7129 
7130 		case SATA_PKT_ABORTED:
7131 			scsipkt->pkt_reason = CMD_ABORTED;
7132 			scsipkt->pkt_statistics |= STAT_ABORTED;
7133 			/* No extended sense key ? */
7134 			break;
7135 
7136 		case SATA_PKT_RESET:
7137 			/* pkt aborted by an explicit reset from a host */
7138 			scsipkt->pkt_reason = CMD_RESET;
7139 			scsipkt->pkt_statistics |= STAT_DEV_RESET;
7140 			break;
7141 
7142 		default:
7143 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
7144 			    "sata_txlt_nodata_cmd_completion: "
7145 			    "invalid packet completion reason %d",
7146 			    sata_pkt->satapkt_reason));
7147 			scsipkt->pkt_reason = CMD_TRAN_ERR;
7148 			break;
7149 		}
7150 
7151 	}
7152 	SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
7153 	    "Scsi_pkt completion reason %x\n", scsipkt->pkt_reason);
7154 }
7155 
7156 
7157 /*
7158  * Build Mode sense R/W recovery page
7159  * NOT IMPLEMENTED
7160  */
7161 
7162 static int
7163 sata_build_msense_page_1(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7164 {
7165 #ifndef __lock_lint
7166 	_NOTE(ARGUNUSED(sdinfo))
7167 	_NOTE(ARGUNUSED(pcntrl))
7168 	_NOTE(ARGUNUSED(buf))
7169 #endif
7170 	return (0);
7171 }
7172 
7173 /*
7174  * Build Mode sense caching page  -  scsi-3 implementation.
7175  * Page length distinguishes previous format from scsi-3 format.
7176  * buf must have space for 0x12 bytes.
7177  * Only DRA (disable read ahead ) and WCE (write cache enable) are changeable.
7178  *
7179  */
7180 static int
7181 sata_build_msense_page_8(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7182 {
7183 	struct mode_cache_scsi3 *page = (struct mode_cache_scsi3 *)buf;
7184 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7185 
7186 	/*
7187 	 * Most of the fields are set to 0, being not supported and/or disabled
7188 	 */
7189 	bzero(buf, PAGELENGTH_DAD_MODE_CACHE_SCSI3);
7190 
7191 	/* Saved paramters not supported */
7192 	if (pcntrl == 3)
7193 		return (0);
7194 	if (pcntrl == 0 || pcntrl == 2) {
7195 		/*
7196 		 * For now treat current and default parameters as same
7197 		 * That may have to change, if target driver will complain
7198 		 */
7199 		page->mode_page.code = MODEPAGE_CACHING;	/* PS = 0 */
7200 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7201 
7202 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id) &&
7203 		    !SATA_READ_AHEAD_ENABLED(*sata_id)) {
7204 			page->dra = 1;		/* Read Ahead disabled */
7205 			page->rcd = 1;		/* Read Cache disabled */
7206 		}
7207 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id) &&
7208 		    SATA_WRITE_CACHE_ENABLED(*sata_id))
7209 			page->wce = 1;		/* Write Cache enabled */
7210 	} else {
7211 		/* Changeable parameters */
7212 		page->mode_page.code = MODEPAGE_CACHING;
7213 		page->mode_page.length = PAGELENGTH_DAD_MODE_CACHE_SCSI3;
7214 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7215 			page->dra = 1;
7216 			page->rcd = 1;
7217 		}
7218 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id))
7219 			page->wce = 1;
7220 	}
7221 	return (PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7222 	    sizeof (struct mode_page));
7223 }
7224 
7225 /*
7226  * Build Mode sense exception cntrl page
7227  */
7228 static int
7229 sata_build_msense_page_1c(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7230 {
7231 	struct mode_info_excpt_page *page = (struct mode_info_excpt_page *)buf;
7232 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7233 
7234 	/*
7235 	 * Most of the fields are set to 0, being not supported and/or disabled
7236 	 */
7237 	bzero(buf, PAGELENGTH_INFO_EXCPT);
7238 
7239 	page->mode_page.code = MODEPAGE_INFO_EXCPT;
7240 	page->mode_page.length = PAGELENGTH_INFO_EXCPT;
7241 
7242 	/* Indicate that this is page is saveable */
7243 	page->mode_page.ps = 1;
7244 
7245 	/*
7246 	 * We will return the same data for default, current and saved page.
7247 	 * The only changeable bit is dexcpt and that bit is required
7248 	 * by the ATA specification to be preserved across power cycles.
7249 	 */
7250 	if (pcntrl != 1) {
7251 		page->dexcpt = !(sata_id->ai_features85 & SATA_SMART_SUPPORTED);
7252 		page->mrie = MRIE_ONLY_ON_REQUEST;
7253 	}
7254 	else
7255 		page->dexcpt = 1;	/* Only changeable parameter */
7256 
7257 	return (PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page));
7258 }
7259 
7260 
7261 static int
7262 sata_build_msense_page_30(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7263 {
7264 	struct mode_acoustic_management *page =
7265 	    (struct mode_acoustic_management *)buf;
7266 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7267 
7268 	/*
7269 	 * Most of the fields are set to 0, being not supported and/or disabled
7270 	 */
7271 	bzero(buf, PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT);
7272 
7273 	switch (pcntrl) {
7274 	case P_CNTRL_DEFAULT:
7275 		/*  default paramters not supported */
7276 		return (0);
7277 
7278 	case P_CNTRL_CURRENT:
7279 	case P_CNTRL_SAVED:
7280 		/* Saved and current are supported and are identical */
7281 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7282 		page->mode_page.length =
7283 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7284 		page->mode_page.ps = 1;
7285 
7286 		/* Word 83 indicates if feature is supported */
7287 		/* If feature is not supported */
7288 		if (!(sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT)) {
7289 			page->acoustic_manag_enable =
7290 			    ACOUSTIC_DISABLED;
7291 		} else {
7292 			page->acoustic_manag_enable =
7293 			    ((sata_id->ai_features86 & SATA_ACOUSTIC_MGMT)
7294 			    != 0);
7295 			/* Word 94 inidicates the value */
7296 #ifdef	_LITTLE_ENDIAN
7297 			page->acoustic_manag_level =
7298 			    (uchar_t)sata_id->ai_acoustic;
7299 			page->vendor_recommended_value =
7300 			    sata_id->ai_acoustic >> 8;
7301 #else
7302 			page->acoustic_manag_level =
7303 			    sata_id->ai_acoustic >> 8;
7304 			page->vendor_recommended_value =
7305 			    (uchar_t)sata_id->ai_acoustic;
7306 #endif
7307 		}
7308 		break;
7309 
7310 	case P_CNTRL_CHANGEABLE:
7311 		page->mode_page.code = MODEPAGE_ACOUSTIC_MANAG;
7312 		page->mode_page.length =
7313 		    PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT;
7314 		page->mode_page.ps = 1;
7315 
7316 		/* Word 83 indicates if the feature is supported */
7317 		if (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT) {
7318 			page->acoustic_manag_enable =
7319 			    ACOUSTIC_ENABLED;
7320 			page->acoustic_manag_level = 0xff;
7321 		}
7322 		break;
7323 	}
7324 	return (PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7325 	    sizeof (struct mode_page));
7326 }
7327 
7328 
7329 /*
7330  * Build Mode sense power condition page.
7331  */
7332 static int
7333 sata_build_msense_page_1a(sata_drive_info_t *sdinfo, int pcntrl, uint8_t *buf)
7334 {
7335 	struct mode_info_power_cond *page = (struct mode_info_power_cond *)buf;
7336 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7337 
7338 	/*
7339 	 * Most of the fields are set to 0, being not supported and/or disabled
7340 	 * power condition page length was 0x0a
7341 	 */
7342 	bzero(buf, sizeof (struct mode_info_power_cond));
7343 
7344 	if (pcntrl == P_CNTRL_DEFAULT) {
7345 		/*  default paramters not supported */
7346 		return (0);
7347 	}
7348 
7349 	page->mode_page.code = MODEPAGE_POWER_COND;
7350 	page->mode_page.length = sizeof (struct mode_info_power_cond);
7351 
7352 	if (sata_id->ai_cap && SATA_STANDBYTIMER) {
7353 		page->standby = 1;
7354 		bcopy(sdinfo->satadrv_standby_timer, page->standby_cond_timer,
7355 		    sizeof (uchar_t) * 4);
7356 	}
7357 
7358 	return (sizeof (struct mode_info_power_cond));
7359 }
7360 
7361 /*
7362  * Process mode select caching page 8 (scsi3 format only).
7363  * Read Ahead (same as read cache) and Write Cache may be turned on and off
7364  * if these features are supported by the device. If these features are not
7365  * supported, the command will be terminated with STATUS_CHECK.
7366  * This function fails only if the SET FEATURE command sent to
7367  * the device fails. The page format is not varified, assuming that the
7368  * target driver operates correctly - if parameters length is too short,
7369  * we just drop the page.
7370  * Two command may be sent if both Read Cache/Read Ahead and Write Cache
7371  * setting have to be changed.
7372  * SET FEATURE command is executed synchronously, i.e. we wait here until
7373  * it is completed, regardless of the scsi pkt directives.
7374  *
7375  * Note: Mode Select Caching page RCD and DRA bits are tied together, i.e.
7376  * changing DRA will change RCD.
7377  *
7378  * More than one SATA command may be executed to perform operations specified
7379  * by mode select pages. The first error terminates further execution.
7380  * Operations performed successully are not backed-up in such case.
7381  *
7382  * Return SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7383  * If operation resulted in changing device setup, dmod flag should be set to
7384  * one (1). If parameters were not changed, dmod flag should be set to 0.
7385  * Upon return, if operation required sending command to the device, the rval
7386  * should be set to the value returned by sata_hba_start. If operation
7387  * did not require device access, rval should be set to TRAN_ACCEPT.
7388  * The pagelen should be set to the length of the page.
7389  *
7390  * This function has to be called with a port mutex held.
7391  *
7392  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7393  */
7394 int
7395 sata_mode_select_page_8(sata_pkt_txlate_t *spx, struct mode_cache_scsi3 *page,
7396     int parmlen, int *pagelen, int *rval, int *dmod)
7397 {
7398 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7399 	sata_drive_info_t *sdinfo;
7400 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7401 	sata_id_t *sata_id;
7402 	struct scsi_extended_sense *sense;
7403 	int wce, dra;	/* Current settings */
7404 
7405 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7406 	    &spx->txlt_sata_pkt->satapkt_device);
7407 	sata_id = &sdinfo->satadrv_id;
7408 	*dmod = 0;
7409 
7410 	/* Verify parameters length. If too short, drop it */
7411 	if ((PAGELENGTH_DAD_MODE_CACHE_SCSI3 +
7412 	    sizeof (struct mode_page)) > parmlen) {
7413 		*scsipkt->pkt_scbp = STATUS_CHECK;
7414 		sense = sata_arq_sense(spx);
7415 		sense->es_key = KEY_ILLEGAL_REQUEST;
7416 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7417 		*pagelen = parmlen;
7418 		*rval = TRAN_ACCEPT;
7419 		return (SATA_FAILURE);
7420 	}
7421 
7422 	*pagelen = PAGELENGTH_DAD_MODE_CACHE_SCSI3 + sizeof (struct mode_page);
7423 
7424 	/* Current setting of Read Ahead (and Read Cache) */
7425 	if (SATA_READ_AHEAD_ENABLED(*sata_id))
7426 		dra = 0;	/* 0 == not disabled */
7427 	else
7428 		dra = 1;
7429 	/* Current setting of Write Cache */
7430 	if (SATA_WRITE_CACHE_ENABLED(*sata_id))
7431 		wce = 1;
7432 	else
7433 		wce = 0;
7434 
7435 	if (page->dra == dra && page->wce == wce && page->rcd == dra) {
7436 		/* nothing to do */
7437 		*rval = TRAN_ACCEPT;
7438 		return (SATA_SUCCESS);
7439 	}
7440 
7441 	/*
7442 	 * Need to flip some setting
7443 	 * Set-up Internal SET FEATURES command(s)
7444 	 */
7445 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7446 	scmd->satacmd_addr_type = 0;
7447 	scmd->satacmd_device_reg = 0;
7448 	scmd->satacmd_status_reg = 0;
7449 	scmd->satacmd_error_reg = 0;
7450 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7451 	if (page->dra != dra || page->rcd != dra) {
7452 		if (SATA_READ_AHEAD_SUPPORTED(*sata_id)) {
7453 			/* Need to flip read ahead setting */
7454 			if (dra == 0)
7455 				/* Disable read ahead / read cache */
7456 				scmd->satacmd_features_reg =
7457 				    SATAC_SF_DISABLE_READ_AHEAD;
7458 			else
7459 				/* Enable read ahead  / read cache */
7460 				scmd->satacmd_features_reg =
7461 				    SATAC_SF_ENABLE_READ_AHEAD;
7462 
7463 			/* Transfer command to HBA */
7464 			if (sata_hba_start(spx, rval) != 0)
7465 				/*
7466 				 * Pkt not accepted for execution.
7467 				 */
7468 				return (SATA_FAILURE);
7469 
7470 			*dmod = 1;
7471 
7472 			/* Now process return */
7473 			if (spx->txlt_sata_pkt->satapkt_reason !=
7474 			    SATA_PKT_COMPLETED) {
7475 				goto failure;	/* Terminate */
7476 			}
7477 		} else {
7478 			*scsipkt->pkt_scbp = STATUS_CHECK;
7479 			sense = sata_arq_sense(spx);
7480 			sense->es_key = KEY_ILLEGAL_REQUEST;
7481 			sense->es_add_code =
7482 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7483 			*pagelen = parmlen;
7484 			*rval = TRAN_ACCEPT;
7485 			return (SATA_FAILURE);
7486 		}
7487 	}
7488 
7489 	/* Note that the packet is not removed, so it could be re-used */
7490 	if (page->wce != wce) {
7491 		if (SATA_WRITE_CACHE_SUPPORTED(*sata_id)) {
7492 			/* Need to flip Write Cache setting */
7493 			if (page->wce == 1)
7494 				/* Enable write cache */
7495 				scmd->satacmd_features_reg =
7496 				    SATAC_SF_ENABLE_WRITE_CACHE;
7497 			else
7498 				/* Disable write cache */
7499 				scmd->satacmd_features_reg =
7500 				    SATAC_SF_DISABLE_WRITE_CACHE;
7501 
7502 			/* Transfer command to HBA */
7503 			if (sata_hba_start(spx, rval) != 0)
7504 				/*
7505 				 * Pkt not accepted for execution.
7506 				 */
7507 				return (SATA_FAILURE);
7508 
7509 			*dmod = 1;
7510 
7511 			/* Now process return */
7512 			if (spx->txlt_sata_pkt->satapkt_reason !=
7513 			    SATA_PKT_COMPLETED) {
7514 				goto failure;
7515 			}
7516 		} else {
7517 			*scsipkt->pkt_scbp = STATUS_CHECK;
7518 			sense = sata_arq_sense(spx);
7519 			sense->es_key = KEY_ILLEGAL_REQUEST;
7520 			sense->es_add_code =
7521 			    SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7522 			*pagelen = parmlen;
7523 			*rval = TRAN_ACCEPT;
7524 			return (SATA_FAILURE);
7525 		}
7526 	}
7527 	return (SATA_SUCCESS);
7528 
7529 failure:
7530 	sata_xlate_errors(spx);
7531 
7532 	return (SATA_FAILURE);
7533 }
7534 
7535 /*
7536  * Process mode select informational exceptions control page 0x1c
7537  *
7538  * The only changeable bit is dexcpt (disable exceptions).
7539  * MRIE (method of reporting informational exceptions) must be
7540  * "only on request".
7541  * This page applies to informational exceptions that report
7542  * additional sense codes with the ADDITIONAL SENSE CODE field set to 5Dh
7543  * (e.g.,FAILURE PREDICTION THRESHOLD EXCEEDED) or 0Bh (e.g., WARNING_).
7544  * Informational exception conditions occur as the result of background scan
7545  * errors, background self-test errors, or vendor specific events within a
7546  * logical unit. An informational exception condition may occur asynchronous
7547  * to any commands.
7548  *
7549  * Returns: SATA_SUCCESS if operation succeeded, SATA_FAILURE otherwise.
7550  * If operation resulted in changing device setup, dmod flag should be set to
7551  * one (1). If parameters were not changed, dmod flag should be set to 0.
7552  * Upon return, if operation required sending command to the device, the rval
7553  * should be set to the value returned by sata_hba_start. If operation
7554  * did not require device access, rval should be set to TRAN_ACCEPT.
7555  * The pagelen should be set to the length of the page.
7556  *
7557  * This function has to be called with a port mutex held.
7558  *
7559  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7560  *
7561  * Cannot be called in the interrupt context.
7562  */
7563 static	int
7564 sata_mode_select_page_1c(
7565 	sata_pkt_txlate_t *spx,
7566 	struct mode_info_excpt_page *page,
7567 	int parmlen,
7568 	int *pagelen,
7569 	int *rval,
7570 	int *dmod)
7571 {
7572 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7573 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7574 	sata_drive_info_t *sdinfo;
7575 	sata_id_t *sata_id;
7576 	struct scsi_extended_sense *sense;
7577 
7578 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7579 	    &spx->txlt_sata_pkt->satapkt_device);
7580 	sata_id = &sdinfo->satadrv_id;
7581 
7582 	*dmod = 0;
7583 
7584 	/* Verify parameters length. If too short, drop it */
7585 	if (((PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page)) > parmlen) ||
7586 	    page->perf || page->test || (page->mrie != MRIE_ONLY_ON_REQUEST)) {
7587 		*scsipkt->pkt_scbp = STATUS_CHECK;
7588 		sense = sata_arq_sense(spx);
7589 		sense->es_key = KEY_ILLEGAL_REQUEST;
7590 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7591 		*pagelen = parmlen;
7592 		*rval = TRAN_ACCEPT;
7593 		return (SATA_FAILURE);
7594 	}
7595 
7596 	*pagelen = PAGELENGTH_INFO_EXCPT + sizeof (struct mode_page);
7597 
7598 	if (! (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED)) {
7599 		*scsipkt->pkt_scbp = STATUS_CHECK;
7600 		sense = sata_arq_sense(spx);
7601 		sense->es_key = KEY_ILLEGAL_REQUEST;
7602 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_CDB;
7603 		*pagelen = parmlen;
7604 		*rval = TRAN_ACCEPT;
7605 		return (SATA_FAILURE);
7606 	}
7607 
7608 	/* If already in the state requested, we are done */
7609 	if (page->dexcpt == ! (sata_id->ai_features85 & SATA_SMART_ENABLED)) {
7610 		/* nothing to do */
7611 		*rval = TRAN_ACCEPT;
7612 		return (SATA_SUCCESS);
7613 	}
7614 
7615 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7616 
7617 	/* Build SMART_ENABLE or SMART_DISABLE command */
7618 	scmd->satacmd_addr_type = 0;		/* N/A */
7619 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
7620 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
7621 	scmd->satacmd_features_reg = page->dexcpt ?
7622 	    SATA_SMART_DISABLE_OPS : SATA_SMART_ENABLE_OPS;
7623 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
7624 	scmd->satacmd_cmd_reg = SATAC_SMART;
7625 
7626 	/* Transfer command to HBA */
7627 	if (sata_hba_start(spx, rval) != 0)
7628 		/*
7629 		 * Pkt not accepted for execution.
7630 		 */
7631 		return (SATA_FAILURE);
7632 
7633 	*dmod = 1;	/* At least may have been modified */
7634 
7635 	/* Now process return */
7636 	if (spx->txlt_sata_pkt->satapkt_reason == SATA_PKT_COMPLETED)
7637 		return (SATA_SUCCESS);
7638 
7639 	/* Packet did not complete successfully */
7640 	sata_xlate_errors(spx);
7641 
7642 	return (SATA_FAILURE);
7643 }
7644 
7645 /*
7646  * Process mode select acoustic management control page 0x30
7647  *
7648  *
7649  * This function has to be called with a port mutex held.
7650  *
7651  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7652  *
7653  * Cannot be called in the interrupt context.
7654  */
7655 int
7656 sata_mode_select_page_30(sata_pkt_txlate_t *spx, struct
7657     mode_acoustic_management *page, int parmlen, int *pagelen,
7658     int *rval, int *dmod)
7659 {
7660 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7661 	sata_drive_info_t *sdinfo;
7662 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7663 	sata_id_t *sata_id;
7664 	struct scsi_extended_sense *sense;
7665 
7666 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7667 	    &spx->txlt_sata_pkt->satapkt_device);
7668 	sata_id = &sdinfo->satadrv_id;
7669 	*dmod = 0;
7670 
7671 	/* If parmlen is too short or the feature is not supported, drop it */
7672 	if (((PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7673 	    sizeof (struct mode_page)) > parmlen) ||
7674 	    (! (sata_id->ai_cmdset83 & SATA_ACOUSTIC_MGMT))) {
7675 		*scsipkt->pkt_scbp = STATUS_CHECK;
7676 		sense = sata_arq_sense(spx);
7677 		sense->es_key = KEY_ILLEGAL_REQUEST;
7678 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7679 		*pagelen = parmlen;
7680 		*rval = TRAN_ACCEPT;
7681 		return (SATA_FAILURE);
7682 	}
7683 
7684 	*pagelen = PAGELENGTH_DAD_MODE_ACOUSTIC_MANAGEMENT +
7685 	    sizeof (struct mode_page);
7686 
7687 	/*
7688 	 * We can enable and disable acoustice management and
7689 	 * set the acoustic management level.
7690 	 */
7691 
7692 	/*
7693 	 * Set-up Internal SET FEATURES command(s)
7694 	 */
7695 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
7696 	scmd->satacmd_addr_type = 0;
7697 	scmd->satacmd_device_reg = 0;
7698 	scmd->satacmd_status_reg = 0;
7699 	scmd->satacmd_error_reg = 0;
7700 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
7701 	if (page->acoustic_manag_enable) {
7702 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_ACOUSTIC;
7703 		scmd->satacmd_sec_count_lsb = page->acoustic_manag_level;
7704 	} else {	/* disabling acoustic management */
7705 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_ACOUSTIC;
7706 	}
7707 
7708 	/* Transfer command to HBA */
7709 	if (sata_hba_start(spx, rval) != 0)
7710 		/*
7711 		 * Pkt not accepted for execution.
7712 		 */
7713 		return (SATA_FAILURE);
7714 
7715 	/* Now process return */
7716 	if (spx->txlt_sata_pkt->satapkt_reason != SATA_PKT_COMPLETED) {
7717 		sata_xlate_errors(spx);
7718 		return (SATA_FAILURE);
7719 	}
7720 
7721 	*dmod = 1;
7722 
7723 	return (SATA_SUCCESS);
7724 }
7725 
7726 /*
7727  * Process mode select power condition page 0x1a
7728  *
7729  * This function has to be called with a port mutex held.
7730  *
7731  * Returns SATA_SUCCESS if operation was successful, SATA_FAILURE otherwise.
7732  *
7733  * Cannot be called in the interrupt context.
7734  */
7735 int
7736 sata_mode_select_page_1a(sata_pkt_txlate_t *spx, struct
7737     mode_info_power_cond *page, int parmlen, int *pagelen,
7738     int *rval, int *dmod)
7739 {
7740 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
7741 	sata_drive_info_t *sdinfo;
7742 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
7743 	sata_id_t *sata_id;
7744 	struct scsi_extended_sense *sense;
7745 	uint8_t ata_count;
7746 	int i, len;
7747 
7748 	sdinfo = sata_get_device_info(spx->txlt_sata_hba_inst,
7749 	    &spx->txlt_sata_pkt->satapkt_device);
7750 	sata_id = &sdinfo->satadrv_id;
7751 	*dmod = 0;
7752 
7753 	len = sizeof (struct mode_info_power_cond);
7754 	len += sizeof (struct mode_page);
7755 
7756 	/* If parmlen is too short or the feature is not supported, drop it */
7757 	if ((len < parmlen) || (page->idle == 1) ||
7758 	    (!(sata_id->ai_cap && SATA_STANDBYTIMER) && page->standby == 1)) {
7759 		*scsipkt->pkt_scbp = STATUS_CHECK;
7760 		sense = sata_arq_sense(spx);
7761 		sense->es_key = KEY_ILLEGAL_REQUEST;
7762 		sense->es_add_code = SD_SCSI_ASC_INVALID_FIELD_IN_PARAMS_LIST;
7763 		*pagelen = parmlen;
7764 		*rval = TRAN_ACCEPT;
7765 		return (SATA_FAILURE);
7766 	}
7767 
7768 	*pagelen = len;
7769 
7770 	/*
7771 	 * Set-up Internal STANDBY command(s)
7772 	 */
7773 	if (page->standby == 0)
7774 		goto out;
7775 
7776 	ata_count = sata_get_standby_timer(page->standby_cond_timer);
7777 
7778 	scmd->satacmd_addr_type = 0;
7779 	scmd->satacmd_sec_count_lsb = ata_count;
7780 	scmd->satacmd_lba_low_lsb = 0;
7781 	scmd->satacmd_lba_mid_lsb = 0;
7782 	scmd->satacmd_lba_high_lsb = 0;
7783 	scmd->satacmd_features_reg = 0;
7784 	scmd->satacmd_device_reg = 0;
7785 	scmd->satacmd_status_reg = 0;
7786 	scmd->satacmd_cmd_reg = SATAC_STANDBY;
7787 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
7788 	scmd->satacmd_flags.sata_copy_out_error_reg = B_TRUE;
7789 
7790 	/* Transfer command to HBA */
7791 	if (sata_hba_start(spx, rval) != 0) {
7792 		return (SATA_FAILURE);
7793 	} else {
7794 		if ((scmd->satacmd_error_reg != 0) ||
7795 		    (spx->txlt_sata_pkt->satapkt_reason !=
7796 		    SATA_PKT_COMPLETED)) {
7797 			sata_xlate_errors(spx);
7798 			return (SATA_FAILURE);
7799 		}
7800 	}
7801 
7802 	for (i = 0; i < 4; i++) {
7803 		sdinfo->satadrv_standby_timer[i] = page->standby_cond_timer[i];
7804 	}
7805 out:
7806 	*dmod = 1;
7807 	return (SATA_SUCCESS);
7808 }
7809 
7810 /*
7811  * sata_build_lsense_page0() is used to create the
7812  * SCSI LOG SENSE page 0 (supported log pages)
7813  *
7814  * Currently supported pages are 0, 0x10, 0x2f, 0x30 and 0x0e
7815  * (supported log pages, self-test results, informational exceptions
7816  * Sun vendor specific ATA SMART data, and start stop cycle counter).
7817  *
7818  * Takes a sata_drive_info t * and the address of a buffer
7819  * in which to create the page information.
7820  *
7821  * Returns the number of bytes valid in the buffer.
7822  */
7823 static	int
7824 sata_build_lsense_page_0(sata_drive_info_t *sdinfo, uint8_t *buf)
7825 {
7826 	struct log_parameter *lpp = (struct log_parameter *)buf;
7827 	uint8_t *page_ptr = (uint8_t *)lpp->param_values;
7828 	int num_pages_supported = 1; /* Always have GET_SUPPORTED_LOG_PAGES */
7829 	sata_id_t *sata_id = &sdinfo->satadrv_id;
7830 
7831 	lpp->param_code[0] = 0;
7832 	lpp->param_code[1] = 0;
7833 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
7834 	*page_ptr++ = PAGE_CODE_GET_SUPPORTED_LOG_PAGES;
7835 
7836 	if (sata_id->ai_cmdset82 & SATA_SMART_SUPPORTED) {
7837 		if (sata_id->ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) {
7838 			*page_ptr++ = PAGE_CODE_SELF_TEST_RESULTS;
7839 			++num_pages_supported;
7840 		}
7841 		*page_ptr++ = PAGE_CODE_INFORMATION_EXCEPTIONS;
7842 		++num_pages_supported;
7843 		*page_ptr++ = PAGE_CODE_SMART_READ_DATA;
7844 		++num_pages_supported;
7845 		*page_ptr++ = PAGE_CODE_START_STOP_CYCLE_COUNTER;
7846 		++num_pages_supported;
7847 	}
7848 
7849 	lpp->param_len = num_pages_supported;
7850 
7851 	return ((&lpp->param_values[0] - (uint8_t *)lpp) +
7852 	    num_pages_supported);
7853 }
7854 
7855 /*
7856  * sata_build_lsense_page_10() is used to create the
7857  * SCSI LOG SENSE page 0x10 (self-test results)
7858  *
7859  * Takes a sata_drive_info t * and the address of a buffer
7860  * in which to create the page information as well as a sata_hba_inst_t *.
7861  *
7862  * Returns the number of bytes valid in the buffer.
7863  *
7864  * Note: Self test and SMART data is accessible in device log pages.
7865  * The log pages can be accessed by SMART READ/WRITE LOG (up to 255 sectors
7866  * of data can be transferred by a single command), or by the General Purpose
7867  * Logging commands (GPL) READ LOG EXT and WRITE LOG EXT (up to 65,535 sectors
7868  * - approximately 33MB - can be transferred by a single command.
7869  * The SCT Command response (either error or command) is the same for both
7870  * the SMART and GPL methods of issuing commands.
7871  * This function uses READ LOG EXT command when drive supports LBA48, and
7872  * SMART READ command otherwise.
7873  *
7874  * Since above commands are executed in a synchronous mode, this function
7875  * should not be called in an interrupt context.
7876  */
7877 static	int
7878 sata_build_lsense_page_10(
7879 	sata_drive_info_t *sdinfo,
7880 	uint8_t *buf,
7881 	sata_hba_inst_t *sata_hba_inst)
7882 {
7883 	struct log_parameter *lpp = (struct log_parameter *)buf;
7884 	int rval;
7885 
7886 	if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48) {
7887 		struct smart_ext_selftest_log *ext_selftest_log;
7888 
7889 		ext_selftest_log = kmem_zalloc(
7890 		    sizeof (struct smart_ext_selftest_log), KM_SLEEP);
7891 
7892 		rval = sata_ext_smart_selftest_read_log(sata_hba_inst, sdinfo,
7893 		    ext_selftest_log, 0);
7894 		if (rval == 0) {
7895 			int index, start_index;
7896 			struct smart_ext_selftest_log_entry *entry;
7897 			static const struct smart_ext_selftest_log_entry empty =
7898 			    {0};
7899 			uint16_t block_num;
7900 			int count;
7901 			boolean_t only_one_block = B_FALSE;
7902 
7903 			index = ext_selftest_log->
7904 			    smart_ext_selftest_log_index[0];
7905 			index |= ext_selftest_log->
7906 			    smart_ext_selftest_log_index[1] << 8;
7907 			if (index == 0)
7908 				goto out;
7909 
7910 			--index;	/* Correct for 0 origin */
7911 			start_index = index;	/* remember where we started */
7912 			block_num = index / ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
7913 			if (block_num != 0) {
7914 				rval = sata_ext_smart_selftest_read_log(
7915 				    sata_hba_inst, sdinfo, ext_selftest_log,
7916 				    block_num);
7917 				if (rval != 0)
7918 					goto out;
7919 			}
7920 			index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
7921 			entry =
7922 			    &ext_selftest_log->
7923 			    smart_ext_selftest_log_entries[index];
7924 
7925 			for (count = 1;
7926 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
7927 			    ++count) {
7928 				uint8_t status;
7929 				uint8_t code;
7930 				uint8_t sense_key;
7931 				uint8_t add_sense_code;
7932 				uint8_t add_sense_code_qual;
7933 
7934 				/* If this is an unused entry, we are done */
7935 				if (bcmp(entry, &empty, sizeof (empty)) == 0) {
7936 					/* Broken firmware on some disks */
7937 					if (index + 1 ==
7938 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK) {
7939 						--entry;
7940 						--index;
7941 						if (bcmp(entry, &empty,
7942 						    sizeof (empty)) == 0)
7943 							goto out;
7944 					} else
7945 						goto out;
7946 				}
7947 
7948 				if (only_one_block &&
7949 				    start_index == index)
7950 					goto out;
7951 
7952 				lpp->param_code[0] = 0;
7953 				lpp->param_code[1] = count;
7954 				lpp->param_ctrl_flags =
7955 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
7956 				lpp->param_len =
7957 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
7958 
7959 				status = entry->smart_ext_selftest_log_status;
7960 				status >>= 4;
7961 				switch (status) {
7962 				case 0:
7963 				default:
7964 					sense_key = KEY_NO_SENSE;
7965 					add_sense_code =
7966 					    SD_SCSI_ASC_NO_ADD_SENSE;
7967 					add_sense_code_qual = 0;
7968 					break;
7969 				case 1:
7970 					sense_key = KEY_ABORTED_COMMAND;
7971 					add_sense_code =
7972 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7973 					add_sense_code_qual = SCSI_COMPONENT_81;
7974 					break;
7975 				case 2:
7976 					sense_key = KEY_ABORTED_COMMAND;
7977 					add_sense_code =
7978 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7979 					add_sense_code_qual = SCSI_COMPONENT_82;
7980 					break;
7981 				case 3:
7982 					sense_key = KEY_ABORTED_COMMAND;
7983 					add_sense_code =
7984 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7985 					add_sense_code_qual = SCSI_COMPONENT_83;
7986 					break;
7987 				case 4:
7988 					sense_key = KEY_HARDWARE_ERROR;
7989 					add_sense_code =
7990 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7991 					add_sense_code_qual = SCSI_COMPONENT_84;
7992 					break;
7993 				case 5:
7994 					sense_key = KEY_HARDWARE_ERROR;
7995 					add_sense_code =
7996 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
7997 					add_sense_code_qual = SCSI_COMPONENT_85;
7998 					break;
7999 				case 6:
8000 					sense_key = KEY_HARDWARE_ERROR;
8001 					add_sense_code =
8002 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8003 					add_sense_code_qual = SCSI_COMPONENT_86;
8004 					break;
8005 				case 7:
8006 					sense_key = KEY_MEDIUM_ERROR;
8007 					add_sense_code =
8008 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8009 					add_sense_code_qual = SCSI_COMPONENT_87;
8010 					break;
8011 				case 8:
8012 					sense_key = KEY_HARDWARE_ERROR;
8013 					add_sense_code =
8014 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8015 					add_sense_code_qual = SCSI_COMPONENT_88;
8016 					break;
8017 				}
8018 				code = 0;	/* unspecified */
8019 				status |= (code << 4);
8020 				lpp->param_values[0] = status;
8021 				lpp->param_values[1] = 0; /* unspecified */
8022 				lpp->param_values[2] = entry->
8023 				    smart_ext_selftest_log_timestamp[1];
8024 				lpp->param_values[3] = entry->
8025 				    smart_ext_selftest_log_timestamp[0];
8026 				if (status != 0) {
8027 					lpp->param_values[4] = 0;
8028 					lpp->param_values[5] = 0;
8029 					lpp->param_values[6] = entry->
8030 					    smart_ext_selftest_log_failing_lba
8031 					    [5];
8032 					lpp->param_values[7] = entry->
8033 					    smart_ext_selftest_log_failing_lba
8034 					    [4];
8035 					lpp->param_values[8] = entry->
8036 					    smart_ext_selftest_log_failing_lba
8037 					    [3];
8038 					lpp->param_values[9] = entry->
8039 					    smart_ext_selftest_log_failing_lba
8040 					    [2];
8041 					lpp->param_values[10] = entry->
8042 					    smart_ext_selftest_log_failing_lba
8043 					    [1];
8044 					lpp->param_values[11] = entry->
8045 					    smart_ext_selftest_log_failing_lba
8046 					    [0];
8047 				} else {	/* No bad block address */
8048 					lpp->param_values[4] = 0xff;
8049 					lpp->param_values[5] = 0xff;
8050 					lpp->param_values[6] = 0xff;
8051 					lpp->param_values[7] = 0xff;
8052 					lpp->param_values[8] = 0xff;
8053 					lpp->param_values[9] = 0xff;
8054 					lpp->param_values[10] = 0xff;
8055 					lpp->param_values[11] = 0xff;
8056 				}
8057 
8058 				lpp->param_values[12] = sense_key;
8059 				lpp->param_values[13] = add_sense_code;
8060 				lpp->param_values[14] = add_sense_code_qual;
8061 				lpp->param_values[15] = 0; /* undefined */
8062 
8063 				lpp = (struct log_parameter *)
8064 				    (((uint8_t *)lpp) +
8065 				    SCSI_LOG_PARAM_HDR_LEN +
8066 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8067 
8068 				--index;	/* Back up to previous entry */
8069 				if (index < 0) {
8070 					if (block_num > 0) {
8071 						--block_num;
8072 					} else {
8073 						struct read_log_ext_directory
8074 						    logdir;
8075 
8076 						rval =
8077 						    sata_read_log_ext_directory(
8078 						    sata_hba_inst, sdinfo,
8079 						    &logdir);
8080 						if (rval == -1)
8081 							goto out;
8082 						if ((logdir.read_log_ext_vers
8083 						    [0] == 0) &&
8084 						    (logdir.read_log_ext_vers
8085 						    [1] == 0))
8086 							goto out;
8087 						block_num =
8088 						    logdir.read_log_ext_nblks
8089 						    [EXT_SMART_SELFTEST_LOG_PAGE
8090 						    - 1][0];
8091 						block_num |= logdir.
8092 						    read_log_ext_nblks
8093 						    [EXT_SMART_SELFTEST_LOG_PAGE
8094 						    - 1][1] << 8;
8095 						--block_num;
8096 						only_one_block =
8097 						    (block_num == 0);
8098 					}
8099 					rval = sata_ext_smart_selftest_read_log(
8100 					    sata_hba_inst, sdinfo,
8101 					    ext_selftest_log, block_num);
8102 					if (rval != 0)
8103 						goto out;
8104 
8105 					index =
8106 					    ENTRIES_PER_EXT_SELFTEST_LOG_BLK -
8107 					    1;
8108 				}
8109 				index %= ENTRIES_PER_EXT_SELFTEST_LOG_BLK;
8110 				entry = &ext_selftest_log->
8111 				    smart_ext_selftest_log_entries[index];
8112 			}
8113 		}
8114 out:
8115 		kmem_free(ext_selftest_log,
8116 		    sizeof (struct smart_ext_selftest_log));
8117 	} else {
8118 		struct smart_selftest_log *selftest_log;
8119 
8120 		selftest_log = kmem_zalloc(sizeof (struct smart_selftest_log),
8121 		    KM_SLEEP);
8122 
8123 		rval = sata_smart_selftest_log(sata_hba_inst, sdinfo,
8124 		    selftest_log);
8125 
8126 		if (rval == 0) {
8127 			int index;
8128 			int count;
8129 			struct smart_selftest_log_entry *entry;
8130 			static const struct smart_selftest_log_entry empty =
8131 			    { 0 };
8132 
8133 			index = selftest_log->smart_selftest_log_index;
8134 			if (index == 0)
8135 				goto done;
8136 			--index;	/* Correct for 0 origin */
8137 			entry = &selftest_log->
8138 			    smart_selftest_log_entries[index];
8139 			for (count = 1;
8140 			    count <= SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS;
8141 			    ++count) {
8142 				uint8_t status;
8143 				uint8_t code;
8144 				uint8_t sense_key;
8145 				uint8_t add_sense_code;
8146 				uint8_t add_sense_code_qual;
8147 
8148 				if (bcmp(entry, &empty, sizeof (empty)) == 0)
8149 					goto done;
8150 
8151 				lpp->param_code[0] = 0;
8152 				lpp->param_code[1] = count;
8153 				lpp->param_ctrl_flags =
8154 				    LOG_CTRL_LP | LOG_CTRL_LBIN;
8155 				lpp->param_len =
8156 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN;
8157 
8158 				status = entry->smart_selftest_log_status;
8159 				status >>= 4;
8160 				switch (status) {
8161 				case 0:
8162 				default:
8163 					sense_key = KEY_NO_SENSE;
8164 					add_sense_code =
8165 					    SD_SCSI_ASC_NO_ADD_SENSE;
8166 					break;
8167 				case 1:
8168 					sense_key = KEY_ABORTED_COMMAND;
8169 					add_sense_code =
8170 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8171 					add_sense_code_qual = SCSI_COMPONENT_81;
8172 					break;
8173 				case 2:
8174 					sense_key = KEY_ABORTED_COMMAND;
8175 					add_sense_code =
8176 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8177 					add_sense_code_qual = SCSI_COMPONENT_82;
8178 					break;
8179 				case 3:
8180 					sense_key = KEY_ABORTED_COMMAND;
8181 					add_sense_code =
8182 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8183 					add_sense_code_qual = SCSI_COMPONENT_83;
8184 					break;
8185 				case 4:
8186 					sense_key = KEY_HARDWARE_ERROR;
8187 					add_sense_code =
8188 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8189 					add_sense_code_qual = SCSI_COMPONENT_84;
8190 					break;
8191 				case 5:
8192 					sense_key = KEY_HARDWARE_ERROR;
8193 					add_sense_code =
8194 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8195 					add_sense_code_qual = SCSI_COMPONENT_85;
8196 					break;
8197 				case 6:
8198 					sense_key = KEY_HARDWARE_ERROR;
8199 					add_sense_code =
8200 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8201 					add_sense_code_qual = SCSI_COMPONENT_86;
8202 					break;
8203 				case 7:
8204 					sense_key = KEY_MEDIUM_ERROR;
8205 					add_sense_code =
8206 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8207 					add_sense_code_qual = SCSI_COMPONENT_87;
8208 					break;
8209 				case 8:
8210 					sense_key = KEY_HARDWARE_ERROR;
8211 					add_sense_code =
8212 					    DIAGNOSTIC_FAILURE_ON_COMPONENT;
8213 					add_sense_code_qual = SCSI_COMPONENT_88;
8214 					break;
8215 				}
8216 				code = 0;	/* unspecified */
8217 				status |= (code << 4);
8218 				lpp->param_values[0] = status;
8219 				lpp->param_values[1] = 0; /* unspecified */
8220 				lpp->param_values[2] = entry->
8221 				    smart_selftest_log_timestamp[1];
8222 				lpp->param_values[3] = entry->
8223 				    smart_selftest_log_timestamp[0];
8224 				if (status != 0) {
8225 					lpp->param_values[4] = 0;
8226 					lpp->param_values[5] = 0;
8227 					lpp->param_values[6] = 0;
8228 					lpp->param_values[7] = 0;
8229 					lpp->param_values[8] = entry->
8230 					    smart_selftest_log_failing_lba[3];
8231 					lpp->param_values[9] = entry->
8232 					    smart_selftest_log_failing_lba[2];
8233 					lpp->param_values[10] = entry->
8234 					    smart_selftest_log_failing_lba[1];
8235 					lpp->param_values[11] = entry->
8236 					    smart_selftest_log_failing_lba[0];
8237 				} else {	/* No block address */
8238 					lpp->param_values[4] = 0xff;
8239 					lpp->param_values[5] = 0xff;
8240 					lpp->param_values[6] = 0xff;
8241 					lpp->param_values[7] = 0xff;
8242 					lpp->param_values[8] = 0xff;
8243 					lpp->param_values[9] = 0xff;
8244 					lpp->param_values[10] = 0xff;
8245 					lpp->param_values[11] = 0xff;
8246 				}
8247 				lpp->param_values[12] = sense_key;
8248 				lpp->param_values[13] = add_sense_code;
8249 				lpp->param_values[14] = add_sense_code_qual;
8250 				lpp->param_values[15] = 0; /* undefined */
8251 
8252 				lpp = (struct log_parameter *)
8253 				    (((uint8_t *)lpp) +
8254 				    SCSI_LOG_PARAM_HDR_LEN +
8255 				    SCSI_LOG_SENSE_SELFTEST_PARAM_LEN);
8256 				--index;	/* back up to previous entry */
8257 				if (index < 0) {
8258 					index =
8259 					    NUM_SMART_SELFTEST_LOG_ENTRIES - 1;
8260 				}
8261 				entry = &selftest_log->
8262 				    smart_selftest_log_entries[index];
8263 			}
8264 		}
8265 done:
8266 		kmem_free(selftest_log, sizeof (struct smart_selftest_log));
8267 	}
8268 
8269 	return ((SCSI_LOG_PARAM_HDR_LEN + SCSI_LOG_SENSE_SELFTEST_PARAM_LEN) *
8270 	    SCSI_ENTRIES_IN_LOG_SENSE_SELFTEST_RESULTS);
8271 }
8272 
8273 /*
8274  * sata_build_lsense_page_2f() is used to create the
8275  * SCSI LOG SENSE page 0x2f (informational exceptions)
8276  *
8277  * Takes a sata_drive_info t * and the address of a buffer
8278  * in which to create the page information as well as a sata_hba_inst_t *.
8279  *
8280  * Returns the number of bytes valid in the buffer.
8281  *
8282  * Because it invokes function(s) that send synchronously executed command
8283  * to the HBA, it cannot be called in the interrupt context.
8284  */
8285 static	int
8286 sata_build_lsense_page_2f(
8287 	sata_drive_info_t *sdinfo,
8288 	uint8_t *buf,
8289 	sata_hba_inst_t *sata_hba_inst)
8290 {
8291 	struct log_parameter *lpp = (struct log_parameter *)buf;
8292 	int rval;
8293 	uint8_t *smart_data;
8294 	uint8_t temp;
8295 	sata_id_t *sata_id;
8296 #define	SMART_NO_TEMP	0xff
8297 
8298 	lpp->param_code[0] = 0;
8299 	lpp->param_code[1] = 0;
8300 	lpp->param_ctrl_flags = LOG_CTRL_LP | LOG_CTRL_LBIN;
8301 
8302 	/* Now get the SMART status w.r.t. threshold exceeded */
8303 	rval = sata_fetch_smart_return_status(sata_hba_inst, sdinfo);
8304 	switch (rval) {
8305 	case 1:
8306 		lpp->param_values[0] = SCSI_PREDICTED_FAILURE;
8307 		lpp->param_values[1] = SCSI_GENERAL_HD_FAILURE;
8308 		break;
8309 	case 0:
8310 	case -1:	/* failed to get data */
8311 		lpp->param_values[0] = 0;	/* No failure predicted */
8312 		lpp->param_values[1] = 0;
8313 		break;
8314 #if defined(SATA_DEBUG)
8315 	default:
8316 		cmn_err(CE_PANIC, "sata_build_lsense_page_2f bad return value");
8317 		/* NOTREACHED */
8318 #endif
8319 	}
8320 
8321 	sata_id = &sdinfo->satadrv_id;
8322 	if (! (sata_id->ai_sctsupport & SATA_SCT_CMD_TRANS_SUP))
8323 		temp = SMART_NO_TEMP;
8324 	else {
8325 		/* Now get the temperature */
8326 		smart_data = kmem_zalloc(512, KM_SLEEP);
8327 		rval = sata_smart_read_log(sata_hba_inst, sdinfo, smart_data,
8328 		    SCT_STATUS_LOG_PAGE, 1);
8329 		if (rval == -1)
8330 			temp = SMART_NO_TEMP;
8331 		else {
8332 			temp = smart_data[200];
8333 			if (temp & 0x80) {
8334 				if (temp & 0x7f)
8335 					temp = 0;
8336 				else
8337 					temp = SMART_NO_TEMP;
8338 			}
8339 		}
8340 		kmem_free(smart_data, 512);
8341 	}
8342 
8343 	lpp->param_values[2] = temp;	/* most recent temperature */
8344 	lpp->param_values[3] = 0;	/* required vendor specific byte */
8345 
8346 	lpp->param_len = SCSI_INFO_EXCEPTIONS_PARAM_LEN;
8347 
8348 
8349 	return (SCSI_INFO_EXCEPTIONS_PARAM_LEN + SCSI_LOG_PARAM_HDR_LEN);
8350 }
8351 
8352 /*
8353  * sata_build_lsense_page_30() is used to create the
8354  * SCSI LOG SENSE page 0x30 (Sun's vendor specific page for ATA SMART data).
8355  *
8356  * Takes a sata_drive_info t * and the address of a buffer
8357  * in which to create the page information as well as a sata_hba_inst_t *.
8358  *
8359  * Returns the number of bytes valid in the buffer.
8360  */
8361 static int
8362 sata_build_lsense_page_30(
8363 	sata_drive_info_t *sdinfo,
8364 	uint8_t *buf,
8365 	sata_hba_inst_t *sata_hba_inst)
8366 {
8367 	struct smart_data *smart_data = (struct smart_data *)buf;
8368 	int rval;
8369 
8370 	/* Now do the SMART READ DATA */
8371 	rval = sata_fetch_smart_data(sata_hba_inst, sdinfo, smart_data);
8372 	if (rval == -1)
8373 		return (0);
8374 
8375 	return (sizeof (struct smart_data));
8376 }
8377 
8378 /*
8379  * sata_build_lsense_page_0e() is used to create the
8380  * SCSI LOG SENSE page 0e (start-stop cycle counter page)
8381  *
8382  * Date of Manufacture (0x0001)
8383  *	YEAR = "0000"
8384  *	WEEK = "00"
8385  * Accounting Date (0x0002)
8386  *	6 ASCII space character(20h)
8387  * Specified cycle count over device lifetime
8388  *	VALUE - THRESH - the delta between max and min;
8389  * Accumulated start-stop cycles
8390  *	VALUE - WORST - the accumulated cycles;
8391  *
8392  * ID FLAG THRESH VALUE WORST RAW on start/stop counter attribute
8393  *
8394  * Takes a sata_drive_info t * and the address of a buffer
8395  * in which to create the page information as well as a sata_hba_inst_t *.
8396  *
8397  * Returns the number of bytes valid in the buffer.
8398  */
8399 static	int
8400 sata_build_lsense_page_0e(sata_drive_info_t *sdinfo, uint8_t *buf,
8401 	sata_pkt_txlate_t *spx)
8402 {
8403 	struct start_stop_cycle_counter_log *log_page;
8404 	int i, rval, index;
8405 	uint8_t smart_data[512], id, value, worst, thresh;
8406 	uint32_t max_count, cycles;
8407 
8408 	/* Now do the SMART READ DATA */
8409 	rval = sata_fetch_smart_data(spx->txlt_sata_hba_inst, sdinfo,
8410 	    (struct smart_data *)smart_data);
8411 	if (rval == -1)
8412 		return (0);
8413 	for (i = 0, id = 0; i < SMART_START_STOP_COUNT_ID * 2; i++) {
8414 		index = (i * 12) + 2;
8415 		id = smart_data[index];
8416 		if (id != SMART_START_STOP_COUNT_ID)
8417 			continue;
8418 		else {
8419 			thresh = smart_data[index + 2];
8420 			value = smart_data[index + 3];
8421 			worst = smart_data[index + 4];
8422 			break;
8423 		}
8424 	}
8425 	if (id != SMART_START_STOP_COUNT_ID)
8426 		return (0);
8427 	max_count = value - thresh;
8428 	cycles = value - worst;
8429 
8430 	log_page = (struct start_stop_cycle_counter_log *)buf;
8431 	bzero(log_page, sizeof (struct start_stop_cycle_counter_log));
8432 	log_page->code = 0x0e;
8433 	log_page->page_len_low = 0x24;
8434 
8435 	log_page->manufactor_date_low = 0x1;
8436 	log_page->param_1.fmt_link = 0x1; /* 01b */
8437 	log_page->param_len_1 = 0x06;
8438 	for (i = 0; i < 4; i++) {
8439 		log_page->year_manu[i] = 0x30;
8440 		if (i < 2)
8441 			log_page->week_manu[i] = 0x30;
8442 	}
8443 
8444 	log_page->account_date_low = 0x02;
8445 	log_page->param_2.fmt_link = 0x01; /* 01b */
8446 	log_page->param_len_2 = 0x06;
8447 	for (i = 0; i < 4; i++) {
8448 		log_page->year_account[i] = 0x20;
8449 		if (i < 2)
8450 			log_page->week_account[i] = 0x20;
8451 	}
8452 
8453 	log_page->lifetime_code_low = 0x03;
8454 	log_page->param_3.fmt_link = 0x03; /* 11b */
8455 	log_page->param_len_3 = 0x04;
8456 	/* VALUE - THRESH - the delta between max and min */
8457 	log_page->cycle_code_low = 0x04;
8458 	log_page->param_4.fmt_link = 0x03; /* 11b */
8459 	log_page->param_len_4 = 0x04;
8460 	/* WORST - THRESH - the distance from 'now' to min */
8461 
8462 	for (i = 0; i < 4; i++) {
8463 		log_page->cycle_lifetime[i] =
8464 		    (max_count >> (8 * (3 - i))) & 0xff;
8465 		log_page->cycle_accumulated[i] =
8466 		    (cycles >> (8 * (3 - i))) & 0xff;
8467 	}
8468 
8469 	return (sizeof (struct start_stop_cycle_counter_log));
8470 }
8471 
8472 /*
8473  * This function was used for build a ATA read verify sector command
8474  */
8475 static void
8476 sata_build_read_verify_cmd(sata_cmd_t *scmd, uint16_t sec, uint64_t lba)
8477 {
8478 	scmd->satacmd_cmd_reg = SATAC_RDVER;
8479 	scmd->satacmd_addr_type = ATA_ADDR_LBA28;
8480 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8481 
8482 	scmd->satacmd_sec_count_lsb = sec & 0xff;
8483 	scmd->satacmd_lba_low_lsb = lba & 0xff;
8484 	scmd->satacmd_lba_mid_lsb = (lba >> 8) & 0xff;
8485 	scmd->satacmd_lba_high_lsb = (lba >> 16) & 0xff;
8486 	scmd->satacmd_device_reg = (SATA_ADH_LBA | (lba >> 24) & 0xf);
8487 	scmd->satacmd_features_reg = 0;
8488 	scmd->satacmd_status_reg = 0;
8489 	scmd->satacmd_error_reg = 0;
8490 }
8491 
8492 /*
8493  * This function was used for building an ATA
8494  * command, and only command register need to
8495  * be defined, other register will be zero or na.
8496  */
8497 static void
8498 sata_build_generic_cmd(sata_cmd_t *scmd, uint8_t cmd)
8499 {
8500 	scmd->satacmd_addr_type = 0;
8501 	scmd->satacmd_cmd_reg = cmd;
8502 	scmd->satacmd_device_reg = 0;
8503 	scmd->satacmd_sec_count_lsb = 0;
8504 	scmd->satacmd_lba_low_lsb = 0;
8505 	scmd->satacmd_lba_mid_lsb = 0;
8506 	scmd->satacmd_lba_high_lsb = 0;
8507 	scmd->satacmd_features_reg = 0;
8508 	scmd->satacmd_status_reg = 0;
8509 	scmd->satacmd_error_reg = 0;
8510 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
8511 }
8512 
8513 /*
8514  * This function was used for changing the standby
8515  * timer format from SCSI to ATA.
8516  */
8517 static uint8_t
8518 sata_get_standby_timer(uint8_t *timer)
8519 {
8520 	uint32_t i = 0, count = 0;
8521 	uint8_t ata_count;
8522 
8523 	for (i = 0; i < 4; i++) {
8524 		count = count << 8 | timer[i];
8525 	}
8526 
8527 	if (count == 0)
8528 		return (0);
8529 
8530 	if (count >= 1 && count <= 12000)
8531 		ata_count = (count -1) / 50 + 1;
8532 	else if (count > 12000 && count <= 12600)
8533 		ata_count = 0xfc;
8534 	else if (count > 12601 && count <= 12750)
8535 		ata_count = 0xff;
8536 	else if (count > 12750 && count <= 17999)
8537 		ata_count = 0xf1;
8538 	else if (count > 18000 && count <= 198000)
8539 		ata_count = count / 18000 + 240;
8540 	else
8541 		ata_count = 0xfd;
8542 	return (ata_count);
8543 }
8544 
8545 /* ************************** ATAPI-SPECIFIC FUNCTIONS ********************** */
8546 
8547 /*
8548  * Start command for ATAPI device.
8549  * This function processes scsi_pkt requests.
8550  * Now CD/DVD, tape and ATAPI disk devices are supported.
8551  * Most commands are packet without any translation into Packet Command.
8552  * Some may be trapped and executed as SATA commands (not clear which one).
8553  *
8554  * Returns TRAN_ACCEPT if command is accepted for execution (or completed
8555  * execution).
8556  * Returns other TRAN_XXXX codes if command is not accepted or completed
8557  * (see return values for sata_hba_start()).
8558  *
8559  * Note:
8560  * Inquiry cdb format differs between transport version 2 and 3.
8561  * However, the transport version 3 devices that were checked did not adhere
8562  * to the specification (ignored MSB of the allocation length). Therefore,
8563  * the transport version is not checked, but Inquiry allocation length is
8564  * truncated to 255 bytes if the original allocation length set-up by the
8565  * target driver is greater than 255 bytes.
8566  */
8567 static int
8568 sata_txlt_atapi(sata_pkt_txlate_t *spx)
8569 {
8570 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8571 	sata_cmd_t *scmd = &spx->txlt_sata_pkt->satapkt_cmd;
8572 	struct buf *bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8573 	sata_hba_inst_t *sata_hba = SATA_TXLT_HBA_INST(spx);
8574 	sata_drive_info_t *sdinfo = sata_get_device_info(sata_hba,
8575 	    &spx->txlt_sata_pkt->satapkt_device);
8576 	int cport = SATA_TXLT_CPORT(spx);
8577 	int cdblen;
8578 	int rval, reason;
8579 	int synch;
8580 	union scsi_cdb *cdbp = (union scsi_cdb *)scsipkt->pkt_cdbp;
8581 
8582 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
8583 
8584 	if (((rval = sata_txlt_generic_pkt_info(spx, &reason, 1)) !=
8585 	    TRAN_ACCEPT) || (reason == CMD_DEV_GONE)) {
8586 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8587 		return (rval);
8588 	}
8589 
8590 	/*
8591 	 * ATAPI device executes some ATA commands in addition to those
8592 	 * commands sent via PACKET command. These ATA commands may be
8593 	 * executed by the regular SATA translation functions. None needs
8594 	 * to be captured now.
8595 	 *
8596 	 * Commands sent via PACKET command include:
8597 	 *	MMC command set for ATAPI CD/DVD device
8598 	 *	SSC command set for ATAPI TAPE device
8599 	 *	SBC command set for ATAPI disk device
8600 	 *
8601 	 */
8602 
8603 	/* Check the size of cdb */
8604 	cdblen = scsi_cdb_size[GETGROUP(cdbp)];
8605 	if (cdblen > sdinfo->satadrv_atapi_cdb_len) {
8606 		sata_log(NULL, CE_WARN,
8607 		    "sata: invalid ATAPI cdb length %d",
8608 		    scsipkt->pkt_cdblen);
8609 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
8610 		return (TRAN_BADPKT);
8611 	}
8612 
8613 	SATAATAPITRACE(spx, cdblen);
8614 
8615 	/*
8616 	 * For non-read/write commands we need to
8617 	 * map buffer
8618 	 */
8619 	switch ((uint_t)scsipkt->pkt_cdbp[0]) {
8620 	case SCMD_READ:
8621 	case SCMD_READ_G1:
8622 	case SCMD_READ_G5:
8623 	case SCMD_READ_G4:
8624 	case SCMD_WRITE:
8625 	case SCMD_WRITE_G1:
8626 	case SCMD_WRITE_G5:
8627 	case SCMD_WRITE_G4:
8628 		break;
8629 	default:
8630 		if (bp != NULL) {
8631 			if (bp->b_flags & (B_PHYS | B_PAGEIO))
8632 				bp_mapin(bp);
8633 		}
8634 		break;
8635 	}
8636 	/*
8637 	 * scmd->satacmd_flags.sata_data_direction default -
8638 	 * SATA_DIR_NODATA_XFER - is set by
8639 	 * sata_txlt_generic_pkt_info().
8640 	 */
8641 	if (scmd->satacmd_bp) {
8642 		if (scmd->satacmd_bp->b_flags & B_READ) {
8643 			scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8644 		} else {
8645 			scmd->satacmd_flags.sata_data_direction =
8646 			    SATA_DIR_WRITE;
8647 		}
8648 	}
8649 
8650 	/*
8651 	 * Set up ATAPI packet command.
8652 	 */
8653 
8654 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8655 
8656 	/* Copy cdb into sata_cmd */
8657 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8658 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
8659 	bcopy(cdbp, scmd->satacmd_acdb, cdblen);
8660 
8661 	/* See note in the command header */
8662 	if (scmd->satacmd_acdb[0] == SCMD_INQUIRY) {
8663 		if (scmd->satacmd_acdb[3] != 0)
8664 			scmd->satacmd_acdb[4] = 255;
8665 	}
8666 
8667 #ifdef SATA_DEBUG
8668 	if (sata_debug_flags & SATA_DBG_ATAPI) {
8669 		uint8_t *p = scmd->satacmd_acdb;
8670 		char buf[3 * SATA_ATAPI_MAX_CDB_LEN];
8671 
8672 		(void) snprintf(buf, SATA_ATAPI_MAX_CDB_LEN,
8673 		    "%02x %02x %02x %02x %02x %02x %02x %02x "
8674 		    "%2x %02x %02x %02x %02x %02x %02x %02x",
8675 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
8676 		    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
8677 		buf[(3 * SATA_ATAPI_MAX_CDB_LEN) - 1] = '\0';
8678 		cmn_err(CE_NOTE, "ATAPI cdb: %s\n", buf);
8679 	}
8680 #endif
8681 
8682 	/*
8683 	 * Preset request sense data to NO SENSE.
8684 	 * If there is no way to get error information via Request Sense,
8685 	 * the packet request sense data would not have to be modified by HBA,
8686 	 * but it could be returned as is.
8687 	 */
8688 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
8689 	sata_fixed_sense_data_preset(
8690 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8691 
8692 	if (!(spx->txlt_sata_pkt->satapkt_op_mode & SATA_OPMODE_SYNCH)) {
8693 		/* Need callback function */
8694 		spx->txlt_sata_pkt->satapkt_comp = sata_txlt_atapi_completion;
8695 		synch = FALSE;
8696 	} else
8697 		synch = TRUE;
8698 
8699 	/* Transfer command to HBA */
8700 	if (sata_hba_start(spx, &rval) != 0) {
8701 		/* Pkt not accepted for execution */
8702 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8703 		return (rval);
8704 	}
8705 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba, cport));
8706 	/*
8707 	 * If execution is non-synchronous,
8708 	 * a callback function will handle potential errors, translate
8709 	 * the response and will do a callback to a target driver.
8710 	 * If it was synchronous, use the same framework callback to check
8711 	 * an execution status.
8712 	 */
8713 	if (synch) {
8714 		SATADBG1(SATA_DBG_SCSI_IF, spx->txlt_sata_hba_inst,
8715 		    "synchronous execution status %x\n",
8716 		    spx->txlt_sata_pkt->satapkt_reason);
8717 		sata_txlt_atapi_completion(spx->txlt_sata_pkt);
8718 	}
8719 	return (TRAN_ACCEPT);
8720 }
8721 
8722 
8723 /*
8724  * ATAPI Packet command completion.
8725  *
8726  * Failure of the command passed via Packet command are considered device
8727  * error. SATA HBA driver would have to retrieve error data (via Request
8728  * Sense command delivered via error retrieval sata packet) and copy it
8729  * to satacmd_rqsense array. From there, it is moved into scsi pkt sense data.
8730  */
8731 static void
8732 sata_txlt_atapi_completion(sata_pkt_t *sata_pkt)
8733 {
8734 	sata_pkt_txlate_t *spx =
8735 	    (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
8736 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
8737 	struct scsi_extended_sense *sense;
8738 	struct buf *bp;
8739 	int rval;
8740 
8741 #ifdef SATA_DEBUG
8742 	uint8_t *rqsp = sata_pkt->satapkt_cmd.satacmd_rqsense;
8743 #endif
8744 
8745 	scsipkt->pkt_state = STATE_GOT_BUS | STATE_GOT_TARGET |
8746 	    STATE_SENT_CMD | STATE_GOT_STATUS;
8747 
8748 	if (sata_pkt->satapkt_reason == SATA_PKT_COMPLETED) {
8749 		/* Normal completion */
8750 		if (sata_pkt->satapkt_cmd.satacmd_bp != NULL)
8751 			scsipkt->pkt_state |= STATE_XFERRED_DATA;
8752 		scsipkt->pkt_reason = CMD_CMPLT;
8753 		*scsipkt->pkt_scbp = STATUS_GOOD;
8754 		if (spx->txlt_tmp_buf != NULL) {
8755 			/* Temporary buffer was used */
8756 			bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
8757 			if (bp->b_flags & B_READ) {
8758 				rval = ddi_dma_sync(
8759 				    spx->txlt_buf_dma_handle, 0, 0,
8760 				    DDI_DMA_SYNC_FORCPU);
8761 				ASSERT(rval == DDI_SUCCESS);
8762 				bcopy(spx->txlt_tmp_buf, bp->b_un.b_addr,
8763 				    bp->b_bcount);
8764 			}
8765 		}
8766 	} else {
8767 		/*
8768 		 * Something went wrong - analyze return
8769 		 */
8770 		*scsipkt->pkt_scbp = STATUS_CHECK;
8771 		sense = sata_arq_sense(spx);
8772 
8773 		if (sata_pkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
8774 			/*
8775 			 * pkt_reason should be CMD_CMPLT for DEVICE ERROR.
8776 			 * Under this condition ERR bit is set for ATA command,
8777 			 * and CHK bit set for ATAPI command.
8778 			 *
8779 			 * Please check st_intr & sdintr about how pkt_reason
8780 			 * is used.
8781 			 */
8782 			scsipkt->pkt_reason = CMD_CMPLT;
8783 
8784 			/*
8785 			 * We may not have ARQ data if there was a double
8786 			 * error. But sense data in sata packet was pre-set
8787 			 * with NO SENSE so it is valid even if HBA could
8788 			 * not retrieve a real sense data.
8789 			 * Just copy this sense data into scsi pkt sense area.
8790 			 */
8791 			bcopy(sata_pkt->satapkt_cmd.satacmd_rqsense, sense,
8792 			    SATA_ATAPI_MIN_RQSENSE_LEN);
8793 #ifdef SATA_DEBUG
8794 			if (sata_debug_flags & SATA_DBG_SCSI_IF) {
8795 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
8796 				    "sata_txlt_atapi_completion: %02x\n"
8797 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
8798 				    "          %02x %02x %02x %02x %02x %02x "
8799 				    "          %02x %02x %02x %02x %02x %02x\n",
8800 				    scsipkt->pkt_reason,
8801 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
8802 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
8803 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
8804 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
8805 				    rqsp[16], rqsp[17]);
8806 			}
8807 #endif
8808 		} else {
8809 			switch (sata_pkt->satapkt_reason) {
8810 			case SATA_PKT_PORT_ERROR:
8811 				/*
8812 				 * We have no device data.
8813 				 */
8814 				scsipkt->pkt_reason = CMD_INCOMPLETE;
8815 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
8816 				    STATE_GOT_TARGET | STATE_SENT_CMD |
8817 				    STATE_GOT_STATUS);
8818 				sense->es_key = KEY_HARDWARE_ERROR;
8819 				break;
8820 
8821 			case SATA_PKT_TIMEOUT:
8822 				scsipkt->pkt_reason = CMD_TIMEOUT;
8823 				scsipkt->pkt_statistics |=
8824 				    STAT_TIMEOUT | STAT_DEV_RESET;
8825 				/*
8826 				 * Need to check if HARDWARE_ERROR/
8827 				 * TIMEOUT_ON_LOGICAL_UNIT 4/3E/2 would be more
8828 				 * appropriate.
8829 				 */
8830 				break;
8831 
8832 			case SATA_PKT_ABORTED:
8833 				scsipkt->pkt_reason = CMD_ABORTED;
8834 				scsipkt->pkt_statistics |= STAT_ABORTED;
8835 				/* Should we set key COMMAND_ABPRTED? */
8836 				break;
8837 
8838 			case SATA_PKT_RESET:
8839 				scsipkt->pkt_reason = CMD_RESET;
8840 				scsipkt->pkt_statistics |= STAT_DEV_RESET;
8841 				/*
8842 				 * May be we should set Unit Attention /
8843 				 * Reset. Perhaps the same should be
8844 				 * returned for disks....
8845 				 */
8846 				sense->es_key = KEY_UNIT_ATTENTION;
8847 				sense->es_add_code = SD_SCSI_ASC_RESET;
8848 				break;
8849 
8850 			default:
8851 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
8852 				    "sata_txlt_atapi_completion: "
8853 				    "invalid packet completion reason"));
8854 				scsipkt->pkt_reason = CMD_TRAN_ERR;
8855 				scsipkt->pkt_state &= ~(STATE_GOT_BUS |
8856 				    STATE_GOT_TARGET | STATE_SENT_CMD |
8857 				    STATE_GOT_STATUS);
8858 				break;
8859 			}
8860 		}
8861 	}
8862 
8863 	SATAATAPITRACE(spx, 0);
8864 
8865 	if ((scsipkt->pkt_flags & FLAG_NOINTR) == 0 &&
8866 	    scsipkt->pkt_comp != NULL) {
8867 		/* scsi callback required */
8868 		(*scsipkt->pkt_comp)(scsipkt);
8869 	}
8870 }
8871 
8872 /*
8873  * Set up error retrieval sata command for ATAPI Packet Command error data
8874  * recovery.
8875  *
8876  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
8877  * returns SATA_FAILURE otherwise.
8878  */
8879 
8880 static int
8881 sata_atapi_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
8882 {
8883 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
8884 	sata_cmd_t *scmd;
8885 	struct buf *bp;
8886 
8887 	/*
8888 	 * Allocate dma-able buffer error data.
8889 	 * Buffer allocation will take care of buffer alignment and other DMA
8890 	 * attributes.
8891 	 */
8892 	bp = sata_alloc_local_buffer(spx, SATA_ATAPI_MIN_RQSENSE_LEN);
8893 	if (bp == NULL) {
8894 		SATADBG1(SATA_DBG_ATAPI, spx->txlt_sata_hba_inst,
8895 		    "sata_get_err_retrieval_pkt: "
8896 		    "cannot allocate buffer for error data", NULL);
8897 		return (SATA_FAILURE);
8898 	}
8899 	bp_mapin(bp); /* make data buffer accessible */
8900 
8901 	/* Operation modes are up to the caller */
8902 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
8903 
8904 	/* Synchronous mode, no callback - may be changed by the caller */
8905 	spkt->satapkt_comp = NULL;
8906 	spkt->satapkt_time = sata_default_pkt_time;
8907 
8908 	scmd = &spkt->satapkt_cmd;
8909 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
8910 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
8911 
8912 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
8913 
8914 	/*
8915 	 * Set-up acdb. Request Sense CDB (packet command content) is
8916 	 * not in DMA-able buffer. Its handling is HBA-specific (how
8917 	 * it is transfered into packet FIS).
8918 	 */
8919 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
8920 	bcopy(sata_rqsense_cdb, scmd->satacmd_acdb, SATA_ATAPI_RQSENSE_CDB_LEN);
8921 	/* Following zeroing of pad bytes may not be necessary */
8922 	bzero(&scmd->satacmd_acdb[SATA_ATAPI_RQSENSE_CDB_LEN],
8923 	    sdinfo->satadrv_atapi_cdb_len - SATA_ATAPI_RQSENSE_CDB_LEN);
8924 
8925 	/*
8926 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
8927 	 * before accessing it. Handle is in usual place in translate struct.
8928 	 */
8929 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
8930 
8931 	/*
8932 	 * Preset request sense data to NO SENSE.
8933 	 * Here it is redundant, only for a symetry with scsi-originated
8934 	 * packets. It should not be used for anything but debugging.
8935 	 */
8936 	bzero(scmd->satacmd_rqsense, SATA_ATAPI_RQSENSE_LEN);
8937 	sata_fixed_sense_data_preset(
8938 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
8939 
8940 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
8941 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
8942 
8943 	return (SATA_SUCCESS);
8944 }
8945 
8946 /*
8947  * Set-up ATAPI packet command.
8948  * Data transfer direction has to be set-up in sata_cmd structure prior to
8949  * calling this function.
8950  *
8951  * Returns void
8952  */
8953 
8954 static void
8955 sata_atapi_packet_cmd_setup(sata_cmd_t *scmd, sata_drive_info_t *sdinfo)
8956 {
8957 	scmd->satacmd_addr_type = 0;		/* N/A */
8958 	scmd->satacmd_sec_count_lsb = 0;	/* no tag */
8959 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
8960 	scmd->satacmd_lba_mid_lsb = (uint8_t)SATA_ATAPI_MAX_BYTES_PER_DRQ;
8961 	scmd->satacmd_lba_high_lsb =
8962 	    (uint8_t)(SATA_ATAPI_MAX_BYTES_PER_DRQ >> 8);
8963 	scmd->satacmd_cmd_reg = SATAC_PACKET;	/* Command */
8964 
8965 	/*
8966 	 * We want all data to be transfered via DMA.
8967 	 * But specify it only if drive supports DMA and DMA mode is
8968 	 * selected - some drives are sensitive about it.
8969 	 * Hopefully it wil work for all drives....
8970 	 */
8971 	if (sdinfo->satadrv_settings & SATA_DEV_DMA)
8972 		scmd->satacmd_features_reg = SATA_ATAPI_F_DMA;
8973 
8974 	/*
8975 	 * Features register requires special care for devices that use
8976 	 * Serial ATA bridge - they need an explicit specification of
8977 	 * the data transfer direction for Packet DMA commands.
8978 	 * Setting this bit is harmless if DMA is not used.
8979 	 *
8980 	 * Many drives do not implement word 80, specifying what ATA/ATAPI
8981 	 * spec they follow.
8982 	 * We are arbitrarily following the latest SerialATA 2.6 spec,
8983 	 * which uses ATA/ATAPI 6 specification for Identify Data, unless
8984 	 * ATA/ATAPI-7 support is explicitly indicated.
8985 	 */
8986 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
8987 	    sdinfo->satadrv_id.ai_majorversion != 0xffff &&
8988 	    (sdinfo->satadrv_id.ai_majorversion & SATA_MAJVER_7) != 0) {
8989 		/*
8990 		 * Specification of major version is valid and version 7
8991 		 * is supported. It does automatically imply that all
8992 		 * spec features are supported. For now, we assume that
8993 		 * DMADIR setting is valid. ATA/ATAPI7 spec is incomplete.
8994 		 */
8995 		if ((sdinfo->satadrv_id.ai_dirdma &
8996 		    SATA_ATAPI_ID_DMADIR_REQ) != 0) {
8997 			if (scmd->satacmd_flags.sata_data_direction ==
8998 			    SATA_DIR_READ)
8999 			scmd->satacmd_features_reg |=
9000 			    SATA_ATAPI_F_DATA_DIR_READ;
9001 		}
9002 	}
9003 }
9004 
9005 
9006 #ifdef SATA_DEBUG
9007 
9008 /* Display 18 bytes of Inquiry data */
9009 static void
9010 sata_show_inqry_data(uint8_t *buf)
9011 {
9012 	struct scsi_inquiry *inq = (struct scsi_inquiry *)buf;
9013 	uint8_t *p;
9014 
9015 	cmn_err(CE_NOTE, "Inquiry data:");
9016 	cmn_err(CE_NOTE, "device type %x", inq->inq_dtype);
9017 	cmn_err(CE_NOTE, "removable media %x", inq->inq_rmb);
9018 	cmn_err(CE_NOTE, "version %x", inq->inq_ansi);
9019 	cmn_err(CE_NOTE, "ATAPI transport version %d",
9020 	    SATA_ATAPI_TRANS_VERSION(inq));
9021 	cmn_err(CE_NOTE, "response data format %d, aenc %d",
9022 	    inq->inq_rdf, inq->inq_aenc);
9023 	cmn_err(CE_NOTE, " additional length %d", inq->inq_len);
9024 	cmn_err(CE_NOTE, "tpgs %d", inq->inq_tpgs);
9025 	p = (uint8_t *)inq->inq_vid;
9026 	cmn_err(CE_NOTE, "vendor id (binary): %02x %02x %02x %02x "
9027 	    "%02x %02x %02x %02x",
9028 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9029 	p = (uint8_t *)inq->inq_vid;
9030 	cmn_err(CE_NOTE, "vendor id: %c %c %c %c %c %c %c %c",
9031 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
9032 
9033 	p = (uint8_t *)inq->inq_pid;
9034 	cmn_err(CE_NOTE, "product id (binary): %02x %02x %02x %02x "
9035 	    "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
9036 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9037 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9038 	p = (uint8_t *)inq->inq_pid;
9039 	cmn_err(CE_NOTE, "product id: %c %c %c %c %c %c %c %c "
9040 	    "%c %c %c %c %c %c %c %c",
9041 	    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7],
9042 	    p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
9043 
9044 	p = (uint8_t *)inq->inq_revision;
9045 	cmn_err(CE_NOTE, "revision (binary): %02x %02x %02x %02x",
9046 	    p[0], p[1], p[2], p[3]);
9047 	p = (uint8_t *)inq->inq_revision;
9048 	cmn_err(CE_NOTE, "revision: %c %c %c %c",
9049 	    p[0], p[1], p[2], p[3]);
9050 
9051 }
9052 
9053 
9054 static void
9055 sata_save_atapi_trace(sata_pkt_txlate_t *spx, int count)
9056 {
9057 	struct scsi_pkt *scsi_pkt = spx->txlt_scsi_pkt;
9058 
9059 	if (scsi_pkt == NULL)
9060 		return;
9061 	if (count != 0) {
9062 		/* saving cdb */
9063 		bzero(sata_atapi_trace[sata_atapi_trace_index].acdb,
9064 		    SATA_ATAPI_MAX_CDB_LEN);
9065 		bcopy(scsi_pkt->pkt_cdbp,
9066 		    sata_atapi_trace[sata_atapi_trace_index].acdb, count);
9067 	} else {
9068 		bcopy(&((struct scsi_arq_status *)scsi_pkt->pkt_scbp)->
9069 		    sts_sensedata,
9070 		    sata_atapi_trace[sata_atapi_trace_index].arqs,
9071 		    SATA_ATAPI_MIN_RQSENSE_LEN);
9072 		sata_atapi_trace[sata_atapi_trace_index].scsi_pkt_reason =
9073 		    scsi_pkt->pkt_reason;
9074 		sata_atapi_trace[sata_atapi_trace_index].sata_pkt_reason =
9075 		    spx->txlt_sata_pkt->satapkt_reason;
9076 
9077 		if (++sata_atapi_trace_index >= 64)
9078 			sata_atapi_trace_index = 0;
9079 	}
9080 }
9081 
9082 #endif
9083 
9084 /*
9085  * Fetch inquiry data from ATAPI device
9086  * Returns SATA_SUCCESS if operation was successfull, SATA_FAILURE otherwise.
9087  *
9088  * Note:
9089  * inqb pointer does not point to a DMA-able buffer. It is a local buffer
9090  * where the caller expects to see the inquiry data.
9091  *
9092  */
9093 
9094 static int
9095 sata_get_atapi_inquiry_data(sata_hba_inst_t *sata_hba,
9096     sata_address_t *saddr, struct scsi_inquiry *inq)
9097 {
9098 	sata_pkt_txlate_t *spx;
9099 	sata_pkt_t *spkt;
9100 	struct buf *bp;
9101 	sata_drive_info_t *sdinfo;
9102 	sata_cmd_t *scmd;
9103 	int rval;
9104 	uint8_t *rqsp;
9105 #ifdef SATA_DEBUG
9106 	char msg_buf[MAXPATHLEN];
9107 #endif
9108 
9109 	ASSERT(sata_hba != NULL);
9110 
9111 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9112 	spx->txlt_sata_hba_inst = sata_hba;
9113 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9114 	spkt = sata_pkt_alloc(spx, NULL);
9115 	if (spkt == NULL) {
9116 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9117 		return (SATA_FAILURE);
9118 	}
9119 	/* address is needed now */
9120 	spkt->satapkt_device.satadev_addr = *saddr;
9121 
9122 	/* scsi_inquiry size buffer */
9123 	bp = sata_alloc_local_buffer(spx, sizeof (struct scsi_inquiry));
9124 	if (bp == NULL) {
9125 		sata_pkt_free(spx);
9126 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9127 		SATA_LOG_D((sata_hba, CE_WARN,
9128 		    "sata_get_atapi_inquiry_data: "
9129 		    "cannot allocate data buffer"));
9130 		return (SATA_FAILURE);
9131 	}
9132 	bp_mapin(bp); /* make data buffer accessible */
9133 
9134 	scmd = &spkt->satapkt_cmd;
9135 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9136 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9137 
9138 	/* Use synchronous mode */
9139 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9140 	spkt->satapkt_comp = NULL;
9141 	spkt->satapkt_time = sata_default_pkt_time;
9142 
9143 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9144 
9145 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9146 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9147 
9148 	mutex_enter(&(SATA_TXLT_CPORT_MUTEX(spx)));
9149 	sdinfo = sata_get_device_info(sata_hba,
9150 	    &spx->txlt_sata_pkt->satapkt_device);
9151 	if (sdinfo == NULL) {
9152 		/* we have to be carefull about the disapearing device */
9153 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9154 		rval = SATA_FAILURE;
9155 		goto cleanup;
9156 	}
9157 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9158 
9159 	/*
9160 	 * Set-up acdb. This works for atapi transport version 2 and later.
9161 	 */
9162 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9163 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9164 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9165 	scmd->satacmd_acdb[1] = 0x00;
9166 	scmd->satacmd_acdb[2] = 0x00;
9167 	scmd->satacmd_acdb[3] = 0x00;
9168 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9169 	scmd->satacmd_acdb[5] = 0x00;
9170 
9171 	sata_fixed_sense_data_preset(
9172 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9173 
9174 	/* Transfer command to HBA */
9175 	if (sata_hba_start(spx, &rval) != 0) {
9176 		/* Pkt not accepted for execution */
9177 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9178 		    "sata_get_atapi_inquiry_data: "
9179 		    "Packet not accepted for execution - ret: %02x", rval);
9180 		mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9181 		rval = SATA_FAILURE;
9182 		goto cleanup;
9183 	}
9184 	mutex_exit(&(SATA_TXLT_CPORT_MUTEX(spx)));
9185 
9186 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9187 		SATADBG1(SATA_DBG_ATAPI, sata_hba,
9188 		    "sata_get_atapi_inquiry_data: "
9189 		    "Packet completed successfully - ret: %02x", rval);
9190 		if (spx->txlt_buf_dma_handle != NULL) {
9191 			/*
9192 			 * Sync buffer. Handle is in usual place in translate
9193 			 * struct.
9194 			 */
9195 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9196 			    DDI_DMA_SYNC_FORCPU);
9197 			ASSERT(rval == DDI_SUCCESS);
9198 		}
9199 		/*
9200 		 * Normal completion - copy data into caller's buffer
9201 		 */
9202 		bcopy(bp->b_un.b_addr, (uint8_t *)inq,
9203 		    sizeof (struct scsi_inquiry));
9204 #ifdef SATA_DEBUG
9205 		if (sata_debug_flags & SATA_DBG_ATAPI) {
9206 			sata_show_inqry_data((uint8_t *)inq);
9207 		}
9208 #endif
9209 		rval = SATA_SUCCESS;
9210 	} else {
9211 		/*
9212 		 * Something went wrong - analyze return - check rqsense data
9213 		 */
9214 		rval = SATA_FAILURE;
9215 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9216 			/*
9217 			 * ARQ data hopefull show something other than NO SENSE
9218 			 */
9219 			rqsp = scmd->satacmd_rqsense;
9220 #ifdef SATA_DEBUG
9221 			if (sata_debug_flags & SATA_DBG_ATAPI) {
9222 				msg_buf[0] = '\0';
9223 				(void) snprintf(msg_buf, MAXPATHLEN,
9224 				    "ATAPI packet completion reason: %02x\n"
9225 				    "RQSENSE:  %02x %02x %02x %02x %02x %02x\n"
9226 				    "          %02x %02x %02x %02x %02x %02x\n"
9227 				    "          %02x %02x %02x %02x %02x %02x",
9228 				    spkt->satapkt_reason,
9229 				    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9230 				    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9231 				    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9232 				    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9233 				    rqsp[16], rqsp[17]);
9234 				sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9235 				    "%s", msg_buf);
9236 			}
9237 #endif
9238 		} else {
9239 			switch (spkt->satapkt_reason) {
9240 			case SATA_PKT_PORT_ERROR:
9241 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9242 				    "sata_get_atapi_inquiry_data: "
9243 				    "packet reason: port error", NULL);
9244 				break;
9245 
9246 			case SATA_PKT_TIMEOUT:
9247 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9248 				    "sata_get_atapi_inquiry_data: "
9249 				    "packet reason: timeout", NULL);
9250 				break;
9251 
9252 			case SATA_PKT_ABORTED:
9253 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9254 				    "sata_get_atapi_inquiry_data: "
9255 				    "packet reason: aborted", NULL);
9256 				break;
9257 
9258 			case SATA_PKT_RESET:
9259 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9260 				    "sata_get_atapi_inquiry_data: "
9261 				    "packet reason: reset\n", NULL);
9262 				break;
9263 			default:
9264 				SATADBG1(SATA_DBG_ATAPI, sata_hba,
9265 				    "sata_get_atapi_inquiry_data: "
9266 				    "invalid packet reason: %02x\n",
9267 				    spkt->satapkt_reason);
9268 				break;
9269 			}
9270 		}
9271 	}
9272 cleanup:
9273 	sata_free_local_buffer(spx);
9274 	sata_pkt_free(spx);
9275 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9276 	return (rval);
9277 }
9278 
9279 
9280 
9281 
9282 
9283 #if 0
9284 #ifdef SATA_DEBUG
9285 
9286 /*
9287  * Test ATAPI packet command.
9288  * Single threaded test: send packet command in synch mode, process completion
9289  *
9290  */
9291 static void
9292 sata_test_atapi_packet_command(sata_hba_inst_t *sata_hba_inst, int cport)
9293 {
9294 	sata_pkt_txlate_t *spx;
9295 	sata_pkt_t *spkt;
9296 	struct buf *bp;
9297 	sata_device_t sata_device;
9298 	sata_drive_info_t *sdinfo;
9299 	sata_cmd_t *scmd;
9300 	int rval;
9301 	uint8_t *rqsp;
9302 
9303 	ASSERT(sata_hba_inst != NULL);
9304 	sata_device.satadev_addr.cport = cport;
9305 	sata_device.satadev_addr.pmport = 0;
9306 	sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
9307 	sata_device.satadev_rev = SATA_DEVICE_REV;
9308 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9309 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
9310 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9311 	if (sdinfo == NULL) {
9312 		sata_log(sata_hba_inst, CE_WARN,
9313 		    "sata_test_atapi_packet_command: "
9314 		    "no device info for cport %d",
9315 		    sata_device.satadev_addr.cport);
9316 		return;
9317 	}
9318 
9319 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
9320 	spx->txlt_sata_hba_inst = sata_hba_inst;
9321 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
9322 	spkt = sata_pkt_alloc(spx, NULL);
9323 	if (spkt == NULL) {
9324 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9325 		return;
9326 	}
9327 	/* address is needed now */
9328 	spkt->satapkt_device.satadev_addr = sata_device.satadev_addr;
9329 
9330 	/* 1024k buffer */
9331 	bp = sata_alloc_local_buffer(spx, 1024);
9332 	if (bp == NULL) {
9333 		sata_pkt_free(spx);
9334 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
9335 		sata_log(sata_hba_inst, CE_WARN,
9336 		    "sata_test_atapi_packet_command: "
9337 		    "cannot allocate data buffer");
9338 		return;
9339 	}
9340 	bp_mapin(bp); /* make data buffer accessible */
9341 
9342 	scmd = &spkt->satapkt_cmd;
9343 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
9344 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
9345 
9346 	/* Use synchronous mode */
9347 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
9348 
9349 	/* Synchronous mode, no callback - may be changed by the caller */
9350 	spkt->satapkt_comp = NULL;
9351 	spkt->satapkt_time = sata_default_pkt_time;
9352 
9353 	/* Issue inquiry command - 6 bytes cdb, data transfer, read */
9354 
9355 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
9356 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
9357 
9358 	sata_atapi_packet_cmd_setup(scmd, sdinfo);
9359 
9360 	/* Set-up acdb. */
9361 	scmd->satacmd_acdb_len = sdinfo->satadrv_atapi_cdb_len;
9362 	bzero(scmd->satacmd_acdb, SATA_ATAPI_MAX_CDB_LEN);
9363 	scmd->satacmd_acdb[0] = 0x12;	/* Inquiry */
9364 	scmd->satacmd_acdb[1] = 0x00;
9365 	scmd->satacmd_acdb[2] = 0x00;
9366 	scmd->satacmd_acdb[3] = 0x00;
9367 	scmd->satacmd_acdb[4] = sizeof (struct scsi_inquiry);
9368 	scmd->satacmd_acdb[5] = 0x00;
9369 
9370 	sata_fixed_sense_data_preset(
9371 	    (struct scsi_extended_sense *)scmd->satacmd_rqsense);
9372 
9373 	/* Transfer command to HBA */
9374 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9375 	if (sata_hba_start(spx, &rval) != 0) {
9376 		/* Pkt not accepted for execution */
9377 		sata_log(sata_hba_inst, CE_WARN,
9378 		    "sata_test_atapi_packet_command: "
9379 		    "Packet not accepted for execution - ret: %02x", rval);
9380 		mutex_exit(
9381 		    &SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9382 		goto cleanup;
9383 	}
9384 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
9385 
9386 	if (spx->txlt_buf_dma_handle != NULL) {
9387 		/*
9388 		 * Sync buffer. Handle is in usual place in translate struct.
9389 		 */
9390 		rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
9391 		    DDI_DMA_SYNC_FORCPU);
9392 		ASSERT(rval == DDI_SUCCESS);
9393 	}
9394 	if (spkt->satapkt_reason == SATA_PKT_COMPLETED) {
9395 		sata_log(sata_hba_inst, CE_WARN,
9396 		    "sata_test_atapi_packet_command: "
9397 		    "Packet completed successfully");
9398 		/*
9399 		 * Normal completion - show inquiry data
9400 		 */
9401 		sata_show_inqry_data((uint8_t *)bp->b_un.b_addr);
9402 	} else {
9403 		/*
9404 		 * Something went wrong - analyze return - check rqsense data
9405 		 */
9406 		if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR) {
9407 			/*
9408 			 * ARQ data hopefull show something other than NO SENSE
9409 			 */
9410 			rqsp = scmd->satacmd_rqsense;
9411 			sata_log(spx->txlt_sata_hba_inst, CE_WARN,
9412 			    "ATAPI packet completion reason: %02x\n"
9413 			    "RQSENSE:  %02x %02x %02x %02x %02x %02x "
9414 			    "          %02x %02x %02x %02x %02x %02x "
9415 			    "          %02x %02x %02x %02x %02x %02x\n",
9416 			    spkt->satapkt_reason,
9417 			    rqsp[0], rqsp[1], rqsp[2], rqsp[3],
9418 			    rqsp[4], rqsp[5], rqsp[6], rqsp[7],
9419 			    rqsp[8], rqsp[9], rqsp[10], rqsp[11],
9420 			    rqsp[12], rqsp[13], rqsp[14], rqsp[15],
9421 			    rqsp[16], rqsp[17]);
9422 		} else {
9423 			switch (spkt->satapkt_reason) {
9424 			case SATA_PKT_PORT_ERROR:
9425 				sata_log(sata_hba_inst, CE_WARN,
9426 				    "sata_test_atapi_packet_command: "
9427 				    "packet reason: port error\n");
9428 				break;
9429 
9430 			case SATA_PKT_TIMEOUT:
9431 				sata_log(sata_hba_inst, CE_WARN,
9432 				    "sata_test_atapi_packet_command: "
9433 				    "packet reason: timeout\n");
9434 				break;
9435 
9436 			case SATA_PKT_ABORTED:
9437 				sata_log(sata_hba_inst, CE_WARN,
9438 				    "sata_test_atapi_packet_command: "
9439 				    "packet reason: aborted\n");
9440 				break;
9441 
9442 			case SATA_PKT_RESET:
9443 				sata_log(sata_hba_inst, CE_WARN,
9444 				    "sata_test_atapi_packet_command: "
9445 				    "packet reason: reset\n");
9446 				break;
9447 			default:
9448 				sata_log(sata_hba_inst, CE_WARN,
9449 				    "sata_test_atapi_packet_command: "
9450 				    "invalid packet reason: %02x\n",
9451 				    spkt->satapkt_reason);
9452 				break;
9453 			}
9454 		}
9455 	}
9456 cleanup:
9457 	sata_free_local_buffer(spx);
9458 	sata_pkt_free(spx);
9459 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
9460 }
9461 
9462 #endif /* SATA_DEBUG */
9463 #endif /* 1 */
9464 
9465 
9466 /* ************************** LOCAL HELPER FUNCTIONS *********************** */
9467 
9468 /*
9469  * Validate sata_tran info
9470  * SATA_FAILURE returns if structure is inconsistent or structure revision
9471  * does not match one used by the framework.
9472  *
9473  * Returns SATA_SUCCESS if sata_hba_tran has matching revision and contains
9474  * required function pointers.
9475  * Returns SATA_FAILURE otherwise.
9476  */
9477 static int
9478 sata_validate_sata_hba_tran(dev_info_t *dip, sata_hba_tran_t *sata_tran)
9479 {
9480 	/*
9481 	 * SATA_TRAN_HBA_REV is the current (highest) revision number
9482 	 * of the SATA interface.
9483 	 */
9484 	if (sata_tran->sata_tran_hba_rev > SATA_TRAN_HBA_REV) {
9485 		sata_log(NULL, CE_WARN,
9486 		    "sata: invalid sata_hba_tran version %d for driver %s",
9487 		    sata_tran->sata_tran_hba_rev, ddi_driver_name(dip));
9488 		return (SATA_FAILURE);
9489 	}
9490 
9491 	if (dip != sata_tran->sata_tran_hba_dip) {
9492 		SATA_LOG_D((NULL, CE_WARN,
9493 		    "sata: inconsistent sata_tran_hba_dip "
9494 		    "%p / %p", sata_tran->sata_tran_hba_dip, dip));
9495 		return (SATA_FAILURE);
9496 	}
9497 
9498 	if (sata_tran->sata_tran_probe_port == NULL ||
9499 	    sata_tran->sata_tran_start == NULL ||
9500 	    sata_tran->sata_tran_abort == NULL ||
9501 	    sata_tran->sata_tran_reset_dport == NULL ||
9502 	    sata_tran->sata_tran_hotplug_ops == NULL ||
9503 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_activate == NULL ||
9504 	    sata_tran->sata_tran_hotplug_ops->sata_tran_port_deactivate ==
9505 	    NULL) {
9506 		SATA_LOG_D((NULL, CE_WARN, "sata: sata_hba_tran missing "
9507 		    "required functions"));
9508 	}
9509 	return (SATA_SUCCESS);
9510 }
9511 
9512 /*
9513  * Remove HBA instance from sata_hba_list.
9514  */
9515 static void
9516 sata_remove_hba_instance(dev_info_t *dip)
9517 {
9518 	sata_hba_inst_t	*sata_hba_inst;
9519 
9520 	mutex_enter(&sata_mutex);
9521 	for (sata_hba_inst = sata_hba_list;
9522 	    sata_hba_inst != (struct sata_hba_inst *)NULL;
9523 	    sata_hba_inst = sata_hba_inst->satahba_next) {
9524 		if (sata_hba_inst->satahba_dip == dip)
9525 			break;
9526 	}
9527 
9528 	if (sata_hba_inst == (struct sata_hba_inst *)NULL) {
9529 #ifdef SATA_DEBUG
9530 		cmn_err(CE_WARN, "sata_remove_hba_instance: "
9531 		    "unknown HBA instance\n");
9532 #endif
9533 		ASSERT(FALSE);
9534 	}
9535 	if (sata_hba_inst == sata_hba_list) {
9536 		sata_hba_list = sata_hba_inst->satahba_next;
9537 		if (sata_hba_list) {
9538 			sata_hba_list->satahba_prev =
9539 			    (struct sata_hba_inst *)NULL;
9540 		}
9541 		if (sata_hba_inst == sata_hba_list_tail) {
9542 			sata_hba_list_tail = NULL;
9543 		}
9544 	} else if (sata_hba_inst == sata_hba_list_tail) {
9545 		sata_hba_list_tail = sata_hba_inst->satahba_prev;
9546 		if (sata_hba_list_tail) {
9547 			sata_hba_list_tail->satahba_next =
9548 			    (struct sata_hba_inst *)NULL;
9549 		}
9550 	} else {
9551 		sata_hba_inst->satahba_prev->satahba_next =
9552 		    sata_hba_inst->satahba_next;
9553 		sata_hba_inst->satahba_next->satahba_prev =
9554 		    sata_hba_inst->satahba_prev;
9555 	}
9556 	mutex_exit(&sata_mutex);
9557 }
9558 
9559 /*
9560  * Probe all SATA ports of the specified HBA instance.
9561  * The assumption is that there are no target and attachment point minor nodes
9562  * created by the boot subsystems, so we do not need to prune device tree.
9563  *
9564  * This function is called only from sata_hba_attach(). It does not have to
9565  * be protected by controller mutex, because the hba_attached flag is not set
9566  * yet and no one would be touching this HBA instance other than this thread.
9567  * Determines if port is active and what type of the device is attached
9568  * (if any). Allocates necessary structures for each port.
9569  *
9570  * An AP (Attachement Point) node is created for each SATA device port even
9571  * when there is no device attached.
9572  */
9573 
9574 static 	void
9575 sata_probe_ports(sata_hba_inst_t *sata_hba_inst)
9576 {
9577 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9578 	int			ncport;
9579 	sata_cport_info_t 	*cportinfo;
9580 	sata_drive_info_t	*drive;
9581 	sata_device_t		sata_device;
9582 	int			rval;
9583 	dev_t			minor_number;
9584 	char			name[16];
9585 	clock_t			start_time, cur_time;
9586 
9587 	/*
9588 	 * Probe controller ports first, to find port status and
9589 	 * any port multiplier attached.
9590 	 */
9591 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
9592 		/* allocate cport structure */
9593 		cportinfo = kmem_zalloc(sizeof (sata_cport_info_t), KM_SLEEP);
9594 		ASSERT(cportinfo != NULL);
9595 		mutex_init(&cportinfo->cport_mutex, NULL, MUTEX_DRIVER, NULL);
9596 
9597 		mutex_enter(&cportinfo->cport_mutex);
9598 
9599 		cportinfo->cport_addr.cport = ncport;
9600 		cportinfo->cport_addr.pmport = 0;
9601 		cportinfo->cport_addr.qual = SATA_ADDR_CPORT;
9602 		cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
9603 		cportinfo->cport_state |= SATA_STATE_PROBING;
9604 		SATA_CPORT_INFO(sata_hba_inst, ncport) = cportinfo;
9605 
9606 		/*
9607 		 * Regardless if a port is usable or not, create
9608 		 * an attachment point
9609 		 */
9610 		mutex_exit(&cportinfo->cport_mutex);
9611 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
9612 		    ncport, 0, SATA_ADDR_CPORT);
9613 		(void) sprintf(name, "%d", ncport);
9614 		if (ddi_create_minor_node(dip, name, S_IFCHR,
9615 		    minor_number, DDI_NT_SATA_ATTACHMENT_POINT, 0) !=
9616 		    DDI_SUCCESS) {
9617 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
9618 			    "cannot create SATA attachment point for port %d",
9619 			    ncport);
9620 		}
9621 
9622 		/* Probe port */
9623 		start_time = ddi_get_lbolt();
9624 	reprobe_cport:
9625 		sata_device.satadev_addr.cport = ncport;
9626 		sata_device.satadev_addr.pmport = 0;
9627 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
9628 		sata_device.satadev_rev = SATA_DEVICE_REV;
9629 
9630 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9631 		    (dip, &sata_device);
9632 
9633 		mutex_enter(&cportinfo->cport_mutex);
9634 		cportinfo->cport_scr = sata_device.satadev_scr;
9635 		if (rval != SATA_SUCCESS) {
9636 			/* Something went wrong? Fail the port */
9637 			cportinfo->cport_state = SATA_PSTATE_FAILED;
9638 			mutex_exit(&cportinfo->cport_mutex);
9639 			continue;
9640 		}
9641 		cportinfo->cport_state &= ~SATA_STATE_PROBING;
9642 		cportinfo->cport_state |= SATA_STATE_PROBED;
9643 		cportinfo->cport_dev_type = sata_device.satadev_type;
9644 
9645 		cportinfo->cport_state |= SATA_STATE_READY;
9646 		if (cportinfo->cport_dev_type == SATA_DTYPE_NONE) {
9647 			mutex_exit(&cportinfo->cport_mutex);
9648 			continue;
9649 		}
9650 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
9651 			/*
9652 			 * There is some device attached.
9653 			 * Allocate device info structure
9654 			 */
9655 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) == NULL) {
9656 				mutex_exit(&cportinfo->cport_mutex);
9657 				SATA_CPORTINFO_DRV_INFO(cportinfo) =
9658 				    kmem_zalloc(sizeof (sata_drive_info_t),
9659 				    KM_SLEEP);
9660 				mutex_enter(&cportinfo->cport_mutex);
9661 			}
9662 			drive = SATA_CPORTINFO_DRV_INFO(cportinfo);
9663 			drive->satadrv_addr = cportinfo->cport_addr;
9664 			drive->satadrv_addr.qual = SATA_ADDR_DCPORT;
9665 			drive->satadrv_type = cportinfo->cport_dev_type;
9666 			drive->satadrv_state = SATA_STATE_UNKNOWN;
9667 
9668 			mutex_exit(&cportinfo->cport_mutex);
9669 			if (sata_add_device(dip, sata_hba_inst, &sata_device) !=
9670 			    SATA_SUCCESS) {
9671 				/*
9672 				 * Plugged device was not correctly identified.
9673 				 * Retry, within a SATA_DEV_IDENTIFY_TIMEOUT
9674 				 */
9675 				cur_time = ddi_get_lbolt();
9676 				if ((cur_time - start_time) <
9677 				    drv_usectohz(SATA_DEV_IDENTIFY_TIMEOUT)) {
9678 					/* sleep for a while */
9679 					delay(drv_usectohz(
9680 					    SATA_DEV_RETRY_DLY));
9681 					goto reprobe_cport;
9682 				}
9683 			}
9684 		} else { /* SATA_DTYPE_PMULT */
9685 			mutex_exit(&cportinfo->cport_mutex);
9686 
9687 			/* Allocate sata_pmult_info and sata_pmport_info */
9688 			if (sata_alloc_pmult(sata_hba_inst, &sata_device) !=
9689 			    SATA_SUCCESS)
9690 				continue;
9691 
9692 			/* Log the information of the port multiplier */
9693 			sata_show_pmult_info(sata_hba_inst, &sata_device);
9694 
9695 			/* Probe its pmports */
9696 			sata_probe_pmports(sata_hba_inst, ncport);
9697 		}
9698 	}
9699 }
9700 
9701 /*
9702  * Probe all device ports behind a port multiplier.
9703  *
9704  * PMult-related structure should be allocated before by sata_alloc_pmult().
9705  *
9706  * NOTE1: Only called from sata_probe_ports()
9707  * NOTE2: No mutex should be hold.
9708  */
9709 static void
9710 sata_probe_pmports(sata_hba_inst_t *sata_hba_inst, uint8_t ncport)
9711 {
9712 	dev_info_t		*dip = SATA_DIP(sata_hba_inst);
9713 	sata_pmult_info_t	*pmultinfo = NULL;
9714 	sata_pmport_info_t 	*pmportinfo = NULL;
9715 	sata_drive_info_t	*drive = NULL;
9716 	sata_device_t		sata_device;
9717 
9718 	clock_t			start_time, cur_time;
9719 	int			npmport;
9720 	int			rval;
9721 
9722 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, ncport);
9723 
9724 	/* Probe Port Multiplier ports */
9725 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports; npmport++) {
9726 		pmportinfo = pmultinfo->pmult_dev_port[npmport];
9727 		start_time = ddi_get_lbolt();
9728 reprobe_pmport:
9729 		sata_device.satadev_addr.cport = ncport;
9730 		sata_device.satadev_addr.pmport = npmport;
9731 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
9732 		sata_device.satadev_rev = SATA_DEVICE_REV;
9733 
9734 		/* Let HBA driver probe it. */
9735 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
9736 		    (dip, &sata_device);
9737 		mutex_enter(&pmportinfo->pmport_mutex);
9738 
9739 		pmportinfo->pmport_scr = sata_device.satadev_scr;
9740 
9741 		if (rval != SATA_SUCCESS) {
9742 			pmportinfo->pmport_state =
9743 			    SATA_PSTATE_FAILED;
9744 			mutex_exit(&pmportinfo->pmport_mutex);
9745 			continue;
9746 		}
9747 		pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
9748 		pmportinfo->pmport_state |= SATA_STATE_PROBED;
9749 		pmportinfo->pmport_dev_type = sata_device.satadev_type;
9750 
9751 		pmportinfo->pmport_state |= SATA_STATE_READY;
9752 		if (pmportinfo->pmport_dev_type ==
9753 		    SATA_DTYPE_NONE) {
9754 			SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
9755 			    "no device found at port %d:%d", ncport, npmport);
9756 			mutex_exit(&pmportinfo->pmport_mutex);
9757 			continue;
9758 		}
9759 		/* Port multipliers cannot be chained */
9760 		ASSERT(pmportinfo->pmport_dev_type != SATA_DTYPE_PMULT);
9761 		/*
9762 		 * There is something attached to Port
9763 		 * Multiplier device port
9764 		 * Allocate device info structure
9765 		 */
9766 		if (pmportinfo->pmport_sata_drive == NULL) {
9767 			mutex_exit(&pmportinfo->pmport_mutex);
9768 			pmportinfo->pmport_sata_drive =
9769 			    kmem_zalloc(sizeof (sata_drive_info_t), KM_SLEEP);
9770 			mutex_enter(&pmportinfo->pmport_mutex);
9771 		}
9772 		drive = pmportinfo->pmport_sata_drive;
9773 		drive->satadrv_addr.cport = pmportinfo->pmport_addr.cport;
9774 		drive->satadrv_addr.pmport = npmport;
9775 		drive->satadrv_addr.qual = SATA_ADDR_DPMPORT;
9776 		drive->satadrv_type = pmportinfo-> pmport_dev_type;
9777 		drive->satadrv_state = SATA_STATE_UNKNOWN;
9778 
9779 		mutex_exit(&pmportinfo->pmport_mutex);
9780 		rval = sata_add_device(dip, sata_hba_inst, &sata_device);
9781 
9782 		if (rval != SATA_SUCCESS) {
9783 			/*
9784 			 * Plugged device was not correctly identified.
9785 			 * Retry, within the SATA_DEV_IDENTIFY_TIMEOUT
9786 			 */
9787 			cur_time = ddi_get_lbolt();
9788 			if ((cur_time - start_time) < drv_usectohz(
9789 			    SATA_DEV_IDENTIFY_TIMEOUT)) {
9790 				/* sleep for a while */
9791 				delay(drv_usectohz(SATA_DEV_RETRY_DLY));
9792 				goto reprobe_pmport;
9793 			}
9794 		}
9795 	}
9796 }
9797 
9798 /*
9799  * Add SATA device for specified HBA instance & port (SCSI target
9800  * device nodes).
9801  * This function is called (indirectly) only from sata_hba_attach().
9802  * A target node is created when there is a supported type device attached,
9803  * but may be removed if it cannot be put online.
9804  *
9805  * This function cannot be called from an interrupt context.
9806  *
9807  * Create target nodes for disk, CD/DVD, Tape and ATAPI disk devices
9808  *
9809  * Returns SATA_SUCCESS when port/device was fully processed, SATA_FAILURE when
9810  * device identification failed - adding a device could be retried.
9811  *
9812  */
9813 static 	int
9814 sata_add_device(dev_info_t *pdip, sata_hba_inst_t *sata_hba_inst,
9815     sata_device_t *sata_device)
9816 {
9817 	sata_cport_info_t 	*cportinfo;
9818 	sata_pmult_info_t	*pminfo;
9819 	sata_pmport_info_t	*pmportinfo;
9820 	dev_info_t		*cdip;		/* child dip */
9821 	sata_address_t		*saddr = &sata_device->satadev_addr;
9822 	uint8_t			cport, pmport;
9823 	int			rval;
9824 
9825 	cport = saddr->cport;
9826 	pmport = saddr->pmport;
9827 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
9828 	ASSERT(cportinfo->cport_dev_type != SATA_DTYPE_NONE);
9829 
9830 	/*
9831 	 * Some device is attached to a controller port.
9832 	 * We rely on controllers distinquishing between no-device,
9833 	 * attached port multiplier and other kind of attached device.
9834 	 * We need to get Identify Device data and determine
9835 	 * positively the dev type before trying to attach
9836 	 * the target driver.
9837 	 */
9838 	sata_device->satadev_rev = SATA_DEVICE_REV;
9839 	switch (saddr->qual) {
9840 	case SATA_ADDR_CPORT:
9841 		/*
9842 		 * Add a non-port-multiplier device at controller port.
9843 		 */
9844 		saddr->qual = SATA_ADDR_DCPORT;
9845 
9846 		rval = sata_probe_device(sata_hba_inst, sata_device);
9847 		if (rval != SATA_SUCCESS ||
9848 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN)
9849 			return (SATA_FAILURE);
9850 
9851 		mutex_enter(&cportinfo->cport_mutex);
9852 		sata_show_drive_info(sata_hba_inst,
9853 		    SATA_CPORTINFO_DRV_INFO(cportinfo));
9854 
9855 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
9856 			/*
9857 			 * Could not determine device type or
9858 			 * a device is not supported.
9859 			 * Degrade this device to unknown.
9860 			 */
9861 			cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
9862 			mutex_exit(&cportinfo->cport_mutex);
9863 			return (SATA_SUCCESS);
9864 		}
9865 		cportinfo->cport_dev_type = sata_device->satadev_type;
9866 		cportinfo->cport_tgtnode_clean = B_TRUE;
9867 		mutex_exit(&cportinfo->cport_mutex);
9868 
9869 		/*
9870 		 * Initialize device to the desired state. Even if it
9871 		 * fails, the device will still attach but syslog
9872 		 * will show the warning.
9873 		 */
9874 		if (sata_initialize_device(sata_hba_inst,
9875 		    SATA_CPORTINFO_DRV_INFO(cportinfo)) != SATA_SUCCESS) {
9876 			/* Retry */
9877 			rval = sata_initialize_device(sata_hba_inst,
9878 			    SATA_CPORTINFO_DRV_INFO(cportinfo));
9879 
9880 			if (rval == SATA_RETRY)
9881 				sata_log(sata_hba_inst, CE_WARN,
9882 				    "SATA device at port %d - "
9883 				    "default device features could not be set."
9884 				    " Device may not operate as expected.",
9885 				    cport);
9886 		}
9887 
9888 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
9889 		if (cdip == NULL) {
9890 			/*
9891 			 * Attaching target node failed.
9892 			 * We retain sata_drive_info structure...
9893 			 */
9894 			return (SATA_SUCCESS);
9895 		}
9896 
9897 		mutex_enter(&cportinfo->cport_mutex);
9898 		(SATA_CPORTINFO_DRV_INFO(cportinfo))->
9899 		    satadrv_state = SATA_STATE_READY;
9900 		mutex_exit(&cportinfo->cport_mutex);
9901 
9902 		break;
9903 
9904 	case SATA_ADDR_PMPORT:
9905 		saddr->qual = SATA_ADDR_DPMPORT;
9906 
9907 		mutex_enter(&cportinfo->cport_mutex);
9908 		/* It must be a Port Multiplier at the controller port */
9909 		ASSERT(cportinfo->cport_dev_type == SATA_DTYPE_PMULT);
9910 
9911 		pminfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
9912 		pmportinfo = pminfo->pmult_dev_port[saddr->pmport];
9913 		mutex_exit(&cportinfo->cport_mutex);
9914 
9915 		rval = sata_probe_device(sata_hba_inst, sata_device);
9916 		if (rval != SATA_SUCCESS ||
9917 		    sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
9918 			return (SATA_FAILURE);
9919 		}
9920 
9921 		mutex_enter(&pmportinfo->pmport_mutex);
9922 		sata_show_drive_info(sata_hba_inst,
9923 		    SATA_PMPORTINFO_DRV_INFO(pmportinfo));
9924 
9925 		if ((sata_device->satadev_type & SATA_VALID_DEV_TYPE) == 0) {
9926 			/*
9927 			 * Could not determine device type.
9928 			 * Degrade this device to unknown.
9929 			 */
9930 			pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
9931 			mutex_exit(&pmportinfo->pmport_mutex);
9932 			return (SATA_SUCCESS);
9933 		}
9934 		pmportinfo->pmport_dev_type = sata_device->satadev_type;
9935 		pmportinfo->pmport_tgtnode_clean = B_TRUE;
9936 		mutex_exit(&pmportinfo->pmport_mutex);
9937 
9938 		/*
9939 		 * Initialize device to the desired state.
9940 		 * Even if it fails, the device will still
9941 		 * attach but syslog will show the warning.
9942 		 */
9943 		if (sata_initialize_device(sata_hba_inst,
9944 		    pmportinfo->pmport_sata_drive) != SATA_SUCCESS) {
9945 			/* Retry */
9946 			rval = sata_initialize_device(sata_hba_inst,
9947 			    pmportinfo->pmport_sata_drive);
9948 
9949 			if (rval == SATA_RETRY)
9950 				sata_log(sata_hba_inst, CE_WARN,
9951 				    "SATA device at port %d:%d - "
9952 				    "default device features could not be set."
9953 				    " Device may not operate as expected.",
9954 				    cport, pmport);
9955 		}
9956 
9957 		cdip = sata_create_target_node(pdip, sata_hba_inst, saddr);
9958 		if (cdip == NULL) {
9959 			/*
9960 			 * Attaching target node failed.
9961 			 * We retain sata_drive_info structure...
9962 			 */
9963 			return (SATA_SUCCESS);
9964 		}
9965 		mutex_enter(&pmportinfo->pmport_mutex);
9966 		pmportinfo->pmport_sata_drive->satadrv_state |=
9967 		    SATA_STATE_READY;
9968 		mutex_exit(&pmportinfo->pmport_mutex);
9969 
9970 		break;
9971 
9972 	default:
9973 		return (SATA_FAILURE);
9974 	}
9975 
9976 	return (SATA_SUCCESS);
9977 }
9978 
9979 /*
9980  * Clean up target node at specific address.
9981  *
9982  * NOTE: No Mutex should be hold.
9983  */
9984 static int
9985 sata_offline_device(sata_hba_inst_t *sata_hba_inst,
9986     sata_device_t *sata_device, sata_drive_info_t *sdinfo)
9987 {
9988 	uint8_t cport, pmport, qual;
9989 	dev_info_t *tdip;
9990 
9991 	cport = sata_device->satadev_addr.cport;
9992 	pmport = sata_device->satadev_addr.pmport;
9993 	qual = sata_device->satadev_addr.qual;
9994 
9995 	if (qual == SATA_ADDR_DCPORT) {
9996 		SATA_LOG_D((sata_hba_inst, CE_WARN,
9997 		    "sata_hba_ioctl: disconnect device at port %d", cport));
9998 	} else {
9999 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10000 		    "sata_hba_ioctl: disconnect device at port %d:%d",
10001 		    cport, pmport));
10002 	}
10003 
10004 	/* We are addressing attached device, not a port */
10005 	sata_device->satadev_addr.qual =
10006 	    sdinfo->satadrv_addr.qual;
10007 	tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
10008 	    &sata_device->satadev_addr);
10009 	if (tdip != NULL && ndi_devi_offline(tdip,
10010 	    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10011 		/*
10012 		 * Problem :
10013 		 * The target node remained attached.
10014 		 * This happens when the device file was open
10015 		 * or a node was waiting for resources.
10016 		 * Cannot do anything about it.
10017 		 */
10018 		if (qual == SATA_ADDR_DCPORT) {
10019 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10020 			    "sata_hba_ioctl: disconnect: could "
10021 			    "not unconfigure device before "
10022 			    "disconnecting the SATA port %d",
10023 			    cport));
10024 		} else {
10025 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10026 			    "sata_hba_ioctl: disconnect: could "
10027 			    "not unconfigure device before "
10028 			    "disconnecting the SATA port %d:%d",
10029 			    cport, pmport));
10030 		}
10031 		/*
10032 		 * Set DEVICE REMOVED state in the target
10033 		 * node. It will prevent access to the device
10034 		 * even when a new device is attached, until
10035 		 * the old target node is released, removed and
10036 		 * recreated for a new  device.
10037 		 */
10038 		sata_set_device_removed(tdip);
10039 
10040 		/*
10041 		 * Instruct event daemon to try the target
10042 		 * node cleanup later.
10043 		 */
10044 		sata_set_target_node_cleanup(
10045 		    sata_hba_inst, &sata_device->satadev_addr);
10046 	}
10047 
10048 
10049 	return (SATA_SUCCESS);
10050 }
10051 
10052 
10053 /*
10054  * Create scsi target node for attached device, create node properties and
10055  * attach the node.
10056  * The node could be removed if the device onlining fails.
10057  *
10058  * A dev_info_t pointer is returned if operation is successful, NULL is
10059  * returned otherwise.
10060  */
10061 
10062 static dev_info_t *
10063 sata_create_target_node(dev_info_t *dip, sata_hba_inst_t *sata_hba_inst,
10064 			sata_address_t *sata_addr)
10065 {
10066 	dev_info_t *cdip = NULL;
10067 	int rval;
10068 	char *nname = NULL;
10069 	char **compatible = NULL;
10070 	int ncompatible;
10071 	struct scsi_inquiry inq;
10072 	sata_device_t sata_device;
10073 	sata_drive_info_t *sdinfo;
10074 	int target;
10075 	int i;
10076 
10077 	sata_device.satadev_rev = SATA_DEVICE_REV;
10078 	sata_device.satadev_addr = *sata_addr;
10079 
10080 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, sata_addr->cport)));
10081 
10082 	sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
10083 
10084 	target = SATA_TO_SCSI_TARGET(sata_addr->cport,
10085 	    sata_addr->pmport, sata_addr->qual);
10086 
10087 	if (sdinfo == NULL) {
10088 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10089 		    sata_addr->cport)));
10090 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10091 		    "sata_create_target_node: no sdinfo for target %x",
10092 		    target));
10093 		return (NULL);
10094 	}
10095 
10096 	/*
10097 	 * create or get scsi inquiry data, expected by
10098 	 * scsi_hba_nodename_compatible_get()
10099 	 * SATA hard disks get Identify Data translated into Inguiry Data.
10100 	 * ATAPI devices respond directly to Inquiry request.
10101 	 */
10102 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
10103 		sata_identdev_to_inquiry(sata_hba_inst, sdinfo,
10104 		    (uint8_t *)&inq);
10105 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10106 		    sata_addr->cport)));
10107 	} else { /* Assume supported ATAPI device */
10108 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
10109 		    sata_addr->cport)));
10110 		if (sata_get_atapi_inquiry_data(sata_hba_inst, sata_addr,
10111 		    &inq) == SATA_FAILURE)
10112 			return (NULL);
10113 		/*
10114 		 * Save supported ATAPI transport version
10115 		 */
10116 		sdinfo->satadrv_atapi_trans_ver =
10117 		    SATA_ATAPI_TRANS_VERSION(&inq);
10118 	}
10119 
10120 	/* determine the node name and compatible */
10121 	scsi_hba_nodename_compatible_get(&inq, NULL,
10122 	    inq.inq_dtype, NULL, &nname, &compatible, &ncompatible);
10123 
10124 #ifdef SATA_DEBUG
10125 	if (sata_debug_flags & SATA_DBG_NODES) {
10126 		if (nname == NULL) {
10127 			cmn_err(CE_NOTE, "sata_create_target_node: "
10128 			    "cannot determine nodename for target %d\n",
10129 			    target);
10130 		} else {
10131 			cmn_err(CE_WARN, "sata_create_target_node: "
10132 			    "target %d nodename: %s\n", target, nname);
10133 		}
10134 		if (compatible == NULL) {
10135 			cmn_err(CE_WARN,
10136 			    "sata_create_target_node: no compatible name\n");
10137 		} else {
10138 			for (i = 0; i < ncompatible; i++) {
10139 				cmn_err(CE_WARN, "sata_create_target_node: "
10140 				    "compatible name: %s\n", compatible[i]);
10141 			}
10142 		}
10143 	}
10144 #endif
10145 
10146 	/* if nodename can't be determined, log error and exit */
10147 	if (nname == NULL) {
10148 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10149 		    "sata_create_target_node: cannot determine nodename "
10150 		    "for target %d\n", target));
10151 		scsi_hba_nodename_compatible_free(nname, compatible);
10152 		return (NULL);
10153 	}
10154 	/*
10155 	 * Create scsi target node
10156 	 */
10157 	ndi_devi_alloc_sleep(dip, nname, (pnode_t)DEVI_SID_NODEID, &cdip);
10158 	rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10159 	    "device-type", "scsi");
10160 
10161 	if (rval != DDI_PROP_SUCCESS) {
10162 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10163 		    "updating device_type prop failed %d", rval));
10164 		goto fail;
10165 	}
10166 
10167 	/*
10168 	 * Create target node properties: target & lun
10169 	 */
10170 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "target", target);
10171 	if (rval != DDI_PROP_SUCCESS) {
10172 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10173 		    "updating target prop failed %d", rval));
10174 		goto fail;
10175 	}
10176 	rval = ndi_prop_update_int(DDI_DEV_T_NONE, cdip, "lun", 0);
10177 	if (rval != DDI_PROP_SUCCESS) {
10178 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10179 		    "updating target prop failed %d", rval));
10180 		goto fail;
10181 	}
10182 
10183 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
10184 		/*
10185 		 * Add "variant" property
10186 		 */
10187 		rval = ndi_prop_update_string(DDI_DEV_T_NONE, cdip,
10188 		    "variant", "atapi");
10189 		if (rval != DDI_PROP_SUCCESS) {
10190 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10191 			    "sata_create_target_node: variant atapi "
10192 			    "property could not be created: %d", rval));
10193 			goto fail;
10194 		}
10195 	}
10196 	/* decorate the node with compatible */
10197 	if (ndi_prop_update_string_array(DDI_DEV_T_NONE, cdip, "compatible",
10198 	    compatible, ncompatible) != DDI_PROP_SUCCESS) {
10199 		SATA_LOG_D((sata_hba_inst, CE_WARN,
10200 		    "sata_create_target_node: FAIL compatible props cdip 0x%p",
10201 		    (void *)cdip));
10202 		goto fail;
10203 	}
10204 
10205 
10206 	/*
10207 	 * Now, try to attach the driver. If probing of the device fails,
10208 	 * the target node may be removed
10209 	 */
10210 	rval = ndi_devi_online(cdip, NDI_ONLINE_ATTACH);
10211 
10212 	scsi_hba_nodename_compatible_free(nname, compatible);
10213 
10214 	if (rval == NDI_SUCCESS)
10215 		return (cdip);
10216 
10217 	/* target node was removed - are we sure? */
10218 	return (NULL);
10219 
10220 fail:
10221 	scsi_hba_nodename_compatible_free(nname, compatible);
10222 	ddi_prop_remove_all(cdip);
10223 	rval = ndi_devi_free(cdip);
10224 	if (rval != NDI_SUCCESS) {
10225 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_create_target_node: "
10226 		    "node removal failed %d", rval));
10227 	}
10228 	sata_log(sata_hba_inst, CE_WARN, "sata_create_target_node: "
10229 	    "cannot create target node for SATA device at port %d",
10230 	    sata_addr->cport);
10231 	return (NULL);
10232 }
10233 
10234 /*
10235  * Remove a target node.
10236  */
10237 static void
10238 sata_remove_target_node(sata_hba_inst_t *sata_hba_inst,
10239 			sata_address_t *sata_addr)
10240 {
10241 	dev_info_t *tdip;
10242 	uint8_t cport = sata_addr->cport;
10243 	uint8_t pmport = sata_addr->pmport;
10244 	uint8_t qual = sata_addr->qual;
10245 
10246 	/* Note the sata daemon uses the address of the port/pmport */
10247 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
10248 
10249 	/* Remove target node */
10250 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), cport, pmport);
10251 	if (tdip != NULL) {
10252 		/*
10253 		 * Target node exists.  Unconfigure device
10254 		 * then remove the target node (one ndi
10255 		 * operation).
10256 		 */
10257 		if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) != NDI_SUCCESS) {
10258 			/*
10259 			 * PROBLEM - no device, but target node remained. This
10260 			 * happens when the file was open or node was waiting
10261 			 * for resources.
10262 			 */
10263 			SATA_LOG_D((sata_hba_inst, CE_WARN,
10264 			    "sata_remove_target_node: "
10265 			    "Failed to remove target node for "
10266 			    "detached SATA device."));
10267 			/*
10268 			 * Set target node state to DEVI_DEVICE_REMOVED. But
10269 			 * re-check first that the node still exists.
10270 			 */
10271 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
10272 			    cport, pmport);
10273 			if (tdip != NULL) {
10274 				sata_set_device_removed(tdip);
10275 				/*
10276 				 * Instruct event daemon to retry the cleanup
10277 				 * later.
10278 				 */
10279 				sata_set_target_node_cleanup(sata_hba_inst,
10280 				    sata_addr);
10281 			}
10282 		}
10283 
10284 		if (qual == SATA_ADDR_CPORT)
10285 			sata_log(sata_hba_inst, CE_WARN,
10286 			    "SATA device detached at port %d", cport);
10287 		else
10288 			sata_log(sata_hba_inst, CE_WARN,
10289 			    "SATA device detached at port %d:%d",
10290 			    cport, pmport);
10291 	}
10292 #ifdef SATA_DEBUG
10293 	else {
10294 		if (qual == SATA_ADDR_CPORT)
10295 			sata_log(sata_hba_inst, CE_WARN,
10296 			    "target node not found at port %d", cport);
10297 		else
10298 			sata_log(sata_hba_inst, CE_WARN,
10299 			    "target node not found at port %d:%d",
10300 			    cport, pmport);
10301 	}
10302 #endif
10303 }
10304 
10305 
10306 /*
10307  * Re-probe sata port, check for a device and attach info
10308  * structures when necessary. Identify Device data is fetched, if possible.
10309  * Assumption: sata address is already validated.
10310  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10311  * the presence of a device and its type.
10312  *
10313  * flag arg specifies that the function should try multiple times to identify
10314  * device type and to initialize it, or it should return immediately on failure.
10315  * SATA_DEV_IDENTIFY_RETRY - retry
10316  * SATA_DEV_IDENTIFY_NORETRY - no retry
10317  *
10318  * SATA_FAILURE is returned if one of the operations failed.
10319  *
10320  * This function cannot be called in interrupt context - it may sleep.
10321  *
10322  * Note: Port multiplier is supported.
10323  */
10324 static int
10325 sata_reprobe_port(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10326     int flag)
10327 {
10328 	sata_cport_info_t *cportinfo;
10329 	sata_pmult_info_t *pmultinfo;
10330 	sata_drive_info_t *sdinfo, *osdinfo;
10331 	boolean_t init_device = B_FALSE;
10332 	int prev_device_type = SATA_DTYPE_NONE;
10333 	int prev_device_settings = 0;
10334 	int prev_device_state = 0;
10335 	clock_t start_time;
10336 	int retry = B_FALSE;
10337 	uint8_t cport = sata_device->satadev_addr.cport;
10338 	int rval_probe, rval_init;
10339 
10340 	/*
10341 	 * If target is pmport, sata_reprobe_pmport() will handle it.
10342 	 */
10343 	if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT ||
10344 	    sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT)
10345 		return (sata_reprobe_pmport(sata_hba_inst, sata_device, flag));
10346 
10347 	/* We only care about host sata cport for now */
10348 	cportinfo = SATA_CPORT_INFO(sata_hba_inst,
10349 	    sata_device->satadev_addr.cport);
10350 
10351 	/*
10352 	 * If a port multiplier was previously attached (we have no idea it
10353 	 * still there or not), sata_reprobe_pmult() will handle it.
10354 	 */
10355 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT)
10356 		return (sata_reprobe_pmult(sata_hba_inst, sata_device, flag));
10357 
10358 	/* Store sata_drive_info when a non-pmult device was attached. */
10359 	osdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10360 	if (osdinfo != NULL) {
10361 		/*
10362 		 * We are re-probing port with a previously attached device.
10363 		 * Save previous device type and settings.
10364 		 */
10365 		prev_device_type = cportinfo->cport_dev_type;
10366 		prev_device_settings = osdinfo->satadrv_settings;
10367 		prev_device_state = osdinfo->satadrv_state;
10368 	}
10369 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
10370 		start_time = ddi_get_lbolt();
10371 		retry = B_TRUE;
10372 	}
10373 retry_probe:
10374 
10375 	/* probe port */
10376 	mutex_enter(&cportinfo->cport_mutex);
10377 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10378 	cportinfo->cport_state |= SATA_STATE_PROBING;
10379 	mutex_exit(&cportinfo->cport_mutex);
10380 
10381 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10382 	    (SATA_DIP(sata_hba_inst), sata_device);
10383 
10384 	mutex_enter(&cportinfo->cport_mutex);
10385 	if (rval_probe != SATA_SUCCESS) {
10386 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10387 		mutex_exit(&cportinfo->cport_mutex);
10388 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_port: "
10389 		    "SATA port %d probing failed",
10390 		    cportinfo->cport_addr.cport));
10391 		return (SATA_FAILURE);
10392 	}
10393 
10394 	/*
10395 	 * update sata port state and set device type
10396 	 */
10397 	sata_update_port_info(sata_hba_inst, sata_device);
10398 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10399 
10400 	/*
10401 	 * Sanity check - Port is active? Is the link active?
10402 	 * Is there any device attached?
10403 	 */
10404 	if ((cportinfo->cport_state &
10405 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10406 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10407 	    SATA_PORT_DEVLINK_UP) {
10408 		/*
10409 		 * Port in non-usable state or no link active/no device.
10410 		 * Free info structure if necessary (direct attached drive
10411 		 * only, for now!
10412 		 */
10413 		sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10414 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10415 		/* Add here differentiation for device attached or not */
10416 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10417 		mutex_exit(&cportinfo->cport_mutex);
10418 		if (sdinfo != NULL)
10419 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10420 		return (SATA_SUCCESS);
10421 	}
10422 
10423 	cportinfo->cport_state |= SATA_STATE_READY;
10424 	cportinfo->cport_state |= SATA_STATE_PROBED;
10425 
10426 	cportinfo->cport_dev_type = sata_device->satadev_type;
10427 	sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
10428 
10429 	/*
10430 	 * If we are re-probing the port, there may be
10431 	 * sata_drive_info structure attached
10432 	 */
10433 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10434 
10435 		/*
10436 		 * There is no device, so remove device info structure,
10437 		 * if necessary.
10438 		 */
10439 		/* Device change: Drive -> None */
10440 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10441 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10442 		if (sdinfo != NULL) {
10443 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10444 			sata_log(sata_hba_inst, CE_WARN,
10445 			    "SATA device detached "
10446 			    "from port %d", cportinfo->cport_addr.cport);
10447 		}
10448 		mutex_exit(&cportinfo->cport_mutex);
10449 		return (SATA_SUCCESS);
10450 
10451 	}
10452 
10453 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10454 
10455 		/* Device (may) change: Drive -> Drive */
10456 		if (sdinfo == NULL) {
10457 			/*
10458 			 * There is some device attached, but there is
10459 			 * no sata_drive_info structure - allocate one
10460 			 */
10461 			mutex_exit(&cportinfo->cport_mutex);
10462 			sdinfo = kmem_zalloc(
10463 			    sizeof (sata_drive_info_t), KM_SLEEP);
10464 			mutex_enter(&cportinfo->cport_mutex);
10465 			/*
10466 			 * Recheck, that the port state did not change when we
10467 			 * released mutex.
10468 			 */
10469 			if (cportinfo->cport_state & SATA_STATE_READY) {
10470 				SATA_CPORTINFO_DRV_INFO(cportinfo) = sdinfo;
10471 				sdinfo->satadrv_addr = cportinfo->cport_addr;
10472 				sdinfo->satadrv_addr.qual = SATA_ADDR_DCPORT;
10473 				sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10474 				sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10475 			} else {
10476 				/*
10477 				 * Port is not in ready state, we
10478 				 * cannot attach a device.
10479 				 */
10480 				mutex_exit(&cportinfo->cport_mutex);
10481 				kmem_free(sdinfo, sizeof (sata_drive_info_t));
10482 				return (SATA_SUCCESS);
10483 			}
10484 			/*
10485 			 * Since we are adding device, presumably new one,
10486 			 * indicate that it  should be initalized,
10487 			 * as well as some internal framework states).
10488 			 */
10489 			init_device = B_TRUE;
10490 		}
10491 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10492 		sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10493 	} else {
10494 		/* Device change: Drive -> PMult */
10495 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10496 		if (sdinfo != NULL) {
10497 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10498 			sata_log(sata_hba_inst, CE_WARN,
10499 			    "SATA device detached "
10500 			    "from port %d", cportinfo->cport_addr.cport);
10501 		}
10502 
10503 		sata_log(sata_hba_inst, CE_WARN,
10504 		    "SATA port multiplier detected at port %d",
10505 		    cportinfo->cport_addr.cport);
10506 
10507 		mutex_exit(&cportinfo->cport_mutex);
10508 		if (sata_alloc_pmult(sata_hba_inst, sata_device) !=
10509 		    SATA_SUCCESS)
10510 			return (SATA_FAILURE);
10511 		sata_show_pmult_info(sata_hba_inst, sata_device);
10512 		mutex_enter(&cportinfo->cport_mutex);
10513 
10514 		/*
10515 		 * Mark all the port multiplier port behind the port
10516 		 * multiplier behind with link events, so that the sata daemon
10517 		 * will update their status.
10518 		 */
10519 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10520 		pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10521 		mutex_exit(&cportinfo->cport_mutex);
10522 		return (SATA_SUCCESS);
10523 	}
10524 	mutex_exit(&cportinfo->cport_mutex);
10525 
10526 	/*
10527 	 * Figure out what kind of device we are really
10528 	 * dealing with. Failure of identifying device does not fail this
10529 	 * function.
10530 	 */
10531 	rval_probe = sata_probe_device(sata_hba_inst, sata_device);
10532 	rval_init = SATA_FAILURE;
10533 	mutex_enter(&cportinfo->cport_mutex);
10534 	if (rval_probe == SATA_SUCCESS) {
10535 		/*
10536 		 * If we are dealing with the same type of a device as before,
10537 		 * restore its settings flags.
10538 		 */
10539 		if (osdinfo != NULL &&
10540 		    sata_device->satadev_type == prev_device_type)
10541 			sdinfo->satadrv_settings = prev_device_settings;
10542 
10543 		mutex_exit(&cportinfo->cport_mutex);
10544 		rval_init = SATA_SUCCESS;
10545 		/* Set initial device features, if necessary */
10546 		if (init_device == B_TRUE) {
10547 			rval_init = sata_initialize_device(sata_hba_inst,
10548 			    sdinfo);
10549 		}
10550 		if (rval_init == SATA_SUCCESS)
10551 			return (rval_init);
10552 		/* else we will retry if retry was asked for */
10553 
10554 	} else {
10555 		/*
10556 		 * If there was some device info before we probe the device,
10557 		 * restore previous device setting, so we can retry from scratch
10558 		 * later. Providing, of course, that device has not disapear
10559 		 * during probing process.
10560 		 */
10561 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
10562 			if (osdinfo != NULL) {
10563 				cportinfo->cport_dev_type = prev_device_type;
10564 				sdinfo->satadrv_type = prev_device_type;
10565 				sdinfo->satadrv_state = prev_device_state;
10566 			}
10567 		} else {
10568 			/* device is gone */
10569 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10570 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10571 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
10572 			mutex_exit(&cportinfo->cport_mutex);
10573 			return (SATA_SUCCESS);
10574 		}
10575 		mutex_exit(&cportinfo->cport_mutex);
10576 	}
10577 
10578 	if (retry) {
10579 		clock_t cur_time = ddi_get_lbolt();
10580 		/*
10581 		 * A device was not successfully identified or initialized.
10582 		 * Track retry time for device identification.
10583 		 */
10584 		if ((cur_time - start_time) <
10585 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10586 			/* sleep for a while */
10587 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10588 			goto retry_probe;
10589 		}
10590 		/* else no more retries */
10591 		mutex_enter(&cportinfo->cport_mutex);
10592 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
10593 			if (rval_init == SATA_RETRY) {
10594 				/*
10595 				 * Setting drive features have failed, but
10596 				 * because the drive is still accessible,
10597 				 * keep it and emit a warning message.
10598 				 */
10599 				sata_log(sata_hba_inst, CE_WARN,
10600 				    "SATA device at port %d - desired "
10601 				    "drive features could not be set. "
10602 				    "Device may not operate as expected.",
10603 				    cportinfo->cport_addr.cport);
10604 			} else {
10605 				SATA_CPORTINFO_DRV_INFO(cportinfo)->
10606 				    satadrv_state = SATA_DSTATE_FAILED;
10607 			}
10608 		}
10609 		mutex_exit(&cportinfo->cport_mutex);
10610 	}
10611 	return (SATA_SUCCESS);
10612 }
10613 
10614 /*
10615  * Reprobe a controller port that connected to a port multiplier.
10616  *
10617  * NOTE: No Mutex should be hold.
10618  */
10619 static int
10620 sata_reprobe_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10621     int flag)
10622 {
10623 	_NOTE(ARGUNUSED(flag))
10624 	sata_cport_info_t *cportinfo;
10625 	sata_pmult_info_t *pmultinfo;
10626 	uint8_t cport = sata_device->satadev_addr.cport;
10627 	int rval_probe;
10628 
10629 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10630 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
10631 
10632 	/* probe port */
10633 	mutex_enter(&cportinfo->cport_mutex);
10634 	cportinfo->cport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10635 	cportinfo->cport_state |= SATA_STATE_PROBING;
10636 	mutex_exit(&cportinfo->cport_mutex);
10637 
10638 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10639 	    (SATA_DIP(sata_hba_inst), sata_device);
10640 
10641 	mutex_enter(&cportinfo->cport_mutex);
10642 	if (rval_probe != SATA_SUCCESS) {
10643 		cportinfo->cport_state = SATA_PSTATE_FAILED;
10644 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmult: "
10645 		    "SATA port %d probing failed", cport));
10646 		sata_log(sata_hba_inst, CE_WARN,
10647 		    "SATA port multiplier detached at port %d", cport);
10648 		mutex_exit(&cportinfo->cport_mutex);
10649 		sata_free_pmult(sata_hba_inst, sata_device);
10650 		return (SATA_FAILURE);
10651 	}
10652 
10653 	/*
10654 	 * update sata port state and set device type
10655 	 */
10656 	sata_update_port_info(sata_hba_inst, sata_device);
10657 	cportinfo->cport_state &= ~SATA_STATE_PROBING;
10658 	cportinfo->cport_state |= SATA_STATE_PROBED;
10659 
10660 	/*
10661 	 * Sanity check - Port is active? Is the link active?
10662 	 * Is there any device attached?
10663 	 */
10664 	if ((cportinfo->cport_state &
10665 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10666 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10667 	    SATA_PORT_DEVLINK_UP ||
10668 	    (sata_device->satadev_type == SATA_DTYPE_NONE)) {
10669 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
10670 		mutex_exit(&cportinfo->cport_mutex);
10671 		sata_free_pmult(sata_hba_inst, sata_device);
10672 		sata_log(sata_hba_inst, CE_WARN,
10673 		    "SATA port multiplier detached at port %d", cport);
10674 		return (SATA_SUCCESS);
10675 	}
10676 
10677 	/*
10678 	 * Device changed: PMult -> Non-PMult
10679 	 *
10680 	 * This situation is uncommon, most possibly being caused by errors
10681 	 * after which the port multiplier is not correct initialized and
10682 	 * recognized. In that case the new device will be marked as unknown
10683 	 * and will not be automatically probed in this routine. Instead
10684 	 * system administrator could manually restart it via cfgadm(1M).
10685 	 */
10686 	if (sata_device->satadev_type != SATA_DTYPE_PMULT) {
10687 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10688 		mutex_exit(&cportinfo->cport_mutex);
10689 		sata_free_pmult(sata_hba_inst, sata_device);
10690 		sata_log(sata_hba_inst, CE_WARN,
10691 		    "SATA port multiplier detached at port %d", cport);
10692 		return (SATA_FAILURE);
10693 	}
10694 
10695 	/*
10696 	 * Now we know it is a port multiplier. However, if this is not the
10697 	 * previously attached port multiplier - they may have different
10698 	 * pmport numbers - we need to re-allocate data structures for every
10699 	 * pmport and drive.
10700 	 *
10701 	 * Port multipliers of the same model have identical values in these
10702 	 * registers, so it is still necessary to update the information of
10703 	 * all drives attached to the previous port multiplier afterwards.
10704 	 */
10705 	/* Device changed: PMult -> another PMult */
10706 	mutex_exit(&cportinfo->cport_mutex);
10707 	sata_free_pmult(sata_hba_inst, sata_device);
10708 	if (sata_alloc_pmult(sata_hba_inst, sata_device) != SATA_SUCCESS)
10709 		return (SATA_FAILURE);
10710 	mutex_enter(&cportinfo->cport_mutex);
10711 
10712 	SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
10713 	    "SATA port multiplier [changed] at port %d", cport);
10714 	sata_log(sata_hba_inst, CE_WARN,
10715 	    "SATA port multiplier detected at port %d", cport);
10716 
10717 	/*
10718 	 * Mark all the port multiplier port behind the port
10719 	 * multiplier behind with link events, so that the sata daemon
10720 	 * will update their status.
10721 	 */
10722 	pmultinfo->pmult_event_flags |= SATA_EVNT_DEVICE_RESET;
10723 	mutex_exit(&cportinfo->cport_mutex);
10724 
10725 	return (SATA_SUCCESS);
10726 }
10727 
10728 /*
10729  * Re-probe a port multiplier port, check for a device and attach info
10730  * structures when necessary. Identify Device data is fetched, if possible.
10731  * Assumption: sata address is already validated as port multiplier port.
10732  * SATA_SUCCESS is returned if port is re-probed sucessfully, regardless of
10733  * the presence of a device and its type.
10734  *
10735  * flag arg specifies that the function should try multiple times to identify
10736  * device type and to initialize it, or it should return immediately on failure.
10737  * SATA_DEV_IDENTIFY_RETRY - retry
10738  * SATA_DEV_IDENTIFY_NORETRY - no retry
10739  *
10740  * SATA_FAILURE is returned if one of the operations failed.
10741  *
10742  * This function cannot be called in interrupt context - it may sleep.
10743  *
10744  * NOTE: Should be only called by sata_probe_port() in case target port is a
10745  *       port multiplier port.
10746  * NOTE: No Mutex should be hold.
10747  */
10748 static int
10749 sata_reprobe_pmport(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device,
10750     int flag)
10751 {
10752 	sata_cport_info_t *cportinfo = NULL;
10753 	sata_pmport_info_t *pmportinfo = NULL;
10754 	sata_drive_info_t *sdinfo, *osdinfo;
10755 	sata_device_t sdevice;
10756 	boolean_t init_device = B_FALSE;
10757 	int prev_device_type = SATA_DTYPE_NONE;
10758 	int prev_device_settings = 0;
10759 	int prev_device_state = 0;
10760 	clock_t start_time;
10761 	uint8_t cport = sata_device->satadev_addr.cport;
10762 	uint8_t pmport = sata_device->satadev_addr.pmport;
10763 	int rval;
10764 
10765 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
10766 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
10767 	osdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10768 
10769 	if (osdinfo != NULL) {
10770 		/*
10771 		 * We are re-probing port with a previously attached device.
10772 		 * Save previous device type and settings.
10773 		 */
10774 		prev_device_type = pmportinfo->pmport_dev_type;
10775 		prev_device_settings = osdinfo->satadrv_settings;
10776 		prev_device_state = osdinfo->satadrv_state;
10777 	}
10778 
10779 	start_time = ddi_get_lbolt();
10780 
10781 	/* check parent status */
10782 	mutex_enter(&cportinfo->cport_mutex);
10783 	if ((cportinfo->cport_state &
10784 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10785 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10786 	    SATA_PORT_DEVLINK_UP) {
10787 		mutex_exit(&cportinfo->cport_mutex);
10788 		return (SATA_FAILURE);
10789 	}
10790 	mutex_exit(&cportinfo->cport_mutex);
10791 
10792 retry_probe_pmport:
10793 
10794 	/* probe port */
10795 	mutex_enter(&pmportinfo->pmport_mutex);
10796 	pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
10797 	pmportinfo->pmport_state |= SATA_STATE_PROBING;
10798 	mutex_exit(&pmportinfo->pmport_mutex);
10799 
10800 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
10801 	    (SATA_DIP(sata_hba_inst), sata_device);
10802 
10803 	/* might need retry because we cannot touch registers. */
10804 	if (rval == SATA_FAILURE) {
10805 		mutex_enter(&pmportinfo->pmport_mutex);
10806 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
10807 		mutex_exit(&pmportinfo->pmport_mutex);
10808 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10809 		    "SATA port %d:%d probing failed",
10810 		    cport, pmport));
10811 		return (SATA_FAILURE);
10812 	} else if (rval == SATA_RETRY) {
10813 		SATA_LOG_D((sata_hba_inst, CE_WARN, "sata_reprobe_pmport: "
10814 		    "SATA port %d:%d probing failed, retrying...",
10815 		    cport, pmport));
10816 		clock_t cur_time = ddi_get_lbolt();
10817 		/*
10818 		 * A device was not successfully identified or initialized.
10819 		 * Track retry time for device identification.
10820 		 */
10821 		if ((cur_time - start_time) <
10822 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
10823 			/* sleep for a while */
10824 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
10825 			goto retry_probe_pmport;
10826 		} else {
10827 			mutex_enter(&pmportinfo->pmport_mutex);
10828 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
10829 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
10830 				    satadrv_state = SATA_DSTATE_FAILED;
10831 			mutex_exit(&pmportinfo->pmport_mutex);
10832 			return (SATA_SUCCESS);
10833 		}
10834 	}
10835 
10836 	/*
10837 	 * Sanity check - Controller port is active? Is the link active?
10838 	 * Is it still a port multiplier?
10839 	 */
10840 	if ((cportinfo->cport_state &
10841 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10842 	    (cportinfo->cport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10843 	    SATA_PORT_DEVLINK_UP ||
10844 	    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
10845 		/*
10846 		 * Port in non-usable state or no link active/no
10847 		 * device. Free info structure.
10848 		 */
10849 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
10850 
10851 		sdevice.satadev_addr.cport = cport;
10852 		sdevice.satadev_addr.pmport = pmport;
10853 		sdevice.satadev_addr.qual = SATA_ADDR_PMULT;
10854 		mutex_exit(&cportinfo->cport_mutex);
10855 
10856 		sata_free_pmult(sata_hba_inst, &sdevice);
10857 		return (SATA_FAILURE);
10858 	}
10859 
10860 	/* SATA_SUCCESS NOW */
10861 	/*
10862 	 * update sata port state and set device type
10863 	 */
10864 	mutex_enter(&pmportinfo->pmport_mutex);
10865 	sata_update_pmport_info(sata_hba_inst, sata_device);
10866 	pmportinfo->pmport_state &= ~SATA_STATE_PROBING;
10867 
10868 	/*
10869 	 * Sanity check - Port is active? Is the link active?
10870 	 * Is there any device attached?
10871 	 */
10872 	if ((pmportinfo->pmport_state &
10873 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
10874 	    (pmportinfo->pmport_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
10875 	    SATA_PORT_DEVLINK_UP) {
10876 		/*
10877 		 * Port in non-usable state or no link active/no device.
10878 		 * Free info structure if necessary (direct attached drive
10879 		 * only, for now!
10880 		 */
10881 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10882 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
10883 		/* Add here differentiation for device attached or not */
10884 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
10885 		mutex_exit(&pmportinfo->pmport_mutex);
10886 		if (sdinfo != NULL)
10887 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10888 		return (SATA_SUCCESS);
10889 	}
10890 
10891 	pmportinfo->pmport_state |= SATA_STATE_READY;
10892 	pmportinfo->pmport_dev_type = sata_device->satadev_type;
10893 	sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
10894 
10895 	/*
10896 	 * If we are re-probing the port, there may be
10897 	 * sata_drive_info structure attached
10898 	 * (or sata_pm_info, if PMult is supported).
10899 	 */
10900 	if (sata_device->satadev_type == SATA_DTYPE_NONE) {
10901 		/*
10902 		 * There is no device, so remove device info structure,
10903 		 * if necessary.
10904 		 */
10905 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
10906 		pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
10907 		if (sdinfo != NULL) {
10908 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10909 			sata_log(sata_hba_inst, CE_WARN,
10910 			    "SATA device detached from port %d:%d",
10911 			    cport, pmport);
10912 		}
10913 		mutex_exit(&pmportinfo->pmport_mutex);
10914 		return (SATA_SUCCESS);
10915 	}
10916 
10917 	/* this should not be a pmult */
10918 	ASSERT(sata_device->satadev_type != SATA_DTYPE_PMULT);
10919 	if (sdinfo == NULL) {
10920 		/*
10921 		 * There is some device attached, but there is
10922 		 * no sata_drive_info structure - allocate one
10923 		 */
10924 		mutex_exit(&pmportinfo->pmport_mutex);
10925 		sdinfo = kmem_zalloc(sizeof (sata_drive_info_t),
10926 		    KM_SLEEP);
10927 		mutex_enter(&pmportinfo->pmport_mutex);
10928 		/*
10929 		 * Recheck, that the port state did not change when we
10930 		 * released mutex.
10931 		 */
10932 		if (pmportinfo->pmport_state & SATA_STATE_READY) {
10933 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = sdinfo;
10934 			sdinfo->satadrv_addr = pmportinfo->pmport_addr;
10935 			sdinfo->satadrv_addr.qual = SATA_ADDR_DPMPORT;
10936 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
10937 			sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
10938 		} else {
10939 			/*
10940 			 * Port is not in ready state, we
10941 			 * cannot attach a device.
10942 			 */
10943 			mutex_exit(&pmportinfo->pmport_mutex);
10944 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10945 			return (SATA_SUCCESS);
10946 		}
10947 		/*
10948 		 * Since we are adding device, presumably new one,
10949 		 * indicate that it  should be initalized,
10950 		 * as well as some internal framework states).
10951 		 */
10952 		init_device = B_TRUE;
10953 	}
10954 
10955 	pmportinfo->pmport_dev_type = SATA_DTYPE_UNKNOWN;
10956 	sata_device->satadev_addr.qual = sdinfo->satadrv_addr.qual;
10957 
10958 	mutex_exit(&pmportinfo->pmport_mutex);
10959 	/*
10960 	 * Figure out what kind of device we are really
10961 	 * dealing with.
10962 	 */
10963 	rval = sata_probe_device(sata_hba_inst, sata_device);
10964 
10965 	mutex_enter(&pmportinfo->pmport_mutex);
10966 	if (rval == SATA_SUCCESS) {
10967 		/*
10968 		 * If we are dealing with the same type of a device as before,
10969 		 * restore its settings flags.
10970 		 */
10971 		if (osdinfo != NULL &&
10972 		    sata_device->satadev_type == prev_device_type)
10973 			sdinfo->satadrv_settings = prev_device_settings;
10974 
10975 		mutex_exit(&pmportinfo->pmport_mutex);
10976 		/* Set initial device features, if necessary */
10977 		if (init_device == B_TRUE) {
10978 			rval = sata_initialize_device(sata_hba_inst, sdinfo);
10979 		}
10980 		if (rval == SATA_SUCCESS)
10981 			return (rval);
10982 	} else {
10983 		/*
10984 		 * If there was some device info before we probe the device,
10985 		 * restore previous device setting, so we can retry from scratch
10986 		 * later. Providing, of course, that device has not disappeared
10987 		 * during probing process.
10988 		 */
10989 		if (sata_device->satadev_type != SATA_DTYPE_NONE) {
10990 			if (osdinfo != NULL) {
10991 				pmportinfo->pmport_dev_type = prev_device_type;
10992 				sdinfo->satadrv_type = prev_device_type;
10993 				sdinfo->satadrv_state = prev_device_state;
10994 			}
10995 		} else {
10996 			/* device is gone */
10997 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
10998 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
10999 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11000 			mutex_exit(&pmportinfo->pmport_mutex);
11001 			return (SATA_SUCCESS);
11002 		}
11003 		mutex_exit(&pmportinfo->pmport_mutex);
11004 	}
11005 
11006 	if (flag == SATA_DEV_IDENTIFY_RETRY) {
11007 		clock_t cur_time = ddi_get_lbolt();
11008 		/*
11009 		 * A device was not successfully identified or initialized.
11010 		 * Track retry time for device identification.
11011 		 */
11012 		if ((cur_time - start_time) <
11013 		    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
11014 			/* sleep for a while */
11015 			delay(drv_usectohz(SATA_DEV_RETRY_DLY));
11016 			goto retry_probe_pmport;
11017 		} else {
11018 			mutex_enter(&pmportinfo->pmport_mutex);
11019 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL)
11020 				SATA_PMPORTINFO_DRV_INFO(pmportinfo)->
11021 				    satadrv_state = SATA_DSTATE_FAILED;
11022 			mutex_exit(&pmportinfo->pmport_mutex);
11023 		}
11024 	}
11025 	return (SATA_SUCCESS);
11026 }
11027 
11028 /*
11029  * Allocated related structure for a port multiplier and its device ports
11030  *
11031  * Port multiplier should be ready and probed, and related information like
11032  * the number of the device ports should be store in sata_device_t.
11033  *
11034  * NOTE: No Mutex should be hold.
11035  */
11036 static int
11037 sata_alloc_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11038 {
11039 	dev_info_t *dip = SATA_DIP(sata_hba_inst);
11040 	sata_cport_info_t *cportinfo = NULL;
11041 	sata_pmult_info_t *pmultinfo = NULL;
11042 	sata_pmport_info_t *pmportinfo = NULL;
11043 	sata_device_t sd;
11044 	dev_t minor_number;
11045 	char name[16];
11046 	uint8_t cport = sata_device->satadev_addr.cport;
11047 	int rval;
11048 	int npmport;
11049 
11050 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11051 
11052 	/* This function might be called while a port-mult is hot-plugged. */
11053 	mutex_enter(&cportinfo->cport_mutex);
11054 
11055 	/* dev_type's not updated when get called from sata_reprobe_port() */
11056 	if (SATA_CPORTINFO_PMULT_INFO(cportinfo) == NULL) {
11057 		/* Create a pmult_info structure */
11058 		SATA_CPORTINFO_PMULT_INFO(cportinfo) =
11059 		    kmem_zalloc(sizeof (sata_pmult_info_t), KM_SLEEP);
11060 	}
11061 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11062 
11063 	pmultinfo->pmult_addr = sata_device->satadev_addr;
11064 	pmultinfo->pmult_addr.qual = SATA_ADDR_PMULT;
11065 	pmultinfo->pmult_state = SATA_STATE_PROBING;
11066 
11067 	/*
11068 	 * Probe the port multiplier with qualifier SATA_ADDR_PMULT_SPEC,
11069 	 * The HBA driver should initialize and register the port multiplier,
11070 	 * sata_register_pmult() will fill following fields,
11071 	 *   + sata_pmult_info.pmult_gscr
11072 	 *   + sata_pmult_info.pmult_num_dev_ports
11073 	 */
11074 	sd.satadev_addr = sata_device->satadev_addr;
11075 	sd.satadev_addr.qual = SATA_ADDR_PMULT_SPEC;
11076 	mutex_exit(&cportinfo->cport_mutex);
11077 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
11078 	    (SATA_DIP(sata_hba_inst), &sd);
11079 	mutex_enter(&cportinfo->cport_mutex);
11080 
11081 	if (rval != SATA_SUCCESS ||
11082 	    (sd.satadev_type != SATA_DTYPE_PMULT) ||
11083 	    !(sd.satadev_state & SATA_DSTATE_PMULT_INIT)) {
11084 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
11085 		kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11086 		cportinfo->cport_state = SATA_PSTATE_FAILED;
11087 		cportinfo->cport_dev_type = SATA_DTYPE_UNKNOWN;
11088 		mutex_exit(&cportinfo->cport_mutex);
11089 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
11090 		    "sata_alloc_pmult: failed to initialize pmult "
11091 		    "at port %d.", cport)
11092 		return (SATA_FAILURE);
11093 	}
11094 
11095 	/* Initialize pmport_info structure */
11096 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11097 	    npmport++) {
11098 
11099 		/* if everything is allocated, skip */
11100 		if (SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) != NULL)
11101 			continue;
11102 
11103 		pmportinfo = kmem_zalloc(sizeof (sata_pmport_info_t), KM_SLEEP);
11104 		mutex_init(&pmportinfo->pmport_mutex, NULL, MUTEX_DRIVER, NULL);
11105 		mutex_exit(&cportinfo->cport_mutex);
11106 
11107 		mutex_enter(&pmportinfo->pmport_mutex);
11108 		pmportinfo->pmport_addr.cport = cport;
11109 		pmportinfo->pmport_addr.pmport = (uint8_t)npmport;
11110 		pmportinfo->pmport_addr.qual = SATA_ADDR_PMPORT;
11111 		pmportinfo->pmport_state &= ~SATA_PORT_STATE_CLEAR_MASK;
11112 		mutex_exit(&pmportinfo->pmport_mutex);
11113 
11114 		mutex_enter(&cportinfo->cport_mutex);
11115 		SATA_PMPORT_INFO(sata_hba_inst, cport, npmport) = pmportinfo;
11116 
11117 		/* Create an attachment point */
11118 		minor_number = SATA_MAKE_AP_MINOR(ddi_get_instance(dip),
11119 		    cport, (uint8_t)npmport, SATA_ADDR_PMPORT);
11120 		(void) sprintf(name, "%d.%d", cport, npmport);
11121 
11122 		if (ddi_create_minor_node(dip, name, S_IFCHR, minor_number,
11123 		    DDI_NT_SATA_ATTACHMENT_POINT, 0) != DDI_SUCCESS) {
11124 			sata_log(sata_hba_inst, CE_WARN, "sata_hba_attach: "
11125 			    "cannot create SATA attachment point for "
11126 			    "port %d:%d", cport, npmport);
11127 		}
11128 	}
11129 
11130 	pmultinfo->pmult_state &= ~SATA_STATE_PROBING;
11131 	pmultinfo->pmult_state |= (SATA_STATE_PROBED|SATA_STATE_READY);
11132 	cportinfo->cport_dev_type = SATA_DTYPE_PMULT;
11133 
11134 	mutex_exit(&cportinfo->cport_mutex);
11135 	return (SATA_SUCCESS);
11136 }
11137 
11138 /*
11139  * Free data structures when a port multiplier is removed.
11140  *
11141  * NOTE: No Mutex should be hold.
11142  */
11143 static void
11144 sata_free_pmult(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11145 {
11146 	sata_cport_info_t *cportinfo;
11147 	sata_pmult_info_t *pmultinfo;
11148 	sata_pmport_info_t *pmportinfo;
11149 	sata_device_t pmport_device;
11150 	sata_drive_info_t *sdinfo;
11151 	dev_info_t *tdip;
11152 	char name[16];
11153 	uint8_t cport = sata_device->satadev_addr.cport;
11154 	int npmport;
11155 
11156 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11157 
11158 	/* This function might be called while port-mult is hot plugged. */
11159 	mutex_enter(&cportinfo->cport_mutex);
11160 
11161 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
11162 	pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11163 	ASSERT(pmultinfo != NULL);
11164 
11165 	/* Free pmport_info structure */
11166 	for (npmport = 0; npmport < pmultinfo->pmult_num_dev_ports;
11167 	    npmport++) {
11168 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
11169 		if (pmportinfo == NULL)
11170 			continue;
11171 		mutex_exit(&cportinfo->cport_mutex);
11172 
11173 		mutex_enter(&pmportinfo->pmport_mutex);
11174 		sdinfo = pmportinfo->pmport_sata_drive;
11175 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
11176 		mutex_exit(&pmportinfo->pmport_mutex);
11177 
11178 		/* Remove attachment point. */
11179 		name[0] = '\0';
11180 		(void) sprintf(name, "%d.%d", cport, npmport);
11181 		ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
11182 		sata_log(sata_hba_inst, CE_NOTE,
11183 		    "Remove attachment point of port %d:%d",
11184 		    cport, npmport);
11185 
11186 		/*
11187 		 * Rumove target node
11188 		 */
11189 		bzero(&pmport_device, sizeof (sata_device_t));
11190 		pmport_device.satadev_rev = SATA_DEVICE_REV;
11191 		pmport_device.satadev_addr.cport = cport;
11192 		pmport_device.satadev_addr.pmport = (uint8_t)npmport;
11193 		pmport_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
11194 
11195 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
11196 		    &(pmport_device.satadev_addr));
11197 		if (tdip != NULL && ndi_devi_offline(tdip,
11198 		    NDI_DEVI_REMOVE) != NDI_SUCCESS) {
11199 			/*
11200 			 * Problem :
11201 			 * The target node remained attached.
11202 			 * This happens when the device file was open
11203 			 * or a node was waiting for resources.
11204 			 * Cannot do anything about it.
11205 			 */
11206 			SATA_LOG_D((sata_hba_inst, CE_WARN,
11207 			    "sata_free_pmult: could not unconfigure device "
11208 			    "before disconnecting the SATA port %d:%d",
11209 			    cport, npmport));
11210 
11211 			/*
11212 			 * Set DEVICE REMOVED state in the target
11213 			 * node. It will prevent access to the device
11214 			 * even when a new device is attached, until
11215 			 * the old target node is released, removed and
11216 			 * recreated for a new  device.
11217 			 */
11218 			sata_set_device_removed(tdip);
11219 
11220 			/*
11221 			 * Instruct event daemon to try the target
11222 			 * node cleanup later.
11223 			 */
11224 			sata_set_target_node_cleanup(
11225 			    sata_hba_inst, &(pmport_device.satadev_addr));
11226 
11227 		}
11228 		mutex_enter(&cportinfo->cport_mutex);
11229 
11230 		/*
11231 		 * Add here differentiation for device attached or not
11232 		 */
11233 		if (sdinfo != NULL)  {
11234 			sata_log(sata_hba_inst, CE_WARN,
11235 			    "SATA device detached from port %d:%d",
11236 			    cport, npmport);
11237 			kmem_free(sdinfo, sizeof (sata_drive_info_t));
11238 		}
11239 
11240 		mutex_destroy(&pmportinfo->pmport_mutex);
11241 		kmem_free(pmportinfo, sizeof (sata_pmport_info_t));
11242 	}
11243 
11244 	kmem_free(pmultinfo, sizeof (sata_pmult_info_t));
11245 
11246 	cportinfo->cport_devp.cport_sata_pmult = NULL;
11247 
11248 	sata_log(sata_hba_inst, CE_WARN,
11249 	    "SATA port multiplier detached at port %d", cport);
11250 
11251 	mutex_exit(&cportinfo->cport_mutex);
11252 }
11253 
11254 /*
11255  * Initialize device
11256  * Specified device is initialized to a default state.
11257  *
11258  * Returns SATA_SUCCESS if all device features are set successfully,
11259  * SATA_RETRY if device is accessible but device features were not set
11260  * successfully, and SATA_FAILURE otherwise.
11261  */
11262 static int
11263 sata_initialize_device(sata_hba_inst_t *sata_hba_inst,
11264     sata_drive_info_t *sdinfo)
11265 {
11266 	int rval;
11267 
11268 	sata_save_drive_settings(sdinfo);
11269 
11270 	sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
11271 
11272 	sata_init_write_cache_mode(sdinfo);
11273 
11274 	rval = sata_set_drive_features(sata_hba_inst, sdinfo, 0);
11275 
11276 	/* Determine current data transfer mode */
11277 	if ((sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT) == 0) {
11278 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11279 	} else if ((sdinfo->satadrv_id.ai_validinfo &
11280 	    SATA_VALIDINFO_88) != 0 &&
11281 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SEL_MASK) != 0) {
11282 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11283 	} else if ((sdinfo->satadrv_id.ai_dworddma &
11284 	    SATA_MDMA_SEL_MASK) != 0) {
11285 		sdinfo->satadrv_settings |= SATA_DEV_DMA;
11286 	} else
11287 		/* DMA supported, not no DMA transfer mode is selected !? */
11288 		sdinfo->satadrv_settings &= ~SATA_DEV_DMA;
11289 
11290 	if ((sdinfo->satadrv_id.ai_cmdset83 & 0x20) &&
11291 	    (sdinfo->satadrv_id.ai_features86 & 0x20))
11292 		sdinfo->satadrv_power_level = SATA_POWER_STANDBY;
11293 	else
11294 		sdinfo->satadrv_power_level = SATA_POWER_ACTIVE;
11295 
11296 	return (rval);
11297 }
11298 
11299 
11300 /*
11301  * Initialize write cache mode.
11302  *
11303  * The default write cache setting for SATA HDD is provided by sata_write_cache
11304  * static variable. ATAPI CD/DVDs devices have write cache default is
11305  * determined by sata_atapicdvd_write_cache static variable.
11306  * ATAPI tape devices have write cache default is determined by
11307  * sata_atapitape_write_cache static variable.
11308  * ATAPI disk devices have write cache default is determined by
11309  * sata_atapidisk_write_cache static variable.
11310  * 1 - enable
11311  * 0 - disable
11312  * any other value - current drive setting
11313  *
11314  * Although there is not reason to disable write cache on CD/DVD devices,
11315  * tape devices and ATAPI disk devices, the default setting control is provided
11316  * for the maximun flexibility.
11317  *
11318  * In the future, it may be overridden by the
11319  * disk-write-cache-enable property setting, if it is defined.
11320  * Returns SATA_SUCCESS if all device features are set successfully,
11321  * SATA_FAILURE otherwise.
11322  */
11323 static void
11324 sata_init_write_cache_mode(sata_drive_info_t *sdinfo)
11325 {
11326 	switch (sdinfo->satadrv_type) {
11327 	case SATA_DTYPE_ATADISK:
11328 		if (sata_write_cache == 1)
11329 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11330 		else if (sata_write_cache == 0)
11331 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11332 		/*
11333 		 * When sata_write_cache value is not 0 or 1,
11334 		 * a current setting of the drive's write cache is used.
11335 		 */
11336 		break;
11337 	case SATA_DTYPE_ATAPICD:
11338 		if (sata_atapicdvd_write_cache == 1)
11339 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11340 		else if (sata_atapicdvd_write_cache == 0)
11341 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11342 		/*
11343 		 * When sata_atapicdvd_write_cache value is not 0 or 1,
11344 		 * a current setting of the drive's write cache is used.
11345 		 */
11346 		break;
11347 	case SATA_DTYPE_ATAPITAPE:
11348 		if (sata_atapitape_write_cache == 1)
11349 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11350 		else if (sata_atapitape_write_cache == 0)
11351 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11352 		/*
11353 		 * When sata_atapitape_write_cache value is not 0 or 1,
11354 		 * a current setting of the drive's write cache is used.
11355 		 */
11356 		break;
11357 	case SATA_DTYPE_ATAPIDISK:
11358 		if (sata_atapidisk_write_cache == 1)
11359 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
11360 		else if (sata_atapidisk_write_cache == 0)
11361 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
11362 		/*
11363 		 * When sata_atapidisk_write_cache value is not 0 or 1,
11364 		 * a current setting of the drive's write cache is used.
11365 		 */
11366 		break;
11367 	}
11368 }
11369 
11370 
11371 /*
11372  * Validate sata address.
11373  * Specified cport, pmport and qualifier has to match
11374  * passed sata_scsi configuration info.
11375  * The presence of an attached device is not verified.
11376  *
11377  * Returns 0 when address is valid, -1 otherwise.
11378  */
11379 static int
11380 sata_validate_sata_address(sata_hba_inst_t *sata_hba_inst, int cport,
11381 	int pmport, int qual)
11382 {
11383 	if (qual == SATA_ADDR_DCPORT && pmport != 0)
11384 		goto invalid_address;
11385 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11386 		goto invalid_address;
11387 	if ((qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) &&
11388 	    ((SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) != SATA_DTYPE_PMULT) ||
11389 	    (SATA_PMULT_INFO(sata_hba_inst, cport) == NULL) ||
11390 	    (pmport >= SATA_NUM_PMPORTS(sata_hba_inst, cport))))
11391 		goto invalid_address;
11392 
11393 	return (0);
11394 
11395 invalid_address:
11396 	return (-1);
11397 
11398 }
11399 
11400 /*
11401  * Validate scsi address
11402  * SCSI target address is translated into SATA cport/pmport and compared
11403  * with a controller port/device configuration. LUN has to be 0.
11404  * Returns 0 if a scsi target refers to an attached device,
11405  * returns 1 if address is valid but no valid device is attached,
11406  * returns 2 if address is valid but device type is unknown (not valid device),
11407  * returns -1 if bad address or device is of an unsupported type.
11408  * Upon return sata_device argument is set.
11409  *
11410  * Port multiplier is supported now.
11411  */
11412 static int
11413 sata_validate_scsi_address(sata_hba_inst_t *sata_hba_inst,
11414 	struct scsi_address *ap, sata_device_t *sata_device)
11415 {
11416 	int cport, pmport, qual, rval;
11417 
11418 	rval = -1;	/* Invalid address */
11419 	if (ap->a_lun != 0)
11420 		goto out;
11421 
11422 	qual = SCSI_TO_SATA_ADDR_QUAL(ap->a_target);
11423 	cport = SCSI_TO_SATA_CPORT(ap->a_target);
11424 	pmport = SCSI_TO_SATA_PMPORT(ap->a_target);
11425 
11426 	if (qual != SATA_ADDR_DCPORT && qual != SATA_ADDR_DPMPORT)
11427 		goto out;
11428 
11429 	if (sata_validate_sata_address(sata_hba_inst, cport, pmport, qual) ==
11430 	    0) {
11431 
11432 		sata_cport_info_t *cportinfo;
11433 		sata_pmult_info_t *pmultinfo;
11434 		sata_drive_info_t *sdinfo = NULL;
11435 
11436 		sata_device->satadev_addr.qual = qual;
11437 		sata_device->satadev_addr.cport = cport;
11438 		sata_device->satadev_addr.pmport = pmport;
11439 		sata_device->satadev_rev = SATA_DEVICE_REV_1;
11440 
11441 		rval = 1;	/* Valid sata address */
11442 
11443 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
11444 		if (qual == SATA_ADDR_DCPORT) {
11445 			if (cportinfo == NULL ||
11446 			    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
11447 				goto out;
11448 
11449 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
11450 			if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN &&
11451 			    sdinfo != NULL) {
11452 				rval = 2;
11453 				goto out;
11454 			}
11455 
11456 			if ((cportinfo->cport_dev_type &
11457 			    SATA_VALID_DEV_TYPE) == 0) {
11458 				rval = -1;
11459 				goto out;
11460 			}
11461 
11462 		} else if (qual == SATA_ADDR_DPMPORT) {
11463 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
11464 			if (pmultinfo == NULL) {
11465 				rval = -1;
11466 				goto out;
11467 			}
11468 			if (SATA_PMPORT_INFO(sata_hba_inst, cport, pmport) ==
11469 			    NULL ||
11470 			    SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11471 			    pmport) == SATA_DTYPE_NONE)
11472 				goto out;
11473 
11474 			sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport,
11475 			    pmport);
11476 			if (SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11477 			    pmport) == SATA_DTYPE_UNKNOWN && sdinfo != NULL) {
11478 				rval = 2;
11479 				goto out;
11480 			}
11481 
11482 			if ((SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport,
11483 			    pmport) && SATA_VALID_DEV_TYPE) == 0) {
11484 				rval = -1;
11485 				goto out;
11486 			}
11487 
11488 		} else {
11489 			rval = -1;
11490 			goto out;
11491 		}
11492 		if ((sdinfo == NULL) ||
11493 		    (sdinfo->satadrv_type & SATA_VALID_DEV_TYPE) == 0)
11494 			goto out;
11495 
11496 		sata_device->satadev_type = sdinfo->satadrv_type;
11497 
11498 		return (0);
11499 	}
11500 out:
11501 	if (rval > 0) {
11502 		SATADBG2(SATA_DBG_SCSI_IF, sata_hba_inst,
11503 		    "sata_validate_scsi_address: no valid target %x lun %x",
11504 		    ap->a_target, ap->a_lun);
11505 	}
11506 	return (rval);
11507 }
11508 
11509 /*
11510  * Find dip corresponding to passed device number
11511  *
11512  * Returns NULL if invalid device number is passed or device cannot be found,
11513  * Returns dip is device is found.
11514  */
11515 static dev_info_t *
11516 sata_devt_to_devinfo(dev_t dev)
11517 {
11518 	dev_info_t *dip;
11519 #ifndef __lock_lint
11520 	struct devnames *dnp;
11521 	major_t major = getmajor(dev);
11522 	int instance = SATA_MINOR2INSTANCE(getminor(dev));
11523 
11524 	if (major >= devcnt)
11525 		return (NULL);
11526 
11527 	dnp = &devnamesp[major];
11528 	LOCK_DEV_OPS(&(dnp->dn_lock));
11529 	dip = dnp->dn_head;
11530 	while (dip && (ddi_get_instance(dip) != instance)) {
11531 		dip = ddi_get_next(dip);
11532 	}
11533 	UNLOCK_DEV_OPS(&(dnp->dn_lock));
11534 #endif
11535 
11536 	return (dip);
11537 }
11538 
11539 
11540 /*
11541  * Probe device.
11542  * This function issues Identify Device command and initializes local
11543  * sata_drive_info structure if the device can be identified.
11544  * The device type is determined by examining Identify Device
11545  * command response.
11546  * If the sata_hba_inst has linked drive info structure for this
11547  * device address, the Identify Device data is stored into sata_drive_info
11548  * structure linked to the port info structure.
11549  *
11550  * sata_device has to refer to the valid sata port(s) for HBA described
11551  * by sata_hba_inst structure.
11552  *
11553  * Returns:
11554  *	SATA_SUCCESS if device type was successfully probed and port-linked
11555  *		drive info structure was updated;
11556  * 	SATA_FAILURE if there is no device, or device was not probed
11557  *		successully;
11558  *	SATA_RETRY if device probe can be retried later.
11559  * If a device cannot be identified, sata_device's dev_state and dev_type
11560  * fields are set to unknown.
11561  * There are no retries in this function. Any retries should be managed by
11562  * the caller.
11563  */
11564 
11565 
11566 static int
11567 sata_probe_device(sata_hba_inst_t *sata_hba_inst, sata_device_t *sata_device)
11568 {
11569 	sata_pmport_info_t *pmportinfo;
11570 	sata_drive_info_t *sdinfo;
11571 	sata_drive_info_t new_sdinfo;	/* local drive info struct */
11572 	int rval;
11573 
11574 	ASSERT((SATA_CPORT_STATE(sata_hba_inst,
11575 	    sata_device->satadev_addr.cport) &
11576 	    (SATA_STATE_PROBED | SATA_STATE_READY)) != 0);
11577 
11578 	sata_device->satadev_type = SATA_DTYPE_NONE;
11579 
11580 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11581 	    sata_device->satadev_addr.cport)));
11582 
11583 	if (sata_device->satadev_addr.qual == SATA_ADDR_DPMPORT) {
11584 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
11585 		    sata_device->satadev_addr.cport,
11586 		    sata_device->satadev_addr.pmport);
11587 		ASSERT(pmportinfo != NULL);
11588 	}
11589 
11590 	/* Get pointer to port-linked sata device info structure */
11591 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11592 	if (sdinfo != NULL) {
11593 		sdinfo->satadrv_state &=
11594 		    ~(SATA_STATE_PROBED | SATA_STATE_READY);
11595 		sdinfo->satadrv_state |= SATA_STATE_PROBING;
11596 	} else {
11597 		/* No device to probe */
11598 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11599 		    sata_device->satadev_addr.cport)));
11600 		sata_device->satadev_type = SATA_DTYPE_NONE;
11601 		sata_device->satadev_state = SATA_STATE_UNKNOWN;
11602 		return (SATA_FAILURE);
11603 	}
11604 	/*
11605 	 * Need to issue both types of identify device command and
11606 	 * determine device type by examining retreived data/status.
11607 	 * First, ATA Identify Device.
11608 	 */
11609 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
11610 	new_sdinfo.satadrv_addr = sata_device->satadev_addr;
11611 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11612 	    sata_device->satadev_addr.cport)));
11613 	new_sdinfo.satadrv_type = SATA_DTYPE_ATADISK;
11614 	rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11615 	if (rval == SATA_RETRY) {
11616 		/* We may try to check for ATAPI device */
11617 		if (SATA_FEATURES(sata_hba_inst) & SATA_CTLF_ATAPI) {
11618 			/*
11619 			 * HBA supports ATAPI - try to issue Identify Packet
11620 			 * Device command.
11621 			 */
11622 			new_sdinfo.satadrv_type = SATA_DTYPE_ATAPI;
11623 			rval = sata_identify_device(sata_hba_inst, &new_sdinfo);
11624 		}
11625 	}
11626 	if (rval == SATA_SUCCESS) {
11627 		/*
11628 		 * Got something responding positively to ATA Identify Device
11629 		 * or to Identify Packet Device cmd.
11630 		 * Save last used device type.
11631 		 */
11632 		sata_device->satadev_type = new_sdinfo.satadrv_type;
11633 
11634 		/* save device info, if possible */
11635 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11636 		    sata_device->satadev_addr.cport)));
11637 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11638 		if (sdinfo == NULL) {
11639 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11640 			    sata_device->satadev_addr.cport)));
11641 			return (SATA_FAILURE);
11642 		}
11643 		/*
11644 		 * Copy drive info into the port-linked drive info structure.
11645 		 */
11646 		*sdinfo = new_sdinfo;
11647 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11648 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11649 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11650 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11651 			    sata_device->satadev_addr.cport) =
11652 			    sdinfo->satadrv_type;
11653 		else { /* SATA_ADDR_DPMPORT */
11654 			mutex_enter(&pmportinfo->pmport_mutex);
11655 			SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11656 			    sata_device->satadev_addr.cport,
11657 			    sata_device->satadev_addr.pmport) =
11658 			    sdinfo->satadrv_type;
11659 			mutex_exit(&pmportinfo->pmport_mutex);
11660 		}
11661 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11662 		    sata_device->satadev_addr.cport)));
11663 		return (SATA_SUCCESS);
11664 	}
11665 
11666 	/*
11667 	 * It may be SATA_RETRY or SATA_FAILURE return.
11668 	 * Looks like we cannot determine the device type at this time.
11669 	 */
11670 	mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
11671 	    sata_device->satadev_addr.cport)));
11672 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
11673 	if (sdinfo != NULL) {
11674 		sata_device->satadev_type = SATA_DTYPE_UNKNOWN;
11675 		sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11676 		sdinfo->satadrv_state &= ~SATA_STATE_PROBING;
11677 		sdinfo->satadrv_state |= SATA_STATE_PROBED;
11678 		if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
11679 			SATA_CPORT_DEV_TYPE(sata_hba_inst,
11680 			    sata_device->satadev_addr.cport) =
11681 			    SATA_DTYPE_UNKNOWN;
11682 		else {
11683 			/* SATA_ADDR_DPMPORT */
11684 			mutex_enter(&pmportinfo->pmport_mutex);
11685 			if ((SATA_PMULT_INFO(sata_hba_inst,
11686 			    sata_device->satadev_addr.cport) != NULL) &&
11687 			    (SATA_PMPORT_INFO(sata_hba_inst,
11688 			    sata_device->satadev_addr.cport,
11689 			    sata_device->satadev_addr.pmport) != NULL))
11690 				SATA_PMPORT_DEV_TYPE(sata_hba_inst,
11691 				    sata_device->satadev_addr.cport,
11692 				    sata_device->satadev_addr.pmport) =
11693 				    SATA_DTYPE_UNKNOWN;
11694 			mutex_exit(&pmportinfo->pmport_mutex);
11695 		}
11696 	}
11697 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
11698 	    sata_device->satadev_addr.cport)));
11699 	return (rval);
11700 }
11701 
11702 
11703 /*
11704  * Get pointer to sata_drive_info structure.
11705  *
11706  * The sata_device has to contain address (cport, pmport and qualifier) for
11707  * specified sata_scsi structure.
11708  *
11709  * Returns NULL if device address is not valid for this HBA configuration.
11710  * Otherwise, returns a pointer to sata_drive_info structure.
11711  *
11712  * This function should be called with a port mutex held.
11713  */
11714 static sata_drive_info_t *
11715 sata_get_device_info(sata_hba_inst_t *sata_hba_inst,
11716     sata_device_t *sata_device)
11717 {
11718 	uint8_t cport = sata_device->satadev_addr.cport;
11719 	uint8_t pmport = sata_device->satadev_addr.pmport;
11720 	uint8_t qual = sata_device->satadev_addr.qual;
11721 
11722 	if (cport >= SATA_NUM_CPORTS(sata_hba_inst))
11723 		return (NULL);
11724 
11725 	if (!(SATA_CPORT_STATE(sata_hba_inst, cport) &
11726 	    (SATA_STATE_PROBED | SATA_STATE_READY)))
11727 		/* Port not probed yet */
11728 		return (NULL);
11729 
11730 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_NONE)
11731 		return (NULL);
11732 
11733 	if (qual == SATA_ADDR_DCPORT) {
11734 		/* Request for a device on a controller port */
11735 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
11736 		    SATA_DTYPE_PMULT)
11737 			/* Port multiplier attached */
11738 			return (NULL);
11739 		return (SATA_CPORT_DRV_INFO(sata_hba_inst, cport));
11740 	}
11741 	if (qual == SATA_ADDR_DPMPORT) {
11742 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
11743 		    SATA_DTYPE_PMULT)
11744 			return (NULL);
11745 
11746 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport))
11747 			return (NULL);
11748 
11749 		if (!(SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) &
11750 		    (SATA_STATE_PROBED | SATA_STATE_READY)))
11751 			/* Port multiplier port not probed yet */
11752 			return (NULL);
11753 
11754 		return (SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport));
11755 	}
11756 
11757 	/* we should not get here */
11758 	return (NULL);
11759 }
11760 
11761 
11762 /*
11763  * sata_identify_device.
11764  * Send Identify Device command to SATA HBA driver.
11765  * If command executes successfully, update sata_drive_info structure pointed
11766  * to by sdinfo argument, including Identify Device data.
11767  * If command fails, invalidate data in sata_drive_info.
11768  *
11769  * Cannot be called from interrupt level.
11770  *
11771  * Returns:
11772  * SATA_SUCCESS if the device was identified as a supported device,
11773  * SATA_RETRY if the device was not identified but could be retried,
11774  * SATA_FAILURE if the device was not identified and identify attempt
11775  *	should not be retried.
11776  */
11777 static int
11778 sata_identify_device(sata_hba_inst_t *sata_hba_inst,
11779     sata_drive_info_t *sdinfo)
11780 {
11781 	uint16_t cfg_word;
11782 	int rval;
11783 
11784 	/* fetch device identify data */
11785 	if ((rval = sata_fetch_device_identify_data(sata_hba_inst,
11786 	    sdinfo)) != SATA_SUCCESS)
11787 		goto fail_unknown;
11788 
11789 	cfg_word = sdinfo->satadrv_id.ai_config;
11790 
11791 	/* Set the correct device type */
11792 	if ((cfg_word & SATA_ATA_TYPE_MASK) == SATA_ATA_TYPE) {
11793 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11794 	} else if (cfg_word == SATA_CFA_TYPE) {
11795 		/* It's a Compact Flash media via CF-to-SATA HDD adapter */
11796 		sdinfo->satadrv_type = SATA_DTYPE_ATADISK;
11797 	} else if ((cfg_word & SATA_ATAPI_TYPE_MASK) == SATA_ATAPI_TYPE) {
11798 		switch (cfg_word & SATA_ATAPI_ID_DEV_TYPE) {
11799 		case SATA_ATAPI_CDROM_DEV:
11800 			sdinfo->satadrv_type = SATA_DTYPE_ATAPICD;
11801 			break;
11802 		case SATA_ATAPI_SQACC_DEV:
11803 			sdinfo->satadrv_type = SATA_DTYPE_ATAPITAPE;
11804 			break;
11805 		case SATA_ATAPI_DIRACC_DEV:
11806 			sdinfo->satadrv_type = SATA_DTYPE_ATAPIDISK;
11807 			break;
11808 		default:
11809 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11810 		}
11811 	} else {
11812 			sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11813 	}
11814 
11815 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11816 		if (sdinfo->satadrv_capacity == 0) {
11817 			/* Non-LBA disk. Too bad... */
11818 			sata_log(sata_hba_inst, CE_WARN,
11819 			    "SATA disk device at port %d does not support LBA",
11820 			    sdinfo->satadrv_addr.cport);
11821 			rval = SATA_FAILURE;
11822 			goto fail_unknown;
11823 		}
11824 	}
11825 #if 0
11826 	/* Left for historical reason */
11827 	/*
11828 	 * Some initial version of SATA spec indicated that at least
11829 	 * UDMA mode 4 has to be supported. It is not metioned in
11830 	 * SerialATA 2.6, so this restriction is removed.
11831 	 */
11832 	/* Check for Ultra DMA modes 6 through 0 being supported */
11833 	for (i = 6; i >= 0; --i) {
11834 		if (sdinfo->satadrv_id.ai_ultradma & (1 << i))
11835 			break;
11836 	}
11837 
11838 	/*
11839 	 * At least UDMA 4 mode has to be supported. If mode 4 or
11840 	 * higher are not supported by the device, fail this
11841 	 * device.
11842 	 */
11843 	if (i < 4) {
11844 		/* No required Ultra DMA mode supported */
11845 		sata_log(sata_hba_inst, CE_WARN,
11846 		    "SATA disk device at port %d does not support UDMA "
11847 		    "mode 4 or higher", sdinfo->satadrv_addr.cport);
11848 		SATA_LOG_D((sata_hba_inst, CE_WARN,
11849 		    "mode 4 or higher required, %d supported", i));
11850 		rval = SATA_FAILURE;
11851 		goto fail_unknown;
11852 	}
11853 #endif
11854 
11855 	/*
11856 	 * For Disk devices, if it doesn't support UDMA mode, we would
11857 	 * like to return failure directly.
11858 	 */
11859 	if ((sdinfo->satadrv_type == SATA_DTYPE_ATADISK) &&
11860 	    !((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
11861 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0)) {
11862 		sata_log(sata_hba_inst, CE_WARN,
11863 		    "SATA disk device at port %d does not support UDMA",
11864 		    sdinfo->satadrv_addr.cport);
11865 		rval = SATA_FAILURE;
11866 		goto fail_unknown;
11867 	}
11868 
11869 	return (SATA_SUCCESS);
11870 
11871 fail_unknown:
11872 	/* Invalidate sata_drive_info ? */
11873 	sdinfo->satadrv_type = SATA_DTYPE_UNKNOWN;
11874 	sdinfo->satadrv_state = SATA_STATE_UNKNOWN;
11875 	return (rval);
11876 }
11877 
11878 /*
11879  * Log/display device information
11880  */
11881 static void
11882 sata_show_drive_info(sata_hba_inst_t *sata_hba_inst,
11883     sata_drive_info_t *sdinfo)
11884 {
11885 	int valid_version;
11886 	char msg_buf[MAXPATHLEN];
11887 	int i;
11888 
11889 	/* Show HBA path */
11890 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), msg_buf);
11891 
11892 	cmn_err(CE_CONT, "?%s :\n", msg_buf);
11893 
11894 	switch (sdinfo->satadrv_type) {
11895 	case SATA_DTYPE_ATADISK:
11896 		(void) sprintf(msg_buf, "SATA disk device at");
11897 		break;
11898 
11899 	case SATA_DTYPE_ATAPICD:
11900 		(void) sprintf(msg_buf, "SATA CD/DVD (ATAPI) device at");
11901 		break;
11902 
11903 	case SATA_DTYPE_ATAPITAPE:
11904 		(void) sprintf(msg_buf, "SATA tape (ATAPI) device at");
11905 		break;
11906 
11907 	case SATA_DTYPE_ATAPIDISK:
11908 		(void) sprintf(msg_buf, "SATA disk (ATAPI) device at");
11909 		break;
11910 
11911 	case SATA_DTYPE_UNKNOWN:
11912 		(void) sprintf(msg_buf,
11913 		    "Unsupported SATA device type (cfg 0x%x) at ",
11914 		    sdinfo->satadrv_id.ai_config);
11915 		break;
11916 	}
11917 
11918 	if (sdinfo->satadrv_addr.qual == SATA_ADDR_DCPORT)
11919 		cmn_err(CE_CONT, "?\t%s port %d\n",
11920 		    msg_buf, sdinfo->satadrv_addr.cport);
11921 	else
11922 		cmn_err(CE_CONT, "?\t%s port %d:%d\n",
11923 		    msg_buf, sdinfo->satadrv_addr.cport,
11924 		    sdinfo->satadrv_addr.pmport);
11925 
11926 	bcopy(&sdinfo->satadrv_id.ai_model, msg_buf,
11927 	    sizeof (sdinfo->satadrv_id.ai_model));
11928 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_model));
11929 	msg_buf[sizeof (sdinfo->satadrv_id.ai_model)] = '\0';
11930 	cmn_err(CE_CONT, "?\tmodel %s\n", msg_buf);
11931 
11932 	bcopy(&sdinfo->satadrv_id.ai_fw, msg_buf,
11933 	    sizeof (sdinfo->satadrv_id.ai_fw));
11934 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_fw));
11935 	msg_buf[sizeof (sdinfo->satadrv_id.ai_fw)] = '\0';
11936 	cmn_err(CE_CONT, "?\tfirmware %s\n", msg_buf);
11937 
11938 	bcopy(&sdinfo->satadrv_id.ai_drvser, msg_buf,
11939 	    sizeof (sdinfo->satadrv_id.ai_drvser));
11940 	swab(msg_buf, msg_buf, sizeof (sdinfo->satadrv_id.ai_drvser));
11941 	msg_buf[sizeof (sdinfo->satadrv_id.ai_drvser)] = '\0';
11942 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11943 		cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
11944 	} else {
11945 		/*
11946 		 * Some drives do not implement serial number and may
11947 		 * violate the spec by providing spaces rather than zeros
11948 		 * in serial number field. Scan the buffer to detect it.
11949 		 */
11950 		for (i = 0; i < sizeof (sdinfo->satadrv_id.ai_drvser); i++) {
11951 			if (msg_buf[i] != '\0' && msg_buf[i] != ' ')
11952 				break;
11953 		}
11954 		if (i == sizeof (sdinfo->satadrv_id.ai_drvser)) {
11955 			cmn_err(CE_CONT, "?\tserial number - none\n");
11956 		} else {
11957 			cmn_err(CE_CONT, "?\tserial number %s\n", msg_buf);
11958 		}
11959 	}
11960 
11961 #ifdef SATA_DEBUG
11962 	if (sdinfo->satadrv_id.ai_majorversion != 0 &&
11963 	    sdinfo->satadrv_id.ai_majorversion != 0xffff) {
11964 		int i;
11965 		for (i = 14; i >= 2; i--) {
11966 			if (sdinfo->satadrv_id.ai_majorversion & (1 << i)) {
11967 				valid_version = i;
11968 				break;
11969 			}
11970 		}
11971 		cmn_err(CE_CONT,
11972 		    "?\tATA/ATAPI-%d supported, majver 0x%x minver 0x%x\n",
11973 		    valid_version,
11974 		    sdinfo->satadrv_id.ai_majorversion,
11975 		    sdinfo->satadrv_id.ai_minorversion);
11976 	}
11977 #endif
11978 	/* Log some info */
11979 	cmn_err(CE_CONT, "?\tsupported features:\n");
11980 	msg_buf[0] = '\0';
11981 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
11982 		if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA48)
11983 			(void) strlcat(msg_buf, "48-bit LBA, ", MAXPATHLEN);
11984 		else if (sdinfo->satadrv_features_support & SATA_DEV_F_LBA28)
11985 			(void) strlcat(msg_buf, "28-bit LBA, ", MAXPATHLEN);
11986 	}
11987 	if (sdinfo->satadrv_features_support & SATA_DEV_F_DMA)
11988 		(void) strlcat(msg_buf, "DMA", MAXPATHLEN);
11989 	if (sdinfo->satadrv_features_support & SATA_DEV_F_NCQ)
11990 		(void) strlcat(msg_buf, ", Native Command Queueing",
11991 		    MAXPATHLEN);
11992 	if (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)
11993 		(void) strlcat(msg_buf, ", Legacy Tagged Queuing", MAXPATHLEN);
11994 	if ((sdinfo->satadrv_id.ai_cmdset82 & SATA_SMART_SUPPORTED) &&
11995 	    (sdinfo->satadrv_id.ai_features85 & SATA_SMART_ENABLED))
11996 		(void) strlcat(msg_buf, ", SMART", MAXPATHLEN);
11997 	if ((sdinfo->satadrv_id.ai_cmdset84 & SATA_SMART_SELF_TEST_SUPPORTED) &&
11998 	    (sdinfo->satadrv_id.ai_features87 & SATA_SMART_SELF_TEST_SUPPORTED))
11999 		(void) strlcat(msg_buf, ", SMART self-test", MAXPATHLEN);
12000 	cmn_err(CE_CONT, "?\t %s\n", msg_buf);
12001 	if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA2)
12002 		cmn_err(CE_CONT, "?\tSATA Gen2 signaling speed (3.0Gbps)\n");
12003 	else if (sdinfo->satadrv_features_support & SATA_DEV_F_SATA1)
12004 		cmn_err(CE_CONT, "?\tSATA Gen1 signaling speed (1.5Gbps)\n");
12005 	if (sdinfo->satadrv_features_support &
12006 	    (SATA_DEV_F_TCQ | SATA_DEV_F_NCQ)) {
12007 		msg_buf[0] = '\0';
12008 		(void) snprintf(msg_buf, MAXPATHLEN,
12009 		    "Supported queue depth %d",
12010 		    sdinfo->satadrv_queue_depth);
12011 		if (!(sata_func_enable &
12012 		    (SATA_ENABLE_QUEUING | SATA_ENABLE_NCQ)))
12013 			(void) strlcat(msg_buf,
12014 			    " - queueing disabled globally", MAXPATHLEN);
12015 		else if (sdinfo->satadrv_queue_depth >
12016 		    sdinfo->satadrv_max_queue_depth) {
12017 			(void) snprintf(&msg_buf[strlen(msg_buf)],
12018 			    MAXPATHLEN - strlen(msg_buf), ", limited to %d",
12019 			    (int)sdinfo->satadrv_max_queue_depth);
12020 		}
12021 		cmn_err(CE_CONT, "?\t%s\n", msg_buf);
12022 	}
12023 
12024 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12025 #ifdef __i386
12026 		(void) sprintf(msg_buf, "\tcapacity = %llu sectors\n",
12027 		    sdinfo->satadrv_capacity);
12028 #else
12029 		(void) sprintf(msg_buf, "\tcapacity = %lu sectors\n",
12030 		    sdinfo->satadrv_capacity);
12031 #endif
12032 		cmn_err(CE_CONT, "?%s", msg_buf);
12033 	}
12034 }
12035 
12036 /*
12037  * Log/display port multiplier information
12038  * No Mutex should be hold.
12039  */
12040 static void
12041 sata_show_pmult_info(sata_hba_inst_t *sata_hba_inst,
12042     sata_device_t *sata_device)
12043 {
12044 	_NOTE(ARGUNUSED(sata_hba_inst))
12045 
12046 	int cport = sata_device->satadev_addr.cport;
12047 	sata_pmult_info_t *pmultinfo;
12048 	char msg_buf[MAXPATHLEN];
12049 	uint32_t gscr0, gscr1, gscr2, gscr64;
12050 
12051 	mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12052 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
12053 	if (pmultinfo == NULL) {
12054 		mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12055 		return;
12056 	}
12057 
12058 	gscr0 = pmultinfo->pmult_gscr.gscr0;
12059 	gscr1 = pmultinfo->pmult_gscr.gscr1;
12060 	gscr2 = pmultinfo->pmult_gscr.gscr2;
12061 	gscr64 = pmultinfo->pmult_gscr.gscr64;
12062 	mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
12063 
12064 	cmn_err(CE_CONT, "?Port Multiplier %d device-ports found at port %d",
12065 	    sata_device->satadev_add_info, sata_device->satadev_addr.cport);
12066 
12067 	(void) sprintf(msg_buf, "\tVendor_ID 0x%04x, Module_ID 0x%04x",
12068 	    gscr0 & 0xffff, (gscr0 >> 16) & 0xffff);
12069 	cmn_err(CE_CONT, "?%s", msg_buf);
12070 
12071 	(void) strcpy(msg_buf, "\tSupport SATA PMP Spec ");
12072 	if (gscr1 & (1 << 3))
12073 		(void) strlcat(msg_buf, "1.2", MAXPATHLEN);
12074 	else if (gscr1 & (1 << 2))
12075 		(void) strlcat(msg_buf, "1.1", MAXPATHLEN);
12076 	else if (gscr1 & (1 << 1))
12077 		(void) strlcat(msg_buf, "1.0", MAXPATHLEN);
12078 	else
12079 		(void) strlcat(msg_buf, "unknown", MAXPATHLEN);
12080 	cmn_err(CE_CONT, "?%s", msg_buf);
12081 
12082 	(void) strcpy(msg_buf, "\tSupport ");
12083 	if (gscr64 & (1 << 3))
12084 		(void) strlcat(msg_buf, "Asy-Notif, ",
12085 		    MAXPATHLEN);
12086 	if (gscr64 & (1 << 2))
12087 		(void) strlcat(msg_buf, "Dyn-SSC, ", MAXPATHLEN);
12088 	if (gscr64 & (1 << 1))
12089 		(void) strlcat(msg_buf, "Iss-PMREQ, ", MAXPATHLEN);
12090 	if (gscr64 & (1 << 0))
12091 		(void) strlcat(msg_buf, "BIST", MAXPATHLEN);
12092 	if ((gscr64 & 0xf) == 0)
12093 		(void) strlcat(msg_buf, "nothing", MAXPATHLEN);
12094 	cmn_err(CE_CONT, "?%s", msg_buf);
12095 
12096 	(void) sprintf(msg_buf, "\tNumber of exposed device fan-out ports: %d",
12097 	    gscr2 & SATA_PMULT_PORTNUM_MASK);
12098 	cmn_err(CE_CONT, "?%s", msg_buf);
12099 }
12100 
12101 /*
12102  * sata_save_drive_settings extracts current setting of the device and stores
12103  * it for future reference, in case the device setup would need to be restored
12104  * after the device reset.
12105  *
12106  * For all devices read ahead and write cache settings are saved, if the
12107  * device supports these features at all.
12108  * For ATAPI devices the Removable Media Status Notification setting is saved.
12109  */
12110 static void
12111 sata_save_drive_settings(sata_drive_info_t *sdinfo)
12112 {
12113 	if (SATA_READ_AHEAD_SUPPORTED(sdinfo->satadrv_id) ||
12114 	    SATA_WRITE_CACHE_SUPPORTED(sdinfo->satadrv_id)) {
12115 
12116 		/* Current setting of Read Ahead (and Read Cache) */
12117 		if (SATA_READ_AHEAD_ENABLED(sdinfo->satadrv_id))
12118 			sdinfo->satadrv_settings |= SATA_DEV_READ_AHEAD;
12119 		else
12120 			sdinfo->satadrv_settings &= ~SATA_DEV_READ_AHEAD;
12121 
12122 		/* Current setting of Write Cache */
12123 		if (SATA_WRITE_CACHE_ENABLED(sdinfo->satadrv_id))
12124 			sdinfo->satadrv_settings |= SATA_DEV_WRITE_CACHE;
12125 		else
12126 			sdinfo->satadrv_settings &= ~SATA_DEV_WRITE_CACHE;
12127 	}
12128 
12129 	if (sdinfo->satadrv_type == SATA_DTYPE_ATAPICD) {
12130 		if (SATA_RM_NOTIFIC_SUPPORTED(sdinfo->satadrv_id))
12131 			sdinfo->satadrv_settings |= SATA_DEV_RMSN;
12132 		else
12133 			sdinfo->satadrv_settings &= ~SATA_DEV_RMSN;
12134 	}
12135 }
12136 
12137 
12138 /*
12139  * sata_check_capacity function determines a disk capacity
12140  * and addressing mode (LBA28/LBA48) by examining a disk identify device data.
12141  *
12142  * NOTE: CHS mode is not supported! If a device does not support LBA,
12143  * this function is not called.
12144  *
12145  * Returns device capacity in number of blocks, i.e. largest addressable LBA+1
12146  */
12147 static uint64_t
12148 sata_check_capacity(sata_drive_info_t *sdinfo)
12149 {
12150 	uint64_t capacity = 0;
12151 	int i;
12152 
12153 	if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK ||
12154 	    !sdinfo->satadrv_id.ai_cap & SATA_LBA_SUPPORT)
12155 		/* Capacity valid only for LBA-addressable disk devices */
12156 		return (0);
12157 
12158 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) &&
12159 	    (sdinfo->satadrv_id.ai_cmdset83 & SATA_EXT48) &&
12160 	    (sdinfo->satadrv_id.ai_features86 & SATA_EXT48)) {
12161 		/* LBA48 mode supported and enabled */
12162 		sdinfo->satadrv_features_support |= SATA_DEV_F_LBA48 |
12163 		    SATA_DEV_F_LBA28;
12164 		for (i = 3;  i >= 0;  --i) {
12165 			capacity <<= 16;
12166 			capacity += sdinfo->satadrv_id.ai_addrsecxt[i];
12167 		}
12168 	} else {
12169 		capacity = sdinfo->satadrv_id.ai_addrsec[1];
12170 		capacity <<= 16;
12171 		capacity += sdinfo->satadrv_id.ai_addrsec[0];
12172 		if (capacity >= 0x1000000)
12173 			/* LBA28 mode */
12174 			sdinfo->satadrv_features_support |= SATA_DEV_F_LBA28;
12175 	}
12176 	return (capacity);
12177 }
12178 
12179 
12180 /*
12181  * Allocate consistent buffer for DMA transfer
12182  *
12183  * Cannot be called from interrupt level or with mutex held - it may sleep.
12184  *
12185  * Returns pointer to allocated buffer structure, or NULL if allocation failed.
12186  */
12187 static struct buf *
12188 sata_alloc_local_buffer(sata_pkt_txlate_t *spx, int len)
12189 {
12190 	struct scsi_address ap;
12191 	struct buf *bp;
12192 	ddi_dma_attr_t	cur_dma_attr;
12193 
12194 	ASSERT(spx->txlt_sata_pkt != NULL);
12195 	ap.a_hba_tran = spx->txlt_sata_hba_inst->satahba_scsi_tran;
12196 	ap.a_target = SATA_TO_SCSI_TARGET(
12197 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.cport,
12198 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.pmport,
12199 	    spx->txlt_sata_pkt->satapkt_device.satadev_addr.qual);
12200 	ap.a_lun = 0;
12201 
12202 	bp = scsi_alloc_consistent_buf(&ap, NULL, len,
12203 	    B_READ, SLEEP_FUNC, NULL);
12204 
12205 	if (bp != NULL) {
12206 		/* Allocate DMA resources for this buffer */
12207 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = bp;
12208 		/*
12209 		 * We use a local version of the dma_attr, to account
12210 		 * for a device addressing limitations.
12211 		 * sata_adjust_dma_attr() will handle sdinfo == NULL which
12212 		 * will cause dma attributes to be adjusted to a lowest
12213 		 * acceptable level.
12214 		 */
12215 		sata_adjust_dma_attr(NULL,
12216 		    SATA_DMA_ATTR(spx->txlt_sata_hba_inst), &cur_dma_attr);
12217 
12218 		if (sata_dma_buf_setup(spx, PKT_CONSISTENT,
12219 		    SLEEP_FUNC, NULL, &cur_dma_attr) != DDI_SUCCESS) {
12220 			scsi_free_consistent_buf(bp);
12221 			spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12222 			bp = NULL;
12223 		}
12224 	}
12225 	return (bp);
12226 }
12227 
12228 /*
12229  * Release local buffer (consistent buffer for DMA transfer) allocated
12230  * via sata_alloc_local_buffer().
12231  */
12232 static void
12233 sata_free_local_buffer(sata_pkt_txlate_t *spx)
12234 {
12235 	ASSERT(spx->txlt_sata_pkt != NULL);
12236 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp != NULL);
12237 
12238 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 0;
12239 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list = NULL;
12240 
12241 	sata_common_free_dma_rsrcs(spx);
12242 
12243 	/* Free buffer */
12244 	scsi_free_consistent_buf(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp);
12245 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp = NULL;
12246 }
12247 
12248 /*
12249  * Allocate sata_pkt
12250  * Pkt structure version and embedded strcutures version are initialized.
12251  * sata_pkt and sata_pkt_txlate structures are cross-linked.
12252  *
12253  * Since this may be called in interrupt context by sata_scsi_init_pkt,
12254  * callback argument determines if it can sleep or not.
12255  * Hence, it should not be called from interrupt context.
12256  *
12257  * If successful, non-NULL pointer to a sata pkt is returned.
12258  * Upon failure, NULL pointer is returned.
12259  */
12260 static sata_pkt_t *
12261 sata_pkt_alloc(sata_pkt_txlate_t *spx, int (*callback)(caddr_t))
12262 {
12263 	sata_pkt_t *spkt;
12264 	int kmsflag;
12265 
12266 	kmsflag = (callback == SLEEP_FUNC) ? KM_SLEEP : KM_NOSLEEP;
12267 	spkt = kmem_zalloc(sizeof (sata_pkt_t), kmsflag);
12268 	if (spkt == NULL) {
12269 		SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12270 		    "sata_pkt_alloc: failed"));
12271 		return (NULL);
12272 	}
12273 	spkt->satapkt_rev = SATA_PKT_REV;
12274 	spkt->satapkt_cmd.satacmd_rev = SATA_CMD_REV;
12275 	spkt->satapkt_device.satadev_rev = SATA_DEVICE_REV;
12276 	spkt->satapkt_framework_private = spx;
12277 	spx->txlt_sata_pkt = spkt;
12278 	return (spkt);
12279 }
12280 
12281 /*
12282  * Free sata pkt allocated via sata_pkt_alloc()
12283  */
12284 static void
12285 sata_pkt_free(sata_pkt_txlate_t *spx)
12286 {
12287 	ASSERT(spx->txlt_sata_pkt != NULL);
12288 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp == NULL);
12289 	kmem_free(spx->txlt_sata_pkt, sizeof (sata_pkt_t));
12290 	spx->txlt_sata_pkt = NULL;
12291 }
12292 
12293 
12294 /*
12295  * Adjust DMA attributes.
12296  * SCSI cmds block count is up to 24 bits, SATA cmd block count vary
12297  * from 8 bits to 16 bits, depending on a command being used.
12298  * Limiting max block count arbitrarily to 256 for all read/write
12299  * commands may affects performance, so check both the device and
12300  * controller capability before adjusting dma attributes.
12301  */
12302 void
12303 sata_adjust_dma_attr(sata_drive_info_t *sdinfo, ddi_dma_attr_t *dma_attr,
12304     ddi_dma_attr_t *adj_dma_attr)
12305 {
12306 	uint32_t count_max;
12307 
12308 	/* Copy original attributes */
12309 	*adj_dma_attr = *dma_attr;
12310 	/*
12311 	 * Things to consider: device addressing capability,
12312 	 * "excessive" controller DMA capabilities.
12313 	 * If a device is being probed/initialized, there are
12314 	 * no device info - use default limits then.
12315 	 */
12316 	if (sdinfo == NULL) {
12317 		count_max = dma_attr->dma_attr_granular * 0x100;
12318 		if (dma_attr->dma_attr_count_max > count_max)
12319 			adj_dma_attr->dma_attr_count_max = count_max;
12320 		if (dma_attr->dma_attr_maxxfer > count_max)
12321 			adj_dma_attr->dma_attr_maxxfer = count_max;
12322 		return;
12323 	}
12324 
12325 	if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12326 		if (sdinfo->satadrv_features_support & (SATA_DEV_F_LBA48)) {
12327 			/*
12328 			 * 16-bit sector count may be used - we rely on
12329 			 * the assumption that only read and write cmds
12330 			 * will request more than 256 sectors worth of data
12331 			 */
12332 			count_max = adj_dma_attr->dma_attr_granular * 0x10000;
12333 		} else {
12334 			/*
12335 			 * 8-bit sector count will be used - default limits
12336 			 * for dma attributes
12337 			 */
12338 			count_max = adj_dma_attr->dma_attr_granular * 0x100;
12339 		}
12340 		/*
12341 		 * Adjust controler dma attributes, if necessary
12342 		 */
12343 		if (dma_attr->dma_attr_count_max > count_max)
12344 			adj_dma_attr->dma_attr_count_max = count_max;
12345 		if (dma_attr->dma_attr_maxxfer > count_max)
12346 			adj_dma_attr->dma_attr_maxxfer = count_max;
12347 	}
12348 }
12349 
12350 
12351 /*
12352  * Allocate DMA resources for the buffer
12353  * This function handles initial DMA resource allocation as well as
12354  * DMA window shift and may be called repeatedly for the same DMA window
12355  * until all DMA cookies in the DMA window are processed.
12356  * To guarantee that there is always a coherent set of cookies to process
12357  * by SATA HBA driver (observing alignment, device granularity, etc.),
12358  * the number of slots for DMA cookies is equal to lesser of  a number of
12359  * cookies in a DMA window and a max number of scatter/gather entries.
12360  *
12361  * Returns DDI_SUCCESS upon successful operation.
12362  * Return failure code of a failing command or DDI_FAILURE when
12363  * internal cleanup failed.
12364  */
12365 static int
12366 sata_dma_buf_setup(sata_pkt_txlate_t *spx, int flags,
12367     int (*callback)(caddr_t), caddr_t arg,
12368     ddi_dma_attr_t *cur_dma_attr)
12369 {
12370 	int	rval;
12371 	off_t	offset;
12372 	size_t	size;
12373 	int	max_sg_len, req_len, i;
12374 	uint_t	dma_flags;
12375 	struct buf	*bp;
12376 	uint64_t	cur_txfer_len;
12377 
12378 
12379 	ASSERT(spx->txlt_sata_pkt != NULL);
12380 	bp = spx->txlt_sata_pkt->satapkt_cmd.satacmd_bp;
12381 	ASSERT(bp != NULL);
12382 
12383 
12384 	if (spx->txlt_buf_dma_handle == NULL) {
12385 		/*
12386 		 * No DMA resources allocated so far - this is a first call
12387 		 * for this sata pkt.
12388 		 */
12389 		rval = ddi_dma_alloc_handle(SATA_DIP(spx->txlt_sata_hba_inst),
12390 		    cur_dma_attr, callback, arg, &spx->txlt_buf_dma_handle);
12391 
12392 		if (rval != DDI_SUCCESS) {
12393 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12394 			    "sata_dma_buf_setup: no buf DMA resources %x",
12395 			    rval));
12396 			return (rval);
12397 		}
12398 
12399 		if (bp->b_flags & B_READ)
12400 			dma_flags = DDI_DMA_READ;
12401 		else
12402 			dma_flags = DDI_DMA_WRITE;
12403 
12404 		if (flags & PKT_CONSISTENT)
12405 			dma_flags |= DDI_DMA_CONSISTENT;
12406 
12407 		if (flags & PKT_DMA_PARTIAL)
12408 			dma_flags |= DDI_DMA_PARTIAL;
12409 
12410 		/*
12411 		 * Check buffer alignment and size against dma attributes
12412 		 * Consider dma_attr_align only. There may be requests
12413 		 * with the size lower than device granularity, but they
12414 		 * will not read/write from/to the device, so no adjustment
12415 		 * is necessary. The dma_attr_minxfer theoretically should
12416 		 * be considered, but no HBA driver is checking it.
12417 		 */
12418 		if (IS_P2ALIGNED(bp->b_un.b_addr,
12419 		    cur_dma_attr->dma_attr_align)) {
12420 			rval = ddi_dma_buf_bind_handle(
12421 			    spx->txlt_buf_dma_handle,
12422 			    bp, dma_flags, callback, arg,
12423 			    &spx->txlt_dma_cookie,
12424 			    &spx->txlt_curwin_num_dma_cookies);
12425 		} else { /* Buffer is not aligned */
12426 
12427 			int	(*ddicallback)(caddr_t);
12428 			size_t	bufsz;
12429 
12430 			/* Check id sleeping is allowed */
12431 			ddicallback = (callback == NULL_FUNC) ?
12432 			    DDI_DMA_DONTWAIT : DDI_DMA_SLEEP;
12433 
12434 			SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12435 			    "mis-aligned buffer: addr=0x%p, cnt=%lu",
12436 			    (void *)bp->b_un.b_addr, bp->b_bcount);
12437 
12438 			if (bp->b_flags & (B_PAGEIO|B_PHYS))
12439 				/*
12440 				 * CPU will need to access data in the buffer
12441 				 * (for copying) so map it.
12442 				 */
12443 				bp_mapin(bp);
12444 
12445 			ASSERT(spx->txlt_tmp_buf == NULL);
12446 
12447 			/* Buffer may be padded by ddi_dma_mem_alloc()! */
12448 			rval = ddi_dma_mem_alloc(
12449 			    spx->txlt_buf_dma_handle,
12450 			    bp->b_bcount,
12451 			    &sata_acc_attr,
12452 			    DDI_DMA_STREAMING,
12453 			    ddicallback, NULL,
12454 			    &spx->txlt_tmp_buf,
12455 			    &bufsz,
12456 			    &spx->txlt_tmp_buf_handle);
12457 
12458 			if (rval != DDI_SUCCESS) {
12459 				/* DMA mapping failed */
12460 				(void) ddi_dma_free_handle(
12461 				    &spx->txlt_buf_dma_handle);
12462 				spx->txlt_buf_dma_handle = NULL;
12463 #ifdef SATA_DEBUG
12464 				mbuffail_count++;
12465 #endif
12466 				SATADBG1(SATA_DBG_DMA_SETUP,
12467 				    spx->txlt_sata_hba_inst,
12468 				    "sata_dma_buf_setup: "
12469 				    "buf dma mem alloc failed %x\n", rval);
12470 				return (rval);
12471 			}
12472 			ASSERT(IS_P2ALIGNED(spx->txlt_tmp_buf,
12473 			    cur_dma_attr->dma_attr_align));
12474 
12475 #ifdef SATA_DEBUG
12476 			mbuf_count++;
12477 
12478 			if (bp->b_bcount != bufsz)
12479 				/*
12480 				 * This will require special handling, because
12481 				 * DMA cookies will be based on the temporary
12482 				 * buffer size, not the original buffer
12483 				 * b_bcount, so the residue may have to
12484 				 * be counted differently.
12485 				 */
12486 				SATADBG2(SATA_DBG_DMA_SETUP,
12487 				    spx->txlt_sata_hba_inst,
12488 				    "sata_dma_buf_setup: bp size %x != "
12489 				    "bufsz %x\n", bp->b_bcount, bufsz);
12490 #endif
12491 			if (dma_flags & DDI_DMA_WRITE) {
12492 				/*
12493 				 * Write operation - copy data into
12494 				 * an aligned temporary buffer. Buffer will be
12495 				 * synced for device by ddi_dma_addr_bind_handle
12496 				 */
12497 				bcopy(bp->b_un.b_addr, spx->txlt_tmp_buf,
12498 				    bp->b_bcount);
12499 			}
12500 
12501 			rval = ddi_dma_addr_bind_handle(
12502 			    spx->txlt_buf_dma_handle,
12503 			    NULL,
12504 			    spx->txlt_tmp_buf,
12505 			    bufsz, dma_flags, ddicallback, 0,
12506 			    &spx->txlt_dma_cookie,
12507 			    &spx->txlt_curwin_num_dma_cookies);
12508 		}
12509 
12510 		switch (rval) {
12511 		case DDI_DMA_PARTIAL_MAP:
12512 			SATADBG1(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12513 			    "sata_dma_buf_setup: DMA Partial Map\n", NULL);
12514 			/*
12515 			 * Partial DMA mapping.
12516 			 * Retrieve number of DMA windows for this request.
12517 			 */
12518 			if (ddi_dma_numwin(spx->txlt_buf_dma_handle,
12519 			    &spx->txlt_num_dma_win) != DDI_SUCCESS) {
12520 				if (spx->txlt_tmp_buf != NULL) {
12521 					ddi_dma_mem_free(
12522 					    &spx->txlt_tmp_buf_handle);
12523 					spx->txlt_tmp_buf = NULL;
12524 				}
12525 				(void) ddi_dma_unbind_handle(
12526 				    spx->txlt_buf_dma_handle);
12527 				(void) ddi_dma_free_handle(
12528 				    &spx->txlt_buf_dma_handle);
12529 				spx->txlt_buf_dma_handle = NULL;
12530 				SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12531 				    "sata_dma_buf_setup: numwin failed\n"));
12532 				return (DDI_FAILURE);
12533 			}
12534 			SATADBG2(SATA_DBG_DMA_SETUP,
12535 			    spx->txlt_sata_hba_inst,
12536 			    "sata_dma_buf_setup: windows: %d, cookies: %d\n",
12537 			    spx->txlt_num_dma_win,
12538 			    spx->txlt_curwin_num_dma_cookies);
12539 			spx->txlt_cur_dma_win = 0;
12540 			break;
12541 
12542 		case DDI_DMA_MAPPED:
12543 			/* DMA fully mapped */
12544 			spx->txlt_num_dma_win = 1;
12545 			spx->txlt_cur_dma_win = 0;
12546 			SATADBG1(SATA_DBG_DMA_SETUP,
12547 			    spx->txlt_sata_hba_inst,
12548 			    "sata_dma_buf_setup: windows: 1 "
12549 			    "cookies: %d\n", spx->txlt_curwin_num_dma_cookies);
12550 			break;
12551 
12552 		default:
12553 			/* DMA mapping failed */
12554 			if (spx->txlt_tmp_buf != NULL) {
12555 				ddi_dma_mem_free(
12556 				    &spx->txlt_tmp_buf_handle);
12557 				spx->txlt_tmp_buf = NULL;
12558 			}
12559 			(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12560 			spx->txlt_buf_dma_handle = NULL;
12561 			SATA_LOG_D((spx->txlt_sata_hba_inst, CE_WARN,
12562 			    "sata_dma_buf_setup: buf dma handle binding "
12563 			    "failed %x\n", rval));
12564 			return (rval);
12565 		}
12566 		spx->txlt_curwin_processed_dma_cookies = 0;
12567 		spx->txlt_dma_cookie_list = NULL;
12568 	} else {
12569 		/*
12570 		 * DMA setup is reused. Check if we need to process more
12571 		 * cookies in current window, or to get next window, if any.
12572 		 */
12573 
12574 		ASSERT(spx->txlt_curwin_processed_dma_cookies <=
12575 		    spx->txlt_curwin_num_dma_cookies);
12576 
12577 		if (spx->txlt_curwin_processed_dma_cookies ==
12578 		    spx->txlt_curwin_num_dma_cookies) {
12579 			/*
12580 			 * All cookies from current DMA window were processed.
12581 			 * Get next DMA window.
12582 			 */
12583 			spx->txlt_cur_dma_win++;
12584 			if (spx->txlt_cur_dma_win < spx->txlt_num_dma_win) {
12585 				(void) ddi_dma_getwin(spx->txlt_buf_dma_handle,
12586 				    spx->txlt_cur_dma_win, &offset, &size,
12587 				    &spx->txlt_dma_cookie,
12588 				    &spx->txlt_curwin_num_dma_cookies);
12589 				spx->txlt_curwin_processed_dma_cookies = 0;
12590 			} else {
12591 				/* No more windows! End of request! */
12592 				/* What to do? - panic for now */
12593 				ASSERT(spx->txlt_cur_dma_win >=
12594 				    spx->txlt_num_dma_win);
12595 
12596 				spx->txlt_curwin_num_dma_cookies = 0;
12597 				spx->txlt_curwin_processed_dma_cookies = 0;
12598 				spx->txlt_sata_pkt->
12599 				    satapkt_cmd.satacmd_num_dma_cookies = 0;
12600 				return (DDI_SUCCESS);
12601 			}
12602 		}
12603 	}
12604 	/* There better be at least one DMA cookie outstanding */
12605 	ASSERT((spx->txlt_curwin_num_dma_cookies -
12606 	    spx->txlt_curwin_processed_dma_cookies) > 0);
12607 
12608 	if (spx->txlt_dma_cookie_list == &spx->txlt_dma_cookie) {
12609 		/* The default cookie slot was used in previous run */
12610 		ASSERT(spx->txlt_curwin_processed_dma_cookies == 0);
12611 		spx->txlt_dma_cookie_list = NULL;
12612 		spx->txlt_dma_cookie_list_len = 0;
12613 	}
12614 	if (spx->txlt_curwin_processed_dma_cookies == 0) {
12615 		/*
12616 		 * Processing a new DMA window - set-up dma cookies list.
12617 		 * We may reuse previously allocated cookie array if it is
12618 		 * possible.
12619 		 */
12620 		if (spx->txlt_dma_cookie_list != NULL &&
12621 		    spx->txlt_dma_cookie_list_len <
12622 		    spx->txlt_curwin_num_dma_cookies) {
12623 			/*
12624 			 * New DMA window contains more cookies than
12625 			 * the previous one. We need larger cookie list - free
12626 			 * the old one.
12627 			 */
12628 			(void) kmem_free(spx->txlt_dma_cookie_list,
12629 			    spx->txlt_dma_cookie_list_len *
12630 			    sizeof (ddi_dma_cookie_t));
12631 			spx->txlt_dma_cookie_list = NULL;
12632 			spx->txlt_dma_cookie_list_len = 0;
12633 		}
12634 		if (spx->txlt_dma_cookie_list == NULL) {
12635 			/*
12636 			 * Calculate lesser of number of cookies in this
12637 			 * DMA window and number of s/g entries.
12638 			 */
12639 			max_sg_len = cur_dma_attr->dma_attr_sgllen;
12640 			req_len = MIN(max_sg_len,
12641 			    spx->txlt_curwin_num_dma_cookies);
12642 
12643 			/* Allocate new dma cookie array if necessary */
12644 			if (req_len == 1) {
12645 				/* Only one cookie - no need for a list */
12646 				spx->txlt_dma_cookie_list =
12647 				    &spx->txlt_dma_cookie;
12648 				spx->txlt_dma_cookie_list_len = 1;
12649 			} else {
12650 				/*
12651 				 * More than one cookie - try to allocate space.
12652 				 */
12653 				spx->txlt_dma_cookie_list = kmem_zalloc(
12654 				    sizeof (ddi_dma_cookie_t) * req_len,
12655 				    callback == NULL_FUNC ? KM_NOSLEEP :
12656 				    KM_SLEEP);
12657 				if (spx->txlt_dma_cookie_list == NULL) {
12658 					SATADBG1(SATA_DBG_DMA_SETUP,
12659 					    spx->txlt_sata_hba_inst,
12660 					    "sata_dma_buf_setup: cookie list "
12661 					    "allocation failed\n", NULL);
12662 					/*
12663 					 * We could not allocate space for
12664 					 * neccessary number of dma cookies in
12665 					 * this window, so we fail this request.
12666 					 * Next invocation would try again to
12667 					 * allocate space for cookie list.
12668 					 * Note:Packet residue was not modified.
12669 					 */
12670 					return (DDI_DMA_NORESOURCES);
12671 				} else {
12672 					spx->txlt_dma_cookie_list_len = req_len;
12673 				}
12674 			}
12675 		}
12676 		/*
12677 		 * Fetch DMA cookies into cookie list in sata_pkt_txlate.
12678 		 * First cookie was already fetched.
12679 		 */
12680 		*(&spx->txlt_dma_cookie_list[0]) = spx->txlt_dma_cookie;
12681 		cur_txfer_len =
12682 		    (uint64_t)spx->txlt_dma_cookie_list[0].dmac_size;
12683 		spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies = 1;
12684 		spx->txlt_curwin_processed_dma_cookies++;
12685 		for (i = 1; (i < spx->txlt_dma_cookie_list_len) &&
12686 		    (i < spx->txlt_curwin_num_dma_cookies); i++) {
12687 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12688 			    &spx->txlt_dma_cookie_list[i]);
12689 			cur_txfer_len +=
12690 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12691 			spx->txlt_curwin_processed_dma_cookies++;
12692 			spx->txlt_sata_pkt->
12693 			    satapkt_cmd.satacmd_num_dma_cookies += 1;
12694 		}
12695 	} else {
12696 		SATADBG2(SATA_DBG_DMA_SETUP, spx->txlt_sata_hba_inst,
12697 		    "sata_dma_buf_setup: sliding within DMA window, "
12698 		    "cur cookie %d, total cookies %d\n",
12699 		    spx->txlt_curwin_processed_dma_cookies,
12700 		    spx->txlt_curwin_num_dma_cookies);
12701 
12702 		/*
12703 		 * Not all cookies from the current dma window were used because
12704 		 * of s/g limitation.
12705 		 * There is no need to re-size the list - it was set at
12706 		 * optimal size, or only default entry is used (s/g = 1).
12707 		 */
12708 		if (spx->txlt_dma_cookie_list == NULL) {
12709 			spx->txlt_dma_cookie_list = &spx->txlt_dma_cookie;
12710 			spx->txlt_dma_cookie_list_len = 1;
12711 		}
12712 		/*
12713 		 * Since we are processing remaining cookies in a DMA window,
12714 		 * there may be less of them than the number of entries in the
12715 		 * current dma cookie list.
12716 		 */
12717 		req_len = MIN(spx->txlt_dma_cookie_list_len,
12718 		    (spx->txlt_curwin_num_dma_cookies -
12719 		    spx->txlt_curwin_processed_dma_cookies));
12720 
12721 		/* Fetch the next batch of cookies */
12722 		for (i = 0, cur_txfer_len = 0; i < req_len; i++) {
12723 			ddi_dma_nextcookie(spx->txlt_buf_dma_handle,
12724 			    &spx->txlt_dma_cookie_list[i]);
12725 			cur_txfer_len +=
12726 			    (uint64_t)spx->txlt_dma_cookie_list[i].dmac_size;
12727 			spx->txlt_sata_pkt->
12728 			    satapkt_cmd.satacmd_num_dma_cookies++;
12729 			spx->txlt_curwin_processed_dma_cookies++;
12730 		}
12731 	}
12732 
12733 	ASSERT(spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies > 0);
12734 
12735 	/* Point sata_cmd to the cookie list */
12736 	spx->txlt_sata_pkt->satapkt_cmd.satacmd_dma_cookie_list =
12737 	    &spx->txlt_dma_cookie_list[0];
12738 
12739 	/* Remember number of DMA cookies passed in sata packet */
12740 	spx->txlt_num_dma_cookies =
12741 	    spx->txlt_sata_pkt->satapkt_cmd.satacmd_num_dma_cookies;
12742 
12743 	ASSERT(cur_txfer_len != 0);
12744 	if (cur_txfer_len <= bp->b_bcount)
12745 		spx->txlt_total_residue -= cur_txfer_len;
12746 	else {
12747 		/*
12748 		 * Temporary DMA buffer has been padded by
12749 		 * ddi_dma_mem_alloc()!
12750 		 * This requires special handling, because DMA cookies are
12751 		 * based on the temporary buffer size, not the b_bcount,
12752 		 * and we have extra bytes to transfer - but the packet
12753 		 * residue has to stay correct because we will copy only
12754 		 * the requested number of bytes.
12755 		 */
12756 		spx->txlt_total_residue -= bp->b_bcount;
12757 	}
12758 
12759 	return (DDI_SUCCESS);
12760 }
12761 
12762 /*
12763  * Common routine for releasing DMA resources
12764  */
12765 static void
12766 sata_common_free_dma_rsrcs(sata_pkt_txlate_t *spx)
12767 {
12768 	if (spx->txlt_buf_dma_handle != NULL) {
12769 		if (spx->txlt_tmp_buf != NULL)  {
12770 			/*
12771 			 * Intermediate DMA buffer was allocated.
12772 			 * Free allocated buffer and associated access handle.
12773 			 */
12774 			ddi_dma_mem_free(&spx->txlt_tmp_buf_handle);
12775 			spx->txlt_tmp_buf = NULL;
12776 		}
12777 		/*
12778 		 * Free DMA resources - cookies and handles
12779 		 */
12780 		/* ASSERT(spx->txlt_dma_cookie_list != NULL); */
12781 		if (spx->txlt_dma_cookie_list != NULL) {
12782 			if (spx->txlt_dma_cookie_list !=
12783 			    &spx->txlt_dma_cookie) {
12784 				(void) kmem_free(spx->txlt_dma_cookie_list,
12785 				    spx->txlt_dma_cookie_list_len *
12786 				    sizeof (ddi_dma_cookie_t));
12787 				spx->txlt_dma_cookie_list = NULL;
12788 			}
12789 		}
12790 		(void) ddi_dma_unbind_handle(spx->txlt_buf_dma_handle);
12791 		(void) ddi_dma_free_handle(&spx->txlt_buf_dma_handle);
12792 		spx->txlt_buf_dma_handle = NULL;
12793 	}
12794 }
12795 
12796 /*
12797  * Free DMA resources
12798  * Used by the HBA driver to release DMA resources that it does not use.
12799  *
12800  * Returns Void
12801  */
12802 void
12803 sata_free_dma_resources(sata_pkt_t *sata_pkt)
12804 {
12805 	sata_pkt_txlate_t *spx;
12806 
12807 	if (sata_pkt == NULL)
12808 		return;
12809 
12810 	spx = (sata_pkt_txlate_t *)sata_pkt->satapkt_framework_private;
12811 
12812 	sata_common_free_dma_rsrcs(spx);
12813 }
12814 
12815 /*
12816  * Fetch Device Identify data.
12817  * Send DEVICE IDENTIFY or IDENTIFY PACKET DEVICE (depending on a device type)
12818  * command to a device and get the device identify data.
12819  * The device_info structure has to be set to device type (for selecting proper
12820  * device identify command).
12821  *
12822  * Returns:
12823  * SATA_SUCCESS if cmd succeeded
12824  * SATA_RETRY if cmd was rejected and could be retried,
12825  * SATA_FAILURE if cmd failed and should not be retried (port error)
12826  *
12827  * Cannot be called in an interrupt context.
12828  */
12829 
12830 static int
12831 sata_fetch_device_identify_data(sata_hba_inst_t *sata_hba_inst,
12832     sata_drive_info_t *sdinfo)
12833 {
12834 	struct buf *bp;
12835 	sata_pkt_t *spkt;
12836 	sata_cmd_t *scmd;
12837 	sata_pkt_txlate_t *spx;
12838 	int rval;
12839 
12840 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
12841 	spx->txlt_sata_hba_inst = sata_hba_inst;
12842 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
12843 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
12844 	if (spkt == NULL) {
12845 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12846 		return (SATA_RETRY); /* may retry later */
12847 	}
12848 	/* address is needed now */
12849 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12850 
12851 	/*
12852 	 * Allocate buffer for Identify Data return data
12853 	 */
12854 	bp = sata_alloc_local_buffer(spx, sizeof (sata_id_t));
12855 	if (bp == NULL) {
12856 		sata_pkt_free(spx);
12857 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
12858 		SATA_LOG_D((sata_hba_inst, CE_WARN,
12859 		    "sata_fetch_device_identify_data: "
12860 		    "cannot allocate buffer for ID"));
12861 		return (SATA_RETRY); /* may retry later */
12862 	}
12863 
12864 	/* Fill sata_pkt */
12865 	sdinfo->satadrv_state = SATA_STATE_PROBING;
12866 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
12867 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
12868 	/* Synchronous mode, no callback */
12869 	spkt->satapkt_comp = NULL;
12870 	/* Timeout 30s */
12871 	spkt->satapkt_time = sata_default_pkt_time;
12872 
12873 	scmd = &spkt->satapkt_cmd;
12874 	scmd->satacmd_bp = bp;
12875 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
12876 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
12877 
12878 	/* Build Identify Device cmd in the sata_pkt */
12879 	scmd->satacmd_addr_type = 0;		/* N/A */
12880 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
12881 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
12882 	scmd->satacmd_lba_mid_lsb = 0;		/* N/A */
12883 	scmd->satacmd_lba_high_lsb = 0;		/* N/A */
12884 	scmd->satacmd_features_reg = 0;		/* N/A */
12885 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
12886 	if (sdinfo->satadrv_type & SATA_DTYPE_ATAPI) {
12887 		/* Identify Packet Device cmd */
12888 		scmd->satacmd_cmd_reg = SATAC_ID_PACKET_DEVICE;
12889 	} else {
12890 		/* Identify Device cmd - mandatory for all other devices */
12891 		scmd->satacmd_cmd_reg = SATAC_ID_DEVICE;
12892 	}
12893 
12894 	/* Send pkt to SATA HBA driver */
12895 	rval = (*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt);
12896 
12897 #ifdef SATA_INJECT_FAULTS
12898 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
12899 #endif
12900 
12901 	if (rval == SATA_TRAN_ACCEPTED &&
12902 	    spkt->satapkt_reason == SATA_PKT_COMPLETED) {
12903 		if (spx->txlt_buf_dma_handle != NULL) {
12904 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
12905 			    DDI_DMA_SYNC_FORKERNEL);
12906 			ASSERT(rval == DDI_SUCCESS);
12907 		}
12908 		if ((((sata_id_t *)(bp->b_un.b_addr))->ai_config &
12909 		    SATA_INCOMPLETE_DATA) == SATA_INCOMPLETE_DATA) {
12910 			SATA_LOG_D((sata_hba_inst, CE_WARN,
12911 			    "SATA disk device at port %d - "
12912 			    "partial Identify Data",
12913 			    sdinfo->satadrv_addr.cport));
12914 			rval = SATA_RETRY; /* may retry later */
12915 			goto fail;
12916 		}
12917 		/* Update sata_drive_info */
12918 		bcopy(bp->b_un.b_addr, &sdinfo->satadrv_id,
12919 		    sizeof (sata_id_t));
12920 
12921 		sdinfo->satadrv_features_support = 0;
12922 		if (sdinfo->satadrv_type == SATA_DTYPE_ATADISK) {
12923 			/*
12924 			 * Retrieve capacity (disks only) and addressing mode
12925 			 */
12926 			sdinfo->satadrv_capacity = sata_check_capacity(sdinfo);
12927 		} else {
12928 			/*
12929 			 * For ATAPI devices one would have to issue
12930 			 * Get Capacity cmd for media capacity. Not here.
12931 			 */
12932 			sdinfo->satadrv_capacity = 0;
12933 			/*
12934 			 * Check what cdb length is supported
12935 			 */
12936 			if ((sdinfo->satadrv_id.ai_config &
12937 			    SATA_ATAPI_ID_PKT_SZ) == SATA_ATAPI_ID_PKT_16B)
12938 				sdinfo->satadrv_atapi_cdb_len = 16;
12939 			else
12940 				sdinfo->satadrv_atapi_cdb_len = 12;
12941 		}
12942 		/* Setup supported features flags */
12943 		if (sdinfo->satadrv_id.ai_cap & SATA_DMA_SUPPORT)
12944 			sdinfo->satadrv_features_support |= SATA_DEV_F_DMA;
12945 
12946 		/* Check for SATA GEN and NCQ support */
12947 		if (sdinfo->satadrv_id.ai_satacap != 0 &&
12948 		    sdinfo->satadrv_id.ai_satacap != 0xffff) {
12949 			/* SATA compliance */
12950 			if (sdinfo->satadrv_id.ai_satacap & SATA_NCQ)
12951 				sdinfo->satadrv_features_support |=
12952 				    SATA_DEV_F_NCQ;
12953 			if (sdinfo->satadrv_id.ai_satacap &
12954 			    (SATA_1_SPEED | SATA_2_SPEED)) {
12955 				if (sdinfo->satadrv_id.ai_satacap &
12956 				    SATA_2_SPEED)
12957 					sdinfo->satadrv_features_support |=
12958 					    SATA_DEV_F_SATA2;
12959 				if (sdinfo->satadrv_id.ai_satacap &
12960 				    SATA_1_SPEED)
12961 					sdinfo->satadrv_features_support |=
12962 					    SATA_DEV_F_SATA1;
12963 			} else {
12964 				sdinfo->satadrv_features_support |=
12965 				    SATA_DEV_F_SATA1;
12966 			}
12967 		}
12968 		if ((sdinfo->satadrv_id.ai_cmdset83 & SATA_RW_DMA_QUEUED_CMD) &&
12969 		    (sdinfo->satadrv_id.ai_features86 & SATA_RW_DMA_QUEUED_CMD))
12970 			sdinfo->satadrv_features_support |= SATA_DEV_F_TCQ;
12971 
12972 		sdinfo->satadrv_queue_depth = sdinfo->satadrv_id.ai_qdepth;
12973 		if ((sdinfo->satadrv_features_support & SATA_DEV_F_NCQ) ||
12974 		    (sdinfo->satadrv_features_support & SATA_DEV_F_TCQ)) {
12975 			++sdinfo->satadrv_queue_depth;
12976 			/* Adjust according to controller capabilities */
12977 			sdinfo->satadrv_max_queue_depth = MIN(
12978 			    sdinfo->satadrv_queue_depth,
12979 			    SATA_QDEPTH(sata_hba_inst));
12980 			/* Adjust according to global queue depth limit */
12981 			sdinfo->satadrv_max_queue_depth = MIN(
12982 			    sdinfo->satadrv_max_queue_depth,
12983 			    sata_current_max_qdepth);
12984 			if (sdinfo->satadrv_max_queue_depth == 0)
12985 				sdinfo->satadrv_max_queue_depth = 1;
12986 		} else
12987 			sdinfo->satadrv_max_queue_depth = 1;
12988 
12989 		rval = SATA_SUCCESS;
12990 	} else {
12991 		/*
12992 		 * Woops, no Identify Data.
12993 		 */
12994 		if (rval == SATA_TRAN_BUSY || rval == SATA_TRAN_QUEUE_FULL) {
12995 			rval = SATA_RETRY; /* may retry later */
12996 		} else if (rval == SATA_TRAN_ACCEPTED) {
12997 			if (spkt->satapkt_reason == SATA_PKT_DEV_ERROR ||
12998 			    spkt->satapkt_reason == SATA_PKT_ABORTED ||
12999 			    spkt->satapkt_reason == SATA_PKT_TIMEOUT ||
13000 			    spkt->satapkt_reason == SATA_PKT_RESET)
13001 				rval = SATA_RETRY; /* may retry later */
13002 			else
13003 				rval = SATA_FAILURE;
13004 		} else {
13005 			rval = SATA_FAILURE;
13006 		}
13007 	}
13008 fail:
13009 	/* Free allocated resources */
13010 	sata_free_local_buffer(spx);
13011 	sata_pkt_free(spx);
13012 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
13013 
13014 	return (rval);
13015 }
13016 
13017 
13018 /*
13019  * Some devices may not come-up with default DMA mode (UDMA or MWDMA).
13020  * UDMA mode is checked first, followed by MWDMA mode.
13021  * set correctly, so this function is setting it to the highest supported level.
13022  * Older SATA spec required that the device supports at least DMA 4 mode and
13023  * UDMA mode is selected.  It is not mentioned in SerialATA 2.6, so this
13024  * restriction has been removed.
13025  *
13026  * Returns SATA_SUCCESS if proper DMA mode is selected or no DMA is supported.
13027  * Returns SATA_FAILURE if proper DMA mode could not be selected.
13028  *
13029  * NOTE: This function should be called only if DMA mode is supported.
13030  */
13031 static int
13032 sata_set_dma_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo)
13033 {
13034 	sata_pkt_t *spkt;
13035 	sata_cmd_t *scmd;
13036 	sata_pkt_txlate_t *spx;
13037 	int i, mode;
13038 	uint8_t subcmd;
13039 	int rval = SATA_SUCCESS;
13040 
13041 	ASSERT(sdinfo != NULL);
13042 	ASSERT(sata_hba_inst != NULL);
13043 
13044 	if ((sdinfo->satadrv_id.ai_validinfo & SATA_VALIDINFO_88) != 0 &&
13045 	    (sdinfo->satadrv_id.ai_ultradma & SATA_UDMA_SUP_MASK) != 0) {
13046 		/* Find highest Ultra DMA mode supported */
13047 		for (mode = 6; mode >= 0; --mode) {
13048 			if (sdinfo->satadrv_id.ai_ultradma & (1 << mode))
13049 				break;
13050 		}
13051 #if 0
13052 		/* Left for historical reasons */
13053 		/*
13054 		 * Some initial version of SATA spec indicated that at least
13055 		 * UDMA mode 4 has to be supported. It is not mentioned in
13056 		 * SerialATA 2.6, so this restriction is removed.
13057 		 */
13058 		if (mode < 4)
13059 			return (SATA_FAILURE);
13060 #endif
13061 
13062 		/*
13063 		 * For disk, we're still going to set DMA mode whatever is
13064 		 * selected by default
13065 		 *
13066 		 * We saw an old maxtor sata drive will select Ultra DMA and
13067 		 * Multi-Word DMA simultaneouly by default, which is going
13068 		 * to cause DMA command timed out, so we need to select DMA
13069 		 * mode even when it's already done by default
13070 		 */
13071 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13072 
13073 			/* Find UDMA mode currently selected */
13074 			for (i = 6; i >= 0; --i) {
13075 				if (sdinfo->satadrv_id.ai_ultradma &
13076 				    (1 << (i + 8)))
13077 					break;
13078 			}
13079 			if (i >= mode)
13080 				/* Nothing to do */
13081 				return (SATA_SUCCESS);
13082 		}
13083 
13084 		subcmd = SATAC_TRANSFER_MODE_ULTRA_DMA;
13085 
13086 	} else if ((sdinfo->satadrv_id.ai_dworddma & SATA_MDMA_SUP_MASK) != 0) {
13087 		/* Find highest MultiWord DMA mode supported */
13088 		for (mode = 2; mode >= 0; --mode) {
13089 			if (sdinfo->satadrv_id.ai_dworddma & (1 << mode))
13090 				break;
13091 		}
13092 
13093 		/*
13094 		 * For disk, We're still going to set DMA mode whatever is
13095 		 * selected by default
13096 		 *
13097 		 * We saw an old maxtor sata drive will select Ultra DMA and
13098 		 * Multi-Word DMA simultaneouly by default, which is going
13099 		 * to cause DMA command timed out, so we need to select DMA
13100 		 * mode even when it's already done by default
13101 		 */
13102 		if (sdinfo->satadrv_type != SATA_DTYPE_ATADISK) {
13103 
13104 			/* Find highest MultiWord DMA mode selected */
13105 			for (i = 2; i >= 0; --i) {
13106 				if (sdinfo->satadrv_id.ai_dworddma &
13107 				    (1 << (i + 8)))
13108 					break;
13109 			}
13110 			if (i >= mode)
13111 				/* Nothing to do */
13112 				return (SATA_SUCCESS);
13113 		}
13114 
13115 		subcmd = SATAC_TRANSFER_MODE_MULTI_WORD_DMA;
13116 	} else
13117 		return (SATA_SUCCESS);
13118 
13119 	/*
13120 	 * Set DMA mode via SET FEATURES COMMAND.
13121 	 * Prepare packet for SET FEATURES COMMAND.
13122 	 */
13123 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13124 	spx->txlt_sata_hba_inst = sata_hba_inst;
13125 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13126 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13127 	if (spkt == NULL) {
13128 		SATA_LOG_D((sata_hba_inst, CE_WARN,
13129 		    "sata_set_dma_mode: could not set DMA mode %", mode));
13130 		rval = SATA_FAILURE;
13131 		goto done;
13132 	}
13133 	/* Fill sata_pkt */
13134 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13135 	/* Timeout 30s */
13136 	spkt->satapkt_time = sata_default_pkt_time;
13137 	/* Synchronous mode, no callback, interrupts */
13138 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13139 	spkt->satapkt_comp = NULL;
13140 	scmd = &spkt->satapkt_cmd;
13141 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13142 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13143 	scmd->satacmd_addr_type = 0;
13144 	scmd->satacmd_device_reg = 0;
13145 	scmd->satacmd_status_reg = 0;
13146 	scmd->satacmd_error_reg = 0;
13147 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13148 	scmd->satacmd_features_reg = SATAC_SF_TRANSFER_MODE;
13149 	scmd->satacmd_sec_count_lsb = subcmd | mode;
13150 
13151 	/* Transfer command to HBA */
13152 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
13153 	    spkt) != SATA_TRAN_ACCEPTED ||
13154 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
13155 		/* Pkt execution failed */
13156 		rval = SATA_FAILURE;
13157 	}
13158 done:
13159 
13160 	/* Free allocated resources */
13161 	if (spkt != NULL)
13162 		sata_pkt_free(spx);
13163 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13164 
13165 	return (rval);
13166 }
13167 
13168 
13169 /*
13170  * Set device caching mode.
13171  * One of the following operations should be specified:
13172  * SATAC_SF_ENABLE_READ_AHEAD
13173  * SATAC_SF_DISABLE_READ_AHEAD
13174  * SATAC_SF_ENABLE_WRITE_CACHE
13175  * SATAC_SF_DISABLE_WRITE_CACHE
13176  *
13177  * If operation fails, system log messgage is emitted.
13178  * Returns SATA_SUCCESS when the operation succeeds, SATA_RETRY if
13179  * command was sent but did not succeed, and SATA_FAILURE otherwise.
13180  */
13181 
13182 static int
13183 sata_set_cache_mode(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13184     int cache_op)
13185 {
13186 	sata_pkt_t *spkt;
13187 	sata_cmd_t *scmd;
13188 	sata_pkt_txlate_t *spx;
13189 	int rval = SATA_SUCCESS;
13190 	int hba_rval;
13191 	char *infop;
13192 
13193 	ASSERT(sdinfo != NULL);
13194 	ASSERT(sata_hba_inst != NULL);
13195 	ASSERT(cache_op == SATAC_SF_ENABLE_READ_AHEAD ||
13196 	    cache_op == SATAC_SF_DISABLE_READ_AHEAD ||
13197 	    cache_op == SATAC_SF_ENABLE_WRITE_CACHE ||
13198 	    cache_op == SATAC_SF_DISABLE_WRITE_CACHE);
13199 
13200 
13201 	/* Prepare packet for SET FEATURES COMMAND */
13202 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13203 	spx->txlt_sata_hba_inst = sata_hba_inst;
13204 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13205 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13206 	if (spkt == NULL) {
13207 		rval = SATA_FAILURE;
13208 		goto failure;
13209 	}
13210 	/* Fill sata_pkt */
13211 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13212 	/* Timeout 30s */
13213 	spkt->satapkt_time = sata_default_pkt_time;
13214 	/* Synchronous mode, no callback, interrupts */
13215 	spkt->satapkt_op_mode =
13216 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13217 	spkt->satapkt_comp = NULL;
13218 	scmd = &spkt->satapkt_cmd;
13219 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13220 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13221 	scmd->satacmd_addr_type = 0;
13222 	scmd->satacmd_device_reg = 0;
13223 	scmd->satacmd_status_reg = 0;
13224 	scmd->satacmd_error_reg = 0;
13225 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13226 	scmd->satacmd_features_reg = cache_op;
13227 
13228 	/* Transfer command to HBA */
13229 	hba_rval = (*SATA_START_FUNC(sata_hba_inst))(
13230 	    SATA_DIP(sata_hba_inst), spkt);
13231 
13232 #ifdef SATA_INJECT_FAULTS
13233 	sata_inject_pkt_fault(spkt, &rval, sata_fault_type);
13234 #endif
13235 
13236 	if ((hba_rval != SATA_TRAN_ACCEPTED) ||
13237 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13238 		/* Pkt execution failed */
13239 		switch (cache_op) {
13240 		case SATAC_SF_ENABLE_READ_AHEAD:
13241 			infop = "enabling read ahead failed";
13242 			break;
13243 		case SATAC_SF_DISABLE_READ_AHEAD:
13244 			infop = "disabling read ahead failed";
13245 			break;
13246 		case SATAC_SF_ENABLE_WRITE_CACHE:
13247 			infop = "enabling write cache failed";
13248 			break;
13249 		case SATAC_SF_DISABLE_WRITE_CACHE:
13250 			infop = "disabling write cache failed";
13251 			break;
13252 		}
13253 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13254 		rval = SATA_RETRY;
13255 	}
13256 failure:
13257 	/* Free allocated resources */
13258 	if (spkt != NULL)
13259 		sata_pkt_free(spx);
13260 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13261 	return (rval);
13262 }
13263 
13264 /*
13265  * Set Removable Media Status Notification (enable/disable)
13266  * state == 0 , disable
13267  * state != 0 , enable
13268  *
13269  * If operation fails, system log messgage is emitted.
13270  * Returns SATA_SUCCESS when the operation succeeds, SATA_FAILURE otherwise.
13271  */
13272 
13273 static int
13274 sata_set_rmsn(sata_hba_inst_t *sata_hba_inst, sata_drive_info_t *sdinfo,
13275     int state)
13276 {
13277 	sata_pkt_t *spkt;
13278 	sata_cmd_t *scmd;
13279 	sata_pkt_txlate_t *spx;
13280 	int rval = SATA_SUCCESS;
13281 	char *infop;
13282 
13283 	ASSERT(sdinfo != NULL);
13284 	ASSERT(sata_hba_inst != NULL);
13285 
13286 	/* Prepare packet for SET FEATURES COMMAND */
13287 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
13288 	spx->txlt_sata_hba_inst = sata_hba_inst;
13289 	spx->txlt_scsi_pkt = NULL;	/* No scsi pkt involved */
13290 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
13291 	if (spkt == NULL) {
13292 		rval = SATA_FAILURE;
13293 		goto failure;
13294 	}
13295 	/* Fill sata_pkt */
13296 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
13297 	/* Timeout 30s */
13298 	spkt->satapkt_time = sata_default_pkt_time;
13299 	/* Synchronous mode, no callback, interrupts */
13300 	spkt->satapkt_op_mode =
13301 	    SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
13302 	spkt->satapkt_comp = NULL;
13303 	scmd = &spkt->satapkt_cmd;
13304 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
13305 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
13306 	scmd->satacmd_addr_type = 0;
13307 	scmd->satacmd_device_reg = 0;
13308 	scmd->satacmd_status_reg = 0;
13309 	scmd->satacmd_error_reg = 0;
13310 	scmd->satacmd_cmd_reg = SATAC_SET_FEATURES;
13311 	if (state == 0)
13312 		scmd->satacmd_features_reg = SATAC_SF_DISABLE_RMSN;
13313 	else
13314 		scmd->satacmd_features_reg = SATAC_SF_ENABLE_RMSN;
13315 
13316 	/* Transfer command to HBA */
13317 	if (((*SATA_START_FUNC(sata_hba_inst))(
13318 	    SATA_DIP(sata_hba_inst), spkt) != SATA_TRAN_ACCEPTED) ||
13319 	    (spkt->satapkt_reason != SATA_PKT_COMPLETED)) {
13320 		/* Pkt execution failed */
13321 		if (state == 0)
13322 			infop = "disabling Removable Media Status "
13323 			    "Notification failed";
13324 		else
13325 			infop = "enabling Removable Media Status "
13326 			    "Notification failed";
13327 
13328 		SATA_LOG_D((sata_hba_inst, CE_WARN, "%s", infop));
13329 		rval = SATA_FAILURE;
13330 	}
13331 failure:
13332 	/* Free allocated resources */
13333 	if (spkt != NULL)
13334 		sata_pkt_free(spx);
13335 	(void) kmem_free(spx, sizeof (sata_pkt_txlate_t));
13336 	return (rval);
13337 }
13338 
13339 
13340 /*
13341  * Update state and copy port ss* values from passed sata_device structure.
13342  * sata_address is validated - if not valid, nothing is changed in sata_scsi
13343  * configuration struct.
13344  *
13345  * SATA_PSTATE_SHUTDOWN in port state is not reset to 0 by this function
13346  * regardless of the state in device argument.
13347  *
13348  * Port mutex should be held while calling this function.
13349  */
13350 static void
13351 sata_update_port_info(sata_hba_inst_t *sata_hba_inst,
13352     sata_device_t *sata_device)
13353 {
13354 	sata_cport_info_t *cportinfo;
13355 
13356 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT ||
13357 	    sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
13358 		if (SATA_NUM_CPORTS(sata_hba_inst) <=
13359 		    sata_device->satadev_addr.cport)
13360 			return;
13361 
13362 		cportinfo = SATA_CPORT_INFO(sata_hba_inst,
13363 		    sata_device->satadev_addr.cport);
13364 
13365 		ASSERT(mutex_owned(&cportinfo->cport_mutex));
13366 		cportinfo->cport_scr = sata_device->satadev_scr;
13367 
13368 		/* Preserve SATA_PSTATE_SHUTDOWN flag */
13369 		cportinfo->cport_state &= ~(SATA_PSTATE_PWRON |
13370 		    SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13371 		cportinfo->cport_state |=
13372 		    sata_device->satadev_state & SATA_PSTATE_VALID;
13373 	}
13374 }
13375 
13376 void
13377 sata_update_pmport_info(sata_hba_inst_t *sata_hba_inst,
13378     sata_device_t *sata_device)
13379 {
13380 	sata_pmport_info_t *pmportinfo;
13381 
13382 	if ((sata_device->satadev_addr.qual != SATA_ADDR_PMPORT &&
13383 	    sata_device->satadev_addr.qual != SATA_ADDR_DPMPORT) ||
13384 	    SATA_NUM_PMPORTS(sata_hba_inst,
13385 	    sata_device->satadev_addr.cport) <
13386 	    sata_device->satadev_addr.pmport) {
13387 		SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
13388 		    "sata_update_port_info: error address %p.",
13389 		    &sata_device->satadev_addr);
13390 		return;
13391 	}
13392 
13393 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
13394 	    sata_device->satadev_addr.cport,
13395 	    sata_device->satadev_addr.pmport);
13396 
13397 	ASSERT(mutex_owned(&pmportinfo->pmport_mutex));
13398 	pmportinfo->pmport_scr = sata_device->satadev_scr;
13399 
13400 	/* Preserve SATA_PSTATE_SHUTDOWN flag */
13401 	pmportinfo->pmport_state &=
13402 	    ~(SATA_PSTATE_PWRON | SATA_PSTATE_PWROFF | SATA_PSTATE_FAILED);
13403 	pmportinfo->pmport_state |=
13404 	    sata_device->satadev_state & SATA_PSTATE_VALID;
13405 }
13406 
13407 /*
13408  * Extract SATA port specification from an IOCTL argument.
13409  *
13410  * This function return the port the user land send us as is, unless it
13411  * cannot retrieve port spec, then -1 is returned.
13412  *
13413  * Support port multiplier.
13414  */
13415 static int32_t
13416 sata_get_port_num(sata_hba_inst_t *sata_hba_inst, struct devctl_iocdata *dcp)
13417 {
13418 	int32_t port;
13419 
13420 	/* Extract port number from nvpair in dca structure  */
13421 	if (nvlist_lookup_int32(ndi_dc_get_ap_data(dcp), "port", &port) != 0) {
13422 		SATA_LOG_D((sata_hba_inst, CE_NOTE,
13423 		    "sata_get_port_num: invalid port spec 0x%x in ioctl",
13424 		    port));
13425 		port = -1;
13426 	}
13427 
13428 	return (port);
13429 }
13430 
13431 /*
13432  * Get dev_info_t pointer to the device node pointed to by port argument.
13433  * NOTE: target argument is a value used in ioctls to identify
13434  * the AP - it is not a sata_address.
13435  * It is a combination of cport, pmport and address qualifier, encodded same
13436  * way as a scsi target number.
13437  * At this moment it carries only cport number.
13438  *
13439  * PMult hotplug is supported now.
13440  *
13441  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13442  */
13443 
13444 static dev_info_t *
13445 sata_get_target_dip(dev_info_t *dip, uint8_t cport, uint8_t pmport)
13446 {
13447 	dev_info_t	*cdip = NULL;
13448 	int		target, tgt;
13449 	int 		circ;
13450 	uint8_t		qual;
13451 
13452 	sata_hba_inst_t	*sata_hba_inst;
13453 	scsi_hba_tran_t *scsi_hba_tran;
13454 
13455 	/* Get target id */
13456 	scsi_hba_tran = ddi_get_driver_private(dip);
13457 	if (scsi_hba_tran == NULL)
13458 		return (NULL);
13459 
13460 	sata_hba_inst = scsi_hba_tran->tran_hba_private;
13461 
13462 	if (sata_hba_inst == NULL)
13463 		return (NULL);
13464 
13465 	/* Identify a port-mult by cport_info.cport_dev_type */
13466 	if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT)
13467 		qual = SATA_ADDR_DPMPORT;
13468 	else
13469 		qual = SATA_ADDR_DCPORT;
13470 
13471 	target = SATA_TO_SCSI_TARGET(cport, pmport, qual);
13472 
13473 	/* Retrieve target dip */
13474 	ndi_devi_enter(dip, &circ);
13475 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13476 		dev_info_t *next = ddi_get_next_sibling(cdip);
13477 
13478 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13479 		    DDI_PROP_DONTPASS, "target", -1);
13480 		if (tgt == -1) {
13481 			/*
13482 			 * This is actually an error condition, but not
13483 			 * a fatal one. Just continue the search.
13484 			 */
13485 			cdip = next;
13486 			continue;
13487 		}
13488 
13489 		if (tgt == target)
13490 			break;
13491 
13492 		cdip = next;
13493 	}
13494 	ndi_devi_exit(dip, circ);
13495 
13496 	return (cdip);
13497 }
13498 
13499 /*
13500  * Get dev_info_t pointer to the device node pointed to by port argument.
13501  * NOTE: target argument is a value used in ioctls to identify
13502  * the AP - it is not a sata_address.
13503  * It is a combination of cport, pmport and address qualifier, encoded same
13504  * way as a scsi target number.
13505  *
13506  * Returns dev_info_t pointer if target device was found, NULL otherwise.
13507  */
13508 
13509 static dev_info_t *
13510 sata_get_scsi_target_dip(dev_info_t *dip, sata_address_t *saddr)
13511 {
13512 	dev_info_t	*cdip = NULL;
13513 	int		target, tgt;
13514 	int 		circ;
13515 
13516 	target = SATA_TO_SCSI_TARGET(saddr->cport, saddr->pmport, saddr->qual);
13517 
13518 	ndi_devi_enter(dip, &circ);
13519 	for (cdip = ddi_get_child(dip); cdip != NULL; ) {
13520 		dev_info_t *next = ddi_get_next_sibling(cdip);
13521 
13522 		tgt = ddi_prop_get_int(DDI_DEV_T_ANY, cdip,
13523 		    DDI_PROP_DONTPASS, "target", -1);
13524 		if (tgt == -1) {
13525 			/*
13526 			 * This is actually an error condition, but not
13527 			 * a fatal one. Just continue the search.
13528 			 */
13529 			cdip = next;
13530 			continue;
13531 		}
13532 
13533 		if (tgt == target)
13534 			break;
13535 
13536 		cdip = next;
13537 	}
13538 	ndi_devi_exit(dip, circ);
13539 
13540 	return (cdip);
13541 }
13542 
13543 /*
13544  * Process sata port disconnect request.
13545  * Normally, cfgadm sata plugin will try to offline (unconfigure) the device
13546  * before this request. Nevertheless, if a device is still configured,
13547  * we need to attempt to offline and unconfigure device.
13548  * Regardless of the unconfigure operation results the port is marked as
13549  * deactivated and no access to the attached device is possible.
13550  * If the target node remains because unconfigure operation failed, its state
13551  * will be set to DEVICE_REMOVED, preventing it to be used again when a device
13552  * is inserted/re-inserted. The event daemon will repeatedly try to unconfigure
13553  * the device and remove old target node.
13554  *
13555  * This function invokes sata_hba_inst->satahba_tran->
13556  * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13557  * If successful, the device structure (if any) attached to the specified port
13558  * is removed and state of the port marked appropriately.
13559  * Failure of the port_deactivate may keep port in the physically active state,
13560  * or may fail the port.
13561  *
13562  * NOTE: Port multiplier is supported.
13563  */
13564 
13565 static int
13566 sata_ioctl_disconnect(sata_hba_inst_t *sata_hba_inst,
13567     sata_device_t *sata_device)
13568 {
13569 	sata_drive_info_t *sdinfo = NULL, *subsdinfo = NULL;
13570 	sata_cport_info_t *cportinfo = NULL;
13571 	sata_pmport_info_t *pmportinfo = NULL;
13572 	sata_pmult_info_t *pmultinfo = NULL;
13573 	sata_device_t subsdevice;
13574 	int cport, pmport, qual;
13575 	int rval = SATA_SUCCESS;
13576 	int npmport = 0;
13577 	int rv = 0;
13578 
13579 	cport = sata_device->satadev_addr.cport;
13580 	pmport = sata_device->satadev_addr.pmport;
13581 	qual = sata_device->satadev_addr.qual;
13582 
13583 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13584 	if (qual == SATA_ADDR_DCPORT)
13585 		qual = SATA_ADDR_CPORT;
13586 	else
13587 		qual = SATA_ADDR_PMPORT;
13588 
13589 	/*
13590 	 * DEVCTL_AP_DISCONNECT invokes sata_hba_inst->satahba_tran->
13591 	 * sata_tran_hotplug_ops->sata_tran_port_deactivate().
13592 	 * Do the sanity check.
13593 	 */
13594 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL) {
13595 		/* No physical port deactivation supported. */
13596 		return (EINVAL);
13597 	}
13598 
13599 	/* Check the current state of the port */
13600 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
13601 	    (SATA_DIP(sata_hba_inst), sata_device);
13602 
13603 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
13604 
13605 	/*
13606 	 * Processing port mulitiplier
13607 	 */
13608 	if (qual == SATA_ADDR_CPORT &&
13609 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
13610 		mutex_enter(&cportinfo->cport_mutex);
13611 
13612 		/* Check controller port status */
13613 		sata_update_port_info(sata_hba_inst, sata_device);
13614 		if (rval != SATA_SUCCESS ||
13615 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13616 			/*
13617 			 * Device port status is unknown or it is in failed
13618 			 * state
13619 			 */
13620 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13621 			    SATA_PSTATE_FAILED;
13622 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13623 			    "sata_hba_ioctl: connect: failed to deactivate "
13624 			    "SATA port %d", cport);
13625 			mutex_exit(&cportinfo->cport_mutex);
13626 			return (EIO);
13627 		}
13628 
13629 		/* Disconnect all sub-devices. */
13630 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13631 		if (pmultinfo != NULL) {
13632 
13633 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
13634 			    sata_hba_inst, cport); npmport ++) {
13635 				subsdinfo = SATA_PMPORT_DRV_INFO(
13636 				    sata_hba_inst, cport, npmport);
13637 				if (subsdinfo == NULL)
13638 					continue;
13639 
13640 				subsdevice.satadev_addr = subsdinfo->
13641 				    satadrv_addr;
13642 
13643 				mutex_exit(&cportinfo->cport_mutex);
13644 				if (sata_ioctl_disconnect(sata_hba_inst,
13645 				    &subsdevice) == SATA_SUCCESS) {
13646 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
13647 					"[Remove] device at port %d:%d "
13648 					"successfully.", cport, npmport);
13649 				}
13650 				mutex_enter(&cportinfo->cport_mutex);
13651 			}
13652 		}
13653 
13654 		/* Disconnect the port multiplier */
13655 		cportinfo->cport_state &= ~SATA_STATE_READY;
13656 		mutex_exit(&cportinfo->cport_mutex);
13657 
13658 		sata_device->satadev_addr.qual = qual;
13659 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13660 		    (SATA_DIP(sata_hba_inst), sata_device);
13661 
13662 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13663 		    SE_NO_HINT);
13664 
13665 		mutex_enter(&cportinfo->cport_mutex);
13666 		sata_update_port_info(sata_hba_inst, sata_device);
13667 		if (rval != SATA_SUCCESS &&
13668 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13669 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13670 			rv = EIO;
13671 		} else {
13672 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13673 		}
13674 		mutex_exit(&cportinfo->cport_mutex);
13675 
13676 		return (rv);
13677 	}
13678 
13679 	/*
13680 	 * Process non-port-multiplier device - it could be a drive connected
13681 	 * to a port multiplier port or a controller port.
13682 	 */
13683 	if (qual == SATA_ADDR_PMPORT) {
13684 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13685 		mutex_enter(&pmportinfo->pmport_mutex);
13686 		sata_update_pmport_info(sata_hba_inst, sata_device);
13687 		if (rval != SATA_SUCCESS ||
13688 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13689 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
13690 			    SATA_PSTATE_FAILED;
13691 			SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
13692 			    "sata_hba_ioctl: connect: failed to deactivate "
13693 			    "SATA port %d:%d", cport, pmport);
13694 			mutex_exit(&pmportinfo->pmport_mutex);
13695 			return (EIO);
13696 		}
13697 
13698 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
13699 			sdinfo = pmportinfo->pmport_sata_drive;
13700 			ASSERT(sdinfo != NULL);
13701 		}
13702 
13703 		/*
13704 		 * Set port's dev_state to not ready - this will disable
13705 		 * an access to a potentially attached device.
13706 		 */
13707 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
13708 
13709 		/* Remove and release sata_drive info structure. */
13710 		if (sdinfo != NULL) {
13711 			if ((sdinfo->satadrv_type &
13712 			    SATA_VALID_DEV_TYPE) != 0) {
13713 				/*
13714 				 * If a target node exists, try to offline
13715 				 * a device and remove target node.
13716 				 */
13717 				mutex_exit(&pmportinfo->pmport_mutex);
13718 				(void) sata_offline_device(sata_hba_inst,
13719 				    sata_device, sdinfo);
13720 				mutex_enter(&pmportinfo->pmport_mutex);
13721 			}
13722 
13723 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
13724 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
13725 			(void) kmem_free((void *)sdinfo,
13726 			    sizeof (sata_drive_info_t));
13727 		}
13728 		mutex_exit(&pmportinfo->pmport_mutex);
13729 
13730 	} else if (qual == SATA_ADDR_CPORT) {
13731 		mutex_enter(&cportinfo->cport_mutex);
13732 		sata_update_port_info(sata_hba_inst, sata_device);
13733 		if (rval != SATA_SUCCESS ||
13734 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
13735 			/*
13736 			 * Device port status is unknown or it is in failed
13737 			 * state
13738 			 */
13739 			SATA_CPORT_STATE(sata_hba_inst, cport) =
13740 			    SATA_PSTATE_FAILED;
13741 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13742 			    "sata_hba_ioctl: connect: failed to deactivate "
13743 			    "SATA port %d", cport);
13744 			mutex_exit(&cportinfo->cport_mutex);
13745 			return (EIO);
13746 		}
13747 
13748 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
13749 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
13750 			ASSERT(pmultinfo != NULL);
13751 		} else if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
13752 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
13753 			ASSERT(sdinfo != NULL);
13754 		}
13755 		cportinfo->cport_state &= ~SATA_STATE_READY;
13756 
13757 		if (sdinfo != NULL) {
13758 			if ((sdinfo->satadrv_type &
13759 			    SATA_VALID_DEV_TYPE) != 0) {
13760 				/*
13761 				 * If a target node exists, try to offline
13762 				 * a device and remove target node.
13763 				 */
13764 				mutex_exit(&cportinfo->cport_mutex);
13765 				(void) sata_offline_device(sata_hba_inst,
13766 				    sata_device, sdinfo);
13767 				mutex_enter(&cportinfo->cport_mutex);
13768 			}
13769 
13770 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
13771 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
13772 			(void) kmem_free((void *)sdinfo,
13773 			    sizeof (sata_drive_info_t));
13774 		}
13775 		mutex_exit(&cportinfo->cport_mutex);
13776 	}
13777 
13778 	/* Just ask HBA driver to deactivate port */
13779 	sata_device->satadev_addr.qual = qual;
13780 
13781 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
13782 	    (SATA_DIP(sata_hba_inst), sata_device);
13783 
13784 	/*
13785 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13786 	 * without the hint (to force listener to investivate the state).
13787 	 */
13788 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13789 	    SE_NO_HINT);
13790 
13791 	if (qual == SATA_ADDR_PMPORT) {
13792 		mutex_enter(&pmportinfo->pmport_mutex);
13793 		sata_update_pmport_info(sata_hba_inst, sata_device);
13794 
13795 		if (rval != SATA_SUCCESS &&
13796 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13797 			/*
13798 			 * Port deactivation failure - do not change port
13799 			 * state unless the state returned by HBA indicates a
13800 			 * port failure.
13801 			 *
13802 			 * NOTE: device structures were released, so devices
13803 			 * now are invisible! Port reset is needed to
13804 			 * re-enumerate devices.
13805 			 */
13806 			pmportinfo->pmport_state = SATA_PSTATE_FAILED;
13807 			rv = EIO;
13808 		} else {
13809 			/*
13810 			 * Deactivation succeded. From now on the sata framework
13811 			 * will not care what is happening to the device, until
13812 			 * the port is activated again.
13813 			 */
13814 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
13815 		}
13816 		mutex_exit(&pmportinfo->pmport_mutex);
13817 	} else if (qual == SATA_ADDR_CPORT) {
13818 		mutex_enter(&cportinfo->cport_mutex);
13819 		sata_update_port_info(sata_hba_inst, sata_device);
13820 
13821 		if (rval != SATA_SUCCESS &&
13822 		    sata_device->satadev_state & SATA_PSTATE_FAILED) {
13823 			cportinfo->cport_state = SATA_PSTATE_FAILED;
13824 			rv = EIO;
13825 		} else {
13826 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
13827 		}
13828 		mutex_exit(&cportinfo->cport_mutex);
13829 	}
13830 
13831 	return (rv);
13832 }
13833 
13834 
13835 
13836 /*
13837  * Process sata port connect request
13838  * The sata cfgadm pluging will invoke this operation only if port was found
13839  * in the disconnect state (failed state is also treated as the disconnected
13840  * state).
13841  * DEVCTL_AP_CONNECT would invoke  sata_hba_inst->satahba_tran->
13842  * sata_tran_hotplug_ops->sata_tran_port_activate().
13843  * If successful and a device is found attached to the port,
13844  * the initialization sequence is executed to attach a device structure to
13845  * a port structure. The state of the port and a device would be set
13846  * appropriately.
13847  * The device is not set in configured state (system-wise) by this operation.
13848  *
13849  * Note, that activating the port may generate link events,
13850  * so it is important that following processing and the
13851  * event processing does not interfere with each other!
13852  *
13853  * This operation may remove port failed state and will
13854  * try to make port active and in good standing.
13855  *
13856  * NOTE: Port multiplier is supported.
13857  */
13858 
13859 static int
13860 sata_ioctl_connect(sata_hba_inst_t *sata_hba_inst,
13861     sata_device_t *sata_device)
13862 {
13863 	sata_pmport_info_t	*pmportinfo = NULL;
13864 	uint8_t cport, pmport, qual;
13865 	int rv = 0;
13866 
13867 	cport = sata_device->satadev_addr.cport;
13868 	pmport = sata_device->satadev_addr.pmport;
13869 	qual = sata_device->satadev_addr.qual;
13870 
13871 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
13872 	if (qual == SATA_ADDR_DCPORT)
13873 		qual = SATA_ADDR_CPORT;
13874 	else
13875 		qual = SATA_ADDR_PMPORT;
13876 
13877 	if (qual == SATA_ADDR_PMPORT)
13878 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
13879 
13880 	/*
13881 	 * DEVCTL_AP_CONNECT would invoke sata_hba_inst->
13882 	 * satahba_tran->sata_tran_hotplug_ops->sata_tran_port_activate().
13883 	 * Perform sanity check now.
13884 	 */
13885 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL) {
13886 		/* No physical port activation supported. */
13887 		return (EINVAL);
13888 	}
13889 
13890 	/* Just ask HBA driver to activate port */
13891 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
13892 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
13893 		/*
13894 		 * Port activation failure.
13895 		 */
13896 		if (qual == SATA_ADDR_CPORT) {
13897 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13898 			    cport)->cport_mutex);
13899 			sata_update_port_info(sata_hba_inst, sata_device);
13900 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
13901 				SATA_CPORT_STATE(sata_hba_inst, cport) =
13902 				    SATA_PSTATE_FAILED;
13903 				SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
13904 				    "sata_hba_ioctl: connect: failed to "
13905 				    "activate SATA port %d", cport);
13906 			}
13907 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
13908 			    cport)->cport_mutex);
13909 		} else { /* port multiplier device port */
13910 			mutex_enter(&pmportinfo->pmport_mutex);
13911 			sata_update_pmport_info(sata_hba_inst, sata_device);
13912 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
13913 				SATA_PMPORT_STATE(sata_hba_inst, cport,
13914 				    pmport) = SATA_PSTATE_FAILED;
13915 				SATADBG2(SATA_DBG_IOCTL_IF, sata_hba_inst,
13916 				    "sata_hba_ioctl: connect: failed to "
13917 				    "activate SATA port %d:%d", cport, pmport);
13918 			}
13919 			mutex_exit(&pmportinfo->pmport_mutex);
13920 		}
13921 		return (EIO);
13922 	}
13923 
13924 	/* Virgin port state - will be updated by the port re-probe. */
13925 	if (qual == SATA_ADDR_CPORT) {
13926 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
13927 		    cport)->cport_mutex);
13928 		SATA_CPORT_STATE(sata_hba_inst, cport) = 0;
13929 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
13930 		    cport)->cport_mutex);
13931 	} else { /* port multiplier device port */
13932 		mutex_enter(&pmportinfo->pmport_mutex);
13933 		SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) = 0;
13934 		mutex_exit(&pmportinfo->pmport_mutex);
13935 	}
13936 
13937 	/*
13938 	 * Probe the port to find its state and attached device.
13939 	 */
13940 	if (sata_reprobe_port(sata_hba_inst, sata_device,
13941 	    SATA_DEV_IDENTIFY_RETRY) == SATA_FAILURE)
13942 		rv = EIO;
13943 
13944 	/*
13945 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
13946 	 * without the hint
13947 	 */
13948 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
13949 	    SE_NO_HINT);
13950 
13951 	/*
13952 	 * If there is a device attached to the port, emit
13953 	 * a message.
13954 	 */
13955 	if (sata_device->satadev_type != SATA_DTYPE_NONE) {
13956 
13957 		if (qual == SATA_ADDR_CPORT) {
13958 			if (sata_device->satadev_type == SATA_DTYPE_PMULT) {
13959 				sata_log(sata_hba_inst, CE_WARN,
13960 				    "SATA port multiplier detected "
13961 				    "at port %d", cport);
13962 			} else {
13963 				sata_log(sata_hba_inst, CE_WARN,
13964 				    "SATA device detected at port %d", cport);
13965 				if (sata_device->satadev_type ==
13966 				    SATA_DTYPE_UNKNOWN) {
13967 				/*
13968 				 * A device was not successfully identified
13969 				 */
13970 				sata_log(sata_hba_inst, CE_WARN,
13971 				    "Could not identify SATA "
13972 				    "device at port %d", cport);
13973 				}
13974 			}
13975 		} else { /* port multiplier device port */
13976 			sata_log(sata_hba_inst, CE_WARN,
13977 			    "SATA device detected at port %d:%d",
13978 			    cport, pmport);
13979 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
13980 				/*
13981 				 * A device was not successfully identified
13982 				 */
13983 				sata_log(sata_hba_inst, CE_WARN,
13984 				    "Could not identify SATA "
13985 				    "device at port %d:%d", cport, pmport);
13986 			}
13987 		}
13988 	}
13989 
13990 	return (rv);
13991 }
13992 
13993 
13994 /*
13995  * Process sata device unconfigure request.
13996  * The unconfigure operation uses generic nexus operation to
13997  * offline a device. It leaves a target device node attached.
13998  * and obviously sata_drive_info attached as well, because
13999  * from the hardware point of view nothing has changed.
14000  */
14001 static int
14002 sata_ioctl_unconfigure(sata_hba_inst_t *sata_hba_inst,
14003     sata_device_t *sata_device)
14004 {
14005 	int rv = 0;
14006 	dev_info_t *tdip;
14007 
14008 	/* We are addressing attached device, not a port */
14009 	if (sata_device->satadev_addr.qual == SATA_ADDR_CPORT)
14010 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14011 	else if (sata_device->satadev_addr.qual == SATA_ADDR_PMPORT)
14012 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14013 
14014 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14015 	    &sata_device->satadev_addr)) != NULL) {
14016 
14017 		if (ndi_devi_offline(tdip, NDI_UNCONFIG) != NDI_SUCCESS) {
14018 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14019 			    "sata_hba_ioctl: unconfigure: "
14020 			    "failed to unconfigure device at SATA port %d:%d",
14021 			    sata_device->satadev_addr.cport,
14022 			    sata_device->satadev_addr.pmport));
14023 			rv = EIO;
14024 		}
14025 		/*
14026 		 * The target node devi_state should be marked with
14027 		 * DEVI_DEVICE_OFFLINE by ndi_devi_offline().
14028 		 * This would be the indication for cfgadm that
14029 		 * the AP node occupant state is 'unconfigured'.
14030 		 */
14031 
14032 	} else {
14033 		/*
14034 		 * This would indicate a failure on the part of cfgadm
14035 		 * to detect correct state of the node prior to this
14036 		 * call - one cannot unconfigure non-existing device.
14037 		 */
14038 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14039 		    "sata_hba_ioctl: unconfigure: "
14040 		    "attempt to unconfigure non-existing device "
14041 		    "at SATA port %d:%d",
14042 		    sata_device->satadev_addr.cport,
14043 		    sata_device->satadev_addr.pmport));
14044 		rv = ENXIO;
14045 	}
14046 	return (rv);
14047 }
14048 
14049 /*
14050  * Process sata device configure request
14051  * If port is in a failed state, operation is aborted - one has to use
14052  * an explicit connect or port activate request to try to get a port into
14053  * non-failed mode. Port reset wil also work in such situation.
14054  * If the port is in disconnected (shutdown) state, the connect operation is
14055  * attempted prior to any other action.
14056  * When port is in the active state, there is a device attached and the target
14057  * node exists, a device was most likely offlined.
14058  * If target node does not exist, a new target node is created. In both cases
14059  * an attempt is made to online (configure) the device.
14060  *
14061  * NOTE: Port multiplier is supported.
14062  */
14063 static int
14064 sata_ioctl_configure(sata_hba_inst_t *sata_hba_inst,
14065     sata_device_t *sata_device)
14066 {
14067 	int cport, pmport, qual;
14068 	int rval;
14069 	boolean_t target = TRUE;
14070 	sata_cport_info_t *cportinfo;
14071 	sata_pmport_info_t *pmportinfo = NULL;
14072 	dev_info_t *tdip;
14073 	sata_drive_info_t *sdinfo;
14074 
14075 	cport = sata_device->satadev_addr.cport;
14076 	pmport = sata_device->satadev_addr.pmport;
14077 	qual = sata_device->satadev_addr.qual;
14078 
14079 	/* Get current port state */
14080 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
14081 	    (SATA_DIP(sata_hba_inst), sata_device);
14082 
14083 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14084 	if (qual == SATA_ADDR_DPMPORT) {
14085 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14086 		mutex_enter(&pmportinfo->pmport_mutex);
14087 		sata_update_pmport_info(sata_hba_inst, sata_device);
14088 		if (rval != SATA_SUCCESS ||
14089 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14090 			/*
14091 			 * Obviously, device on a failed port is not visible
14092 			 */
14093 			mutex_exit(&pmportinfo->pmport_mutex);
14094 			return (ENXIO);
14095 		}
14096 		mutex_exit(&pmportinfo->pmport_mutex);
14097 	} else {
14098 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14099 		    cport)->cport_mutex);
14100 		sata_update_port_info(sata_hba_inst, sata_device);
14101 		if (rval != SATA_SUCCESS ||
14102 		    (sata_device->satadev_state & SATA_PSTATE_FAILED) != 0) {
14103 			/*
14104 			 * Obviously, device on a failed port is not visible
14105 			 */
14106 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14107 			    cport)->cport_mutex);
14108 			return (ENXIO);
14109 		}
14110 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14111 		    cport)->cport_mutex);
14112 	}
14113 
14114 	if ((sata_device->satadev_state & SATA_PSTATE_SHUTDOWN) != 0) {
14115 		/* need to activate port */
14116 		target = FALSE;
14117 
14118 		/* Sanity check */
14119 		if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14120 			return (ENXIO);
14121 
14122 		/* Just let HBA driver to activate port */
14123 		if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14124 		    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14125 			/*
14126 			 * Port activation failure - do not change port state
14127 			 * unless the state returned by HBA indicates a port
14128 			 * failure.
14129 			 */
14130 			if (qual == SATA_ADDR_DPMPORT) {
14131 				mutex_enter(&pmportinfo->pmport_mutex);
14132 				sata_update_pmport_info(sata_hba_inst,
14133 				    sata_device);
14134 				if (sata_device->satadev_state &
14135 				    SATA_PSTATE_FAILED)
14136 					pmportinfo->pmport_state =
14137 					    SATA_PSTATE_FAILED;
14138 				mutex_exit(&pmportinfo->pmport_mutex);
14139 			} else {
14140 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14141 				    cport)->cport_mutex);
14142 				sata_update_port_info(sata_hba_inst,
14143 				    sata_device);
14144 				if (sata_device->satadev_state &
14145 				    SATA_PSTATE_FAILED)
14146 					cportinfo->cport_state =
14147 					    SATA_PSTATE_FAILED;
14148 				mutex_exit(&SATA_CPORT_INFO(
14149 				    sata_hba_inst, cport)->cport_mutex);
14150 			}
14151 		}
14152 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14153 		    "sata_hba_ioctl: configure: "
14154 		    "failed to activate SATA port %d:%d",
14155 		    cport, pmport));
14156 		return (EIO);
14157 	}
14158 	/*
14159 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14160 	 * without the hint.
14161 	 */
14162 	sata_gen_sysevent(sata_hba_inst,
14163 	    &sata_device->satadev_addr, SE_NO_HINT);
14164 
14165 	/* Virgin port state */
14166 	if (qual == SATA_ADDR_DPMPORT) {
14167 		mutex_enter(&pmportinfo->pmport_mutex);
14168 		pmportinfo->pmport_state = 0;
14169 		mutex_exit(&pmportinfo->pmport_mutex);
14170 	} else {
14171 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14172 		    cport)-> cport_mutex);
14173 		cportinfo->cport_state = 0;
14174 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14175 		    cport)->cport_mutex);
14176 	}
14177 	/*
14178 	 * Always reprobe port, to get current device info.
14179 	 */
14180 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14181 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14182 		return (EIO);
14183 
14184 	if (sata_device->satadev_type != SATA_DTYPE_NONE && target == FALSE) {
14185 		if (qual == SATA_ADDR_DPMPORT) {
14186 			/*
14187 			 * That's the transition from "inactive" port
14188 			 * to active one with device attached.
14189 			 */
14190 			sata_log(sata_hba_inst, CE_WARN,
14191 			    "SATA device detected at port %d:%d",
14192 			    cport, pmport);
14193 		} else {
14194 			/*
14195 			 * When PM is attached to the cport and cport is
14196 			 * activated, every PM device port needs to be reprobed.
14197 			 * We need to emit message for all devices detected
14198 			 * at port multiplier's device ports.
14199 			 * Add such code here.
14200 			 * For now, just inform about device attached to
14201 			 * cport.
14202 			 */
14203 			sata_log(sata_hba_inst, CE_WARN,
14204 			    "SATA device detected at port %d", cport);
14205 		}
14206 	}
14207 
14208 	/*
14209 	 * This is where real configuration operation starts.
14210 	 *
14211 	 * When PM is attached to the cport and cport is activated,
14212 	 * devices attached PM device ports may have to be configured
14213 	 * explicitly. This may change when port multiplier is supported.
14214 	 * For now, configure only disks and other valid target devices.
14215 	 */
14216 	if (!(sata_device->satadev_type & SATA_VALID_DEV_TYPE)) {
14217 		if (qual == SATA_ADDR_DCPORT) {
14218 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14219 				/*
14220 				 * A device was not successfully identified
14221 				 */
14222 				sata_log(sata_hba_inst, CE_WARN,
14223 				    "Could not identify SATA "
14224 				    "device at port %d", cport);
14225 			}
14226 		} else { /* port multiplier device port */
14227 			if (sata_device->satadev_type == SATA_DTYPE_UNKNOWN) {
14228 				/*
14229 				 * A device was not successfully identified
14230 				 */
14231 				sata_log(sata_hba_inst, CE_WARN,
14232 				    "Could not identify SATA "
14233 				    "device at port %d:%d", cport, pmport);
14234 			}
14235 		}
14236 		return (ENXIO);		/* No device to configure */
14237 	}
14238 
14239 	/*
14240 	 * Here we may have a device in reset condition,
14241 	 * but because we are just configuring it, there is
14242 	 * no need to process the reset other than just
14243 	 * to clear device reset condition in the HBA driver.
14244 	 * Setting the flag SATA_EVNT_CLEAR_DEVICE_RESET will
14245 	 * cause a first command sent the HBA driver with the request
14246 	 * to clear device reset condition.
14247 	 */
14248 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14249 	if (qual == SATA_ADDR_DPMPORT)
14250 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14251 	else
14252 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14253 	sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
14254 	if (sdinfo == NULL) {
14255 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14256 		return (ENXIO);
14257 	}
14258 	if (sdinfo->satadrv_event_flags &
14259 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
14260 		sdinfo->satadrv_event_flags = 0;
14261 	}
14262 	sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
14263 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14264 
14265 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14266 	    &sata_device->satadev_addr)) != NULL) {
14267 		/*
14268 		 * Target node exists. Verify, that it belongs
14269 		 * to existing, attached device and not to
14270 		 * a removed device.
14271 		 */
14272 		if (sata_check_device_removed(tdip) == B_TRUE) {
14273 			if (qual == SATA_ADDR_DPMPORT)
14274 				sata_log(sata_hba_inst, CE_WARN,
14275 				    "SATA device at port %d cannot be "
14276 				    "configured. "
14277 				    "Application(s) accessing "
14278 				    "previously attached device "
14279 				    "have to release it before newly "
14280 				    "inserted device can be made accessible.",
14281 				    cport);
14282 			else
14283 				sata_log(sata_hba_inst, CE_WARN,
14284 				    "SATA device at port %d:%d cannot be"
14285 				    "configured. "
14286 				    "Application(s) accessing "
14287 				    "previously attached device "
14288 				    "have to release it before newly "
14289 				    "inserted device can be made accessible.",
14290 				    cport, pmport);
14291 			return (EIO);
14292 		}
14293 		/*
14294 		 * Device was not removed and re-inserted.
14295 		 * Try to online it.
14296 		 */
14297 		if (ndi_devi_online(tdip, 0) != NDI_SUCCESS) {
14298 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14299 			    "sata_hba_ioctl: configure: "
14300 			    "onlining device at SATA port "
14301 			    "%d:%d failed", cport, pmport));
14302 			return (EIO);
14303 		}
14304 
14305 		if (qual == SATA_ADDR_DPMPORT) {
14306 			mutex_enter(&pmportinfo->pmport_mutex);
14307 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14308 			mutex_exit(&pmportinfo->pmport_mutex);
14309 		} else {
14310 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14311 			    cport)->cport_mutex);
14312 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14313 			mutex_exit(&SATA_CPORT_INFO(
14314 			    sata_hba_inst, cport)->cport_mutex);
14315 		}
14316 	} else {
14317 		/*
14318 		 * No target node - need to create a new target node.
14319 		 */
14320 		if (qual == SATA_ADDR_DPMPORT) {
14321 			mutex_enter(&pmportinfo->pmport_mutex);
14322 			pmportinfo->pmport_tgtnode_clean = B_TRUE;
14323 			mutex_exit(&pmportinfo->pmport_mutex);
14324 		} else {
14325 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14326 			    cport_mutex);
14327 			cportinfo-> cport_tgtnode_clean = B_TRUE;
14328 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14329 			    cport_mutex);
14330 		}
14331 
14332 		tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
14333 		    sata_hba_inst, &sata_device->satadev_addr);
14334 		if (tdip == NULL) {
14335 			/* Configure operation failed */
14336 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14337 			    "sata_hba_ioctl: configure: "
14338 			    "configuring SATA device at port %d:%d "
14339 			    "failed", cport, pmport));
14340 			return (EIO);
14341 		}
14342 	}
14343 	return (0);
14344 }
14345 
14346 
14347 /*
14348  * Process ioctl deactivate port request.
14349  * Arbitrarily unconfigure attached device, if any.
14350  * Even if the unconfigure fails, proceed with the
14351  * port deactivation.
14352  *
14353  * NOTE: Port Multiplier is supported now.
14354  */
14355 
14356 static int
14357 sata_ioctl_deactivate(sata_hba_inst_t *sata_hba_inst,
14358     sata_device_t *sata_device)
14359 {
14360 	int cport, pmport, qual;
14361 	int rval, rv = 0;
14362 	int npmport;
14363 	sata_cport_info_t *cportinfo;
14364 	sata_pmport_info_t *pmportinfo;
14365 	sata_pmult_info_t *pmultinfo;
14366 	dev_info_t *tdip;
14367 	sata_drive_info_t *sdinfo = NULL;
14368 	sata_device_t subsdevice;
14369 
14370 	/* Sanity check */
14371 	if (SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst) == NULL)
14372 		return (ENOTSUP);
14373 
14374 	cport = sata_device->satadev_addr.cport;
14375 	pmport = sata_device->satadev_addr.pmport;
14376 	qual = sata_device->satadev_addr.qual;
14377 
14378 	/* SCSI_TO_SATA_ADDR_QUAL() translate ap_id into a device qualifier */
14379 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14380 	if (qual == SATA_ADDR_DCPORT)
14381 		qual = SATA_ADDR_CPORT;
14382 	else
14383 		qual = SATA_ADDR_PMPORT;
14384 
14385 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14386 	if (qual == SATA_ADDR_PMPORT)
14387 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14388 
14389 	/*
14390 	 * Processing port multiplier
14391 	 */
14392 	if (qual == SATA_ADDR_CPORT &&
14393 	    SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) == SATA_DTYPE_PMULT) {
14394 		mutex_enter(&cportinfo->cport_mutex);
14395 
14396 		/* Deactivate all sub-deices */
14397 		pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
14398 		if (pmultinfo != NULL) {
14399 			for (npmport = 0; npmport < SATA_NUM_PMPORTS(
14400 			    sata_hba_inst, cport); npmport++) {
14401 
14402 				subsdevice.satadev_addr.cport = cport;
14403 				subsdevice.satadev_addr.pmport =
14404 				    (uint8_t)npmport;
14405 				subsdevice.satadev_addr.qual =
14406 				    SATA_ADDR_DPMPORT;
14407 
14408 				SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14409 				    "sata_hba_ioctl: deactivate: trying to "
14410 				    "deactivate SATA port %d:%d",
14411 				    cport, npmport);
14412 
14413 				mutex_exit(&cportinfo->cport_mutex);
14414 				if (sata_ioctl_deactivate(sata_hba_inst,
14415 				    &subsdevice) == SATA_SUCCESS) {
14416 					SATADBG2(SATA_DBG_PMULT, sata_hba_inst,
14417 					    "[Deactivate] device at port %d:%d "
14418 					    "successfully.", cport, npmport);
14419 				}
14420 				mutex_enter(&cportinfo->cport_mutex);
14421 			}
14422 		}
14423 
14424 		/* Deactivate the port multiplier now. */
14425 		cportinfo->cport_state &= ~SATA_STATE_READY;
14426 		mutex_exit(&cportinfo->cport_mutex);
14427 
14428 		sata_device->satadev_addr.qual = qual;
14429 		rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14430 		    (SATA_DIP(sata_hba_inst), sata_device);
14431 
14432 		sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14433 		    SE_NO_HINT);
14434 
14435 		mutex_enter(&cportinfo->cport_mutex);
14436 		sata_update_port_info(sata_hba_inst, sata_device);
14437 		if (rval != SATA_SUCCESS) {
14438 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14439 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14440 			}
14441 			rv = EIO;
14442 		} else {
14443 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14444 		}
14445 		mutex_exit(&cportinfo->cport_mutex);
14446 
14447 		return (rv);
14448 	}
14449 
14450 	/*
14451 	 * Process non-port-multiplier device - it could be a drive connected
14452 	 * to a port multiplier port or a controller port.
14453 	 */
14454 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14455 	if (qual == SATA_ADDR_CPORT) {
14456 		sata_device->satadev_addr.qual = SATA_ADDR_DCPORT;
14457 		if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14458 			/* deal only with valid devices */
14459 			if ((cportinfo->cport_dev_type &
14460 			    SATA_VALID_DEV_TYPE) != 0)
14461 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
14462 		}
14463 		cportinfo->cport_state &= ~SATA_STATE_READY;
14464 	} else {
14465 		/* Port multiplier device port */
14466 		mutex_enter(&pmportinfo->pmport_mutex);
14467 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14468 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
14469 		    (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) != 0)
14470 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
14471 		pmportinfo->pmport_state &= ~SATA_STATE_READY;
14472 		mutex_exit(&pmportinfo->pmport_mutex);
14473 	}
14474 
14475 	if (sdinfo != NULL) {
14476 		/*
14477 		 * If a target node exists, try to offline a device and
14478 		 * to remove a target node.
14479 		 */
14480 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14481 		    cport_mutex);
14482 		tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
14483 		    &sata_device->satadev_addr);
14484 		if (tdip != NULL) {
14485 			/* target node exist */
14486 			SATADBG1(SATA_DBG_IOCTL_IF, sata_hba_inst,
14487 			    "sata_hba_ioctl: port deactivate: "
14488 			    "target node exists.", NULL);
14489 
14490 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) !=
14491 			    NDI_SUCCESS) {
14492 				SATA_LOG_D((sata_hba_inst, CE_WARN,
14493 				    "sata_hba_ioctl: port deactivate: "
14494 				    "failed to unconfigure device at port "
14495 				    "%d:%d before deactivating the port",
14496 				    cport, pmport));
14497 				/*
14498 				 * Set DEVICE REMOVED state in the target
14499 				 * node. It will prevent an access to
14500 				 * the device even when a new device is
14501 				 * attached, until the old target node is
14502 				 * released, removed and recreated for a new
14503 				 * device.
14504 				 */
14505 				sata_set_device_removed(tdip);
14506 
14507 				/*
14508 				 * Instruct the event daemon to try the
14509 				 * target node cleanup later.
14510 				 */
14511 				sata_set_target_node_cleanup(sata_hba_inst,
14512 				    &sata_device->satadev_addr);
14513 			}
14514 		}
14515 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14516 		    cport_mutex);
14517 		/*
14518 		 * In any case, remove and release sata_drive_info
14519 		 * structure.
14520 		 */
14521 		if (qual == SATA_ADDR_CPORT) {
14522 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
14523 			cportinfo->cport_dev_type = SATA_DTYPE_NONE;
14524 		} else { /* port multiplier device port */
14525 			mutex_enter(&pmportinfo->pmport_mutex);
14526 			SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
14527 			pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
14528 			mutex_exit(&pmportinfo->pmport_mutex);
14529 		}
14530 		(void) kmem_free((void *)sdinfo, sizeof (sata_drive_info_t));
14531 	}
14532 
14533 	if (qual == SATA_ADDR_CPORT) {
14534 		cportinfo->cport_state &= ~(SATA_STATE_PROBED |
14535 		    SATA_STATE_PROBING);
14536 	} else if (qual == SATA_ADDR_PMPORT) {
14537 		mutex_enter(&pmportinfo->pmport_mutex);
14538 		pmportinfo->pmport_state &= ~(SATA_STATE_PROBED |
14539 		    SATA_STATE_PROBING);
14540 		mutex_exit(&pmportinfo->pmport_mutex);
14541 	}
14542 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14543 
14544 	/* Just let HBA driver to deactivate port */
14545 	sata_device->satadev_addr.qual = qual;
14546 	rval = (*SATA_PORT_DEACTIVATE_FUNC(sata_hba_inst))
14547 	    (SATA_DIP(sata_hba_inst), sata_device);
14548 
14549 	/*
14550 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14551 	 * without the hint
14552 	 */
14553 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14554 	    SE_NO_HINT);
14555 
14556 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14557 	sata_update_port_info(sata_hba_inst, sata_device);
14558 	if (qual == SATA_ADDR_CPORT) {
14559 		if (rval != SATA_SUCCESS) {
14560 			/*
14561 			 * Port deactivation failure - do not change port state
14562 			 * unless the state returned by HBA indicates a port
14563 			 * failure.
14564 			 */
14565 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14566 				SATA_CPORT_STATE(sata_hba_inst, cport) =
14567 				    SATA_PSTATE_FAILED;
14568 			}
14569 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14570 			    "sata_hba_ioctl: port deactivate: "
14571 			    "cannot deactivate SATA port %d", cport));
14572 			rv = EIO;
14573 		} else {
14574 			cportinfo->cport_state |= SATA_PSTATE_SHUTDOWN;
14575 		}
14576 	} else {
14577 		mutex_enter(&pmportinfo->pmport_mutex);
14578 		if (rval != SATA_SUCCESS) {
14579 			if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14580 				SATA_PMPORT_STATE(sata_hba_inst, cport,
14581 				    pmport) = SATA_PSTATE_FAILED;
14582 			}
14583 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14584 			    "sata_hba_ioctl: port deactivate: "
14585 			    "cannot deactivate SATA port %d:%d",
14586 			    cport, pmport));
14587 			rv = EIO;
14588 		} else {
14589 			pmportinfo->pmport_state |= SATA_PSTATE_SHUTDOWN;
14590 		}
14591 		mutex_exit(&pmportinfo->pmport_mutex);
14592 	}
14593 
14594 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14595 
14596 	return (rv);
14597 }
14598 
14599 /*
14600  * Process ioctl port activate request.
14601  *
14602  * NOTE: Port multiplier is supported now.
14603  */
14604 static int
14605 sata_ioctl_activate(sata_hba_inst_t *sata_hba_inst,
14606     sata_device_t *sata_device)
14607 {
14608 	int cport, pmport, qual;
14609 	sata_cport_info_t *cportinfo;
14610 	sata_pmport_info_t *pmportinfo = NULL;
14611 	boolean_t dev_existed = TRUE;
14612 
14613 	/* Sanity check */
14614 	if (SATA_PORT_ACTIVATE_FUNC(sata_hba_inst) == NULL)
14615 		return (ENOTSUP);
14616 
14617 	cport = sata_device->satadev_addr.cport;
14618 	pmport = sata_device->satadev_addr.pmport;
14619 	qual = sata_device->satadev_addr.qual;
14620 
14621 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
14622 
14623 	/*
14624 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14625 	 * is a device. But what we are dealing with is port/pmport.
14626 	 */
14627 	ASSERT(qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_DPMPORT);
14628 	if (qual == SATA_ADDR_DCPORT)
14629 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14630 	else
14631 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14632 
14633 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14634 	if (qual == SATA_ADDR_PMPORT) {
14635 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
14636 		if (pmportinfo->pmport_state & SATA_PSTATE_SHUTDOWN ||
14637 		    pmportinfo->pmport_dev_type == SATA_DTYPE_NONE)
14638 			dev_existed = FALSE;
14639 	} else { /* cport */
14640 		if (cportinfo->cport_state & SATA_PSTATE_SHUTDOWN ||
14641 		    cportinfo->cport_dev_type == SATA_DTYPE_NONE)
14642 			dev_existed = FALSE;
14643 	}
14644 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14645 
14646 	/* Just let HBA driver to activate port, if necessary */
14647 	if ((*SATA_PORT_ACTIVATE_FUNC(sata_hba_inst))
14648 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14649 		/*
14650 		 * Port activation failure - do not change port state unless
14651 		 * the state returned by HBA indicates a port failure.
14652 		 */
14653 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
14654 		    cport)->cport_mutex);
14655 		sata_update_port_info(sata_hba_inst, sata_device);
14656 		if (sata_device->satadev_state & SATA_PSTATE_FAILED) {
14657 			if (qual == SATA_ADDR_PMPORT) {
14658 				mutex_enter(&pmportinfo->pmport_mutex);
14659 				pmportinfo->pmport_state = SATA_PSTATE_FAILED;
14660 				mutex_exit(&pmportinfo->pmport_mutex);
14661 			} else
14662 				cportinfo->cport_state = SATA_PSTATE_FAILED;
14663 
14664 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
14665 			    cport)->cport_mutex);
14666 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14667 			    "sata_hba_ioctl: port activate: cannot activate "
14668 			    "SATA port %d:%d", cport, pmport));
14669 			return (EIO);
14670 		}
14671 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14672 	}
14673 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14674 	if (qual == SATA_ADDR_PMPORT) {
14675 		mutex_enter(&pmportinfo->pmport_mutex);
14676 		pmportinfo->pmport_state &= ~SATA_PSTATE_SHUTDOWN;
14677 		mutex_exit(&pmportinfo->pmport_mutex);
14678 	} else
14679 		cportinfo->cport_state &= ~SATA_PSTATE_SHUTDOWN;
14680 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14681 
14682 	/*
14683 	 * Re-probe port to find its current state and possibly attached device.
14684 	 * Port re-probing may change the cportinfo device type if device is
14685 	 * found attached.
14686 	 * If port probing failed, the device type would be set to
14687 	 * SATA_DTYPE_NONE.
14688 	 */
14689 	(void) sata_reprobe_port(sata_hba_inst, sata_device,
14690 	    SATA_DEV_IDENTIFY_RETRY);
14691 
14692 	/*
14693 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
14694 	 * without the hint.
14695 	 */
14696 	sata_gen_sysevent(sata_hba_inst, &sata_device->satadev_addr,
14697 	    SE_NO_HINT);
14698 
14699 	if (dev_existed == FALSE) {
14700 		if (qual == SATA_ADDR_PMPORT &&
14701 		    pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
14702 			/*
14703 			 * That's the transition from the "inactive" port state
14704 			 * or the active port without a device attached to the
14705 			 * active port state with a device attached.
14706 			 */
14707 			sata_log(sata_hba_inst, CE_WARN,
14708 			    "SATA device detected at port %d:%d",
14709 			    cport, pmport);
14710 		} else if (qual == SATA_ADDR_CPORT &&
14711 		    cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
14712 			/*
14713 			 * That's the transition from the "inactive" port state
14714 			 * or the active port without a device attached to the
14715 			 * active port state with a device attached.
14716 			 */
14717 			if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
14718 				sata_log(sata_hba_inst, CE_WARN,
14719 				    "SATA device detected at port %d", cport);
14720 			} else {
14721 				sata_log(sata_hba_inst, CE_WARN,
14722 				    "SATA port multiplier detected at port %d",
14723 				    cport);
14724 			}
14725 		}
14726 	}
14727 	return (0);
14728 }
14729 
14730 
14731 
14732 /*
14733  * Process ioctl reset port request.
14734  *
14735  * NOTE: Port-Multiplier is supported.
14736  */
14737 static int
14738 sata_ioctl_reset_port(sata_hba_inst_t *sata_hba_inst,
14739     sata_device_t *sata_device)
14740 {
14741 	int cport, pmport, qual;
14742 	int rv = 0;
14743 
14744 	cport = sata_device->satadev_addr.cport;
14745 	pmport = sata_device->satadev_addr.pmport;
14746 	qual = sata_device->satadev_addr.qual;
14747 
14748 	/*
14749 	 * The qual translate from ap_id (by SCSI_TO_SATA_ADDR_QUAL())
14750 	 * is a device. But what we are dealing with is port/pmport.
14751 	 */
14752 	if (qual == SATA_ADDR_DCPORT)
14753 		sata_device->satadev_addr.qual = qual = SATA_ADDR_CPORT;
14754 	else
14755 		sata_device->satadev_addr.qual = qual = SATA_ADDR_PMPORT;
14756 	ASSERT(qual == SATA_ADDR_CPORT || qual == SATA_ADDR_PMPORT);
14757 
14758 	/* Sanity check */
14759 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14760 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14761 		    "sata_hba_ioctl: sata_hba_tran missing required "
14762 		    "function sata_tran_reset_dport"));
14763 		return (ENOTSUP);
14764 	}
14765 
14766 	/* Ask HBA to reset port */
14767 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst),
14768 	    sata_device) != SATA_SUCCESS) {
14769 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14770 		    "sata_hba_ioctl: reset port: failed %d:%d",
14771 		    cport, pmport));
14772 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14773 		    cport_mutex);
14774 		sata_update_port_info(sata_hba_inst, sata_device);
14775 		if (qual == SATA_ADDR_CPORT)
14776 			SATA_CPORT_STATE(sata_hba_inst, cport) =
14777 			    SATA_PSTATE_FAILED;
14778 		else {
14779 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14780 			    pmport));
14781 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
14782 			    SATA_PSTATE_FAILED;
14783 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport,
14784 			    pmport));
14785 		}
14786 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14787 		    cport_mutex);
14788 		rv = EIO;
14789 	}
14790 	/*
14791 	 * Beacuse the port was reset, it should be probed and
14792 	 * attached device reinitialized. At this point the
14793 	 * port state is unknown - it's state is HBA-specific.
14794 	 * Re-probe port to get its state.
14795 	 */
14796 	if (sata_reprobe_port(sata_hba_inst, sata_device,
14797 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS) {
14798 		rv = EIO;
14799 	}
14800 	return (rv);
14801 }
14802 
14803 /*
14804  * Process ioctl reset device request.
14805  *
14806  * NOTE: Port multiplier is supported.
14807  */
14808 static int
14809 sata_ioctl_reset_device(sata_hba_inst_t *sata_hba_inst,
14810     sata_device_t *sata_device)
14811 {
14812 	sata_drive_info_t *sdinfo = NULL;
14813 	sata_pmult_info_t *pmultinfo = NULL;
14814 	int cport, pmport;
14815 	int rv = 0;
14816 
14817 	/* Sanity check */
14818 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14819 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14820 		    "sata_hba_ioctl: sata_hba_tran missing required "
14821 		    "function sata_tran_reset_dport"));
14822 		return (ENOTSUP);
14823 	}
14824 
14825 	cport = sata_device->satadev_addr.cport;
14826 	pmport = sata_device->satadev_addr.pmport;
14827 
14828 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14829 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT) {
14830 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) ==
14831 		    SATA_DTYPE_PMULT)
14832 			pmultinfo = SATA_CPORT_INFO(sata_hba_inst, cport)->
14833 			    cport_devp.cport_sata_pmult;
14834 		else
14835 			sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
14836 			    sata_device->satadev_addr.cport);
14837 	} else { /* port multiplier */
14838 		sata_device->satadev_addr.qual = SATA_ADDR_DPMPORT;
14839 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
14840 		    sata_device->satadev_addr.cport,
14841 		    sata_device->satadev_addr.pmport);
14842 	}
14843 	if (sdinfo == NULL && pmultinfo == NULL) {
14844 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14845 		return (EINVAL);
14846 	}
14847 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14848 
14849 	/* Ask HBA to reset device */
14850 	if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
14851 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
14852 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14853 		    "sata_hba_ioctl: reset device: failed at port %d:%d",
14854 		    cport, pmport));
14855 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
14856 		    cport_mutex);
14857 		sata_update_port_info(sata_hba_inst, sata_device);
14858 		/*
14859 		 * Device info structure remains attached. Another device reset
14860 		 * or port disconnect/connect and re-probing is
14861 		 * needed to change it's state
14862 		 */
14863 		if (sdinfo != NULL) {
14864 			sdinfo->satadrv_state &= ~SATA_STATE_READY;
14865 			sdinfo->satadrv_state |= SATA_DSTATE_FAILED;
14866 		} else if (pmultinfo != NULL) {
14867 			pmultinfo->pmult_state &= ~SATA_STATE_READY;
14868 			pmultinfo->pmult_state |= SATA_DSTATE_FAILED;
14869 		}
14870 
14871 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->cport_mutex);
14872 		rv = EIO;
14873 	}
14874 	/*
14875 	 * If attached device was a port multiplier, some extra processing
14876 	 * may be needed to bring it back. SATA specification requies a
14877 	 * mandatory software reset on host port to reliably enumerate a port
14878 	 * multiplier, the HBA driver should handle that after reset
14879 	 * operation.
14880 	 */
14881 	return (rv);
14882 }
14883 
14884 
14885 /*
14886  * Process ioctl reset all request.
14887  */
14888 static int
14889 sata_ioctl_reset_all(sata_hba_inst_t *sata_hba_inst)
14890 {
14891 	sata_device_t sata_device;
14892 	int rv = 0;
14893 	int tcport;
14894 	int tpmport = 0;
14895 
14896 	sata_device.satadev_rev = SATA_DEVICE_REV;
14897 
14898 	/*
14899 	 * There is no protection here for configured devices.
14900 	 */
14901 	/* Sanity check */
14902 	if (SATA_RESET_DPORT_FUNC(sata_hba_inst) == NULL) {
14903 		SATA_LOG_D((sata_hba_inst, CE_WARN,
14904 		    "sata_hba_ioctl: sata_hba_tran missing required "
14905 		    "function sata_tran_reset_dport"));
14906 		return (ENOTSUP);
14907 	}
14908 
14909 	/*
14910 	 * Need to lock all ports, not just one.
14911 	 * If any port is locked by event processing, fail the whole operation.
14912 	 * One port is already locked, but for simplicity lock it again.
14913 	 */
14914 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
14915 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14916 		    cport_mutex);
14917 		if (((SATA_CPORT_INFO(sata_hba_inst, tcport)->
14918 		    cport_event_flags) & SATA_EVNT_LOCK_PORT_BUSY) != 0) {
14919 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14920 			    cport_mutex);
14921 			rv = EBUSY;
14922 			break;
14923 		} else {
14924 			/*
14925 			 * It is enough to lock cport in command-based
14926 			 * switching mode.
14927 			 */
14928 			SATA_CPORT_INFO(sata_hba_inst, tcport)->
14929 			    cport_event_flags |= SATA_APCTL_LOCK_PORT_BUSY;
14930 		}
14931 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14932 		    cport_mutex);
14933 	}
14934 
14935 	if (rv == 0) {
14936 		/*
14937 		 * All cports were successfully locked.
14938 		 * Reset main SATA controller.
14939 		 * Set the device address to port 0, to have a valid device
14940 		 * address.
14941 		 */
14942 		sata_device.satadev_addr.qual = SATA_ADDR_CNTRL;
14943 		sata_device.satadev_addr.cport = 0;
14944 		sata_device.satadev_addr.pmport = 0;
14945 
14946 		if ((*SATA_RESET_DPORT_FUNC(sata_hba_inst))
14947 		    (SATA_DIP(sata_hba_inst), &sata_device) != SATA_SUCCESS) {
14948 			SATA_LOG_D((sata_hba_inst, CE_WARN,
14949 			    "sata_hba_ioctl: reset controller failed"));
14950 			return (EIO);
14951 		}
14952 		/*
14953 		 * Because ports were reset, port states are unknown.
14954 		 * They should be re-probed to get their state and
14955 		 * attached devices should be reinitialized.
14956 		 */
14957 		for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst);
14958 		    tcport++) {
14959 			sata_device.satadev_addr.cport = tcport;
14960 			sata_device.satadev_addr.pmport = tpmport;
14961 			sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
14962 
14963 			/*
14964 			 * The sata_reprobe_port() will mark a
14965 			 * SATA_EVNT_DEVICE_RESET event on the port
14966 			 * multiplier, all its sub-ports will be probed by
14967 			 * sata daemon afterwards.
14968 			 */
14969 			if (sata_reprobe_port(sata_hba_inst, &sata_device,
14970 			    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
14971 				rv = EIO;
14972 		}
14973 	}
14974 	/*
14975 	 * Unlock all ports
14976 	 */
14977 	for (tcport = 0; tcport < SATA_NUM_CPORTS(sata_hba_inst); tcport++) {
14978 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14979 		    cport_mutex);
14980 		SATA_CPORT_INFO(sata_hba_inst, tcport)->
14981 		    cport_event_flags &= ~SATA_APCTL_LOCK_PORT_BUSY;
14982 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, tcport)->
14983 		    cport_mutex);
14984 	}
14985 
14986 	/*
14987 	 * This operation returns EFAULT if either reset
14988 	 * controller failed or a re-probing of any port failed.
14989 	 */
14990 	return (rv);
14991 }
14992 
14993 
14994 /*
14995  * Process ioctl port self test request.
14996  *
14997  * NOTE: Port multiplier code is not completed nor tested.
14998  */
14999 static int
15000 sata_ioctl_port_self_test(sata_hba_inst_t *sata_hba_inst,
15001     sata_device_t *sata_device)
15002 {
15003 	int cport, pmport, qual;
15004 	int rv = 0;
15005 
15006 	/* Sanity check */
15007 	if (SATA_SELFTEST_FUNC(sata_hba_inst) == NULL)
15008 		return (ENOTSUP);
15009 
15010 	cport = sata_device->satadev_addr.cport;
15011 	pmport = sata_device->satadev_addr.pmport;
15012 	qual = sata_device->satadev_addr.qual;
15013 
15014 	/*
15015 	 * There is no protection here for a configured
15016 	 * device attached to this port.
15017 	 */
15018 
15019 	if ((*SATA_SELFTEST_FUNC(sata_hba_inst))
15020 	    (SATA_DIP(sata_hba_inst), sata_device) != SATA_SUCCESS) {
15021 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15022 		    "sata_hba_ioctl: port selftest: "
15023 		    "failed port %d:%d", cport, pmport));
15024 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15025 		    cport_mutex);
15026 		sata_update_port_info(sata_hba_inst, sata_device);
15027 		if (qual == SATA_ADDR_CPORT)
15028 			SATA_CPORT_STATE(sata_hba_inst, cport) =
15029 			    SATA_PSTATE_FAILED;
15030 		else { /* port multiplier device port */
15031 			mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
15032 			    cport, pmport));
15033 			SATA_PMPORT_STATE(sata_hba_inst, cport, pmport) =
15034 			    SATA_PSTATE_FAILED;
15035 			mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
15036 			    cport, pmport));
15037 		}
15038 
15039 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, cport)->
15040 		    cport_mutex);
15041 		return (EIO);
15042 	}
15043 	/*
15044 	 * Beacuse the port was reset in the course of testing, it should be
15045 	 * re-probed and attached device state should be restored. At this
15046 	 * point the port state is unknown - it's state is HBA-specific.
15047 	 * Force port re-probing to get it into a known state.
15048 	 */
15049 	if (sata_reprobe_port(sata_hba_inst, sata_device,
15050 	    SATA_DEV_IDENTIFY_RETRY) != SATA_SUCCESS)
15051 		rv = EIO;
15052 	return (rv);
15053 }
15054 
15055 
15056 /*
15057  * sata_cfgadm_state:
15058  * Use the sata port state and state of the target node to figure out
15059  * the cfgadm_state.
15060  *
15061  * The port argument is a value with encoded cport,
15062  * pmport and address qualifier, in the same manner as a scsi target number.
15063  * SCSI_TO_SATA_CPORT macro extracts cport number,
15064  * SCSI_TO_SATA_PMPORT extracts pmport number and
15065  * SCSI_TO_SATA_ADDR_QUAL extracts port mulitplier qualifier flag.
15066  *
15067  * Port multiplier is supported.
15068  */
15069 
15070 static void
15071 sata_cfgadm_state(sata_hba_inst_t *sata_hba_inst, int32_t port,
15072     devctl_ap_state_t *ap_state)
15073 {
15074 	uint8_t		cport, pmport, qual;
15075 	uint32_t	port_state, pmult_state;
15076 	uint32_t	dev_type;
15077 	sata_drive_info_t *sdinfo;
15078 
15079 	cport = SCSI_TO_SATA_CPORT(port);
15080 	pmport = SCSI_TO_SATA_PMPORT(port);
15081 	qual = SCSI_TO_SATA_ADDR_QUAL(port);
15082 
15083 	/* Check cport state */
15084 	port_state = SATA_CPORT_STATE(sata_hba_inst, cport);
15085 	if (port_state & SATA_PSTATE_SHUTDOWN ||
15086 	    port_state & SATA_PSTATE_FAILED) {
15087 		ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15088 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15089 		if (port_state & SATA_PSTATE_FAILED)
15090 			ap_state->ap_condition = AP_COND_FAILED;
15091 		else
15092 			ap_state->ap_condition = AP_COND_UNKNOWN;
15093 
15094 		return;
15095 	}
15096 
15097 	/* cport state is okay. Now check pmport state */
15098 	if (qual == SATA_ADDR_DPMPORT || qual == SATA_ADDR_PMPORT) {
15099 		/* Sanity check */
15100 		if (SATA_CPORT_DEV_TYPE(sata_hba_inst, cport) !=
15101 		    SATA_DTYPE_PMULT || SATA_PMPORT_INFO(sata_hba_inst,
15102 		    cport, pmport) == NULL)
15103 			return;
15104 		port_state = SATA_PMPORT_STATE(sata_hba_inst, cport, pmport);
15105 		if (port_state & SATA_PSTATE_SHUTDOWN ||
15106 		    port_state & SATA_PSTATE_FAILED) {
15107 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15108 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15109 			if (port_state & SATA_PSTATE_FAILED)
15110 				ap_state->ap_condition = AP_COND_FAILED;
15111 			else
15112 				ap_state->ap_condition = AP_COND_UNKNOWN;
15113 
15114 			return;
15115 		}
15116 	}
15117 
15118 	/* Port is enabled and ready */
15119 	if (qual == SATA_ADDR_DCPORT || qual == SATA_ADDR_CPORT)
15120 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst, cport);
15121 	else
15122 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst, cport, pmport);
15123 
15124 	switch (dev_type) {
15125 	case SATA_DTYPE_NONE:
15126 	{
15127 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15128 		ap_state->ap_condition = AP_COND_OK;
15129 		/* No device attached */
15130 		ap_state->ap_rstate = AP_RSTATE_EMPTY;
15131 		break;
15132 	}
15133 	case SATA_DTYPE_PMULT:
15134 	{
15135 		/* Need to check port multiplier state */
15136 		ASSERT(qual == SATA_ADDR_DCPORT);
15137 		pmult_state = SATA_PMULT_INFO(sata_hba_inst, cport)->
15138 		    pmult_state;
15139 		if (pmult_state & (SATA_PSTATE_SHUTDOWN|SATA_PSTATE_FAILED)) {
15140 			ap_state->ap_rstate = AP_RSTATE_DISCONNECTED;
15141 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15142 			if (pmult_state & SATA_PSTATE_FAILED)
15143 				ap_state->ap_condition = AP_COND_FAILED;
15144 			else
15145 				ap_state->ap_condition = AP_COND_UNKNOWN;
15146 
15147 			return;
15148 		}
15149 
15150 		/* Port multiplier is not configurable */
15151 		ap_state->ap_ostate = AP_OSTATE_CONFIGURED;
15152 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15153 		ap_state->ap_condition = AP_COND_OK;
15154 		break;
15155 	}
15156 
15157 	case SATA_DTYPE_ATADISK:
15158 	case SATA_DTYPE_ATAPICD:
15159 	case SATA_DTYPE_ATAPITAPE:
15160 	case SATA_DTYPE_ATAPIDISK:
15161 	{
15162 		dev_info_t *tdip = NULL;
15163 		dev_info_t *dip = NULL;
15164 		int circ;
15165 
15166 		dip = SATA_DIP(sata_hba_inst);
15167 		tdip = sata_get_target_dip(dip, cport, pmport);
15168 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15169 		if (tdip != NULL) {
15170 			ndi_devi_enter(dip, &circ);
15171 			mutex_enter(&(DEVI(tdip)->devi_lock));
15172 			if (DEVI_IS_DEVICE_REMOVED(tdip)) {
15173 				/*
15174 				 * There could be the case where previously
15175 				 * configured and opened device was removed
15176 				 * and unknown device was plugged.
15177 				 * In such case we want to show a device, and
15178 				 * its configured or unconfigured state but
15179 				 * indicate unusable condition untill the
15180 				 * old target node is released and removed.
15181 				 */
15182 				ap_state->ap_condition = AP_COND_UNUSABLE;
15183 			} else {
15184 				mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst,
15185 				    cport));
15186 				sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15187 				    cport);
15188 				if (sdinfo != NULL) {
15189 					if ((sdinfo->satadrv_state &
15190 					    SATA_DSTATE_FAILED) != 0)
15191 						ap_state->ap_condition =
15192 						    AP_COND_FAILED;
15193 					else
15194 						ap_state->ap_condition =
15195 						    AP_COND_OK;
15196 				} else {
15197 					ap_state->ap_condition =
15198 					    AP_COND_UNKNOWN;
15199 				}
15200 				mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst,
15201 				    cport));
15202 			}
15203 			if ((DEVI_IS_DEVICE_OFFLINE(tdip)) ||
15204 			    (DEVI_IS_DEVICE_DOWN(tdip))) {
15205 				ap_state->ap_ostate =
15206 				    AP_OSTATE_UNCONFIGURED;
15207 			} else {
15208 				ap_state->ap_ostate =
15209 				    AP_OSTATE_CONFIGURED;
15210 			}
15211 			mutex_exit(&(DEVI(tdip)->devi_lock));
15212 			ndi_devi_exit(dip, circ);
15213 		} else {
15214 			ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15215 			ap_state->ap_condition = AP_COND_UNKNOWN;
15216 		}
15217 		break;
15218 	}
15219 	default:
15220 		ap_state->ap_rstate = AP_RSTATE_CONNECTED;
15221 		ap_state->ap_ostate = AP_OSTATE_UNCONFIGURED;
15222 		ap_state->ap_condition = AP_COND_UNKNOWN;
15223 		/*
15224 		 * This is actually internal error condition (non fatal),
15225 		 * because we have already checked all defined device types.
15226 		 */
15227 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15228 		    "sata_cfgadm_state: Internal error: "
15229 		    "unknown device type"));
15230 		break;
15231 	}
15232 }
15233 
15234 
15235 /*
15236  * Process ioctl get device path request.
15237  *
15238  * NOTE: Port multiplier has no target dip. Devices connected to port
15239  * multiplier have target node attached to the HBA node. The only difference
15240  * between them and the directly-attached device node is a target address.
15241  */
15242 static int
15243 sata_ioctl_get_device_path(sata_hba_inst_t *sata_hba_inst,
15244     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15245 {
15246 	char path[MAXPATHLEN];
15247 	uint32_t size;
15248 	dev_info_t *tdip;
15249 
15250 	(void) strcpy(path, "/devices");
15251 	if ((tdip = sata_get_scsi_target_dip(SATA_DIP(sata_hba_inst),
15252 	    &sata_device->satadev_addr)) == NULL) {
15253 		/*
15254 		 * No such device. If this is a request for a size, do not
15255 		 * return EINVAL for non-existing target, because cfgadm
15256 		 * will then indicate a meaningless ioctl failure.
15257 		 * If this is a request for a path, indicate invalid
15258 		 * argument.
15259 		 */
15260 		if (ioc->get_size == 0)
15261 			return (EINVAL);
15262 	} else {
15263 		(void) ddi_pathname(tdip, path + strlen(path));
15264 	}
15265 	size = strlen(path) + 1;
15266 
15267 	if (ioc->get_size != 0) {
15268 		if (ddi_copyout((void *)&size, ioc->buf, ioc->bufsiz,
15269 		    mode) != 0)
15270 			return (EFAULT);
15271 	} else {
15272 		if (ioc->bufsiz != size)
15273 			return (EINVAL);
15274 
15275 		else if (ddi_copyout((void *)&path, ioc->buf, ioc->bufsiz,
15276 		    mode) != 0)
15277 			return (EFAULT);
15278 	}
15279 	return (0);
15280 }
15281 
15282 /*
15283  * Process ioctl get attachment point type request.
15284  *
15285  * NOTE: Port multiplier is supported.
15286  */
15287 static	int
15288 sata_ioctl_get_ap_type(sata_hba_inst_t *sata_hba_inst,
15289     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15290 {
15291 	uint32_t	type_len;
15292 	const char	*ap_type;
15293 	int		dev_type;
15294 
15295 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15296 		dev_type = SATA_CPORT_DEV_TYPE(sata_hba_inst,
15297 		    sata_device->satadev_addr.cport);
15298 	else /* pmport */
15299 		dev_type = SATA_PMPORT_DEV_TYPE(sata_hba_inst,
15300 		    sata_device->satadev_addr.cport,
15301 		    sata_device->satadev_addr.pmport);
15302 
15303 	switch (dev_type) {
15304 	case SATA_DTYPE_NONE:
15305 		ap_type = "port";
15306 		break;
15307 
15308 	case SATA_DTYPE_ATADISK:
15309 	case SATA_DTYPE_ATAPIDISK:
15310 		ap_type = "disk";
15311 		break;
15312 
15313 	case SATA_DTYPE_ATAPICD:
15314 		ap_type = "cd/dvd";
15315 		break;
15316 
15317 	case SATA_DTYPE_ATAPITAPE:
15318 		ap_type = "tape";
15319 		break;
15320 
15321 	case SATA_DTYPE_PMULT:
15322 		ap_type = "sata-pmult";
15323 		break;
15324 
15325 	case SATA_DTYPE_UNKNOWN:
15326 		ap_type = "unknown";
15327 		break;
15328 
15329 	default:
15330 		ap_type = "unsupported";
15331 		break;
15332 
15333 	} /* end of dev_type switch */
15334 
15335 	type_len = strlen(ap_type) + 1;
15336 
15337 	if (ioc->get_size) {
15338 		if (ddi_copyout((void *)&type_len, ioc->buf, ioc->bufsiz,
15339 		    mode) != 0)
15340 			return (EFAULT);
15341 	} else {
15342 		if (ioc->bufsiz != type_len)
15343 			return (EINVAL);
15344 
15345 		if (ddi_copyout((void *)ap_type, ioc->buf,
15346 		    ioc->bufsiz, mode) != 0)
15347 			return (EFAULT);
15348 	}
15349 	return (0);
15350 
15351 }
15352 
15353 /*
15354  * Process ioctl get device model info request.
15355  * This operation should return to cfgadm the device model
15356  * information string
15357  *
15358  * NOTE: Port multiplier is supported.
15359  */
15360 static	int
15361 sata_ioctl_get_model_info(sata_hba_inst_t *sata_hba_inst,
15362     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15363 {
15364 	sata_drive_info_t *sdinfo;
15365 	uint32_t info_len;
15366 	char ap_info[SATA_ID_MODEL_LEN + 1];
15367 
15368 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15369 	    sata_device->satadev_addr.cport)->cport_mutex);
15370 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15371 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15372 		    sata_device->satadev_addr.cport);
15373 	else /* port multiplier */
15374 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15375 		    sata_device->satadev_addr.cport,
15376 		    sata_device->satadev_addr.pmport);
15377 	if (sdinfo == NULL) {
15378 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15379 		    sata_device->satadev_addr.cport)->cport_mutex);
15380 		return (EINVAL);
15381 	}
15382 
15383 #ifdef	_LITTLE_ENDIAN
15384 	swab(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15385 #else	/* _LITTLE_ENDIAN */
15386 	bcopy(sdinfo->satadrv_id.ai_model, ap_info, SATA_ID_MODEL_LEN);
15387 #endif	/* _LITTLE_ENDIAN */
15388 
15389 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15390 	    sata_device->satadev_addr.cport)->cport_mutex);
15391 
15392 	ap_info[SATA_ID_MODEL_LEN] = '\0';
15393 
15394 	info_len = strlen(ap_info) + 1;
15395 
15396 	if (ioc->get_size) {
15397 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15398 		    mode) != 0)
15399 			return (EFAULT);
15400 	} else {
15401 		if (ioc->bufsiz < info_len)
15402 			return (EINVAL);
15403 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15404 		    mode) != 0)
15405 			return (EFAULT);
15406 	}
15407 	return (0);
15408 }
15409 
15410 
15411 /*
15412  * Process ioctl get device firmware revision info request.
15413  * This operation should return to cfgadm the device firmware revision
15414  * information string
15415  *
15416  * Port multiplier is supported.
15417  */
15418 static	int
15419 sata_ioctl_get_revfirmware_info(sata_hba_inst_t *sata_hba_inst,
15420     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15421 {
15422 	sata_drive_info_t *sdinfo;
15423 	uint32_t info_len;
15424 	char ap_info[SATA_ID_FW_LEN + 1];
15425 
15426 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15427 	    sata_device->satadev_addr.cport)->cport_mutex);
15428 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15429 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15430 		    sata_device->satadev_addr.cport);
15431 	else /* port multiplier */
15432 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15433 		    sata_device->satadev_addr.cport,
15434 		    sata_device->satadev_addr.pmport);
15435 	if (sdinfo == NULL) {
15436 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15437 		    sata_device->satadev_addr.cport)->cport_mutex);
15438 		return (EINVAL);
15439 	}
15440 
15441 #ifdef	_LITTLE_ENDIAN
15442 	swab(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15443 #else	/* _LITTLE_ENDIAN */
15444 	bcopy(sdinfo->satadrv_id.ai_fw, ap_info, SATA_ID_FW_LEN);
15445 #endif	/* _LITTLE_ENDIAN */
15446 
15447 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15448 	    sata_device->satadev_addr.cport)->cport_mutex);
15449 
15450 	ap_info[SATA_ID_FW_LEN] = '\0';
15451 
15452 	info_len = strlen(ap_info) + 1;
15453 
15454 	if (ioc->get_size) {
15455 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15456 		    mode) != 0)
15457 			return (EFAULT);
15458 	} else {
15459 		if (ioc->bufsiz < info_len)
15460 			return (EINVAL);
15461 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15462 		    mode) != 0)
15463 			return (EFAULT);
15464 	}
15465 	return (0);
15466 }
15467 
15468 
15469 /*
15470  * Process ioctl get device serial number info request.
15471  * This operation should return to cfgadm the device serial number string.
15472  *
15473  * NOTE: Port multiplier is supported.
15474  */
15475 static	int
15476 sata_ioctl_get_serialnumber_info(sata_hba_inst_t *sata_hba_inst,
15477     sata_device_t *sata_device, sata_ioctl_data_t *ioc, int mode)
15478 {
15479 	sata_drive_info_t *sdinfo;
15480 	uint32_t info_len;
15481 	char ap_info[SATA_ID_SERIAL_LEN + 1];
15482 
15483 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
15484 	    sata_device->satadev_addr.cport)->cport_mutex);
15485 	if (sata_device->satadev_addr.qual == SATA_ADDR_DCPORT)
15486 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst,
15487 		    sata_device->satadev_addr.cport);
15488 	else /* port multiplier */
15489 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst,
15490 		    sata_device->satadev_addr.cport,
15491 		    sata_device->satadev_addr.pmport);
15492 	if (sdinfo == NULL) {
15493 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15494 		    sata_device->satadev_addr.cport)->cport_mutex);
15495 		return (EINVAL);
15496 	}
15497 
15498 #ifdef	_LITTLE_ENDIAN
15499 	swab(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15500 #else	/* _LITTLE_ENDIAN */
15501 	bcopy(sdinfo->satadrv_id.ai_drvser, ap_info, SATA_ID_SERIAL_LEN);
15502 #endif	/* _LITTLE_ENDIAN */
15503 
15504 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
15505 	    sata_device->satadev_addr.cport)->cport_mutex);
15506 
15507 	ap_info[SATA_ID_SERIAL_LEN] = '\0';
15508 
15509 	info_len = strlen(ap_info) + 1;
15510 
15511 	if (ioc->get_size) {
15512 		if (ddi_copyout((void *)&info_len, ioc->buf, ioc->bufsiz,
15513 		    mode) != 0)
15514 			return (EFAULT);
15515 	} else {
15516 		if (ioc->bufsiz < info_len)
15517 			return (EINVAL);
15518 		if (ddi_copyout((void *)ap_info, ioc->buf, ioc->bufsiz,
15519 		    mode) != 0)
15520 			return (EFAULT);
15521 	}
15522 	return (0);
15523 }
15524 
15525 
15526 /*
15527  * Preset scsi extended sense data (to NO SENSE)
15528  * First 18 bytes of the sense data are preset to current valid sense
15529  * with a key NO SENSE data.
15530  *
15531  * Returns void
15532  */
15533 static void
15534 sata_fixed_sense_data_preset(struct scsi_extended_sense *sense)
15535 {
15536 	sense->es_valid = 1;		/* Valid sense */
15537 	sense->es_class = CLASS_EXTENDED_SENSE;	/* 0x70 - current err */
15538 	sense->es_key = KEY_NO_SENSE;
15539 	sense->es_info_1 = 0;
15540 	sense->es_info_2 = 0;
15541 	sense->es_info_3 = 0;
15542 	sense->es_info_4 = 0;
15543 	sense->es_add_len = 10;	/* Additional length - replace with a def */
15544 	sense->es_cmd_info[0] = 0;
15545 	sense->es_cmd_info[1] = 0;
15546 	sense->es_cmd_info[2] = 0;
15547 	sense->es_cmd_info[3] = 0;
15548 	sense->es_add_code = 0;
15549 	sense->es_qual_code = 0;
15550 }
15551 
15552 /*
15553  * Register a legacy cmdk-style devid for the target (disk) device.
15554  *
15555  * Note: This function is called only when the HBA devinfo node has the
15556  * property "use-cmdk-devid-format" set. This property indicates that
15557  * devid compatible with old cmdk (target) driver is to be generated
15558  * for any target device attached to this controller. This will take
15559  * precedence over the devid generated by sd (target) driver.
15560  * This function is derived from cmdk_devid_setup() function in cmdk.c.
15561  */
15562 static void
15563 sata_target_devid_register(dev_info_t *dip, sata_drive_info_t *sdinfo)
15564 {
15565 	char	*hwid;
15566 	int	modlen;
15567 	int	serlen;
15568 	int	rval;
15569 	ddi_devid_t	devid;
15570 
15571 	/*
15572 	 * device ID is a concatanation of model number, "=", serial number.
15573 	 */
15574 	hwid = kmem_zalloc(LEGACY_HWID_LEN, KM_SLEEP);
15575 	bcopy(&sdinfo->satadrv_id.ai_model, hwid,
15576 	    sizeof (sdinfo->satadrv_id.ai_model));
15577 	swab(hwid, hwid, sizeof (sdinfo->satadrv_id.ai_model));
15578 	modlen = sata_check_modser(hwid, sizeof (sdinfo->satadrv_id.ai_model));
15579 	if (modlen == 0)
15580 		goto err;
15581 	hwid[modlen++] = '=';
15582 	bcopy(&sdinfo->satadrv_id.ai_drvser, &hwid[modlen],
15583 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15584 	swab(&hwid[modlen], &hwid[modlen],
15585 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15586 	serlen = sata_check_modser(&hwid[modlen],
15587 	    sizeof (sdinfo->satadrv_id.ai_drvser));
15588 	if (serlen == 0)
15589 		goto err;
15590 	hwid[modlen + serlen] = 0; /* terminate the hwid string */
15591 
15592 	/* initialize/register devid */
15593 	if ((rval = ddi_devid_init(dip, DEVID_ATA_SERIAL,
15594 	    (ushort_t)(modlen + serlen), hwid, &devid)) == DDI_SUCCESS) {
15595 		rval = ddi_devid_register(dip, devid);
15596 		/*
15597 		 * Free up the allocated devid buffer.
15598 		 * NOTE: This doesn't mean unregistering devid.
15599 		 */
15600 		ddi_devid_free(devid);
15601 	}
15602 
15603 	if (rval != DDI_SUCCESS)
15604 		cmn_err(CE_WARN, "sata: failed to create devid for the disk"
15605 		    " on port %d", sdinfo->satadrv_addr.cport);
15606 err:
15607 	kmem_free(hwid, LEGACY_HWID_LEN);
15608 }
15609 
15610 /*
15611  * valid model/serial string must contain a non-zero non-space characters.
15612  * trim trailing spaces/NULLs.
15613  */
15614 static int
15615 sata_check_modser(char *buf, int buf_len)
15616 {
15617 	boolean_t ret;
15618 	char *s;
15619 	int i;
15620 	int tb;
15621 	char ch;
15622 
15623 	ret = B_FALSE;
15624 	s = buf;
15625 	for (i = 0; i < buf_len; i++) {
15626 		ch = *s++;
15627 		if (ch != ' ' && ch != '\0')
15628 			tb = i + 1;
15629 		if (ch != ' ' && ch != '\0' && ch != '0')
15630 			ret = B_TRUE;
15631 	}
15632 
15633 	if (ret == B_FALSE)
15634 		return (0); /* invalid string */
15635 
15636 	return (tb); /* return length */
15637 }
15638 
15639 /*
15640  * sata_set_drive_features function compares current device features setting
15641  * with the saved device features settings and, if there is a difference,
15642  * it restores device features setting to the previously saved state.
15643  * It also arbitrarily tries to select the highest supported DMA mode.
15644  * Device Identify or Identify Packet Device data has to be current.
15645  * At the moment read ahead and write cache are considered for all devices.
15646  * For atapi devices, Removable Media Status Notification is set in addition
15647  * to common features.
15648  *
15649  * This function cannot be called in the interrupt context (it may sleep).
15650  *
15651  * The input argument sdinfo should point to the drive info structure
15652  * to be updated after features are set. Note, that only
15653  * device (packet) identify data is updated, not the flags indicating the
15654  * supported features.
15655  *
15656  * Returns SATA_SUCCESS if successful or there was nothing to do.
15657  * Device Identify data in the drive info structure pointed to by the sdinfo
15658  * arguments is updated even when no features were set or changed.
15659  *
15660  * Returns SATA_FAILURE if device features could not be set or DMA mode
15661  * for a disk cannot be set and device identify data cannot be fetched.
15662  *
15663  * Returns SATA_RETRY if device features could not be set (other than disk
15664  * DMA mode) but the device identify data was fetched successfully.
15665  *
15666  * Note: This function may fail the port, making it inaccessible.
15667  * In such case the explicit port disconnect/connect or physical device
15668  * detach/attach is required to re-evaluate port state again.
15669  */
15670 
15671 static int
15672 sata_set_drive_features(sata_hba_inst_t *sata_hba_inst,
15673     sata_drive_info_t *sdinfo, int restore)
15674 {
15675 	int rval = SATA_SUCCESS;
15676 	int rval_set;
15677 	sata_drive_info_t new_sdinfo;
15678 	char *finfo = "sata_set_drive_features: cannot";
15679 	char *finfox;
15680 	int cache_op;
15681 
15682 	bzero(&new_sdinfo, sizeof (sata_drive_info_t));
15683 	new_sdinfo.satadrv_addr = sdinfo->satadrv_addr;
15684 	new_sdinfo.satadrv_type = sdinfo->satadrv_type;
15685 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15686 		/*
15687 		 * Cannot get device identification - caller may retry later
15688 		 */
15689 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15690 		    "%s fetch device identify data\n", finfo);
15691 		return (SATA_FAILURE);
15692 	}
15693 	finfox = (restore != 0) ? " restore device features" :
15694 	    " initialize device features\n";
15695 
15696 	switch (sdinfo->satadrv_type) {
15697 	case SATA_DTYPE_ATADISK:
15698 		/* Arbitrarily set UDMA mode */
15699 		if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15700 		    SATA_SUCCESS) {
15701 			SATA_LOG_D((sata_hba_inst, CE_WARN,
15702 			    "%s set UDMA mode\n", finfo));
15703 			return (SATA_FAILURE);
15704 		}
15705 		break;
15706 	case SATA_DTYPE_ATAPICD:
15707 	case SATA_DTYPE_ATAPITAPE:
15708 	case SATA_DTYPE_ATAPIDISK:
15709 		/*  Set Removable Media Status Notification, if necessary */
15710 		if (SATA_RM_NOTIFIC_SUPPORTED(new_sdinfo.satadrv_id) &&
15711 		    restore != 0) {
15712 			if (((sdinfo->satadrv_settings & SATA_DEV_RMSN) &&
15713 			    (!SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id)))||
15714 			    ((!(sdinfo->satadrv_settings & SATA_DEV_RMSN)) &&
15715 			    SATA_RM_NOTIFIC_ENABLED(new_sdinfo.satadrv_id))) {
15716 				/* Current setting does not match saved one */
15717 				if (sata_set_rmsn(sata_hba_inst, sdinfo,
15718 				    sdinfo->satadrv_settings &
15719 				    SATA_DEV_RMSN) != SATA_SUCCESS)
15720 					rval = SATA_FAILURE;
15721 			}
15722 		}
15723 		/*
15724 		 * We have to set Multiword DMA or UDMA, if it is supported, as
15725 		 * we want to use DMA transfer mode whenever possible.
15726 		 * Some devices require explicit setting of the DMA mode.
15727 		 */
15728 		if (new_sdinfo.satadrv_id.ai_cap & SATA_DMA_SUPPORT) {
15729 			/* Set highest supported DMA mode */
15730 			if (sata_set_dma_mode(sata_hba_inst, &new_sdinfo) !=
15731 			    SATA_SUCCESS) {
15732 				SATA_LOG_D((sata_hba_inst, CE_WARN,
15733 				    "%s set UDMA mode\n", finfo));
15734 				rval = SATA_FAILURE;
15735 			}
15736 		}
15737 		break;
15738 	}
15739 
15740 	if (!SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id) &&
15741 	    !SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15742 		/*
15743 		 * neither READ AHEAD nor WRITE CACHE is supported
15744 		 * - do nothing
15745 		 */
15746 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15747 		    "settable features not supported\n", NULL);
15748 		goto update_sdinfo;
15749 	}
15750 
15751 	if ((SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id) &&
15752 	    (sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD)) &&
15753 	    (SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id) &&
15754 	    (sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE))) {
15755 		/*
15756 		 * both READ AHEAD and WRITE CACHE are enabled
15757 		 * - Nothing to do
15758 		 */
15759 		SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15760 		    "no device features to set\n", NULL);
15761 		goto update_sdinfo;
15762 	}
15763 
15764 	cache_op = 0;
15765 
15766 	if (SATA_READ_AHEAD_SUPPORTED(new_sdinfo.satadrv_id)) {
15767 		if ((sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15768 		    !SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15769 			/* Enable read ahead / read cache */
15770 			cache_op = SATAC_SF_ENABLE_READ_AHEAD;
15771 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15772 			    "enabling read cache\n", NULL);
15773 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_READ_AHEAD) &&
15774 		    SATA_READ_AHEAD_ENABLED(new_sdinfo.satadrv_id)) {
15775 			/* Disable read ahead  / read cache */
15776 			cache_op = SATAC_SF_DISABLE_READ_AHEAD;
15777 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15778 			    "disabling read cache\n", NULL);
15779 		}
15780 
15781 		if (cache_op != 0) {
15782 			/* Try to set read cache mode */
15783 			rval_set = sata_set_cache_mode(sata_hba_inst,
15784 			    &new_sdinfo, cache_op);
15785 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15786 				rval = rval_set;
15787 		}
15788 	}
15789 
15790 	cache_op = 0;
15791 
15792 	if (SATA_WRITE_CACHE_SUPPORTED(new_sdinfo.satadrv_id)) {
15793 		if ((sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15794 		    !SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15795 			/* Enable write cache */
15796 			cache_op = SATAC_SF_ENABLE_WRITE_CACHE;
15797 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15798 			    "enabling write cache\n", NULL);
15799 		} else if (!(sdinfo->satadrv_settings & SATA_DEV_WRITE_CACHE) &&
15800 		    SATA_WRITE_CACHE_ENABLED(new_sdinfo.satadrv_id)) {
15801 			/* Disable write cache */
15802 			cache_op = SATAC_SF_DISABLE_WRITE_CACHE;
15803 			SATADBG1(SATA_DBG_DEV_SETTINGS, sata_hba_inst,
15804 			    "disabling write cache\n", NULL);
15805 		}
15806 
15807 		if (cache_op != 0) {
15808 			/* Try to set write cache mode */
15809 			rval_set = sata_set_cache_mode(sata_hba_inst,
15810 			    &new_sdinfo, cache_op);
15811 			if (rval != SATA_FAILURE && rval_set != SATA_SUCCESS)
15812 				rval = rval_set;
15813 		}
15814 	}
15815 	if (rval != SATA_SUCCESS)
15816 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15817 		    "%s %s", finfo, finfox));
15818 
15819 update_sdinfo:
15820 	/*
15821 	 * We need to fetch Device Identify data again
15822 	 */
15823 	if (sata_fetch_device_identify_data(sata_hba_inst, &new_sdinfo) != 0) {
15824 		/*
15825 		 * Cannot get device identification - retry later
15826 		 */
15827 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15828 		    "%s re-fetch device identify data\n", finfo));
15829 		rval = SATA_FAILURE;
15830 	}
15831 	/* Copy device sata info. */
15832 	sdinfo->satadrv_id = new_sdinfo.satadrv_id;
15833 
15834 	return (rval);
15835 }
15836 
15837 
15838 /*
15839  *
15840  * Returns 1 if threshold exceeded, 0 if threshold not exceeded, -1 if
15841  * unable to determine.
15842  *
15843  * Cannot be called in an interrupt context.
15844  *
15845  * Called by sata_build_lsense_page_2f()
15846  */
15847 
15848 static int
15849 sata_fetch_smart_return_status(sata_hba_inst_t *sata_hba_inst,
15850     sata_drive_info_t *sdinfo)
15851 {
15852 	sata_pkt_t *spkt;
15853 	sata_cmd_t *scmd;
15854 	sata_pkt_txlate_t *spx;
15855 	int rval;
15856 
15857 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15858 	spx->txlt_sata_hba_inst = sata_hba_inst;
15859 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15860 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15861 	if (spkt == NULL) {
15862 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15863 		return (-1);
15864 	}
15865 	/* address is needed now */
15866 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15867 
15868 
15869 	/* Fill sata_pkt */
15870 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15871 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15872 	/* Synchronous mode, no callback */
15873 	spkt->satapkt_comp = NULL;
15874 	/* Timeout 30s */
15875 	spkt->satapkt_time = sata_default_pkt_time;
15876 
15877 	scmd = &spkt->satapkt_cmd;
15878 	scmd->satacmd_flags.sata_special_regs = B_TRUE;
15879 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_NODATA_XFER;
15880 
15881 	/* Set up which registers need to be returned */
15882 	scmd->satacmd_flags.sata_copy_out_lba_mid_lsb = B_TRUE;
15883 	scmd->satacmd_flags.sata_copy_out_lba_high_lsb = B_TRUE;
15884 
15885 	/* Build SMART_RETURN_STATUS cmd in the sata_pkt */
15886 	scmd->satacmd_addr_type = 0;		/* N/A */
15887 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
15888 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
15889 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
15890 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
15891 	scmd->satacmd_features_reg = SATA_SMART_RETURN_STATUS;
15892 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
15893 	scmd->satacmd_cmd_reg = SATAC_SMART;
15894 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
15895 	    sdinfo->satadrv_addr.cport)));
15896 
15897 
15898 	/* Send pkt to SATA HBA driver */
15899 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
15900 	    SATA_TRAN_ACCEPTED ||
15901 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
15902 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15903 		    sdinfo->satadrv_addr.cport)));
15904 		/*
15905 		 * Whoops, no SMART RETURN STATUS
15906 		 */
15907 		rval = -1;
15908 	} else {
15909 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
15910 		    sdinfo->satadrv_addr.cport)));
15911 		if (scmd->satacmd_error_reg & SATA_ERROR_ABORT) {
15912 			rval = -1;
15913 			goto fail;
15914 		}
15915 		if (scmd->satacmd_status_reg & SATA_STATUS_ERR) {
15916 			rval = -1;
15917 			goto fail;
15918 		}
15919 		if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_1) &&
15920 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_2))
15921 			rval = 0;
15922 		else if ((scmd->satacmd_lba_mid_lsb == SMART_MAGIC_VAL_3) &&
15923 		    (scmd->satacmd_lba_high_lsb == SMART_MAGIC_VAL_4))
15924 			rval = 1;
15925 		else {
15926 			rval = -1;
15927 			goto fail;
15928 		}
15929 	}
15930 fail:
15931 	/* Free allocated resources */
15932 	sata_pkt_free(spx);
15933 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
15934 
15935 	return (rval);
15936 }
15937 
15938 /*
15939  *
15940  * Returns 0 if succeeded, -1 otherwise
15941  *
15942  * Cannot be called in an interrupt context.
15943  *
15944  */
15945 static int
15946 sata_fetch_smart_data(
15947 	sata_hba_inst_t *sata_hba_inst,
15948 	sata_drive_info_t *sdinfo,
15949 	struct smart_data *smart_data)
15950 {
15951 	sata_pkt_t *spkt;
15952 	sata_cmd_t *scmd;
15953 	sata_pkt_txlate_t *spx;
15954 	int rval;
15955 
15956 #if ! defined(lint)
15957 	ASSERT(sizeof (struct smart_data) == 512);
15958 #endif
15959 
15960 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
15961 	spx->txlt_sata_hba_inst = sata_hba_inst;
15962 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
15963 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
15964 	if (spkt == NULL) {
15965 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15966 		return (-1);
15967 	}
15968 	/* address is needed now */
15969 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15970 
15971 
15972 	/* Fill sata_pkt */
15973 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
15974 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
15975 	/* Synchronous mode, no callback */
15976 	spkt->satapkt_comp = NULL;
15977 	/* Timeout 30s */
15978 	spkt->satapkt_time = sata_default_pkt_time;
15979 
15980 	scmd = &spkt->satapkt_cmd;
15981 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
15982 
15983 	/*
15984 	 * Allocate buffer for SMART data
15985 	 */
15986 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
15987 	    sizeof (struct smart_data));
15988 	if (scmd->satacmd_bp == NULL) {
15989 		sata_pkt_free(spx);
15990 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
15991 		SATA_LOG_D((sata_hba_inst, CE_WARN,
15992 		    "sata_fetch_smart_data: "
15993 		    "cannot allocate buffer"));
15994 		return (-1);
15995 	}
15996 
15997 
15998 	/* Build SMART_READ_DATA cmd in the sata_pkt */
15999 	scmd->satacmd_addr_type = 0;		/* N/A */
16000 	scmd->satacmd_sec_count_lsb = 0;	/* N/A */
16001 	scmd->satacmd_lba_low_lsb = 0;		/* N/A */
16002 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16003 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16004 	scmd->satacmd_features_reg = SATA_SMART_READ_DATA;
16005 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16006 	scmd->satacmd_cmd_reg = SATAC_SMART;
16007 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16008 	    sdinfo->satadrv_addr.cport)));
16009 
16010 	/* Send pkt to SATA HBA driver */
16011 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16012 	    SATA_TRAN_ACCEPTED ||
16013 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16014 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16015 		    sdinfo->satadrv_addr.cport)));
16016 		/*
16017 		 * Whoops, no SMART DATA available
16018 		 */
16019 		rval = -1;
16020 		goto fail;
16021 	} else {
16022 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16023 		    sdinfo->satadrv_addr.cport)));
16024 		if (spx->txlt_buf_dma_handle != NULL) {
16025 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16026 			    DDI_DMA_SYNC_FORKERNEL);
16027 			ASSERT(rval == DDI_SUCCESS);
16028 		}
16029 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)smart_data,
16030 		    sizeof (struct smart_data));
16031 	}
16032 
16033 fail:
16034 	/* Free allocated resources */
16035 	sata_free_local_buffer(spx);
16036 	sata_pkt_free(spx);
16037 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16038 
16039 	return (rval);
16040 }
16041 
16042 /*
16043  * Used by LOG SENSE page 0x10
16044  * Reads (in synchronous mode) the self test log data using Read Log Ext cmd.
16045  * Note: cannot be called in the interrupt context.
16046  *
16047  * return 0 for success, -1 otherwise
16048  *
16049  */
16050 static int
16051 sata_ext_smart_selftest_read_log(
16052 	sata_hba_inst_t *sata_hba_inst,
16053 	sata_drive_info_t *sdinfo,
16054 	struct smart_ext_selftest_log *ext_selftest_log,
16055 	uint16_t block_num)
16056 {
16057 	sata_pkt_txlate_t *spx;
16058 	sata_pkt_t *spkt;
16059 	sata_cmd_t *scmd;
16060 	int rval;
16061 
16062 #if ! defined(lint)
16063 	ASSERT(sizeof (struct smart_ext_selftest_log) == 512);
16064 #endif
16065 
16066 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16067 	spx->txlt_sata_hba_inst = sata_hba_inst;
16068 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16069 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16070 	if (spkt == NULL) {
16071 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16072 		return (-1);
16073 	}
16074 	/* address is needed now */
16075 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16076 
16077 
16078 	/* Fill sata_pkt */
16079 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16080 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16081 	/* Synchronous mode, no callback */
16082 	spkt->satapkt_comp = NULL;
16083 	/* Timeout 30s */
16084 	spkt->satapkt_time = sata_default_pkt_time;
16085 
16086 	scmd = &spkt->satapkt_cmd;
16087 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16088 
16089 	/*
16090 	 * Allocate buffer for SMART extended self-test log
16091 	 */
16092 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16093 	    sizeof (struct smart_ext_selftest_log));
16094 	if (scmd->satacmd_bp == NULL) {
16095 		sata_pkt_free(spx);
16096 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16097 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16098 		    "sata_ext_smart_selftest_log: "
16099 		    "cannot allocate buffer"));
16100 		return (-1);
16101 	}
16102 
16103 	/* Build READ LOG EXT w/ extended self-test log cmd in the sata_pkt */
16104 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16105 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of selftest log */
16106 	scmd->satacmd_sec_count_msb = 0;	/* One sector of selftest log */
16107 	scmd->satacmd_lba_low_lsb = EXT_SMART_SELFTEST_LOG_PAGE;
16108 	scmd->satacmd_lba_low_msb = 0;
16109 	scmd->satacmd_lba_mid_lsb = block_num & 0xff;
16110 	scmd->satacmd_lba_mid_msb = block_num >> 8;
16111 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16112 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16113 
16114 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16115 	    sdinfo->satadrv_addr.cport)));
16116 
16117 	/* Send pkt to SATA HBA driver */
16118 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16119 	    SATA_TRAN_ACCEPTED ||
16120 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16121 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16122 		    sdinfo->satadrv_addr.cport)));
16123 
16124 		/*
16125 		 * Whoops, no SMART selftest log info available
16126 		 */
16127 		rval = -1;
16128 		goto fail;
16129 	} else {
16130 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16131 		    sdinfo->satadrv_addr.cport)));
16132 
16133 		if (spx->txlt_buf_dma_handle != NULL) {
16134 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16135 			    DDI_DMA_SYNC_FORKERNEL);
16136 			ASSERT(rval == DDI_SUCCESS);
16137 		}
16138 		bcopy(scmd->satacmd_bp->b_un.b_addr,
16139 		    (uint8_t *)ext_selftest_log,
16140 		    sizeof (struct smart_ext_selftest_log));
16141 		rval = 0;
16142 	}
16143 
16144 fail:
16145 	/* Free allocated resources */
16146 	sata_free_local_buffer(spx);
16147 	sata_pkt_free(spx);
16148 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16149 
16150 	return (rval);
16151 }
16152 
16153 /*
16154  * Returns 0 for success, -1 otherwise
16155  *
16156  * SMART self-test log data is returned in buffer pointed to by selftest_log
16157  */
16158 static int
16159 sata_smart_selftest_log(
16160 	sata_hba_inst_t *sata_hba_inst,
16161 	sata_drive_info_t *sdinfo,
16162 	struct smart_selftest_log *selftest_log)
16163 {
16164 	sata_pkt_t *spkt;
16165 	sata_cmd_t *scmd;
16166 	sata_pkt_txlate_t *spx;
16167 	int rval;
16168 
16169 #if ! defined(lint)
16170 	ASSERT(sizeof (struct smart_selftest_log) == 512);
16171 #endif
16172 
16173 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16174 	spx->txlt_sata_hba_inst = sata_hba_inst;
16175 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16176 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16177 	if (spkt == NULL) {
16178 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16179 		return (-1);
16180 	}
16181 	/* address is needed now */
16182 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16183 
16184 
16185 	/* Fill sata_pkt */
16186 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16187 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16188 	/* Synchronous mode, no callback */
16189 	spkt->satapkt_comp = NULL;
16190 	/* Timeout 30s */
16191 	spkt->satapkt_time = sata_default_pkt_time;
16192 
16193 	scmd = &spkt->satapkt_cmd;
16194 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16195 
16196 	/*
16197 	 * Allocate buffer for SMART SELFTEST LOG
16198 	 */
16199 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16200 	    sizeof (struct smart_selftest_log));
16201 	if (scmd->satacmd_bp == NULL) {
16202 		sata_pkt_free(spx);
16203 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16204 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16205 		    "sata_smart_selftest_log: "
16206 		    "cannot allocate buffer"));
16207 		return (-1);
16208 	}
16209 
16210 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16211 	scmd->satacmd_addr_type = 0;		/* N/A */
16212 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of SMART log */
16213 	scmd->satacmd_lba_low_lsb = SMART_SELFTEST_LOG_PAGE;
16214 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16215 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16216 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16217 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16218 	scmd->satacmd_cmd_reg = SATAC_SMART;
16219 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16220 	    sdinfo->satadrv_addr.cport)));
16221 
16222 	/* Send pkt to SATA HBA driver */
16223 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16224 	    SATA_TRAN_ACCEPTED ||
16225 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16226 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16227 		    sdinfo->satadrv_addr.cport)));
16228 		/*
16229 		 * Whoops, no SMART DATA available
16230 		 */
16231 		rval = -1;
16232 		goto fail;
16233 	} else {
16234 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16235 		    sdinfo->satadrv_addr.cport)));
16236 		if (spx->txlt_buf_dma_handle != NULL) {
16237 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16238 			    DDI_DMA_SYNC_FORKERNEL);
16239 			ASSERT(rval == DDI_SUCCESS);
16240 		}
16241 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)selftest_log,
16242 		    sizeof (struct smart_selftest_log));
16243 		rval = 0;
16244 	}
16245 
16246 fail:
16247 	/* Free allocated resources */
16248 	sata_free_local_buffer(spx);
16249 	sata_pkt_free(spx);
16250 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16251 
16252 	return (rval);
16253 }
16254 
16255 
16256 /*
16257  * Returns 0 for success, -1 otherwise
16258  *
16259  * SMART READ LOG data is returned in buffer pointed to by smart_log
16260  */
16261 static int
16262 sata_smart_read_log(
16263 	sata_hba_inst_t *sata_hba_inst,
16264 	sata_drive_info_t *sdinfo,
16265 	uint8_t *smart_log,		/* where the data should be returned */
16266 	uint8_t which_log,		/* which log should be returned */
16267 	uint8_t log_size)		/* # of 512 bytes in log */
16268 {
16269 	sata_pkt_t *spkt;
16270 	sata_cmd_t *scmd;
16271 	sata_pkt_txlate_t *spx;
16272 	int rval;
16273 
16274 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16275 	spx->txlt_sata_hba_inst = sata_hba_inst;
16276 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16277 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16278 	if (spkt == NULL) {
16279 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16280 		return (-1);
16281 	}
16282 	/* address is needed now */
16283 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16284 
16285 
16286 	/* Fill sata_pkt */
16287 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16288 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16289 	/* Synchronous mode, no callback */
16290 	spkt->satapkt_comp = NULL;
16291 	/* Timeout 30s */
16292 	spkt->satapkt_time = sata_default_pkt_time;
16293 
16294 	scmd = &spkt->satapkt_cmd;
16295 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16296 
16297 	/*
16298 	 * Allocate buffer for SMART READ LOG
16299 	 */
16300 	scmd->satacmd_bp = sata_alloc_local_buffer(spx, log_size * 512);
16301 	if (scmd->satacmd_bp == NULL) {
16302 		sata_pkt_free(spx);
16303 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16304 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16305 		    "sata_smart_read_log: " "cannot allocate buffer"));
16306 		return (-1);
16307 	}
16308 
16309 	/* Build SMART_READ_LOG cmd in the sata_pkt */
16310 	scmd->satacmd_addr_type = 0;		/* N/A */
16311 	scmd->satacmd_sec_count_lsb = log_size;	/* what the caller asked for */
16312 	scmd->satacmd_lba_low_lsb = which_log;	/* which log page */
16313 	scmd->satacmd_lba_mid_lsb = SMART_MAGIC_VAL_1;
16314 	scmd->satacmd_lba_high_lsb = SMART_MAGIC_VAL_2;
16315 	scmd->satacmd_features_reg = SATA_SMART_READ_LOG;
16316 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16317 	scmd->satacmd_cmd_reg = SATAC_SMART;
16318 
16319 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16320 	    sdinfo->satadrv_addr.cport)));
16321 
16322 	/* Send pkt to SATA HBA driver */
16323 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16324 	    SATA_TRAN_ACCEPTED ||
16325 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16326 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16327 		    sdinfo->satadrv_addr.cport)));
16328 
16329 		/*
16330 		 * Whoops, no SMART DATA available
16331 		 */
16332 		rval = -1;
16333 		goto fail;
16334 	} else {
16335 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16336 		    sdinfo->satadrv_addr.cport)));
16337 
16338 		if (spx->txlt_buf_dma_handle != NULL) {
16339 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16340 			    DDI_DMA_SYNC_FORKERNEL);
16341 			ASSERT(rval == DDI_SUCCESS);
16342 		}
16343 		bcopy(scmd->satacmd_bp->b_un.b_addr, smart_log, log_size * 512);
16344 		rval = 0;
16345 	}
16346 
16347 fail:
16348 	/* Free allocated resources */
16349 	sata_free_local_buffer(spx);
16350 	sata_pkt_free(spx);
16351 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16352 
16353 	return (rval);
16354 }
16355 
16356 /*
16357  * Used by LOG SENSE page 0x10
16358  *
16359  * return 0 for success, -1 otherwise
16360  *
16361  */
16362 static int
16363 sata_read_log_ext_directory(
16364 	sata_hba_inst_t *sata_hba_inst,
16365 	sata_drive_info_t *sdinfo,
16366 	struct read_log_ext_directory *logdir)
16367 {
16368 	sata_pkt_txlate_t *spx;
16369 	sata_pkt_t *spkt;
16370 	sata_cmd_t *scmd;
16371 	int rval;
16372 
16373 #if ! defined(lint)
16374 	ASSERT(sizeof (struct read_log_ext_directory) == 512);
16375 #endif
16376 
16377 	spx = kmem_zalloc(sizeof (sata_pkt_txlate_t), KM_SLEEP);
16378 	spx->txlt_sata_hba_inst = sata_hba_inst;
16379 	spx->txlt_scsi_pkt = NULL;		/* No scsi pkt involved */
16380 	spkt = sata_pkt_alloc(spx, SLEEP_FUNC);
16381 	if (spkt == NULL) {
16382 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16383 		return (-1);
16384 	}
16385 
16386 	/* Fill sata_pkt */
16387 	spkt->satapkt_device.satadev_addr = sdinfo->satadrv_addr;
16388 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16389 	/* Synchronous mode, no callback */
16390 	spkt->satapkt_comp = NULL;
16391 	/* Timeout 30s */
16392 	spkt->satapkt_time = sata_default_pkt_time;
16393 
16394 	scmd = &spkt->satapkt_cmd;
16395 	scmd->satacmd_flags.sata_data_direction = SATA_DIR_READ;
16396 
16397 	/*
16398 	 * Allocate buffer for SMART READ LOG EXTENDED command
16399 	 */
16400 	scmd->satacmd_bp = sata_alloc_local_buffer(spx,
16401 	    sizeof (struct read_log_ext_directory));
16402 	if (scmd->satacmd_bp == NULL) {
16403 		sata_pkt_free(spx);
16404 		kmem_free(spx, sizeof (sata_pkt_txlate_t));
16405 		SATA_LOG_D((sata_hba_inst, CE_WARN,
16406 		    "sata_read_log_ext_directory: "
16407 		    "cannot allocate buffer"));
16408 		return (-1);
16409 	}
16410 
16411 	/* Build READ LOG EXT w/ log directory cmd in the  sata_pkt */
16412 	scmd->satacmd_addr_type = ATA_ADDR_LBA48;
16413 	scmd->satacmd_sec_count_lsb = 1;	/* One sector of directory */
16414 	scmd->satacmd_sec_count_msb = 0;	/* One sector of directory */
16415 	scmd->satacmd_lba_low_lsb = READ_LOG_EXT_LOG_DIRECTORY;
16416 	scmd->satacmd_lba_low_msb = 0;
16417 	scmd->satacmd_lba_mid_lsb = 0;
16418 	scmd->satacmd_lba_mid_msb = 0;
16419 	scmd->satacmd_device_reg = 0;		/* Always device 0 */
16420 	scmd->satacmd_cmd_reg = SATAC_READ_LOG_EXT;
16421 
16422 	mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst,
16423 	    sdinfo->satadrv_addr.cport)));
16424 
16425 	/* Send pkt to SATA HBA driver */
16426 	if ((*SATA_START_FUNC(sata_hba_inst))(SATA_DIP(sata_hba_inst), spkt) !=
16427 	    SATA_TRAN_ACCEPTED ||
16428 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
16429 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16430 		    sdinfo->satadrv_addr.cport)));
16431 		/*
16432 		 * Whoops, no SMART selftest log info available
16433 		 */
16434 		rval = -1;
16435 		goto fail;
16436 	} else {
16437 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst,
16438 		    sdinfo->satadrv_addr.cport)));
16439 		if (spx->txlt_buf_dma_handle != NULL) {
16440 			rval = ddi_dma_sync(spx->txlt_buf_dma_handle, 0, 0,
16441 			    DDI_DMA_SYNC_FORKERNEL);
16442 			ASSERT(rval == DDI_SUCCESS);
16443 		}
16444 		bcopy(scmd->satacmd_bp->b_un.b_addr, (uint8_t *)logdir,
16445 		    sizeof (struct read_log_ext_directory));
16446 		rval = 0;
16447 	}
16448 
16449 fail:
16450 	/* Free allocated resources */
16451 	sata_free_local_buffer(spx);
16452 	sata_pkt_free(spx);
16453 	kmem_free(spx, sizeof (sata_pkt_txlate_t));
16454 
16455 	return (rval);
16456 }
16457 
16458 /*
16459  * Set up error retrieval sata command for NCQ command error data
16460  * recovery.
16461  *
16462  * Returns SATA_SUCCESS when data buffer is allocated and packet set-up,
16463  * returns SATA_FAILURE otherwise.
16464  */
16465 static int
16466 sata_ncq_err_ret_cmd_setup(sata_pkt_txlate_t *spx, sata_drive_info_t *sdinfo)
16467 {
16468 #ifndef __lock_lint
16469 	_NOTE(ARGUNUSED(sdinfo))
16470 #endif
16471 
16472 	sata_pkt_t *spkt = spx->txlt_sata_pkt;
16473 	sata_cmd_t *scmd;
16474 	struct buf *bp;
16475 
16476 	/* Operation modes are up to the caller */
16477 	spkt->satapkt_op_mode = SATA_OPMODE_SYNCH | SATA_OPMODE_INTERRUPTS;
16478 
16479 	/* Synchronous mode, no callback - may be changed by the caller */
16480 	spkt->satapkt_comp = NULL;
16481 	spkt->satapkt_time = sata_default_pkt_time;
16482 
16483 	scmd = &spkt->satapkt_cmd;
16484 	bcopy(&sata_rle_cmd, scmd, sizeof (sata_cmd_t));
16485 	scmd->satacmd_flags.sata_ignore_dev_reset = B_TRUE;
16486 
16487 	/*
16488 	 * Allocate dma_able buffer error data.
16489 	 * Buffer allocation will take care of buffer alignment and other DMA
16490 	 * attributes.
16491 	 */
16492 	bp = sata_alloc_local_buffer(spx,
16493 	    sizeof (struct sata_ncq_error_recovery_page));
16494 	if (bp == NULL)
16495 		return (SATA_FAILURE);
16496 
16497 	bp_mapin(bp); /* make data buffer accessible */
16498 	scmd->satacmd_bp = bp;
16499 
16500 	/*
16501 	 * Set-up pointer to the buffer handle, so HBA can sync buffer
16502 	 * before accessing it. Handle is in usual place in translate struct.
16503 	 */
16504 	scmd->satacmd_err_ret_buf_handle = &spx->txlt_buf_dma_handle;
16505 
16506 	ASSERT(scmd->satacmd_num_dma_cookies != 0);
16507 	ASSERT(scmd->satacmd_dma_cookie_list != NULL);
16508 
16509 	return (SATA_SUCCESS);
16510 }
16511 
16512 /*
16513  * sata_xlate_errors() is used to translate (S)ATA error
16514  * information to SCSI information returned in the SCSI
16515  * packet.
16516  */
16517 static void
16518 sata_xlate_errors(sata_pkt_txlate_t *spx)
16519 {
16520 	struct scsi_pkt *scsipkt = spx->txlt_scsi_pkt;
16521 	struct scsi_extended_sense *sense;
16522 
16523 	scsipkt->pkt_reason = CMD_INCOMPLETE;
16524 	*scsipkt->pkt_scbp = STATUS_CHECK;
16525 	sense = sata_arq_sense(spx);
16526 
16527 	switch (spx->txlt_sata_pkt->satapkt_reason) {
16528 	case SATA_PKT_PORT_ERROR:
16529 		/*
16530 		 * We have no device data. Assume no data transfered.
16531 		 */
16532 		sense->es_key = KEY_HARDWARE_ERROR;
16533 		break;
16534 
16535 	case SATA_PKT_DEV_ERROR:
16536 		if (spx->txlt_sata_pkt->satapkt_cmd.satacmd_status_reg &
16537 		    SATA_STATUS_ERR) {
16538 			/*
16539 			 * determine dev error reason from error
16540 			 * reg content
16541 			 */
16542 			sata_decode_device_error(spx, sense);
16543 			break;
16544 		}
16545 		/* No extended sense key - no info available */
16546 		break;
16547 
16548 	case SATA_PKT_TIMEOUT:
16549 		scsipkt->pkt_reason = CMD_TIMEOUT;
16550 		scsipkt->pkt_statistics |= STAT_TIMEOUT | STAT_DEV_RESET;
16551 		/* No extended sense key */
16552 		break;
16553 
16554 	case SATA_PKT_ABORTED:
16555 		scsipkt->pkt_reason = CMD_ABORTED;
16556 		scsipkt->pkt_statistics |= STAT_ABORTED;
16557 		/* No extended sense key */
16558 		break;
16559 
16560 	case SATA_PKT_RESET:
16561 		/*
16562 		 * pkt aborted either by an explicit reset request from
16563 		 * a host, or due to error recovery
16564 		 */
16565 		scsipkt->pkt_reason = CMD_RESET;
16566 		scsipkt->pkt_statistics |= STAT_DEV_RESET;
16567 		break;
16568 
16569 	default:
16570 		scsipkt->pkt_reason = CMD_TRAN_ERR;
16571 		break;
16572 	}
16573 }
16574 
16575 
16576 
16577 
16578 /*
16579  * Log sata message
16580  * dev pathname msg line preceeds the logged message.
16581  */
16582 
16583 static	void
16584 sata_log(sata_hba_inst_t *sata_hba_inst, uint_t level, char *fmt, ...)
16585 {
16586 	char pathname[128];
16587 	dev_info_t *dip = NULL;
16588 	va_list ap;
16589 
16590 	mutex_enter(&sata_log_mutex);
16591 
16592 	va_start(ap, fmt);
16593 	(void) vsprintf(sata_log_buf, fmt, ap);
16594 	va_end(ap);
16595 
16596 	if (sata_hba_inst != NULL) {
16597 		dip = SATA_DIP(sata_hba_inst);
16598 		(void) ddi_pathname(dip, pathname);
16599 	} else {
16600 		pathname[0] = 0;
16601 	}
16602 	if (level == CE_CONT) {
16603 		if (sata_debug_flags == 0)
16604 			cmn_err(level, "?%s:\n %s\n", pathname, sata_log_buf);
16605 		else
16606 			cmn_err(level, "%s:\n %s\n", pathname, sata_log_buf);
16607 	} else {
16608 		if (level != CE_NOTE) {
16609 			cmn_err(level, "%s:\n %s", pathname, sata_log_buf);
16610 		} else if (sata_msg) {
16611 			cmn_err(level, "%s:\n %s", pathname,
16612 			    sata_log_buf);
16613 		}
16614 	}
16615 
16616 	/* sata trace debug */
16617 	sata_trace_debug(dip, sata_log_buf);
16618 
16619 	mutex_exit(&sata_log_mutex);
16620 }
16621 
16622 
16623 /* ******** Asynchronous HBA events handling & hotplugging support ******** */
16624 
16625 /*
16626  * Start or terminate the thread, depending on flag arg and current state
16627  */
16628 static void
16629 sata_event_thread_control(int startstop)
16630 {
16631 	static 	int sata_event_thread_terminating = 0;
16632 	static 	int sata_event_thread_starting = 0;
16633 	int i;
16634 
16635 	mutex_enter(&sata_event_mutex);
16636 
16637 	if (startstop == 0 && (sata_event_thread_starting == 1 ||
16638 	    sata_event_thread_terminating == 1)) {
16639 		mutex_exit(&sata_event_mutex);
16640 		return;
16641 	}
16642 	if (startstop == 1 && sata_event_thread_starting == 1) {
16643 		mutex_exit(&sata_event_mutex);
16644 		return;
16645 	}
16646 	if (startstop == 1 && sata_event_thread_terminating == 1) {
16647 		sata_event_thread_starting = 1;
16648 		/* wait til terminate operation completes */
16649 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16650 		while (sata_event_thread_terminating == 1) {
16651 			if (i-- <= 0) {
16652 				sata_event_thread_starting = 0;
16653 				mutex_exit(&sata_event_mutex);
16654 #ifdef SATA_DEBUG
16655 				cmn_err(CE_WARN, "sata_event_thread_control: "
16656 				    "timeout waiting for thread to terminate");
16657 #endif
16658 				return;
16659 			}
16660 			mutex_exit(&sata_event_mutex);
16661 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16662 			mutex_enter(&sata_event_mutex);
16663 		}
16664 	}
16665 	if (startstop == 1) {
16666 		if (sata_event_thread == NULL) {
16667 			sata_event_thread = thread_create(NULL, 0,
16668 			    (void (*)())sata_event_daemon,
16669 			    &sata_hba_list, 0, &p0, TS_RUN, minclsyspri);
16670 		}
16671 		sata_event_thread_starting = 0;
16672 		mutex_exit(&sata_event_mutex);
16673 		return;
16674 	}
16675 
16676 	/*
16677 	 * If we got here, thread may need to be terminated
16678 	 */
16679 	if (sata_event_thread != NULL) {
16680 		int i;
16681 		/* Signal event thread to go away */
16682 		sata_event_thread_terminating = 1;
16683 		sata_event_thread_terminate = 1;
16684 		cv_signal(&sata_event_cv);
16685 		/*
16686 		 * Wait til daemon terminates.
16687 		 */
16688 		i = SATA_EVNT_DAEMON_TERM_WAIT/SATA_EVNT_DAEMON_TERM_TIMEOUT;
16689 		while (sata_event_thread_terminate == 1) {
16690 			mutex_exit(&sata_event_mutex);
16691 			if (i-- <= 0) {
16692 				/* Daemon did not go away !!! */
16693 #ifdef SATA_DEBUG
16694 				cmn_err(CE_WARN, "sata_event_thread_control: "
16695 				    "cannot terminate event daemon thread");
16696 #endif
16697 				mutex_enter(&sata_event_mutex);
16698 				break;
16699 			}
16700 			delay(drv_usectohz(SATA_EVNT_DAEMON_TERM_TIMEOUT));
16701 			mutex_enter(&sata_event_mutex);
16702 		}
16703 		sata_event_thread_terminating = 0;
16704 	}
16705 	ASSERT(sata_event_thread_terminating == 0);
16706 	ASSERT(sata_event_thread_starting == 0);
16707 	mutex_exit(&sata_event_mutex);
16708 }
16709 
16710 
16711 /*
16712  * SATA HBA event notification function.
16713  * Events reported by SATA HBA drivers per HBA instance relate to a change in
16714  * a port and/or device state or a controller itself.
16715  * Events for different addresses/addr types cannot be combined.
16716  * A warning message is generated for each event type.
16717  * Events are not processed by this function, so only the
16718  * event flag(s)is set for an affected entity and the event thread is
16719  * waken up. Event daemon thread processes all events.
16720  *
16721  * NOTE: Since more than one event may be reported at the same time, one
16722  * cannot determine a sequence of events when opposite event are reported, eg.
16723  * LINK_LOST and LINK_ESTABLISHED. Actual port status during event processing
16724  * is taking precedence over reported events, i.e. may cause ignoring some
16725  * events.
16726  */
16727 #define	SATA_EVENT_MAX_MSG_LENGTH	79
16728 
16729 void
16730 sata_hba_event_notify(dev_info_t *dip, sata_device_t *sata_device, int event)
16731 {
16732 	sata_hba_inst_t *sata_hba_inst = NULL;
16733 	sata_address_t *saddr;
16734 	sata_pmult_info_t *pmultinfo;
16735 	sata_drive_info_t *sdinfo;
16736 	sata_port_stats_t *pstats;
16737 	sata_cport_info_t *cportinfo;
16738 	sata_pmport_info_t *pmportinfo;
16739 	int cport, pmport;
16740 	char buf1[SATA_EVENT_MAX_MSG_LENGTH + 1];
16741 	char buf2[SATA_EVENT_MAX_MSG_LENGTH + 1];
16742 	char *lcp;
16743 	static char *err_msg_evnt_1 =
16744 	    "sata_hba_event_notify: invalid port event 0x%x ";
16745 	static char *err_msg_evnt_2 =
16746 	    "sata_hba_event_notify: invalid device event 0x%x ";
16747 	int linkevent;
16748 
16749 	/*
16750 	 * There is a possibility that an event will be generated on HBA
16751 	 * that has not completed attachment or is detaching. We still want
16752 	 * to process events until HBA is detached.
16753 	 */
16754 	mutex_enter(&sata_mutex);
16755 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
16756 	    sata_hba_inst = sata_hba_inst->satahba_next) {
16757 		if (SATA_DIP(sata_hba_inst) == dip)
16758 			if (sata_hba_inst->satahba_attached == 1)
16759 				break;
16760 	}
16761 	mutex_exit(&sata_mutex);
16762 	if (sata_hba_inst == NULL)
16763 		/* HBA not attached */
16764 		return;
16765 
16766 	ASSERT(sata_device != NULL);
16767 
16768 	/*
16769 	 * Validate address before - do not proceed with invalid address.
16770 	 */
16771 	saddr = &sata_device->satadev_addr;
16772 	if (saddr->cport >= SATA_NUM_CPORTS(sata_hba_inst))
16773 		return;
16774 
16775 	cport = saddr->cport;
16776 	pmport = saddr->pmport;
16777 
16778 	buf1[0] = buf2[0] = '\0';
16779 
16780 	/*
16781 	 * If event relates to port or device, check port state.
16782 	 * Port has to be initialized, or we cannot accept an event.
16783 	 */
16784 	if ((saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT |
16785 	    SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT | SATA_ADDR_PMULT)) != 0) {
16786 		mutex_enter(&sata_hba_inst->satahba_mutex);
16787 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
16788 		mutex_exit(&sata_hba_inst->satahba_mutex);
16789 		if (cportinfo == NULL || cportinfo->cport_state == 0)
16790 			return;
16791 	}
16792 
16793 	if ((saddr->qual & (SATA_ADDR_PMULT | SATA_ADDR_PMPORT |
16794 	    SATA_ADDR_DPMPORT)) != 0) {
16795 		if (cportinfo->cport_dev_type != SATA_DTYPE_PMULT) {
16796 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16797 			    "sata_hba_event_notify: Non-pmult device (0x%x)"
16798 			    "is attached to port %d, ignore pmult/pmport "
16799 			    "event 0x%x", cportinfo->cport_dev_type,
16800 			    cport, event));
16801 			return;
16802 		}
16803 
16804 		mutex_enter(&cportinfo->cport_mutex);
16805 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
16806 		mutex_exit(&cportinfo->cport_mutex);
16807 
16808 		/*
16809 		 * The daemon might be processing attachment of port
16810 		 * multiplier, in that case we should ignore events on its
16811 		 * sub-devices.
16812 		 *
16813 		 * NOTE: Only pmult_state is checked in sata_hba_event_notify.
16814 		 * The pmport_state is checked by sata daemon.
16815 		 */
16816 		if (pmultinfo == NULL ||
16817 		    pmultinfo->pmult_state == SATA_STATE_UNKNOWN) {
16818 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16819 			    "sata_hba_event_notify: pmult is not"
16820 			    "available at port %d:%d, ignore event 0x%x",
16821 			    cport, pmport, event));
16822 			return;
16823 		}
16824 	}
16825 
16826 	if ((saddr->qual &
16827 	    (SATA_ADDR_PMPORT | SATA_ADDR_DPMPORT)) != 0) {
16828 
16829 		mutex_enter(&cportinfo->cport_mutex);
16830 		if (pmport > SATA_NUM_PMPORTS(sata_hba_inst, cport)) {
16831 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16832 			    "sata_hba_event_notify: invalid/"
16833 			    "un-implemented port %d:%d (%d ports), "
16834 			    "ignore event 0x%x", cport, pmport,
16835 			    SATA_NUM_PMPORTS(sata_hba_inst, cport), event));
16836 			mutex_exit(&cportinfo->cport_mutex);
16837 			return;
16838 		}
16839 		mutex_exit(&cportinfo->cport_mutex);
16840 
16841 		mutex_enter(&sata_hba_inst->satahba_mutex);
16842 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
16843 		    cport, pmport);
16844 		mutex_exit(&sata_hba_inst->satahba_mutex);
16845 
16846 		/* pmport is implemented/valid? */
16847 		if (pmportinfo == NULL) {
16848 			SATA_LOG_D((sata_hba_inst, CE_WARN,
16849 			    "sata_hba_event_notify: invalid/"
16850 			    "un-implemented port %d:%d, ignore "
16851 			    "event 0x%x", cport, pmport, event));
16852 			return;
16853 		}
16854 	}
16855 
16856 	/*
16857 	 * Events refer to devices, ports and controllers - each has
16858 	 * unique address. Events for different addresses cannot be combined.
16859 	 */
16860 	if (saddr->qual & (SATA_ADDR_CPORT | SATA_ADDR_PMPORT)) {
16861 
16862 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16863 
16864 		/* qualify this event(s) */
16865 		if ((event & SATA_EVNT_PORT_EVENTS) == 0) {
16866 			/* Invalid event for the device port */
16867 			(void) sprintf(buf2, err_msg_evnt_1,
16868 			    event & SATA_EVNT_PORT_EVENTS);
16869 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16870 			goto event_info;
16871 		}
16872 		if (saddr->qual == SATA_ADDR_CPORT) {
16873 			/* Controller's device port event */
16874 
16875 			(SATA_CPORT_INFO(sata_hba_inst, cport))->
16876 			    cport_event_flags |=
16877 			    event & SATA_EVNT_PORT_EVENTS;
16878 			pstats =
16879 			    &(SATA_CPORT_INFO(sata_hba_inst, cport))->
16880 			    cport_stats;
16881 		} else {
16882 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16883 			mutex_enter(&pmportinfo->pmport_mutex);
16884 			/* Port multiplier's device port event */
16885 			(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
16886 			    pmport_event_flags |=
16887 			    event & SATA_EVNT_PORT_EVENTS;
16888 			pstats =
16889 			    &(SATA_PMPORT_INFO(sata_hba_inst, cport, pmport))->
16890 			    pmport_stats;
16891 			mutex_exit(&pmportinfo->pmport_mutex);
16892 			mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16893 		}
16894 
16895 		/*
16896 		 * Add to statistics and log the message. We have to do it
16897 		 * here rather than in the event daemon, because there may be
16898 		 * multiple events occuring before they are processed.
16899 		 */
16900 		linkevent = event &
16901 		    (SATA_EVNT_LINK_LOST | SATA_EVNT_LINK_ESTABLISHED);
16902 		if (linkevent) {
16903 			if (linkevent == (SATA_EVNT_LINK_LOST |
16904 			    SATA_EVNT_LINK_ESTABLISHED)) {
16905 				/* This is likely event combination */
16906 				(void) strlcat(buf1, "link lost/established, ",
16907 				    SATA_EVENT_MAX_MSG_LENGTH);
16908 
16909 				if (pstats->link_lost < 0xffffffffffffffffULL)
16910 					pstats->link_lost++;
16911 				if (pstats->link_established <
16912 				    0xffffffffffffffffULL)
16913 					pstats->link_established++;
16914 				linkevent = 0;
16915 			} else if (linkevent & SATA_EVNT_LINK_LOST) {
16916 				(void) strlcat(buf1, "link lost, ",
16917 				    SATA_EVENT_MAX_MSG_LENGTH);
16918 
16919 				if (pstats->link_lost < 0xffffffffffffffffULL)
16920 					pstats->link_lost++;
16921 			} else {
16922 				(void) strlcat(buf1, "link established, ",
16923 				    SATA_EVENT_MAX_MSG_LENGTH);
16924 				if (pstats->link_established <
16925 				    0xffffffffffffffffULL)
16926 					pstats->link_established++;
16927 			}
16928 		}
16929 		if (event & SATA_EVNT_DEVICE_ATTACHED) {
16930 			(void) strlcat(buf1, "device attached, ",
16931 			    SATA_EVENT_MAX_MSG_LENGTH);
16932 			if (pstats->device_attached < 0xffffffffffffffffULL)
16933 				pstats->device_attached++;
16934 		}
16935 		if (event & SATA_EVNT_DEVICE_DETACHED) {
16936 			(void) strlcat(buf1, "device detached, ",
16937 			    SATA_EVENT_MAX_MSG_LENGTH);
16938 			if (pstats->device_detached < 0xffffffffffffffffULL)
16939 				pstats->device_detached++;
16940 		}
16941 		if (event & SATA_EVNT_PWR_LEVEL_CHANGED) {
16942 			SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
16943 			    "port %d power level changed", cport);
16944 			if (pstats->port_pwr_changed < 0xffffffffffffffffULL)
16945 				pstats->port_pwr_changed++;
16946 		}
16947 
16948 		if ((event & ~SATA_EVNT_PORT_EVENTS) != 0) {
16949 			/* There should be no other events for this address */
16950 			(void) sprintf(buf2, err_msg_evnt_1,
16951 			    event & ~SATA_EVNT_PORT_EVENTS);
16952 		}
16953 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16954 
16955 	} else if (saddr->qual & (SATA_ADDR_DCPORT | SATA_ADDR_DPMPORT)) {
16956 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16957 
16958 		/* qualify this event */
16959 		if ((event & SATA_EVNT_DEVICE_RESET) == 0) {
16960 			/* Invalid event for a device */
16961 			(void) sprintf(buf2, err_msg_evnt_2,
16962 			    event & SATA_EVNT_DEVICE_RESET);
16963 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16964 			goto event_info;
16965 		}
16966 		/* drive event */
16967 		sdinfo = sata_get_device_info(sata_hba_inst, sata_device);
16968 		if (sdinfo != NULL) {
16969 			if (event & SATA_EVNT_DEVICE_RESET) {
16970 				(void) strlcat(buf1, "device reset, ",
16971 				    SATA_EVENT_MAX_MSG_LENGTH);
16972 				if (sdinfo->satadrv_stats.drive_reset <
16973 				    0xffffffffffffffffULL)
16974 					sdinfo->satadrv_stats.drive_reset++;
16975 				sdinfo->satadrv_event_flags |=
16976 				    SATA_EVNT_DEVICE_RESET;
16977 			}
16978 		}
16979 		if ((event & ~SATA_EVNT_DEVICE_RESET) != 0) {
16980 			/* Invalid event for a device */
16981 			(void) sprintf(buf2, err_msg_evnt_2,
16982 			    event & ~SATA_EVNT_DRIVE_EVENTS);
16983 		}
16984 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16985 	} else if (saddr->qual == SATA_ADDR_PMULT) {
16986 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16987 
16988 		/* qualify this event */
16989 		if ((event & (SATA_EVNT_DEVICE_RESET |
16990 		    SATA_EVNT_PMULT_LINK_CHANGED)) == 0) {
16991 			/* Invalid event for a port multiplier */
16992 			(void) sprintf(buf2, err_msg_evnt_2,
16993 			    event & SATA_EVNT_DEVICE_RESET);
16994 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
16995 			goto event_info;
16996 		}
16997 
16998 		pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
16999 
17000 		if (event & SATA_EVNT_DEVICE_RESET) {
17001 
17002 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17003 			    "[Reset] port-mult on cport %d", cport);
17004 			pmultinfo->pmult_event_flags |=
17005 			    SATA_EVNT_DEVICE_RESET;
17006 			(void) strlcat(buf1, "pmult reset, ",
17007 			    SATA_EVENT_MAX_MSG_LENGTH);
17008 		}
17009 
17010 		if (event & SATA_EVNT_PMULT_LINK_CHANGED) {
17011 
17012 			SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17013 			    "pmult link changed on cport %d", cport);
17014 			pmultinfo->pmult_event_flags |=
17015 			    SATA_EVNT_PMULT_LINK_CHANGED;
17016 			(void) strlcat(buf1, "pmult link changed, ",
17017 			    SATA_EVENT_MAX_MSG_LENGTH);
17018 		}
17019 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, cport)));
17020 
17021 	} else {
17022 		if (saddr->qual != SATA_ADDR_NULL) {
17023 			/* Wrong address qualifier */
17024 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17025 			    "sata_hba_event_notify: invalid address 0x%x",
17026 			    *(uint32_t *)saddr));
17027 			return;
17028 		}
17029 		if ((event & SATA_EVNT_CONTROLLER_EVENTS) == 0 ||
17030 		    (event & ~SATA_EVNT_CONTROLLER_EVENTS) != 0) {
17031 			/* Invalid event for the controller */
17032 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17033 			    "sata_hba_event_notify: invalid event 0x%x for "
17034 			    "controller",
17035 			    event & SATA_EVNT_CONTROLLER_EVENTS));
17036 			return;
17037 		}
17038 		buf1[0] = '\0';
17039 		/* This may be a frequent and not interesting event */
17040 		SATADBG1(SATA_DBG_EVENTS, sata_hba_inst,
17041 		    "controller power level changed\n", NULL);
17042 
17043 		mutex_enter(&sata_hba_inst->satahba_mutex);
17044 		if (sata_hba_inst->satahba_stats.ctrl_pwr_change <
17045 		    0xffffffffffffffffULL)
17046 			sata_hba_inst->satahba_stats.ctrl_pwr_change++;
17047 
17048 		sata_hba_inst->satahba_event_flags |=
17049 		    SATA_EVNT_PWR_LEVEL_CHANGED;
17050 		mutex_exit(&sata_hba_inst->satahba_mutex);
17051 	}
17052 	/*
17053 	 * If we got here, there is something to do with this HBA
17054 	 * instance.
17055 	 */
17056 	mutex_enter(&sata_hba_inst->satahba_mutex);
17057 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17058 	mutex_exit(&sata_hba_inst->satahba_mutex);
17059 	mutex_enter(&sata_mutex);
17060 	sata_event_pending |= SATA_EVNT_MAIN;	/* global event indicator */
17061 	mutex_exit(&sata_mutex);
17062 
17063 	/* Tickle event thread */
17064 	mutex_enter(&sata_event_mutex);
17065 	if (sata_event_thread_active == 0)
17066 		cv_signal(&sata_event_cv);
17067 	mutex_exit(&sata_event_mutex);
17068 
17069 event_info:
17070 	if (buf1[0] != '\0') {
17071 		lcp = strrchr(buf1, ',');
17072 		if (lcp != NULL)
17073 			*lcp = '\0';
17074 	}
17075 	if (saddr->qual == SATA_ADDR_CPORT ||
17076 	    saddr->qual == SATA_ADDR_DCPORT) {
17077 		if (buf1[0] != '\0') {
17078 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17079 			    cport, buf1);
17080 		}
17081 		if (buf2[0] != '\0') {
17082 			sata_log(sata_hba_inst, CE_NOTE, "port %d: %s\n",
17083 			    cport, buf2);
17084 		}
17085 	} else if (saddr->qual == SATA_ADDR_PMPORT ||
17086 	    saddr->qual == SATA_ADDR_DPMPORT) {
17087 		if (buf1[0] != '\0') {
17088 			sata_log(sata_hba_inst, CE_NOTE,
17089 			    "port %d pmport %d: %s\n", cport, pmport, buf1);
17090 		}
17091 		if (buf2[0] != '\0') {
17092 			sata_log(sata_hba_inst, CE_NOTE,
17093 			    "port %d pmport %d: %s\n", cport, pmport, buf2);
17094 		}
17095 	}
17096 }
17097 
17098 
17099 /*
17100  * Event processing thread.
17101  * Arg is a pointer to the sata_hba_list pointer.
17102  * It is not really needed, because sata_hba_list is global and static
17103  */
17104 static void
17105 sata_event_daemon(void *arg)
17106 {
17107 #ifndef __lock_lint
17108 	_NOTE(ARGUNUSED(arg))
17109 #endif
17110 	sata_hba_inst_t *sata_hba_inst;
17111 	clock_t delta;
17112 
17113 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17114 	    "SATA event daemon started\n", NULL);
17115 loop:
17116 	/*
17117 	 * Process events here. Walk through all registered HBAs
17118 	 */
17119 	mutex_enter(&sata_mutex);
17120 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17121 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17122 		ASSERT(sata_hba_inst != NULL);
17123 		mutex_enter(&sata_hba_inst->satahba_mutex);
17124 		if (sata_hba_inst->satahba_attached == 0 ||
17125 		    (sata_hba_inst->satahba_event_flags &
17126 		    SATA_EVNT_SKIP) != 0) {
17127 			mutex_exit(&sata_hba_inst->satahba_mutex);
17128 			continue;
17129 		}
17130 		if (sata_hba_inst->satahba_event_flags & SATA_EVNT_MAIN) {
17131 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_SKIP;
17132 			mutex_exit(&sata_hba_inst->satahba_mutex);
17133 			mutex_exit(&sata_mutex);
17134 			/* Got the controller with pending event */
17135 			sata_process_controller_events(sata_hba_inst);
17136 			/*
17137 			 * Since global mutex was released, there is a
17138 			 * possibility that HBA list has changed, so start
17139 			 * over from the top. Just processed controller
17140 			 * will be passed-over because of the SKIP flag.
17141 			 */
17142 			goto loop;
17143 		}
17144 		mutex_exit(&sata_hba_inst->satahba_mutex);
17145 	}
17146 	/* Clear SKIP flag in all controllers */
17147 	for (sata_hba_inst = sata_hba_list; sata_hba_inst != NULL;
17148 	    sata_hba_inst = sata_hba_inst->satahba_next) {
17149 		mutex_enter(&sata_hba_inst->satahba_mutex);
17150 		sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_SKIP;
17151 		mutex_exit(&sata_hba_inst->satahba_mutex);
17152 	}
17153 	mutex_exit(&sata_mutex);
17154 
17155 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17156 	    "SATA EVENT DAEMON suspending itself", NULL);
17157 
17158 #ifdef SATA_DEBUG
17159 	if ((sata_func_enable & SATA_ENABLE_PROCESS_EVENTS) == 0) {
17160 		sata_log(sata_hba_inst, CE_WARN,
17161 		    "SATA EVENTS PROCESSING DISABLED\n");
17162 		thread_exit(); /* Daemon will not run again */
17163 	}
17164 #endif
17165 	mutex_enter(&sata_event_mutex);
17166 	sata_event_thread_active = 0;
17167 	mutex_exit(&sata_event_mutex);
17168 	/*
17169 	 * Go to sleep/suspend itself and wake up either because new event or
17170 	 * wait timeout. Exit if there is a termination request (driver
17171 	 * unload).
17172 	 */
17173 	delta = drv_usectohz(SATA_EVNT_DAEMON_SLEEP_TIME);
17174 	do {
17175 		mutex_enter(&sata_event_mutex);
17176 		(void) cv_reltimedwait(&sata_event_cv, &sata_event_mutex,
17177 		    delta, TR_CLOCK_TICK);
17178 
17179 		if (sata_event_thread_active != 0) {
17180 			mutex_exit(&sata_event_mutex);
17181 			continue;
17182 		}
17183 
17184 		/* Check if it is time to go away */
17185 		if (sata_event_thread_terminate == 1) {
17186 			/*
17187 			 * It is up to the thread setting above flag to make
17188 			 * sure that this thread is not killed prematurely.
17189 			 */
17190 			sata_event_thread_terminate = 0;
17191 			sata_event_thread = NULL;
17192 			mutex_exit(&sata_event_mutex);
17193 			SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17194 			    "SATA_EVENT_DAEMON_TERMINATING", NULL);
17195 			thread_exit();  { _NOTE(NOT_REACHED) }
17196 		}
17197 		mutex_exit(&sata_event_mutex);
17198 	} while (!(sata_event_pending & SATA_EVNT_MAIN));
17199 
17200 	mutex_enter(&sata_event_mutex);
17201 	sata_event_thread_active = 1;
17202 	mutex_exit(&sata_event_mutex);
17203 
17204 	mutex_enter(&sata_mutex);
17205 	sata_event_pending &= ~SATA_EVNT_MAIN;
17206 	mutex_exit(&sata_mutex);
17207 
17208 	SATADBG1(SATA_DBG_EVENTS_DAEMON, NULL,
17209 	    "SATA EVENT DAEMON READY TO PROCESS EVENT", NULL);
17210 
17211 	goto loop;
17212 }
17213 
17214 /*
17215  * Specific HBA instance event processing.
17216  *
17217  * NOTE: At the moment, device event processing is limited to hard disks
17218  * only.
17219  * Port multiplier is supported now.
17220  */
17221 static void
17222 sata_process_controller_events(sata_hba_inst_t *sata_hba_inst)
17223 {
17224 	int ncport;
17225 	uint32_t event_flags;
17226 	sata_address_t *saddr;
17227 	sata_cport_info_t *cportinfo;
17228 	sata_pmult_info_t *pmultinfo;
17229 
17230 	SATADBG1(SATA_DBG_EVENTS_CNTRL, sata_hba_inst,
17231 	    "Processing controller %d event(s)",
17232 	    ddi_get_instance(SATA_DIP(sata_hba_inst)));
17233 
17234 	mutex_enter(&sata_hba_inst->satahba_mutex);
17235 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_MAIN;
17236 	event_flags = sata_hba_inst->satahba_event_flags;
17237 	mutex_exit(&sata_hba_inst->satahba_mutex);
17238 	/*
17239 	 * Process controller power change first
17240 	 * HERE
17241 	 */
17242 	if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED)
17243 		sata_process_cntrl_pwr_level_change(sata_hba_inst);
17244 
17245 	/*
17246 	 * Search through ports/devices to identify affected port/device.
17247 	 * We may have to process events for more than one port/device.
17248 	 */
17249 	for (ncport = 0; ncport < SATA_NUM_CPORTS(sata_hba_inst); ncport++) {
17250 		/*
17251 		 * Not all ports may be processed in attach by the time we
17252 		 * get an event. Check if port info is initialized.
17253 		 */
17254 		mutex_enter(&sata_hba_inst->satahba_mutex);
17255 		cportinfo = SATA_CPORT_INFO(sata_hba_inst, ncport);
17256 		mutex_exit(&sata_hba_inst->satahba_mutex);
17257 		if (cportinfo == NULL || cportinfo->cport_state == NULL)
17258 			continue;
17259 
17260 		/* We have initialized controller port info */
17261 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17262 		event_flags = (SATA_CPORT_INFO(sata_hba_inst, ncport))->
17263 		    cport_event_flags;
17264 		/* Check if port was locked by IOCTL processing */
17265 		if (event_flags & SATA_APCTL_LOCK_PORT_BUSY) {
17266 			/*
17267 			 * We ignore port events because port is busy
17268 			 * with AP control processing. Set again
17269 			 * controller and main event flag, so that
17270 			 * events may be processed by the next daemon
17271 			 * run.
17272 			 */
17273 			mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17274 			mutex_enter(&sata_hba_inst->satahba_mutex);
17275 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
17276 			mutex_exit(&sata_hba_inst->satahba_mutex);
17277 			mutex_enter(&sata_mutex);
17278 			sata_event_pending |= SATA_EVNT_MAIN;
17279 			mutex_exit(&sata_mutex);
17280 			SATADBG1(SATA_DBG_EVENTS_PROCPST, sata_hba_inst,
17281 			    "Event processing postponed until "
17282 			    "AP control processing completes",
17283 			    NULL);
17284 			/* Check other ports */
17285 			continue;
17286 		} else {
17287 			/*
17288 			 * Set BSY flag so that AP control would not
17289 			 * interfere with events processing for
17290 			 * this port.
17291 			 */
17292 			(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17293 			    cport_event_flags |= SATA_EVNT_LOCK_PORT_BUSY;
17294 		}
17295 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17296 
17297 		saddr = &(SATA_CPORT_INFO(sata_hba_inst, ncport))->cport_addr;
17298 
17299 		if ((event_flags &
17300 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17301 			/*
17302 			 * Got port event.
17303 			 * We need some hierarchy of event processing as they
17304 			 * are affecting each other:
17305 			 * 1. port failed
17306 			 * 2. device detached/attached
17307 			 * 3. link events - link events may trigger device
17308 			 *    detached or device attached events in some
17309 			 *    circumstances.
17310 			 * 4. port power level changed
17311 			 */
17312 			if (event_flags & SATA_EVNT_PORT_FAILED) {
17313 				sata_process_port_failed_event(sata_hba_inst,
17314 				    saddr);
17315 			}
17316 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17317 				sata_process_device_detached(sata_hba_inst,
17318 				    saddr);
17319 			}
17320 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17321 				sata_process_device_attached(sata_hba_inst,
17322 				    saddr);
17323 			}
17324 			if (event_flags &
17325 			    (SATA_EVNT_LINK_ESTABLISHED |
17326 			    SATA_EVNT_LINK_LOST)) {
17327 				sata_process_port_link_events(sata_hba_inst,
17328 				    saddr);
17329 			}
17330 			if (event_flags & SATA_EVNT_PWR_LEVEL_CHANGED) {
17331 				sata_process_port_pwr_change(sata_hba_inst,
17332 				    saddr);
17333 			}
17334 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17335 				sata_process_target_node_cleanup(
17336 				    sata_hba_inst, saddr);
17337 			}
17338 			if (event_flags & SATA_EVNT_AUTOONLINE_DEVICE) {
17339 				sata_process_device_autoonline(
17340 				    sata_hba_inst, saddr);
17341 			}
17342 		}
17343 
17344 
17345 		/*
17346 		 * Scan port multiplier and all its sub-ports event flags.
17347 		 * The events are marked by
17348 		 * (1) sata_pmult_info.pmult_event_flags
17349 		 * (2) sata_pmport_info.pmport_event_flags
17350 		 */
17351 		mutex_enter(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17352 		if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
17353 			/*
17354 			 * There should be another extra check: this
17355 			 * port multiplier still exists?
17356 			 */
17357 			pmultinfo = SATA_PMULT_INFO(sata_hba_inst,
17358 			    ncport);
17359 
17360 			if (pmultinfo != NULL) {
17361 				mutex_exit(&(SATA_CPORT_MUTEX(
17362 				    sata_hba_inst, ncport)));
17363 				sata_process_pmult_events(
17364 				    sata_hba_inst, ncport);
17365 				mutex_enter(&(SATA_CPORT_MUTEX(
17366 				    sata_hba_inst, ncport)));
17367 			} else {
17368 				SATADBG1(SATA_DBG_PMULT, sata_hba_inst,
17369 				    "Port-multiplier is gone. "
17370 				    "Ignore all sub-device events "
17371 				    "at port %d.", ncport);
17372 			}
17373 		}
17374 
17375 		if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, ncport) !=
17376 		    SATA_DTYPE_NONE) &&
17377 		    (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport) != NULL)) {
17378 			if (SATA_CPORT_DRV_INFO(sata_hba_inst, ncport)->
17379 			    satadrv_event_flags &
17380 			    (SATA_EVNT_DEVICE_RESET |
17381 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17382 				/* Have device event */
17383 				sata_process_device_reset(sata_hba_inst,
17384 				    saddr);
17385 			}
17386 		}
17387 		/* Release PORT_BUSY flag */
17388 		(SATA_CPORT_INFO(sata_hba_inst, ncport))->
17389 		    cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17390 		mutex_exit(&(SATA_CPORT_MUTEX(sata_hba_inst, ncport)));
17391 
17392 	} /* End of loop through the controller SATA ports */
17393 }
17394 
17395 /*
17396  * Specific port multiplier instance event processing. At the moment, device
17397  * event processing is limited to link/attach event only.
17398  *
17399  * NOTE: power management event is not supported yet.
17400  */
17401 static void
17402 sata_process_pmult_events(sata_hba_inst_t *sata_hba_inst, uint8_t cport)
17403 {
17404 	sata_cport_info_t *cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17405 	sata_pmult_info_t *pmultinfo;
17406 	sata_pmport_info_t *pmportinfo;
17407 	sata_address_t *saddr;
17408 	sata_device_t sata_device;
17409 	uint32_t event_flags;
17410 	int npmport;
17411 	int rval;
17412 
17413 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17414 	    "Processing pmult event(s) on cport %d of controller %d",
17415 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17416 
17417 	/* First process events on port multiplier */
17418 	mutex_enter(&cportinfo->cport_mutex);
17419 	pmultinfo = SATA_PMULT_INFO(sata_hba_inst, cport);
17420 	event_flags = pmultinfo->pmult_event_flags;
17421 
17422 	/*
17423 	 * Reset event (of port multiplier) has higher priority because the
17424 	 * port multiplier itself might be failed or removed after reset.
17425 	 */
17426 	if (event_flags & SATA_EVNT_DEVICE_RESET) {
17427 		/*
17428 		 * The status of the sub-links are uncertain,
17429 		 * so mark all sub-ports as RESET
17430 		 */
17431 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(
17432 		    sata_hba_inst, cport); npmport ++) {
17433 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
17434 			    cport, npmport);
17435 			if (pmportinfo == NULL) {
17436 				/* That's weird. */
17437 				SATA_LOG_D((sata_hba_inst, CE_WARN,
17438 				    "sata_hba_event_notify: "
17439 				    "invalid/un-implemented "
17440 				    "port %d:%d (%d ports), ",
17441 				    cport, npmport, SATA_NUM_PMPORTS(
17442 				    sata_hba_inst, cport)));
17443 				continue;
17444 			}
17445 
17446 			mutex_enter(&pmportinfo->pmport_mutex);
17447 
17448 			/* Mark all pmport to unknow state. */
17449 			pmportinfo->pmport_state = SATA_STATE_UNKNOWN;
17450 			/* Mark all pmports with link events. */
17451 			pmportinfo->pmport_event_flags =
17452 			    (SATA_EVNT_LINK_ESTABLISHED|SATA_EVNT_LINK_LOST);
17453 			mutex_exit(&pmportinfo->pmport_mutex);
17454 		}
17455 
17456 	} else if (event_flags & SATA_EVNT_PMULT_LINK_CHANGED) {
17457 		/*
17458 		 * We need probe the port multiplier to know what has
17459 		 * happened.
17460 		 */
17461 		bzero(&sata_device, sizeof (sata_device_t));
17462 		sata_device.satadev_rev = SATA_DEVICE_REV;
17463 		sata_device.satadev_addr.cport = cport;
17464 		sata_device.satadev_addr.pmport = SATA_PMULT_HOSTPORT;
17465 		sata_device.satadev_addr.qual = SATA_ADDR_PMULT;
17466 
17467 		mutex_exit(&cportinfo->cport_mutex);
17468 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17469 		    (SATA_DIP(sata_hba_inst), &sata_device);
17470 		mutex_enter(&cportinfo->cport_mutex);
17471 		if (rval != SATA_SUCCESS) {
17472 			/* Something went wrong? Fail the port */
17473 			cportinfo->cport_state = SATA_PSTATE_FAILED;
17474 			mutex_exit(&cportinfo->cport_mutex);
17475 			SATA_LOG_D((sata_hba_inst, CE_WARN,
17476 			    "SATA port %d probing failed", cport));
17477 
17478 			/* PMult structure must be released.  */
17479 			sata_free_pmult(sata_hba_inst, &sata_device);
17480 			return;
17481 		}
17482 
17483 		sata_update_port_info(sata_hba_inst, &sata_device);
17484 
17485 		/*
17486 		 * Sanity check - Port is active? Is the link active?
17487 		 * The device is still a port multiplier?
17488 		 */
17489 		if ((cportinfo->cport_state &
17490 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) ||
17491 		    ((cportinfo->cport_scr.sstatus &
17492 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) ||
17493 		    (cportinfo->cport_dev_type != SATA_DTYPE_PMULT)) {
17494 			mutex_exit(&cportinfo->cport_mutex);
17495 
17496 			/* PMult structure must be released.  */
17497 			sata_free_pmult(sata_hba_inst, &sata_device);
17498 			return;
17499 		}
17500 
17501 		/* Probed succeed, set port ready. */
17502 		cportinfo->cport_state |=
17503 		    SATA_STATE_PROBED | SATA_STATE_READY;
17504 	}
17505 
17506 	/* Release port multiplier event flags. */
17507 	pmultinfo->pmult_event_flags &=
17508 	    ~(SATA_EVNT_DEVICE_RESET|SATA_EVNT_PMULT_LINK_CHANGED);
17509 	mutex_exit(&cportinfo->cport_mutex);
17510 
17511 	/*
17512 	 * Check all sub-links.
17513 	 */
17514 	for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst, cport);
17515 	    npmport ++) {
17516 		pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, npmport);
17517 		mutex_enter(&pmportinfo->pmport_mutex);
17518 		event_flags = pmportinfo->pmport_event_flags;
17519 		mutex_exit(&pmportinfo->pmport_mutex);
17520 		saddr = &pmportinfo->pmport_addr;
17521 
17522 		if ((event_flags &
17523 		    (SATA_EVNT_PORT_EVENTS | SATA_EVNT_DRIVE_EVENTS)) != 0) {
17524 			/*
17525 			 * Got port multiplier port event.
17526 			 * We need some hierarchy of event processing as they
17527 			 * are affecting each other:
17528 			 * 1. device detached/attached
17529 			 * 2. link events - link events may trigger device
17530 			 *    detached or device attached events in some
17531 			 *    circumstances.
17532 			 */
17533 			if (event_flags & SATA_EVNT_DEVICE_DETACHED) {
17534 				sata_process_pmdevice_detached(sata_hba_inst,
17535 				    saddr);
17536 			}
17537 			if (event_flags & SATA_EVNT_DEVICE_ATTACHED) {
17538 				sata_process_pmdevice_attached(sata_hba_inst,
17539 				    saddr);
17540 			}
17541 			if (event_flags & SATA_EVNT_LINK_ESTABLISHED ||
17542 			    event_flags & SATA_EVNT_LINK_LOST) {
17543 				sata_process_pmport_link_events(sata_hba_inst,
17544 				    saddr);
17545 			}
17546 			if (event_flags & SATA_EVNT_TARGET_NODE_CLEANUP) {
17547 				sata_process_target_node_cleanup(
17548 				    sata_hba_inst, saddr);
17549 			}
17550 		}
17551 
17552 		/* Checking drive event(s). */
17553 		mutex_enter(&pmportinfo->pmport_mutex);
17554 		if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE &&
17555 		    pmportinfo->pmport_sata_drive != NULL) {
17556 			event_flags = pmportinfo->pmport_sata_drive->
17557 			    satadrv_event_flags;
17558 			if (event_flags & (SATA_EVNT_DEVICE_RESET |
17559 			    SATA_EVNT_INPROC_DEVICE_RESET)) {
17560 
17561 				/* Have device event */
17562 				sata_process_pmdevice_reset(sata_hba_inst,
17563 				    saddr);
17564 			}
17565 		}
17566 		mutex_exit(&pmportinfo->pmport_mutex);
17567 
17568 		/* Release PORT_BUSY flag */
17569 		mutex_enter(&cportinfo->cport_mutex);
17570 		cportinfo->cport_event_flags &= ~SATA_EVNT_LOCK_PORT_BUSY;
17571 		mutex_exit(&cportinfo->cport_mutex);
17572 	}
17573 
17574 	SATADBG2(SATA_DBG_EVENTS_CNTRL|SATA_DBG_PMULT, sata_hba_inst,
17575 	    "[DONE] pmult event(s) on cport %d of controller %d",
17576 	    cport, ddi_get_instance(SATA_DIP(sata_hba_inst)));
17577 }
17578 
17579 /*
17580  * Process HBA power level change reported by HBA driver.
17581  * Not implemented at this time - event is ignored.
17582  */
17583 static void
17584 sata_process_cntrl_pwr_level_change(sata_hba_inst_t *sata_hba_inst)
17585 {
17586 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17587 	    "Processing controller power level change", NULL);
17588 
17589 	/* Ignoring it for now */
17590 	mutex_enter(&sata_hba_inst->satahba_mutex);
17591 	sata_hba_inst->satahba_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17592 	mutex_exit(&sata_hba_inst->satahba_mutex);
17593 }
17594 
17595 /*
17596  * Process port power level change reported by HBA driver.
17597  * Not implemented at this time - event is ignored.
17598  */
17599 static void
17600 sata_process_port_pwr_change(sata_hba_inst_t *sata_hba_inst,
17601     sata_address_t *saddr)
17602 {
17603 	sata_cport_info_t *cportinfo;
17604 
17605 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17606 	    "Processing port power level change", NULL);
17607 
17608 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17609 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17610 	/* Reset event flag */
17611 	cportinfo->cport_event_flags &= ~SATA_EVNT_PWR_LEVEL_CHANGED;
17612 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17613 }
17614 
17615 /*
17616  * Process port failure reported by HBA driver.
17617  * cports support only - no pmports.
17618  */
17619 static void
17620 sata_process_port_failed_event(sata_hba_inst_t *sata_hba_inst,
17621     sata_address_t *saddr)
17622 {
17623 	sata_cport_info_t *cportinfo;
17624 
17625 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17626 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17627 	/* Reset event flag first */
17628 	cportinfo->cport_event_flags &= ~SATA_EVNT_PORT_FAILED;
17629 	/* If the port is in SHUTDOWN or FAILED state, ignore this event. */
17630 	if ((cportinfo->cport_state &
17631 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0) {
17632 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17633 		    cport_mutex);
17634 		return;
17635 	}
17636 	/* Fail the port */
17637 	cportinfo->cport_state = SATA_PSTATE_FAILED;
17638 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17639 	sata_log(sata_hba_inst, CE_WARN, "SATA port %d failed", saddr->cport);
17640 }
17641 
17642 /*
17643  * Device Reset Event processing.
17644  * The seqeunce is managed by 3 stage flags:
17645  * - reset event reported,
17646  * - reset event being processed,
17647  * - request to clear device reset state.
17648  *
17649  * NOTE: This function has to be entered with cport mutex held. It exits with
17650  * mutex held as well, but can release mutex during the processing.
17651  */
17652 static void
17653 sata_process_device_reset(sata_hba_inst_t *sata_hba_inst,
17654     sata_address_t *saddr)
17655 {
17656 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
17657 	sata_drive_info_t *sdinfo;
17658 	sata_cport_info_t *cportinfo;
17659 	sata_device_t sata_device;
17660 	int rval_probe, rval_set;
17661 
17662 	/* We only care about host sata cport for now */
17663 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
17664 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17665 	/*
17666 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
17667 	 * state, ignore reset event.
17668 	 */
17669 	if (((cportinfo->cport_state &
17670 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
17671 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
17672 		sdinfo->satadrv_event_flags &=
17673 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
17674 		return;
17675 	}
17676 
17677 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) ==
17678 	    SATA_DTYPE_PMULT)) {
17679 		/*
17680 		 * Should not happened: this is already handled in
17681 		 * sata_hba_event_notify()
17682 		 */
17683 		mutex_exit(&cportinfo->cport_mutex);
17684 		goto done;
17685 	}
17686 
17687 	if ((SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) &
17688 	    SATA_VALID_DEV_TYPE) == 0) {
17689 		/*
17690 		 * This should not happen - coding error.
17691 		 * But we can recover, so do not panic, just clean up
17692 		 * and if in debug mode, log the message.
17693 		 */
17694 #ifdef SATA_DEBUG
17695 		sata_log(sata_hba_inst, CE_WARN,
17696 		    "sata_process_device_reset: "
17697 		    "Invalid device type with sdinfo!", NULL);
17698 #endif
17699 		sdinfo->satadrv_event_flags = 0;
17700 		return;
17701 	}
17702 
17703 #ifdef SATA_DEBUG
17704 	if ((sdinfo->satadrv_event_flags &
17705 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
17706 		/* Nothing to do */
17707 		/* Something is weird - why we are processing dev reset? */
17708 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17709 		    "No device reset event!!!!", NULL);
17710 
17711 		return;
17712 	}
17713 	if ((sdinfo->satadrv_event_flags &
17714 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
17715 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
17716 		/* Something is weird - new device reset event */
17717 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17718 		    "Overlapping device reset events!", NULL);
17719 	}
17720 #endif
17721 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17722 	    "Processing port %d device reset", saddr->cport);
17723 
17724 	/* Clear event flag */
17725 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
17726 
17727 	/* It seems that we always need to check the port state first */
17728 	sata_device.satadev_rev = SATA_DEVICE_REV;
17729 	sata_device.satadev_addr = *saddr;
17730 	/*
17731 	 * We have to exit mutex, because the HBA probe port function may
17732 	 * block on its own mutex.
17733 	 */
17734 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17735 	rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17736 	    (SATA_DIP(sata_hba_inst), &sata_device);
17737 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17738 	sata_update_port_info(sata_hba_inst, &sata_device);
17739 	if (rval_probe != SATA_SUCCESS) {
17740 		/* Something went wrong? Fail the port */
17741 		cportinfo->cport_state = SATA_PSTATE_FAILED;
17742 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17743 		if (sdinfo != NULL)
17744 			sdinfo->satadrv_event_flags = 0;
17745 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17746 		    cport_mutex);
17747 		SATA_LOG_D((sata_hba_inst, CE_WARN,
17748 		    "SATA port %d probing failed",
17749 		    saddr->cport));
17750 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
17751 		    saddr->cport)->cport_mutex);
17752 		return;
17753 	}
17754 	if ((sata_device.satadev_scr.sstatus  &
17755 	    SATA_PORT_DEVLINK_UP_MASK) !=
17756 	    SATA_PORT_DEVLINK_UP ||
17757 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
17758 		/*
17759 		 * No device to process, anymore. Some other event processing
17760 		 * would or have already performed port info cleanup.
17761 		 * To be safe (HBA may need it), request clearing device
17762 		 * reset condition.
17763 		 */
17764 		sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17765 		if (sdinfo != NULL) {
17766 			sdinfo->satadrv_event_flags &=
17767 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17768 			sdinfo->satadrv_event_flags |=
17769 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17770 		}
17771 		return;
17772 	}
17773 
17774 	sdinfo = SATA_CPORT_DRV_INFO(sata_hba_inst, saddr->cport);
17775 	if (sdinfo == NULL) {
17776 		return;
17777 	}
17778 	if ((sdinfo->satadrv_event_flags &
17779 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
17780 		/*
17781 		 * Start tracking time for device feature restoration and
17782 		 * identification. Save current time (lbolt value).
17783 		 */
17784 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
17785 	}
17786 	/* Mark device reset processing as active */
17787 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
17788 
17789 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
17790 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17791 
17792 	rval_set = sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1);
17793 
17794 	if (rval_set  != SATA_SUCCESS) {
17795 		/*
17796 		 * Restoring drive setting failed.
17797 		 * Probe the port first, to check if the port state has changed
17798 		 */
17799 		sata_device.satadev_rev = SATA_DEVICE_REV;
17800 		sata_device.satadev_addr = *saddr;
17801 		sata_device.satadev_addr.qual = SATA_ADDR_CPORT;
17802 		/* probe port */
17803 		rval_probe = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17804 		    (SATA_DIP(sata_hba_inst), &sata_device);
17805 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
17806 		    cport_mutex);
17807 		if (rval_probe == SATA_SUCCESS &&
17808 		    (sata_device.satadev_state &
17809 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
17810 		    (sata_device.satadev_scr.sstatus  &
17811 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
17812 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
17813 			/*
17814 			 * We may retry this a bit later - in-process reset
17815 			 * condition should be already set.
17816 			 * Track retry time for device identification.
17817 			 */
17818 			if ((cportinfo->cport_dev_type &
17819 			    SATA_VALID_DEV_TYPE) != 0 &&
17820 			    SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL &&
17821 			    sdinfo->satadrv_reset_time != 0) {
17822 				clock_t cur_time = ddi_get_lbolt();
17823 				/*
17824 				 * If the retry time limit was not
17825 				 * exceeded, retry.
17826 				 */
17827 				if ((cur_time - sdinfo->satadrv_reset_time) <
17828 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
17829 					mutex_enter(
17830 					    &sata_hba_inst->satahba_mutex);
17831 					sata_hba_inst->satahba_event_flags |=
17832 					    SATA_EVNT_MAIN;
17833 					mutex_exit(
17834 					    &sata_hba_inst->satahba_mutex);
17835 					mutex_enter(&sata_mutex);
17836 					sata_event_pending |= SATA_EVNT_MAIN;
17837 					mutex_exit(&sata_mutex);
17838 					return;
17839 				}
17840 				if (rval_set == SATA_RETRY) {
17841 					/*
17842 					 * Setting drive features failed, but
17843 					 * the drive is still accessible,
17844 					 * so emit a warning message before
17845 					 * return.
17846 					 */
17847 					mutex_exit(&SATA_CPORT_INFO(
17848 					    sata_hba_inst,
17849 					    saddr->cport)->cport_mutex);
17850 					goto done;
17851 				}
17852 			}
17853 			/* Fail the drive */
17854 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
17855 
17856 			sata_log(sata_hba_inst, CE_WARN,
17857 			    "SATA device at port %d - device failed",
17858 			    saddr->cport);
17859 		}
17860 		/*
17861 		 * No point of retrying - device failed or some other event
17862 		 * processing or already did or will do port info cleanup.
17863 		 * To be safe (HBA may need it),
17864 		 * request clearing device reset condition.
17865 		 */
17866 		sdinfo->satadrv_event_flags |= SATA_EVNT_CLEAR_DEVICE_RESET;
17867 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
17868 		sdinfo->satadrv_reset_time = 0;
17869 		return;
17870 	}
17871 done:
17872 	/*
17873 	 * If setting of drive features failed, but the drive is still
17874 	 * accessible, emit a warning message.
17875 	 */
17876 	if (rval_set == SATA_RETRY) {
17877 		sata_log(sata_hba_inst, CE_WARN,
17878 		    "SATA device at port %d - desired setting could not be "
17879 		    "restored after reset. Device may not operate as expected.",
17880 		    saddr->cport);
17881 	}
17882 	/*
17883 	 * Raise the flag indicating that the next sata command could
17884 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
17885 	 * reset is reported.
17886 	 */
17887 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
17888 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
17889 		sdinfo->satadrv_reset_time = 0;
17890 		if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) != 0) {
17891 			sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
17892 			sdinfo->satadrv_event_flags &=
17893 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
17894 			sdinfo->satadrv_event_flags |=
17895 			    SATA_EVNT_CLEAR_DEVICE_RESET;
17896 		}
17897 	}
17898 }
17899 
17900 
17901 /*
17902  * Port Multiplier Port Device Reset Event processing.
17903  *
17904  * NOTE: This function has to be entered with pmport mutex held. It exits with
17905  * mutex held as well, but can release mutex during the processing.
17906  */
17907 static void
17908 sata_process_pmdevice_reset(sata_hba_inst_t *sata_hba_inst,
17909     sata_address_t *saddr)
17910 {
17911 	sata_drive_info_t old_sdinfo; /* local copy of the drive info */
17912 	sata_drive_info_t *sdinfo = NULL;
17913 	sata_cport_info_t *cportinfo = NULL;
17914 	sata_pmport_info_t *pmportinfo = NULL;
17915 	sata_pmult_info_t *pminfo = NULL;
17916 	sata_device_t sata_device;
17917 	uint8_t cport = saddr->cport;
17918 	uint8_t pmport = saddr->pmport;
17919 	int rval;
17920 
17921 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17922 	    "Processing drive reset at port %d:%d", cport, pmport);
17923 
17924 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, cport);
17925 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
17926 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, cport, pmport);
17927 
17928 	/*
17929 	 * If the port is in SHUTDOWN or FAILED state, or device is in FAILED
17930 	 * state, ignore reset event.
17931 	 */
17932 	if (((cportinfo->cport_state &
17933 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) ||
17934 	    (sdinfo->satadrv_state & SATA_DSTATE_FAILED) != 0) {
17935 		sdinfo->satadrv_event_flags &=
17936 		    ~(SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET);
17937 		return;
17938 	}
17939 
17940 	if ((pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
17941 		/*
17942 		 * This should not happen - coding error.
17943 		 * But we can recover, so do not panic, just clean up
17944 		 * and if in debug mode, log the message.
17945 		 */
17946 #ifdef SATA_DEBUG
17947 		sata_log(sata_hba_inst, CE_WARN,
17948 		    "sata_process_pmdevice_reset: "
17949 		    "Invalid device type with sdinfo!", NULL);
17950 #endif
17951 		sdinfo->satadrv_event_flags = 0;
17952 		return;
17953 	}
17954 
17955 #ifdef SATA_DEBUG
17956 	if ((sdinfo->satadrv_event_flags &
17957 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) == 0) {
17958 		/* Nothing to do */
17959 		/* Something is weird - why we are processing dev reset? */
17960 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17961 		    "No device reset event!!!!", NULL);
17962 
17963 		return;
17964 	}
17965 	if ((sdinfo->satadrv_event_flags &
17966 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) ==
17967 	    (SATA_EVNT_DEVICE_RESET | SATA_EVNT_INPROC_DEVICE_RESET)) {
17968 		/* Something is weird - new device reset event */
17969 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17970 		    "Overlapping device reset events!", NULL);
17971 	}
17972 #endif
17973 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
17974 	    "Processing port %d:%d device reset", cport, pmport);
17975 
17976 	/* Clear event flag */
17977 	sdinfo->satadrv_event_flags &= ~SATA_EVNT_DEVICE_RESET;
17978 
17979 	/* It seems that we always need to check the port state first */
17980 	sata_device.satadev_rev = SATA_DEVICE_REV;
17981 	sata_device.satadev_addr = *saddr;
17982 	/*
17983 	 * We have to exit mutex, because the HBA probe port function may
17984 	 * block on its own mutex.
17985 	 */
17986 	mutex_exit(&pmportinfo->pmport_mutex);
17987 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
17988 	    (SATA_DIP(sata_hba_inst), &sata_device);
17989 	mutex_enter(&pmportinfo->pmport_mutex);
17990 
17991 	sata_update_pmport_info(sata_hba_inst, &sata_device);
17992 	if (rval != SATA_SUCCESS) {
17993 		/* Something went wrong? Fail the port */
17994 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
17995 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
17996 		    saddr->pmport);
17997 		if (sdinfo != NULL)
17998 			sdinfo->satadrv_event_flags = 0;
17999 		mutex_exit(&pmportinfo->pmport_mutex);
18000 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18001 		    "SATA port %d:%d probing failed",
18002 		    saddr->cport, saddr->pmport));
18003 		mutex_enter(&pmportinfo->pmport_mutex);
18004 		return;
18005 	}
18006 	if ((sata_device.satadev_scr.sstatus  &
18007 	    SATA_PORT_DEVLINK_UP_MASK) !=
18008 	    SATA_PORT_DEVLINK_UP ||
18009 	    sata_device.satadev_type == SATA_DTYPE_NONE) {
18010 		/*
18011 		 * No device to process, anymore. Some other event processing
18012 		 * would or have already performed port info cleanup.
18013 		 * To be safe (HBA may need it), request clearing device
18014 		 * reset condition.
18015 		 */
18016 		sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18017 		    saddr->pmport);
18018 		if (sdinfo != NULL) {
18019 			sdinfo->satadrv_event_flags &=
18020 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18021 			/* must clear flags on cport */
18022 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18023 			    saddr->cport);
18024 			pminfo->pmult_event_flags |=
18025 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18026 		}
18027 		return;
18028 	}
18029 
18030 	sdinfo = SATA_PMPORT_DRV_INFO(sata_hba_inst, saddr->cport,
18031 	    saddr->pmport);
18032 	if (sdinfo == NULL) {
18033 		return;
18034 	}
18035 	if ((sdinfo->satadrv_event_flags &
18036 	    SATA_EVNT_INPROC_DEVICE_RESET) == 0) {
18037 		/*
18038 		 * Start tracking time for device feature restoration and
18039 		 * identification. Save current time (lbolt value).
18040 		 */
18041 		sdinfo->satadrv_reset_time = ddi_get_lbolt();
18042 	}
18043 	/* Mark device reset processing as active */
18044 	sdinfo->satadrv_event_flags |= SATA_EVNT_INPROC_DEVICE_RESET;
18045 
18046 	old_sdinfo = *sdinfo;	/* local copy of the drive info */
18047 	mutex_exit(&pmportinfo->pmport_mutex);
18048 
18049 	if (sata_set_drive_features(sata_hba_inst, &old_sdinfo, 1) ==
18050 	    SATA_FAILURE) {
18051 		/*
18052 		 * Restoring drive setting failed.
18053 		 * Probe the port first, to check if the port state has changed
18054 		 */
18055 		sata_device.satadev_rev = SATA_DEVICE_REV;
18056 		sata_device.satadev_addr = *saddr;
18057 		sata_device.satadev_addr.qual = SATA_ADDR_PMPORT;
18058 
18059 		/* probe port */
18060 		rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18061 		    (SATA_DIP(sata_hba_inst), &sata_device);
18062 		mutex_enter(&pmportinfo->pmport_mutex);
18063 		if (rval == SATA_SUCCESS &&
18064 		    (sata_device.satadev_state &
18065 		    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) == 0 &&
18066 		    (sata_device.satadev_scr.sstatus  &
18067 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP &&
18068 		    sata_device.satadev_type != SATA_DTYPE_NONE) {
18069 			/*
18070 			 * We may retry this a bit later - in-process reset
18071 			 * condition should be already set.
18072 			 * Track retry time for device identification.
18073 			 */
18074 			if ((pmportinfo->pmport_dev_type &
18075 			    SATA_VALID_DEV_TYPE) != 0 &&
18076 			    SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL &&
18077 			    sdinfo->satadrv_reset_time != 0) {
18078 				clock_t cur_time = ddi_get_lbolt();
18079 				/*
18080 				 * If the retry time limit was not
18081 				 * exceeded, retry.
18082 				 */
18083 				if ((cur_time - sdinfo->satadrv_reset_time) <
18084 				    drv_usectohz(SATA_DEV_REPROBE_TIMEOUT)) {
18085 					mutex_enter(
18086 					    &sata_hba_inst->satahba_mutex);
18087 					sata_hba_inst->satahba_event_flags |=
18088 					    SATA_EVNT_MAIN;
18089 					mutex_exit(
18090 					    &sata_hba_inst->satahba_mutex);
18091 					mutex_enter(&sata_mutex);
18092 					sata_event_pending |= SATA_EVNT_MAIN;
18093 					mutex_exit(&sata_mutex);
18094 					return;
18095 				}
18096 			}
18097 			/* Fail the drive */
18098 			sdinfo->satadrv_state = SATA_DSTATE_FAILED;
18099 
18100 			sata_log(sata_hba_inst, CE_WARN,
18101 			    "SATA device at port %d:%d - device failed",
18102 			    saddr->cport, saddr->pmport);
18103 		} else {
18104 			/*
18105 			 * No point of retrying - some other event processing
18106 			 * would or already did port info cleanup.
18107 			 * To be safe (HBA may need it),
18108 			 * request clearing device reset condition.
18109 			 */
18110 			sdinfo->satadrv_event_flags |=
18111 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18112 		}
18113 		sdinfo->satadrv_event_flags &= ~SATA_EVNT_INPROC_DEVICE_RESET;
18114 		sdinfo->satadrv_reset_time = 0;
18115 		return;
18116 	}
18117 	/*
18118 	 * Raise the flag indicating that the next sata command could
18119 	 * be sent with SATA_CLEAR_DEV_RESET_STATE flag, if no new device
18120 	 * reset is reported.
18121 	 */
18122 	mutex_enter(&pmportinfo->pmport_mutex);
18123 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18124 		sdinfo->satadrv_reset_time = 0;
18125 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
18126 			sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18127 			sdinfo->satadrv_event_flags &=
18128 			    ~SATA_EVNT_INPROC_DEVICE_RESET;
18129 			/* must clear flags on cport */
18130 			pminfo = SATA_PMULT_INFO(sata_hba_inst,
18131 			    saddr->cport);
18132 			pminfo->pmult_event_flags |=
18133 			    SATA_EVNT_CLEAR_DEVICE_RESET;
18134 		}
18135 	}
18136 }
18137 
18138 /*
18139  * Port Link Events processing.
18140  * Every link established event may involve device reset (due to
18141  * COMRESET signal, equivalent of the hard reset) so arbitrarily
18142  * set device reset event for an attached device (if any).
18143  * If the port is in SHUTDOWN or FAILED state, ignore link events.
18144  *
18145  * The link established event processing varies, depending on the state
18146  * of the target node, HBA hotplugging capabilities, state of the port.
18147  * If the link is not active, the link established event is ignored.
18148  * If HBA cannot detect device attachment and there is no target node,
18149  * the link established event triggers device attach event processing.
18150  * Else, link established event triggers device reset event processing.
18151  *
18152  * The link lost event processing varies, depending on a HBA hotplugging
18153  * capability and the state of the port (link active or not active).
18154  * If the link is active, the lost link event is ignored.
18155  * If HBA cannot detect device removal, the lost link event triggers
18156  * device detached event processing after link lost timeout.
18157  * Else, the event is ignored.
18158  *
18159  * NOTE: Port multiplier ports events are handled by
18160  * sata_process_pmport_link_events();
18161  */
18162 static void
18163 sata_process_port_link_events(sata_hba_inst_t *sata_hba_inst,
18164     sata_address_t *saddr)
18165 {
18166 	sata_device_t sata_device;
18167 	sata_cport_info_t *cportinfo;
18168 	sata_drive_info_t *sdinfo;
18169 	uint32_t event_flags;
18170 	int rval;
18171 
18172 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18173 	    "Processing port %d link event(s)", saddr->cport);
18174 
18175 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18176 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18177 	event_flags = cportinfo->cport_event_flags;
18178 
18179 	/* Reset event flags first */
18180 	cportinfo->cport_event_flags &=
18181 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18182 
18183 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18184 	if ((cportinfo->cport_state &
18185 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18186 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18187 		    cport_mutex);
18188 		return;
18189 	}
18190 
18191 	/*
18192 	 * For the sanity sake get current port state.
18193 	 * Set device address only. Other sata_device fields should be
18194 	 * set by HBA driver.
18195 	 */
18196 	sata_device.satadev_rev = SATA_DEVICE_REV;
18197 	sata_device.satadev_addr = *saddr;
18198 	/*
18199 	 * We have to exit mutex, because the HBA probe port function may
18200 	 * block on its own mutex.
18201 	 */
18202 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18203 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18204 	    (SATA_DIP(sata_hba_inst), &sata_device);
18205 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18206 	sata_update_port_info(sata_hba_inst, &sata_device);
18207 	if (rval != SATA_SUCCESS) {
18208 		/* Something went wrong? Fail the port */
18209 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18210 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18211 		    cport_mutex);
18212 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18213 		    "SATA port %d probing failed",
18214 		    saddr->cport));
18215 		/*
18216 		 * We may want to release device info structure, but
18217 		 * it is not necessary.
18218 		 */
18219 		return;
18220 	} else {
18221 		/* port probed successfully */
18222 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18223 	}
18224 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18225 
18226 		if ((sata_device.satadev_scr.sstatus &
18227 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18228 			/* Ignore event */
18229 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18230 			    "Ignoring port %d link established event - "
18231 			    "link down",
18232 			    saddr->cport);
18233 			goto linklost;
18234 		}
18235 
18236 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18237 		    "Processing port %d link established event",
18238 		    saddr->cport);
18239 
18240 		/*
18241 		 * For the sanity sake check if a device is attached - check
18242 		 * return state of a port probing.
18243 		 */
18244 		if (sata_device.satadev_type != SATA_DTYPE_NONE) {
18245 			/*
18246 			 * HBA port probe indicated that there is a device
18247 			 * attached. Check if the framework had device info
18248 			 * structure attached for this device.
18249 			 */
18250 			if (cportinfo->cport_dev_type != SATA_DTYPE_NONE) {
18251 				ASSERT(SATA_CPORTINFO_DRV_INFO(cportinfo) !=
18252 				    NULL);
18253 
18254 				sdinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18255 				if ((sdinfo->satadrv_type &
18256 				    SATA_VALID_DEV_TYPE) != 0) {
18257 					/*
18258 					 * Dev info structure is present.
18259 					 * If dev_type is set to known type in
18260 					 * the framework's drive info struct
18261 					 * then the device existed before and
18262 					 * the link was probably lost
18263 					 * momentarily - in such case
18264 					 * we may want to check device
18265 					 * identity.
18266 					 * Identity check is not supported now.
18267 					 *
18268 					 * Link established event
18269 					 * triggers device reset event.
18270 					 */
18271 					(SATA_CPORTINFO_DRV_INFO(cportinfo))->
18272 					    satadrv_event_flags |=
18273 					    SATA_EVNT_DEVICE_RESET;
18274 				}
18275 			} else if (cportinfo->cport_dev_type ==
18276 			    SATA_DTYPE_NONE) {
18277 				/*
18278 				 * We got new device attached! If HBA does not
18279 				 * generate device attached events, trigger it
18280 				 * here.
18281 				 */
18282 				if (!(SATA_FEATURES(sata_hba_inst) &
18283 				    SATA_CTLF_HOTPLUG)) {
18284 					cportinfo->cport_event_flags |=
18285 					    SATA_EVNT_DEVICE_ATTACHED;
18286 				}
18287 			}
18288 			/* Reset link lost timeout */
18289 			cportinfo->cport_link_lost_time = 0;
18290 		}
18291 	}
18292 linklost:
18293 	if (event_flags & SATA_EVNT_LINK_LOST) {
18294 		if ((sata_device.satadev_scr.sstatus &
18295 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18296 			/* Ignore event */
18297 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18298 			    "Ignoring port %d link lost event - link is up",
18299 			    saddr->cport);
18300 			goto done;
18301 		}
18302 #ifdef SATA_DEBUG
18303 		if (cportinfo->cport_link_lost_time == 0) {
18304 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18305 			    "Processing port %d link lost event",
18306 			    saddr->cport);
18307 		}
18308 #endif
18309 		/*
18310 		 * When HBA cannot generate device attached/detached events,
18311 		 * we need to track link lost time and eventually generate
18312 		 * device detach event.
18313 		 */
18314 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18315 			/* We are tracking link lost time */
18316 			if (cportinfo->cport_link_lost_time == 0) {
18317 				/* save current time (lbolt value) */
18318 				cportinfo->cport_link_lost_time =
18319 				    ddi_get_lbolt();
18320 				/* just keep link lost event */
18321 				cportinfo->cport_event_flags |=
18322 				    SATA_EVNT_LINK_LOST;
18323 			} else {
18324 				clock_t cur_time = ddi_get_lbolt();
18325 				if ((cur_time -
18326 				    cportinfo->cport_link_lost_time) >=
18327 				    drv_usectohz(
18328 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18329 					/* trigger device detach event */
18330 					cportinfo->cport_event_flags |=
18331 					    SATA_EVNT_DEVICE_DETACHED;
18332 					cportinfo->cport_link_lost_time = 0;
18333 					SATADBG1(SATA_DBG_EVENTS,
18334 					    sata_hba_inst,
18335 					    "Triggering port %d "
18336 					    "device detached event",
18337 					    saddr->cport);
18338 				} else {
18339 					/* keep link lost event */
18340 					cportinfo->cport_event_flags |=
18341 					    SATA_EVNT_LINK_LOST;
18342 				}
18343 			}
18344 		}
18345 		/*
18346 		 * We could change port state to disable/delay access to
18347 		 * the attached device until the link is recovered.
18348 		 */
18349 	}
18350 done:
18351 	event_flags = cportinfo->cport_event_flags;
18352 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18353 	if (event_flags != 0) {
18354 		mutex_enter(&sata_hba_inst->satahba_mutex);
18355 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18356 		mutex_exit(&sata_hba_inst->satahba_mutex);
18357 		mutex_enter(&sata_mutex);
18358 		sata_event_pending |= SATA_EVNT_MAIN;
18359 		mutex_exit(&sata_mutex);
18360 	}
18361 }
18362 
18363 /*
18364  * Port Multiplier Port Link Events processing.
18365  */
18366 static void
18367 sata_process_pmport_link_events(sata_hba_inst_t *sata_hba_inst,
18368     sata_address_t *saddr)
18369 {
18370 	sata_device_t sata_device;
18371 	sata_pmport_info_t *pmportinfo = NULL;
18372 	sata_drive_info_t *sdinfo = NULL;
18373 	uint32_t event_flags;
18374 	uint8_t cport = saddr->cport;
18375 	uint8_t pmport = saddr->pmport;
18376 	int rval;
18377 
18378 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18379 	    "Processing port %d:%d link event(s)",
18380 	    cport, pmport);
18381 
18382 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18383 	mutex_enter(&pmportinfo->pmport_mutex);
18384 	event_flags = pmportinfo->pmport_event_flags;
18385 
18386 	/* Reset event flags first */
18387 	pmportinfo->pmport_event_flags &=
18388 	    ~(SATA_EVNT_LINK_ESTABLISHED | SATA_EVNT_LINK_LOST);
18389 
18390 	/* If the port is in SHUTDOWN or FAILED state, ignore link events. */
18391 	if ((pmportinfo->pmport_state &
18392 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18393 		mutex_exit(&pmportinfo->pmport_mutex);
18394 		return;
18395 	}
18396 
18397 	/*
18398 	 * For the sanity sake get current port state.
18399 	 * Set device address only. Other sata_device fields should be
18400 	 * set by HBA driver.
18401 	 */
18402 	sata_device.satadev_rev = SATA_DEVICE_REV;
18403 	sata_device.satadev_addr = *saddr;
18404 	/*
18405 	 * We have to exit mutex, because the HBA probe port function may
18406 	 * block on its own mutex.
18407 	 */
18408 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18409 	    saddr->pmport));
18410 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18411 	    (SATA_DIP(sata_hba_inst), &sata_device);
18412 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18413 	    saddr->pmport));
18414 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18415 	if (rval != SATA_SUCCESS) {
18416 		/* Something went wrong? Fail the port */
18417 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18418 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18419 		    saddr->pmport));
18420 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18421 		    "SATA port %d:%d probing failed",
18422 		    saddr->cport, saddr->pmport));
18423 		/*
18424 		 * We may want to release device info structure, but
18425 		 * it is not necessary.
18426 		 */
18427 		return;
18428 	} else {
18429 		/* port probed successfully */
18430 		pmportinfo->pmport_state |=
18431 		    SATA_STATE_PROBED | SATA_STATE_READY;
18432 	}
18433 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst,
18434 	    saddr->cport, saddr->pmport));
18435 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst,
18436 	    saddr->cport, saddr->pmport));
18437 	if (event_flags & SATA_EVNT_LINK_ESTABLISHED) {
18438 
18439 		if ((sata_device.satadev_scr.sstatus &
18440 		    SATA_PORT_DEVLINK_UP_MASK) != SATA_PORT_DEVLINK_UP) {
18441 			/* Ignore event */
18442 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18443 			    "Ignoring port %d:%d link established event - "
18444 			    "link down",
18445 			    saddr->cport, saddr->pmport);
18446 			goto linklost;
18447 		}
18448 
18449 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18450 		    "Processing port %d:%d link established event",
18451 		    cport, pmport);
18452 
18453 		/*
18454 		 * For the sanity sake check if a device is attached - check
18455 		 * return state of a port probing.
18456 		 */
18457 		if (sata_device.satadev_type != SATA_DTYPE_NONE &&
18458 		    sata_device.satadev_type != SATA_DTYPE_PMULT) {
18459 			/*
18460 			 * HBA port probe indicated that there is a device
18461 			 * attached. Check if the framework had device info
18462 			 * structure attached for this device.
18463 			 */
18464 			if (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE) {
18465 				ASSERT(SATA_PMPORTINFO_DRV_INFO(pmportinfo) !=
18466 				    NULL);
18467 
18468 				sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18469 				if ((sdinfo->satadrv_type &
18470 				    SATA_VALID_DEV_TYPE) != 0) {
18471 					/*
18472 					 * Dev info structure is present.
18473 					 * If dev_type is set to known type in
18474 					 * the framework's drive info struct
18475 					 * then the device existed before and
18476 					 * the link was probably lost
18477 					 * momentarily - in such case
18478 					 * we may want to check device
18479 					 * identity.
18480 					 * Identity check is not supported now.
18481 					 *
18482 					 * Link established event
18483 					 * triggers device reset event.
18484 					 */
18485 					(SATA_PMPORTINFO_DRV_INFO(pmportinfo))->
18486 					    satadrv_event_flags |=
18487 					    SATA_EVNT_DEVICE_RESET;
18488 				}
18489 			} else if (pmportinfo->pmport_dev_type ==
18490 			    SATA_DTYPE_NONE) {
18491 				/*
18492 				 * We got new device attached! If HBA does not
18493 				 * generate device attached events, trigger it
18494 				 * here.
18495 				 */
18496 				if (!(SATA_FEATURES(sata_hba_inst) &
18497 				    SATA_CTLF_HOTPLUG)) {
18498 					pmportinfo->pmport_event_flags |=
18499 					    SATA_EVNT_DEVICE_ATTACHED;
18500 				}
18501 			}
18502 			/* Reset link lost timeout */
18503 			pmportinfo->pmport_link_lost_time = 0;
18504 		}
18505 	}
18506 linklost:
18507 	if (event_flags & SATA_EVNT_LINK_LOST) {
18508 #ifdef SATA_DEBUG
18509 		if (pmportinfo->pmport_link_lost_time == 0) {
18510 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18511 			    "Processing port %d:%d link lost event",
18512 			    saddr->cport, saddr->pmport);
18513 		}
18514 #endif
18515 		if ((sata_device.satadev_scr.sstatus &
18516 		    SATA_PORT_DEVLINK_UP_MASK) == SATA_PORT_DEVLINK_UP) {
18517 			/* Ignore event */
18518 			SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18519 			    "Ignoring port %d:%d link lost event - link is up",
18520 			    saddr->cport, saddr->pmport);
18521 			goto done;
18522 		}
18523 		/*
18524 		 * When HBA cannot generate device attached/detached events,
18525 		 * we need to track link lost time and eventually generate
18526 		 * device detach event.
18527 		 */
18528 		if (!(SATA_FEATURES(sata_hba_inst) & SATA_CTLF_HOTPLUG)) {
18529 			/* We are tracking link lost time */
18530 			if (pmportinfo->pmport_link_lost_time == 0) {
18531 				/* save current time (lbolt value) */
18532 				pmportinfo->pmport_link_lost_time =
18533 				    ddi_get_lbolt();
18534 				/* just keep link lost event */
18535 				pmportinfo->pmport_event_flags |=
18536 				    SATA_EVNT_LINK_LOST;
18537 			} else {
18538 				clock_t cur_time = ddi_get_lbolt();
18539 				if ((cur_time -
18540 				    pmportinfo->pmport_link_lost_time) >=
18541 				    drv_usectohz(
18542 				    SATA_EVNT_LINK_LOST_TIMEOUT)) {
18543 					/* trigger device detach event */
18544 					pmportinfo->pmport_event_flags |=
18545 					    SATA_EVNT_DEVICE_DETACHED;
18546 					pmportinfo->pmport_link_lost_time = 0;
18547 					SATADBG2(SATA_DBG_EVENTS,
18548 					    sata_hba_inst,
18549 					    "Triggering port %d:%d "
18550 					    "device detached event",
18551 					    saddr->cport, saddr->pmport);
18552 				} else {
18553 					/* keep link lost event */
18554 					pmportinfo->pmport_event_flags |=
18555 					    SATA_EVNT_LINK_LOST;
18556 				}
18557 			}
18558 		}
18559 		/*
18560 		 * We could change port state to disable/delay access to
18561 		 * the attached device until the link is recovered.
18562 		 */
18563 	}
18564 done:
18565 	event_flags = pmportinfo->pmport_event_flags;
18566 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, saddr->cport,
18567 	    saddr->pmport));
18568 	if (event_flags != 0) {
18569 		mutex_enter(&sata_hba_inst->satahba_mutex);
18570 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
18571 		mutex_exit(&sata_hba_inst->satahba_mutex);
18572 		mutex_enter(&sata_mutex);
18573 		sata_event_pending |= SATA_EVNT_MAIN;
18574 		mutex_exit(&sata_mutex);
18575 	}
18576 }
18577 
18578 /*
18579  * Device Detached Event processing.
18580  * Port is probed to find if a device is really gone. If so,
18581  * the device info structure is detached from the SATA port info structure
18582  * and released.
18583  * Port status is updated.
18584  *
18585  * NOTE: Port multiplier ports events are handled by
18586  * sata_process_pmdevice_detached()
18587  */
18588 static void
18589 sata_process_device_detached(sata_hba_inst_t *sata_hba_inst,
18590     sata_address_t *saddr)
18591 {
18592 	sata_cport_info_t *cportinfo;
18593 	sata_pmport_info_t *pmportinfo;
18594 	sata_drive_info_t *sdevinfo;
18595 	sata_device_t sata_device;
18596 	sata_address_t pmport_addr;
18597 	char name[16];
18598 	uint8_t cport = saddr->cport;
18599 	int npmport;
18600 	int rval;
18601 
18602 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18603 	    "Processing port %d device detached", saddr->cport);
18604 
18605 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18606 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18607 	/* Clear event flag */
18608 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18609 
18610 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18611 	if ((cportinfo->cport_state &
18612 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18613 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18614 		    cport_mutex);
18615 		return;
18616 	}
18617 	/* For sanity, re-probe the port */
18618 	sata_device.satadev_rev = SATA_DEVICE_REV;
18619 	sata_device.satadev_addr = *saddr;
18620 
18621 	/*
18622 	 * We have to exit mutex, because the HBA probe port function may
18623 	 * block on its own mutex.
18624 	 */
18625 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18626 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18627 	    (SATA_DIP(sata_hba_inst), &sata_device);
18628 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18629 	sata_update_port_info(sata_hba_inst, &sata_device);
18630 	if (rval != SATA_SUCCESS) {
18631 		/* Something went wrong? Fail the port */
18632 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18633 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18634 		    cport_mutex);
18635 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18636 		    "SATA port %d probing failed",
18637 		    saddr->cport));
18638 		/*
18639 		 * We may want to release device info structure, but
18640 		 * it is not necessary.
18641 		 */
18642 		return;
18643 	} else {
18644 		/* port probed successfully */
18645 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18646 	}
18647 	/*
18648 	 * Check if a device is still attached. For sanity, check also
18649 	 * link status - if no link, there is no device.
18650 	 */
18651 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
18652 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
18653 	    SATA_DTYPE_NONE) {
18654 		/*
18655 		 * Device is still attached - ignore detach event.
18656 		 */
18657 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18658 		    cport_mutex);
18659 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18660 		    "Ignoring detach - device still attached to port %d",
18661 		    sata_device.satadev_addr.cport);
18662 		return;
18663 	}
18664 	/*
18665 	 * We need to detach and release device info structure here
18666 	 */
18667 	if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
18668 		/*
18669 		 * A port-multiplier is removed.
18670 		 *
18671 		 * Calling sata_process_pmdevice_detached() does not work
18672 		 * here. The port multiplier is gone, so we cannot probe
18673 		 * sub-port any more and all pmult-related data structure must
18674 		 * be de-allocated immediately. Following structure of every
18675 		 * implemented sub-port behind the pmult are required to
18676 		 * released.
18677 		 *
18678 		 *   - attachment point
18679 		 *   - target node
18680 		 *   - sata_drive_info
18681 		 *   - sata_pmport_info
18682 		 */
18683 		for (npmport = 0; npmport < SATA_NUM_PMPORTS(sata_hba_inst,
18684 		    cport); npmport ++) {
18685 			SATADBG2(SATA_DBG_PMULT|SATA_DBG_EVENTS_PROC,
18686 			    sata_hba_inst,
18687 			    "Detaching target node at port %d:%d",
18688 			    cport, npmport);
18689 
18690 			mutex_exit(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18691 
18692 			/* Remove attachment point. */
18693 			name[0] = '\0';
18694 			(void) sprintf(name, "%d.%d", cport, npmport);
18695 			ddi_remove_minor_node(SATA_DIP(sata_hba_inst), name);
18696 			sata_log(sata_hba_inst, CE_NOTE,
18697 			    "Remove attachment point of port %d:%d",
18698 			    cport, npmport);
18699 
18700 			/* Remove target node */
18701 			pmport_addr.cport = cport;
18702 			pmport_addr.pmport = (uint8_t)npmport;
18703 			pmport_addr.qual = SATA_ADDR_PMPORT;
18704 			sata_remove_target_node(sata_hba_inst, &pmport_addr);
18705 
18706 			mutex_enter(&SATA_CPORT_MUTEX(sata_hba_inst, cport));
18707 
18708 			/* Release sata_pmport_info & sata_drive_info. */
18709 			pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
18710 			    cport, npmport);
18711 			ASSERT(pmportinfo != NULL);
18712 
18713 			sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18714 			if (sdevinfo != NULL) {
18715 				(void) kmem_free((void *) sdevinfo,
18716 				    sizeof (sata_drive_info_t));
18717 			}
18718 
18719 			/* Release sata_pmport_info at last */
18720 			(void) kmem_free((void *) pmportinfo,
18721 			    sizeof (sata_pmport_info_t));
18722 		}
18723 
18724 		/* Finally, release sata_pmult_info */
18725 		(void) kmem_free((void *)
18726 		    SATA_CPORTINFO_PMULT_INFO(cportinfo),
18727 		    sizeof (sata_pmult_info_t));
18728 		SATA_CPORTINFO_PMULT_INFO(cportinfo) = NULL;
18729 
18730 		sata_log(sata_hba_inst, CE_WARN,
18731 		    "SATA port-multiplier detached at port %d", cport);
18732 
18733 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18734 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18735 		    saddr->cport)->cport_mutex);
18736 	} else {
18737 		if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18738 			sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18739 			SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
18740 			(void) kmem_free((void *)sdevinfo,
18741 			    sizeof (sata_drive_info_t));
18742 		}
18743 		sata_log(sata_hba_inst, CE_WARN,
18744 		    "SATA device detached at port %d", cport);
18745 
18746 		cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18747 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
18748 		    saddr->cport)->cport_mutex);
18749 
18750 		/*
18751 		 * Try to offline a device and remove target node
18752 		 * if it still exists
18753 		 */
18754 		sata_remove_target_node(sata_hba_inst, saddr);
18755 	}
18756 
18757 
18758 	/*
18759 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18760 	 * with the hint: SE_HINT_REMOVE
18761 	 */
18762 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
18763 }
18764 
18765 /*
18766  * Port Multiplier Port Device Deattached Event processing.
18767  *
18768  * NOTE: No Mutex should be hold.
18769  */
18770 static void
18771 sata_process_pmdevice_detached(sata_hba_inst_t *sata_hba_inst,
18772     sata_address_t *saddr)
18773 {
18774 	sata_pmport_info_t *pmportinfo;
18775 	sata_drive_info_t *sdevinfo;
18776 	sata_device_t sata_device;
18777 	int rval;
18778 	uint8_t cport, pmport;
18779 
18780 	cport = saddr->cport;
18781 	pmport = saddr->pmport;
18782 
18783 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18784 	    "Processing port %d:%d device detached",
18785 	    cport, pmport);
18786 
18787 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
18788 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18789 
18790 	/* Clear event flag */
18791 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_DETACHED;
18792 
18793 	/* If the port is in SHUTDOWN or FAILED state, ignore detach event. */
18794 	if ((pmportinfo->pmport_state &
18795 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18796 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18797 		return;
18798 	}
18799 	/* For sanity, re-probe the port */
18800 	sata_device.satadev_rev = SATA_DEVICE_REV;
18801 	sata_device.satadev_addr = *saddr;
18802 
18803 	/*
18804 	 * We have to exit mutex, because the HBA probe port function may
18805 	 * block on its own mutex.
18806 	 */
18807 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18808 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18809 	    (SATA_DIP(sata_hba_inst), &sata_device);
18810 	mutex_enter(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18811 	sata_update_pmport_info(sata_hba_inst, &sata_device);
18812 	if (rval != SATA_SUCCESS) {
18813 		/* Something went wrong? Fail the port */
18814 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
18815 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18816 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18817 		    "SATA port %d:%d probing failed",
18818 		    saddr->pmport));
18819 		/*
18820 		 * We may want to release device info structure, but
18821 		 * it is not necessary.
18822 		 */
18823 		return;
18824 	} else {
18825 		/* port probed successfully */
18826 		pmportinfo->pmport_state |=
18827 		    SATA_STATE_PROBED | SATA_STATE_READY;
18828 	}
18829 	/*
18830 	 * Check if a device is still attached. For sanity, check also
18831 	 * link status - if no link, there is no device.
18832 	 */
18833 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) ==
18834 	    SATA_PORT_DEVLINK_UP && sata_device.satadev_type !=
18835 	    SATA_DTYPE_NONE) {
18836 		/*
18837 		 * Device is still attached - ignore detach event.
18838 		 */
18839 		mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18840 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18841 		    "Ignoring detach - device still attached to port %d",
18842 		    sata_device.satadev_addr.pmport);
18843 		return;
18844 	}
18845 	/*
18846 	 * We need to detach and release device info structure here
18847 	 */
18848 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
18849 		sdevinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
18850 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
18851 		(void) kmem_free((void *)sdevinfo,
18852 		    sizeof (sata_drive_info_t));
18853 	}
18854 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
18855 	/*
18856 	 * Device cannot be reached anymore, even if the target node may be
18857 	 * still present.
18858 	 */
18859 	mutex_exit(&SATA_PMPORT_MUTEX(sata_hba_inst, cport, pmport));
18860 
18861 	/*
18862 	 * Try to offline a device and remove target node if it still exists
18863 	 */
18864 	sata_remove_target_node(sata_hba_inst, saddr);
18865 
18866 	/*
18867 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18868 	 * with the hint: SE_HINT_REMOVE
18869 	 */
18870 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_REMOVE);
18871 }
18872 
18873 
18874 /*
18875  * Device Attached Event processing.
18876  * Port state is checked to verify that a device is really attached. If so,
18877  * the device info structure is created and attached to the SATA port info
18878  * structure.
18879  *
18880  * If attached device cannot be identified or set-up, the retry for the
18881  * attach processing is set-up. Subsequent daemon run would try again to
18882  * identify the device, until the time limit is reached
18883  * (SATA_DEV_IDENTIFY_TIMEOUT).
18884  *
18885  * This function cannot be called in interrupt context (it may sleep).
18886  *
18887  * NOTE: Port multiplier ports events are handled by
18888  * sata_process_pmdevice_attached()
18889  */
18890 static void
18891 sata_process_device_attached(sata_hba_inst_t *sata_hba_inst,
18892     sata_address_t *saddr)
18893 {
18894 	sata_cport_info_t *cportinfo = NULL;
18895 	sata_drive_info_t *sdevinfo = NULL;
18896 	sata_pmult_info_t *pmultinfo = NULL;
18897 	sata_pmport_info_t *pmportinfo = NULL;
18898 	sata_device_t sata_device;
18899 	dev_info_t *tdip;
18900 	uint32_t event_flags = 0, pmult_event_flags = 0;
18901 	int rval;
18902 	int npmport;
18903 
18904 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18905 	    "Processing port %d device attached", saddr->cport);
18906 
18907 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
18908 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18909 
18910 	/* Clear attach event flag first */
18911 	cportinfo->cport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
18912 
18913 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
18914 	if ((cportinfo->cport_state &
18915 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
18916 		cportinfo->cport_dev_attach_time = 0;
18917 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18918 		    cport_mutex);
18919 		return;
18920 	}
18921 
18922 	/*
18923 	 * If the sata_drive_info structure is found attached to the port info,
18924 	 * despite the fact the device was removed and now it is re-attached,
18925 	 * the old drive info structure was not removed.
18926 	 * Arbitrarily release device info structure.
18927 	 */
18928 	if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
18929 		sdevinfo = SATA_CPORTINFO_DRV_INFO(cportinfo);
18930 		SATA_CPORTINFO_DRV_INFO(cportinfo) = NULL;
18931 		(void) kmem_free((void *)sdevinfo,
18932 		    sizeof (sata_drive_info_t));
18933 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18934 		    "Arbitrarily detaching old device info.", NULL);
18935 	}
18936 	cportinfo->cport_dev_type = SATA_DTYPE_NONE;
18937 
18938 	/* For sanity, re-probe the port */
18939 	sata_device.satadev_rev = SATA_DEVICE_REV;
18940 	sata_device.satadev_addr = *saddr;
18941 
18942 	/*
18943 	 * We have to exit mutex, because the HBA probe port function may
18944 	 * block on its own mutex.
18945 	 */
18946 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18947 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
18948 	    (SATA_DIP(sata_hba_inst), &sata_device);
18949 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18950 	sata_update_port_info(sata_hba_inst, &sata_device);
18951 	if (rval != SATA_SUCCESS) {
18952 		/* Something went wrong? Fail the port */
18953 		cportinfo->cport_state = SATA_PSTATE_FAILED;
18954 		cportinfo->cport_dev_attach_time = 0;
18955 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18956 		    cport_mutex);
18957 		SATA_LOG_D((sata_hba_inst, CE_WARN,
18958 		    "SATA port %d probing failed",
18959 		    saddr->cport));
18960 		return;
18961 	} else {
18962 		/* port probed successfully */
18963 		cportinfo->cport_state |= SATA_STATE_PROBED | SATA_STATE_READY;
18964 	}
18965 	/*
18966 	 * Check if a device is still attached. For sanity, check also
18967 	 * link status - if no link, there is no device.
18968 	 */
18969 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
18970 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
18971 	    SATA_DTYPE_NONE) {
18972 		/*
18973 		 * No device - ignore attach event.
18974 		 */
18975 		cportinfo->cport_dev_attach_time = 0;
18976 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
18977 		    cport_mutex);
18978 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
18979 		    "Ignoring attach - no device connected to port %d",
18980 		    sata_device.satadev_addr.cport);
18981 		return;
18982 	}
18983 
18984 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
18985 	/*
18986 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
18987 	 * with the hint: SE_HINT_INSERT
18988 	 */
18989 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
18990 
18991 	/*
18992 	 * Port reprobing will take care of the creation of the device
18993 	 * info structure and determination of the device type.
18994 	 */
18995 	sata_device.satadev_addr = *saddr;
18996 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
18997 	    SATA_DEV_IDENTIFY_NORETRY);
18998 
18999 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19000 	    cport_mutex);
19001 	if ((cportinfo->cport_state & SATA_STATE_READY) &&
19002 	    (cportinfo->cport_dev_type != SATA_DTYPE_NONE)) {
19003 		/* Some device is attached to the port */
19004 		if (cportinfo->cport_dev_type == SATA_DTYPE_UNKNOWN) {
19005 			/*
19006 			 * A device was not successfully attached.
19007 			 * Track retry time for device identification.
19008 			 */
19009 			if (cportinfo->cport_dev_attach_time != 0) {
19010 				clock_t cur_time = ddi_get_lbolt();
19011 				/*
19012 				 * If the retry time limit was not exceeded,
19013 				 * reinstate attach event.
19014 				 */
19015 				if ((cur_time -
19016 				    cportinfo->cport_dev_attach_time) <
19017 				    drv_usectohz(
19018 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19019 					/* OK, restore attach event */
19020 					cportinfo->cport_event_flags |=
19021 					    SATA_EVNT_DEVICE_ATTACHED;
19022 				} else {
19023 					/* Timeout - cannot identify device */
19024 					cportinfo->cport_dev_attach_time = 0;
19025 					sata_log(sata_hba_inst,
19026 					    CE_WARN,
19027 					    "Could not identify SATA device "
19028 					    "at port %d",
19029 					    saddr->cport);
19030 				}
19031 			} else {
19032 				/*
19033 				 * Start tracking time for device
19034 				 * identification.
19035 				 * Save current time (lbolt value).
19036 				 */
19037 				cportinfo->cport_dev_attach_time =
19038 				    ddi_get_lbolt();
19039 				/* Restore attach event */
19040 				cportinfo->cport_event_flags |=
19041 				    SATA_EVNT_DEVICE_ATTACHED;
19042 			}
19043 		} else if (cportinfo->cport_dev_type == SATA_DTYPE_PMULT) {
19044 			cportinfo->cport_dev_attach_time = 0;
19045 			sata_log(sata_hba_inst, CE_NOTE,
19046 			    "SATA port-multiplier detected at port %d",
19047 			    saddr->cport);
19048 
19049 			if (SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL) {
19050 				/* Log the info of new port multiplier */
19051 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19052 				    saddr->cport)->cport_mutex);
19053 				sata_show_pmult_info(sata_hba_inst,
19054 				    &sata_device);
19055 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19056 				    saddr->cport)->cport_mutex);
19057 			}
19058 
19059 			ASSERT(SATA_CPORTINFO_PMULT_INFO(cportinfo) != NULL);
19060 			pmultinfo = SATA_CPORTINFO_PMULT_INFO(cportinfo);
19061 			for (npmport = 0; npmport <
19062 			    pmultinfo->pmult_num_dev_ports; npmport++) {
19063 				pmportinfo = SATA_PMPORT_INFO(sata_hba_inst,
19064 				    saddr->cport, npmport);
19065 				ASSERT(pmportinfo != NULL);
19066 
19067 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19068 				    saddr->cport)->cport_mutex);
19069 				mutex_enter(&pmportinfo->pmport_mutex);
19070 				/* Marked all pmports with link events. */
19071 				pmportinfo->pmport_event_flags =
19072 				    SATA_EVNT_LINK_ESTABLISHED;
19073 				pmult_event_flags |=
19074 				    pmportinfo->pmport_event_flags;
19075 				mutex_exit(&pmportinfo->pmport_mutex);
19076 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19077 				    saddr->cport)->cport_mutex);
19078 			}
19079 			/* Auto-online is not available for PMult now. */
19080 
19081 		} else {
19082 			/*
19083 			 * If device was successfully attached, the subsequent
19084 			 * action depends on a state of the
19085 			 * sata_auto_online variable. If it is set to zero.
19086 			 * an explicit 'configure' command will be needed to
19087 			 * configure it. If its value is non-zero, we will
19088 			 * attempt to online (configure) the device.
19089 			 * First, log the message indicating that a device
19090 			 * was attached.
19091 			 */
19092 			cportinfo->cport_dev_attach_time = 0;
19093 			sata_log(sata_hba_inst, CE_WARN,
19094 			    "SATA device detected at port %d", saddr->cport);
19095 
19096 			if (SATA_CPORTINFO_DRV_INFO(cportinfo) != NULL) {
19097 				sata_drive_info_t new_sdinfo;
19098 
19099 				/* Log device info data */
19100 				new_sdinfo = *(SATA_CPORTINFO_DRV_INFO(
19101 				    cportinfo));
19102 				sata_show_drive_info(sata_hba_inst,
19103 				    &new_sdinfo);
19104 			}
19105 
19106 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19107 			    saddr->cport)->cport_mutex);
19108 
19109 			/*
19110 			 * Make sure that there is no target node for that
19111 			 * device. If so, release it. It should not happen,
19112 			 * unless we had problem removing the node when
19113 			 * device was detached.
19114 			 */
19115 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19116 			    saddr->cport, saddr->pmport);
19117 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19118 			    saddr->cport)->cport_mutex);
19119 			if (tdip != NULL) {
19120 
19121 #ifdef SATA_DEBUG
19122 				if ((cportinfo->cport_event_flags &
19123 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19124 					sata_log(sata_hba_inst, CE_WARN,
19125 					    "sata_process_device_attached: "
19126 					    "old device target node exists!");
19127 #endif
19128 				/*
19129 				 * target node exists - try to unconfigure
19130 				 * device and remove the node.
19131 				 */
19132 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19133 				    saddr->cport)->cport_mutex);
19134 				rval = ndi_devi_offline(tdip,
19135 				    NDI_DEVI_REMOVE);
19136 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19137 				    saddr->cport)->cport_mutex);
19138 
19139 				if (rval == NDI_SUCCESS) {
19140 					cportinfo->cport_event_flags &=
19141 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19142 					cportinfo->cport_tgtnode_clean = B_TRUE;
19143 				} else {
19144 					/*
19145 					 * PROBLEM - the target node remained
19146 					 * and it belongs to a previously
19147 					 * attached device.
19148 					 * This happens when the file was open
19149 					 * or the node was waiting for
19150 					 * resources at the time the
19151 					 * associated device was removed.
19152 					 * Instruct event daemon to retry the
19153 					 * cleanup later.
19154 					 */
19155 					sata_log(sata_hba_inst,
19156 					    CE_WARN,
19157 					    "Application(s) accessing "
19158 					    "previously attached SATA "
19159 					    "device have to release "
19160 					    "it before newly inserted "
19161 					    "device can be made accessible.",
19162 					    saddr->cport);
19163 					cportinfo->cport_event_flags |=
19164 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19165 					cportinfo->cport_tgtnode_clean =
19166 					    B_FALSE;
19167 				}
19168 			}
19169 			if (sata_auto_online != 0) {
19170 				cportinfo->cport_event_flags |=
19171 				    SATA_EVNT_AUTOONLINE_DEVICE;
19172 			}
19173 
19174 		}
19175 	} else {
19176 		cportinfo->cport_dev_attach_time = 0;
19177 	}
19178 
19179 	event_flags = cportinfo->cport_event_flags;
19180 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19181 	if (event_flags != 0 || pmult_event_flags != 0) {
19182 		mutex_enter(&sata_hba_inst->satahba_mutex);
19183 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19184 		mutex_exit(&sata_hba_inst->satahba_mutex);
19185 		mutex_enter(&sata_mutex);
19186 		sata_event_pending |= SATA_EVNT_MAIN;
19187 		mutex_exit(&sata_mutex);
19188 	}
19189 }
19190 
19191 /*
19192  * Port Multiplier Port Device Attached Event processing.
19193  *
19194  * NOTE: No Mutex should be hold.
19195  */
19196 static void
19197 sata_process_pmdevice_attached(sata_hba_inst_t *sata_hba_inst,
19198     sata_address_t *saddr)
19199 {
19200 	sata_pmport_info_t *pmportinfo;
19201 	sata_drive_info_t *sdinfo;
19202 	sata_device_t sata_device;
19203 	dev_info_t *tdip;
19204 	uint32_t event_flags;
19205 	uint8_t cport = saddr->cport;
19206 	uint8_t pmport = saddr->pmport;
19207 	int rval;
19208 
19209 	SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19210 	    "Processing port %d:%d device attached", cport, pmport);
19211 
19212 	pmportinfo = SATA_PMPORT_INFO(sata_hba_inst, cport, pmport);
19213 
19214 	mutex_enter(&pmportinfo->pmport_mutex);
19215 
19216 	/* Clear attach event flag first */
19217 	pmportinfo->pmport_event_flags &= ~SATA_EVNT_DEVICE_ATTACHED;
19218 
19219 	/* If the port is in SHUTDOWN or FAILED state, ignore event. */
19220 	if ((pmportinfo->pmport_state &
19221 	    (SATA_PSTATE_SHUTDOWN | SATA_PSTATE_FAILED)) != 0) {
19222 		pmportinfo->pmport_dev_attach_time = 0;
19223 		mutex_exit(&pmportinfo->pmport_mutex);
19224 		return;
19225 	}
19226 
19227 	/*
19228 	 * If the sata_drive_info structure is found attached to the port info,
19229 	 * despite the fact the device was removed and now it is re-attached,
19230 	 * the old drive info structure was not removed.
19231 	 * Arbitrarily release device info structure.
19232 	 */
19233 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19234 		sdinfo = SATA_PMPORTINFO_DRV_INFO(pmportinfo);
19235 		SATA_PMPORTINFO_DRV_INFO(pmportinfo) = NULL;
19236 		(void) kmem_free((void *)sdinfo,
19237 		    sizeof (sata_drive_info_t));
19238 		SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19239 		    "Arbitrarily detaching old device info.", NULL);
19240 	}
19241 	pmportinfo->pmport_dev_type = SATA_DTYPE_NONE;
19242 
19243 	/* For sanity, re-probe the port */
19244 	sata_device.satadev_rev = SATA_DEVICE_REV;
19245 	sata_device.satadev_addr = *saddr;
19246 
19247 	/*
19248 	 * We have to exit mutex, because the HBA probe port function may
19249 	 * block on its own mutex.
19250 	 */
19251 	mutex_exit(&pmportinfo->pmport_mutex);
19252 	rval = (*SATA_PROBE_PORT_FUNC(sata_hba_inst))
19253 	    (SATA_DIP(sata_hba_inst), &sata_device);
19254 	mutex_enter(&pmportinfo->pmport_mutex);
19255 
19256 	sata_update_pmport_info(sata_hba_inst, &sata_device);
19257 	if (rval != SATA_SUCCESS) {
19258 		/* Something went wrong? Fail the port */
19259 		pmportinfo->pmport_state = SATA_PSTATE_FAILED;
19260 		pmportinfo->pmport_dev_attach_time = 0;
19261 		mutex_exit(&pmportinfo->pmport_mutex);
19262 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19263 		    "SATA port %d:%d probing failed", cport, pmport));
19264 		return;
19265 	} else {
19266 		/* pmport probed successfully */
19267 		pmportinfo->pmport_state |=
19268 		    SATA_STATE_PROBED | SATA_STATE_READY;
19269 	}
19270 	/*
19271 	 * Check if a device is still attached. For sanity, check also
19272 	 * link status - if no link, there is no device.
19273 	 */
19274 	if ((sata_device.satadev_scr.sstatus & SATA_PORT_DEVLINK_UP_MASK) !=
19275 	    SATA_PORT_DEVLINK_UP || sata_device.satadev_type ==
19276 	    SATA_DTYPE_NONE) {
19277 		/*
19278 		 * No device - ignore attach event.
19279 		 */
19280 		pmportinfo->pmport_dev_attach_time = 0;
19281 		mutex_exit(&pmportinfo->pmport_mutex);
19282 		SATADBG2(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19283 		    "Ignoring attach - no device connected to port %d:%d",
19284 		    cport, pmport);
19285 		return;
19286 	}
19287 
19288 	mutex_exit(&pmportinfo->pmport_mutex);
19289 	/*
19290 	 * Generate sysevent - EC_DR / ESC_DR_AP_STATE_CHANGE
19291 	 * with the hint: SE_HINT_INSERT
19292 	 */
19293 	sata_gen_sysevent(sata_hba_inst, saddr, SE_HINT_INSERT);
19294 
19295 	/*
19296 	 * Port reprobing will take care of the creation of the device
19297 	 * info structure and determination of the device type.
19298 	 */
19299 	sata_device.satadev_addr = *saddr;
19300 	(void) sata_reprobe_port(sata_hba_inst, &sata_device,
19301 	    SATA_DEV_IDENTIFY_NORETRY);
19302 
19303 	mutex_enter(&pmportinfo->pmport_mutex);
19304 	if ((pmportinfo->pmport_state & SATA_STATE_READY) &&
19305 	    (pmportinfo->pmport_dev_type != SATA_DTYPE_NONE)) {
19306 		/* Some device is attached to the port */
19307 		if (pmportinfo->pmport_dev_type == SATA_DTYPE_UNKNOWN) {
19308 			/*
19309 			 * A device was not successfully attached.
19310 			 * Track retry time for device identification.
19311 			 */
19312 			if (pmportinfo->pmport_dev_attach_time != 0) {
19313 				clock_t cur_time = ddi_get_lbolt();
19314 				/*
19315 				 * If the retry time limit was not exceeded,
19316 				 * reinstate attach event.
19317 				 */
19318 				if ((cur_time -
19319 				    pmportinfo->pmport_dev_attach_time) <
19320 				    drv_usectohz(
19321 				    SATA_DEV_IDENTIFY_TIMEOUT)) {
19322 					/* OK, restore attach event */
19323 					pmportinfo->pmport_event_flags |=
19324 					    SATA_EVNT_DEVICE_ATTACHED;
19325 				} else {
19326 					/* Timeout - cannot identify device */
19327 					pmportinfo->pmport_dev_attach_time = 0;
19328 					sata_log(sata_hba_inst, CE_WARN,
19329 					    "Could not identify SATA device "
19330 					    "at port %d:%d",
19331 					    cport, pmport);
19332 				}
19333 			} else {
19334 				/*
19335 				 * Start tracking time for device
19336 				 * identification.
19337 				 * Save current time (lbolt value).
19338 				 */
19339 				pmportinfo->pmport_dev_attach_time =
19340 				    ddi_get_lbolt();
19341 				/* Restore attach event */
19342 				pmportinfo->pmport_event_flags |=
19343 				    SATA_EVNT_DEVICE_ATTACHED;
19344 			}
19345 		} else {
19346 			/*
19347 			 * If device was successfully attached, the subsequent
19348 			 * action depends on a state of the
19349 			 * sata_auto_online variable. If it is set to zero.
19350 			 * an explicit 'configure' command will be needed to
19351 			 * configure it. If its value is non-zero, we will
19352 			 * attempt to online (configure) the device.
19353 			 * First, log the message indicating that a device
19354 			 * was attached.
19355 			 */
19356 			pmportinfo->pmport_dev_attach_time = 0;
19357 			sata_log(sata_hba_inst, CE_WARN,
19358 			    "SATA device detected at port %d:%d",
19359 			    cport, pmport);
19360 
19361 			if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19362 				sata_drive_info_t new_sdinfo;
19363 
19364 				/* Log device info data */
19365 				new_sdinfo = *(SATA_PMPORTINFO_DRV_INFO(
19366 				    pmportinfo));
19367 				sata_show_drive_info(sata_hba_inst,
19368 				    &new_sdinfo);
19369 			}
19370 
19371 			mutex_exit(&pmportinfo->pmport_mutex);
19372 
19373 			/*
19374 			 * Make sure that there is no target node for that
19375 			 * device. If so, release it. It should not happen,
19376 			 * unless we had problem removing the node when
19377 			 * device was detached.
19378 			 */
19379 			tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst),
19380 			    saddr->cport, saddr->pmport);
19381 			mutex_enter(&pmportinfo->pmport_mutex);
19382 			if (tdip != NULL) {
19383 
19384 #ifdef SATA_DEBUG
19385 				if ((pmportinfo->pmport_event_flags &
19386 				    SATA_EVNT_TARGET_NODE_CLEANUP) == 0)
19387 					sata_log(sata_hba_inst, CE_WARN,
19388 					    "sata_process_device_attached: "
19389 					    "old device target node exists!");
19390 #endif
19391 				/*
19392 				 * target node exists - try to unconfigure
19393 				 * device and remove the node.
19394 				 */
19395 				mutex_exit(&pmportinfo->pmport_mutex);
19396 				rval = ndi_devi_offline(tdip,
19397 				    NDI_DEVI_REMOVE);
19398 				mutex_enter(&pmportinfo->pmport_mutex);
19399 
19400 				if (rval == NDI_SUCCESS) {
19401 					pmportinfo->pmport_event_flags &=
19402 					    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19403 					pmportinfo->pmport_tgtnode_clean =
19404 					    B_TRUE;
19405 				} else {
19406 					/*
19407 					 * PROBLEM - the target node remained
19408 					 * and it belongs to a previously
19409 					 * attached device.
19410 					 * This happens when the file was open
19411 					 * or the node was waiting for
19412 					 * resources at the time the
19413 					 * associated device was removed.
19414 					 * Instruct event daemon to retry the
19415 					 * cleanup later.
19416 					 */
19417 					sata_log(sata_hba_inst,
19418 					    CE_WARN,
19419 					    "Application(s) accessing "
19420 					    "previously attached SATA "
19421 					    "device have to release "
19422 					    "it before newly inserted "
19423 					    "device can be made accessible."
19424 					    "at port %d:%d",
19425 					    cport, pmport);
19426 					pmportinfo->pmport_event_flags |=
19427 					    SATA_EVNT_TARGET_NODE_CLEANUP;
19428 					pmportinfo->pmport_tgtnode_clean =
19429 					    B_FALSE;
19430 				}
19431 			}
19432 			if (sata_auto_online != 0) {
19433 				pmportinfo->pmport_event_flags |=
19434 				    SATA_EVNT_AUTOONLINE_DEVICE;
19435 			}
19436 
19437 		}
19438 	} else {
19439 		pmportinfo->pmport_dev_attach_time = 0;
19440 	}
19441 
19442 	event_flags = pmportinfo->pmport_event_flags;
19443 	mutex_exit(&pmportinfo->pmport_mutex);
19444 	if (event_flags != 0) {
19445 		mutex_enter(&sata_hba_inst->satahba_mutex);
19446 		sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19447 		mutex_exit(&sata_hba_inst->satahba_mutex);
19448 		mutex_enter(&sata_mutex);
19449 		sata_event_pending |= SATA_EVNT_MAIN;
19450 		mutex_exit(&sata_mutex);
19451 	}
19452 
19453 	/* clear the reset_in_progress events */
19454 	if (SATA_PMPORTINFO_DRV_INFO(pmportinfo) != NULL) {
19455 		if (pmportinfo->pmport_dev_type & SATA_VALID_DEV_TYPE) {
19456 			/* must clear flags on cport */
19457 			sata_pmult_info_t *pminfo =
19458 			    SATA_PMULT_INFO(sata_hba_inst,
19459 			    saddr->cport);
19460 			pminfo->pmult_event_flags |=
19461 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19462 		}
19463 	}
19464 }
19465 
19466 /*
19467  * Device Target Node Cleanup Event processing.
19468  * If the target node associated with a sata port device is in
19469  * DEVI_DEVICE_REMOVED state, an attempt is made to remove it.
19470  * If the target node cannot be removed, the event flag is left intact,
19471  * so that event daemon may re-run this function later.
19472  *
19473  * This function cannot be called in interrupt context (it may sleep).
19474  *
19475  * NOTE: Processes cport events only, not port multiplier ports.
19476  */
19477 static void
19478 sata_process_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19479     sata_address_t *saddr)
19480 {
19481 	sata_cport_info_t *cportinfo;
19482 	dev_info_t *tdip;
19483 
19484 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19485 	    "Processing port %d device target node cleanup", saddr->cport);
19486 
19487 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19488 
19489 	/*
19490 	 * Check if there is target node for that device and it is in the
19491 	 * DEVI_DEVICE_REMOVED state. If so, release it.
19492 	 */
19493 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19494 	    saddr->pmport);
19495 	if (tdip != NULL) {
19496 		/*
19497 		 * target node exists - check if it is target node of
19498 		 * a removed device.
19499 		 */
19500 		if (sata_check_device_removed(tdip) == B_TRUE) {
19501 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19502 			    "sata_process_target_node_cleanup: "
19503 			    "old device target node exists!", NULL);
19504 			/*
19505 			 * Unconfigure and remove the target node
19506 			 */
19507 			if (ndi_devi_offline(tdip, NDI_DEVI_REMOVE) ==
19508 			    NDI_SUCCESS) {
19509 				mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19510 				    saddr->cport)->cport_mutex);
19511 				cportinfo->cport_event_flags &=
19512 				    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19513 				mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19514 				    saddr->cport)->cport_mutex);
19515 				return;
19516 			}
19517 			/*
19518 			 * Event daemon will retry the cleanup later.
19519 			 */
19520 			mutex_enter(&sata_hba_inst->satahba_mutex);
19521 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19522 			mutex_exit(&sata_hba_inst->satahba_mutex);
19523 			mutex_enter(&sata_mutex);
19524 			sata_event_pending |= SATA_EVNT_MAIN;
19525 			mutex_exit(&sata_mutex);
19526 		}
19527 	} else {
19528 		if (saddr->qual == SATA_ADDR_CPORT ||
19529 		    saddr->qual == SATA_ADDR_DCPORT) {
19530 			mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19531 			    saddr->cport)->cport_mutex);
19532 			cportinfo->cport_event_flags &=
19533 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19534 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19535 			    saddr->cport)->cport_mutex);
19536 		} else {
19537 			/* sanity check */
19538 			if (SATA_CPORT_DEV_TYPE(sata_hba_inst, saddr->cport) !=
19539 			    SATA_DTYPE_PMULT || SATA_PMULT_INFO(sata_hba_inst,
19540 			    saddr->cport) == NULL)
19541 				return;
19542 			if (SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19543 			    saddr->pmport) == NULL)
19544 				return;
19545 
19546 			mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19547 			    saddr->cport, saddr->pmport)->pmport_mutex);
19548 			SATA_PMPORT_INFO(sata_hba_inst, saddr->cport,
19549 			    saddr->pmport)->pmport_event_flags &=
19550 			    ~SATA_EVNT_TARGET_NODE_CLEANUP;
19551 			mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19552 			    saddr->cport, saddr->pmport)->pmport_mutex);
19553 		}
19554 	}
19555 }
19556 
19557 /*
19558  * Device AutoOnline Event processing.
19559  * If attached device is to be onlined, an attempt is made to online this
19560  * device, but only if there is no lingering (old) target node present.
19561  * If the device cannot be onlined, the event flag is left intact,
19562  * so that event daemon may re-run this function later.
19563  *
19564  * This function cannot be called in interrupt context (it may sleep).
19565  *
19566  * NOTE: Processes cport events only, not port multiplier ports.
19567  */
19568 static void
19569 sata_process_device_autoonline(sata_hba_inst_t *sata_hba_inst,
19570     sata_address_t *saddr)
19571 {
19572 	sata_cport_info_t *cportinfo;
19573 	sata_drive_info_t *sdinfo;
19574 	sata_device_t sata_device;
19575 	dev_info_t *tdip;
19576 
19577 	SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19578 	    "Processing port %d attached device auto-onlining", saddr->cport);
19579 
19580 	cportinfo = SATA_CPORT_INFO(sata_hba_inst, saddr->cport);
19581 
19582 	/*
19583 	 * Check if device is present and recognized. If not, reset event.
19584 	 */
19585 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19586 	if ((cportinfo->cport_dev_type & SATA_VALID_DEV_TYPE) == 0) {
19587 		/* Nothing to online */
19588 		cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19589 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19590 		    saddr->cport)->cport_mutex);
19591 		return;
19592 	}
19593 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19594 
19595 	/*
19596 	 * Check if there is target node for this device and if it is in the
19597 	 * DEVI_DEVICE_REMOVED state. If so, abort onlining but keep
19598 	 * the event for later processing.
19599 	 */
19600 	tdip = sata_get_target_dip(SATA_DIP(sata_hba_inst), saddr->cport,
19601 	    saddr->pmport);
19602 	if (tdip != NULL) {
19603 		/*
19604 		 * target node exists - check if it is target node of
19605 		 * a removed device.
19606 		 */
19607 		if (sata_check_device_removed(tdip) == B_TRUE) {
19608 			SATADBG1(SATA_DBG_EVENTS_PROC, sata_hba_inst,
19609 			    "sata_process_device_autoonline: "
19610 			    "old device target node exists!", NULL);
19611 			/*
19612 			 * Event daemon will retry device onlining later.
19613 			 */
19614 			mutex_enter(&sata_hba_inst->satahba_mutex);
19615 			sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19616 			mutex_exit(&sata_hba_inst->satahba_mutex);
19617 			mutex_enter(&sata_mutex);
19618 			sata_event_pending |= SATA_EVNT_MAIN;
19619 			mutex_exit(&sata_mutex);
19620 			return;
19621 		}
19622 		/*
19623 		 * If the target node is not in the 'removed" state, assume
19624 		 * that it belongs to this device. There is nothing more to do,
19625 		 * but reset the event.
19626 		 */
19627 	} else {
19628 
19629 		/*
19630 		 * Try to online the device
19631 		 * If there is any reset-related event, remove it. We are
19632 		 * configuring the device and no state restoring is needed.
19633 		 */
19634 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19635 		    saddr->cport)->cport_mutex);
19636 		sata_device.satadev_addr = *saddr;
19637 		if (saddr->qual == SATA_ADDR_CPORT)
19638 			sata_device.satadev_addr.qual = SATA_ADDR_DCPORT;
19639 		else
19640 			sata_device.satadev_addr.qual = SATA_ADDR_DPMPORT;
19641 		sdinfo = sata_get_device_info(sata_hba_inst, &sata_device);
19642 		if (sdinfo != NULL) {
19643 			if (sdinfo->satadrv_event_flags &
19644 			    (SATA_EVNT_DEVICE_RESET |
19645 			    SATA_EVNT_INPROC_DEVICE_RESET))
19646 				sdinfo->satadrv_event_flags = 0;
19647 			sdinfo->satadrv_event_flags |=
19648 			    SATA_EVNT_CLEAR_DEVICE_RESET;
19649 
19650 			/* Need to create a new target node. */
19651 			cportinfo->cport_tgtnode_clean = B_TRUE;
19652 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19653 			    saddr->cport)->cport_mutex);
19654 			tdip = sata_create_target_node(SATA_DIP(sata_hba_inst),
19655 			    sata_hba_inst, &sata_device.satadev_addr);
19656 			if (tdip == NULL) {
19657 				/*
19658 				 * Configure (onlining) failed.
19659 				 * We will NOT retry
19660 				 */
19661 				SATA_LOG_D((sata_hba_inst, CE_WARN,
19662 				    "sata_process_device_autoonline: "
19663 				    "configuring SATA device at port %d failed",
19664 				    saddr->cport));
19665 			}
19666 		} else {
19667 			mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19668 			    saddr->cport)->cport_mutex);
19669 		}
19670 
19671 	}
19672 	mutex_enter(&SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->cport_mutex);
19673 	cportinfo->cport_event_flags &= ~SATA_EVNT_AUTOONLINE_DEVICE;
19674 	mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19675 	    saddr->cport)->cport_mutex);
19676 }
19677 
19678 
19679 static void
19680 sata_gen_sysevent(sata_hba_inst_t *sata_hba_inst, sata_address_t *saddr,
19681     int hint)
19682 {
19683 	char ap[MAXPATHLEN];
19684 	nvlist_t *ev_attr_list = NULL;
19685 	int err;
19686 
19687 	/* Allocate and build sysevent attribute list */
19688 	err = nvlist_alloc(&ev_attr_list, NV_UNIQUE_NAME_TYPE, DDI_NOSLEEP);
19689 	if (err != 0) {
19690 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19691 		    "sata_gen_sysevent: "
19692 		    "cannot allocate memory for sysevent attributes\n"));
19693 		return;
19694 	}
19695 	/* Add hint attribute */
19696 	err = nvlist_add_string(ev_attr_list, DR_HINT, SE_HINT2STR(hint));
19697 	if (err != 0) {
19698 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19699 		    "sata_gen_sysevent: "
19700 		    "failed to add DR_HINT attr for sysevent"));
19701 		nvlist_free(ev_attr_list);
19702 		return;
19703 	}
19704 	/*
19705 	 * Add AP attribute.
19706 	 * Get controller pathname and convert it into AP pathname by adding
19707 	 * a target number.
19708 	 */
19709 	(void) snprintf(ap, MAXPATHLEN, "/devices");
19710 	(void) ddi_pathname(SATA_DIP(sata_hba_inst), ap + strlen(ap));
19711 	(void) snprintf(ap + strlen(ap), MAXPATHLEN - strlen(ap), ":%d",
19712 	    SATA_MAKE_AP_NUMBER(saddr->cport, saddr->pmport, saddr->qual));
19713 
19714 	err = nvlist_add_string(ev_attr_list, DR_AP_ID, ap);
19715 	if (err != 0) {
19716 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19717 		    "sata_gen_sysevent: "
19718 		    "failed to add DR_AP_ID attr for sysevent"));
19719 		nvlist_free(ev_attr_list);
19720 		return;
19721 	}
19722 
19723 	/* Generate/log sysevent */
19724 	err = ddi_log_sysevent(SATA_DIP(sata_hba_inst), DDI_VENDOR_SUNW, EC_DR,
19725 	    ESC_DR_AP_STATE_CHANGE, ev_attr_list, NULL, DDI_NOSLEEP);
19726 	if (err != DDI_SUCCESS) {
19727 		SATA_LOG_D((sata_hba_inst, CE_WARN,
19728 		    "sata_gen_sysevent: "
19729 		    "cannot log sysevent, err code %x\n", err));
19730 	}
19731 
19732 	nvlist_free(ev_attr_list);
19733 }
19734 
19735 
19736 
19737 
19738 /*
19739  * Set DEVI_DEVICE_REMOVED state in the SATA device target node.
19740  */
19741 static void
19742 sata_set_device_removed(dev_info_t *tdip)
19743 {
19744 	int circ;
19745 
19746 	ASSERT(tdip != NULL);
19747 
19748 	ndi_devi_enter(tdip, &circ);
19749 	mutex_enter(&DEVI(tdip)->devi_lock);
19750 	DEVI_SET_DEVICE_REMOVED(tdip);
19751 	mutex_exit(&DEVI(tdip)->devi_lock);
19752 	ndi_devi_exit(tdip, circ);
19753 }
19754 
19755 
19756 /*
19757  * Set internal event instructing event daemon to try
19758  * to perform the target node cleanup.
19759  */
19760 static void
19761 sata_set_target_node_cleanup(sata_hba_inst_t *sata_hba_inst,
19762     sata_address_t *saddr)
19763 {
19764 	if (saddr->qual == SATA_ADDR_CPORT ||
19765 	    saddr->qual == SATA_ADDR_DCPORT) {
19766 		mutex_enter(&SATA_CPORT_INFO(sata_hba_inst,
19767 		    saddr->cport)->cport_mutex);
19768 		SATA_CPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport) |=
19769 		    SATA_EVNT_TARGET_NODE_CLEANUP;
19770 		SATA_CPORT_INFO(sata_hba_inst, saddr->cport)->
19771 		    cport_tgtnode_clean = B_FALSE;
19772 		mutex_exit(&SATA_CPORT_INFO(sata_hba_inst,
19773 		    saddr->cport)->cport_mutex);
19774 	} else {
19775 		mutex_enter(&SATA_PMPORT_INFO(sata_hba_inst,
19776 		    saddr->cport, saddr->pmport)->pmport_mutex);
19777 		SATA_PMPORT_EVENT_FLAGS(sata_hba_inst, saddr->cport,
19778 		    saddr->pmport) |= SATA_EVNT_TARGET_NODE_CLEANUP;
19779 		SATA_PMPORT_INFO(sata_hba_inst, saddr->cport, saddr->pmport)->
19780 		    pmport_tgtnode_clean = B_FALSE;
19781 		mutex_exit(&SATA_PMPORT_INFO(sata_hba_inst,
19782 		    saddr->cport, saddr->pmport)->pmport_mutex);
19783 	}
19784 	mutex_enter(&sata_hba_inst->satahba_mutex);
19785 	sata_hba_inst->satahba_event_flags |= SATA_EVNT_MAIN;
19786 	mutex_exit(&sata_hba_inst->satahba_mutex);
19787 	mutex_enter(&sata_mutex);
19788 	sata_event_pending |= SATA_EVNT_MAIN;
19789 	mutex_exit(&sata_mutex);
19790 }
19791 
19792 
19793 /*
19794  * Check if the SATA device target node is in DEVI_DEVICE_REMOVED state,
19795  * i.e. check if the target node state indicates that it belongs to a removed
19796  * device.
19797  *
19798  * Returns B_TRUE if the target node is in DEVI_DEVICE_REMOVED state,
19799  * B_FALSE otherwise.
19800  */
19801 static boolean_t
19802 sata_check_device_removed(dev_info_t *tdip)
19803 {
19804 	ASSERT(tdip != NULL);
19805 
19806 	if (DEVI_IS_DEVICE_REMOVED(tdip))
19807 		return (B_TRUE);
19808 	else
19809 		return (B_FALSE);
19810 }
19811 
19812 /* ************************ FAULT INJECTTION **************************** */
19813 
19814 #ifdef SATA_INJECT_FAULTS
19815 
19816 static	uint32_t sata_fault_count = 0;
19817 static	uint32_t sata_fault_suspend_count = 0;
19818 
19819 /*
19820  * Inject sata pkt fault
19821  * It modifies returned values of the sata packet.
19822  * It returns immediately if:
19823  * pkt fault injection is not enabled (via sata_inject_fault,
19824  * sata_inject_fault_count), or invalid fault is specified (sata_fault_type),
19825  * or pkt does not contain command to be faulted (set in sata_fault_cmd), or
19826  * pkt is not directed to specified fault controller/device
19827  * (sata_fault_ctrl_dev and sata_fault_device).
19828  * If fault controller is not specified, fault injection applies to all
19829  * controllers and devices.
19830  *
19831  * First argument is the pointer to the executed sata packet.
19832  * Second argument is a pointer to a value returned by the HBA tran_start
19833  * function.
19834  * Third argument specifies injected error. Injected sata packet faults
19835  * are the satapkt_reason values.
19836  * SATA_PKT_BUSY		-1	Not completed, busy
19837  * SATA_PKT_DEV_ERROR		1	Device reported error
19838  * SATA_PKT_QUEUE_FULL		2	Not accepted, queue full
19839  * SATA_PKT_PORT_ERROR		3	Not completed, port error
19840  * SATA_PKT_CMD_UNSUPPORTED	4	Cmd unsupported
19841  * SATA_PKT_ABORTED		5	Aborted by request
19842  * SATA_PKT_TIMEOUT		6	Operation timeut
19843  * SATA_PKT_RESET		7	Aborted by reset request
19844  *
19845  * Additional global variables affecting the execution:
19846  *
19847  * sata_inject_fault_count variable specifies number of times in row the
19848  * error is injected. Value of -1 specifies permanent fault, ie. every time
19849  * the fault injection point is reached, the fault is injected and a pause
19850  * between fault injection specified by sata_inject_fault_pause_count is
19851  * ignored). Fault injection routine decrements sata_inject_fault_count
19852  * (if greater than zero) until it reaches 0. No fault is injected when
19853  * sata_inject_fault_count is 0 (zero).
19854  *
19855  * sata_inject_fault_pause_count variable specifies number of times a fault
19856  * injection is bypassed (pause between fault injections).
19857  * If set to 0, a fault is injected only a number of times specified by
19858  * sata_inject_fault_count.
19859  *
19860  * The fault counts are static, so for periodic errors they have to be manually
19861  * reset to start repetition sequence from scratch.
19862  * If the original value returned by the HBA tran_start function is not
19863  * SATA_TRAN_ACCEPTED and pkt reason is not SATA_PKT_COMPLETED, no error
19864  * is injected (to avoid masking real problems);
19865  *
19866  * NOTE: In its current incarnation, this function should be invoked only for
19867  * commands executed in SYNCHRONOUS mode.
19868  */
19869 
19870 
19871 static void
19872 sata_inject_pkt_fault(sata_pkt_t *spkt, int *rval, int fault)
19873 {
19874 
19875 	if (sata_inject_fault != SATA_INJECT_PKT_FAULT)
19876 		return;
19877 
19878 	if (sata_inject_fault_count == 0)
19879 		return;
19880 
19881 	if (fault == 0)
19882 		return;
19883 
19884 	if (sata_fault_cmd != spkt->satapkt_cmd.satacmd_cmd_reg)
19885 		return;
19886 
19887 	if (sata_fault_ctrl != NULL) {
19888 		sata_pkt_txlate_t *spx =
19889 		    (sata_pkt_txlate_t *)spkt->satapkt_framework_private;
19890 
19891 		if (sata_fault_ctrl != NULL && sata_fault_ctrl !=
19892 		    spx->txlt_sata_hba_inst->satahba_dip)
19893 			return;
19894 
19895 		if (sata_fault_device.satadev_addr.cport !=
19896 		    spkt->satapkt_device.satadev_addr.cport ||
19897 		    sata_fault_device.satadev_addr.pmport !=
19898 		    spkt->satapkt_device.satadev_addr.pmport ||
19899 		    sata_fault_device.satadev_addr.qual !=
19900 		    spkt->satapkt_device.satadev_addr.qual)
19901 			return;
19902 	}
19903 
19904 	/* Modify pkt return parameters */
19905 	if (*rval != SATA_TRAN_ACCEPTED ||
19906 	    spkt->satapkt_reason != SATA_PKT_COMPLETED) {
19907 		sata_fault_count = 0;
19908 		sata_fault_suspend_count = 0;
19909 		return;
19910 	}
19911 	if (sata_fault_count == 0 && sata_fault_suspend_count != 0) {
19912 		/* Pause in the injection */
19913 		sata_fault_suspend_count -= 1;
19914 		return;
19915 	}
19916 
19917 	if (sata_fault_count == 0 && sata_fault_suspend_count == 0) {
19918 		/*
19919 		 * Init inject fault cycle. If fault count is set to -1,
19920 		 * it is a permanent fault.
19921 		 */
19922 		if (sata_inject_fault_count != -1) {
19923 			sata_fault_count = sata_inject_fault_count;
19924 			sata_fault_suspend_count =
19925 			    sata_inject_fault_pause_count;
19926 			if (sata_fault_suspend_count == 0)
19927 				sata_inject_fault_count = 0;
19928 		}
19929 	}
19930 
19931 	if (sata_fault_count != 0)
19932 		sata_fault_count -= 1;
19933 
19934 	switch (fault) {
19935 	case SATA_PKT_BUSY:
19936 		*rval = SATA_TRAN_BUSY;
19937 		spkt->satapkt_reason = SATA_PKT_BUSY;
19938 		break;
19939 
19940 	case SATA_PKT_QUEUE_FULL:
19941 		*rval = SATA_TRAN_QUEUE_FULL;
19942 		spkt->satapkt_reason = SATA_PKT_QUEUE_FULL;
19943 		break;
19944 
19945 	case SATA_PKT_CMD_UNSUPPORTED:
19946 		*rval = SATA_TRAN_CMD_UNSUPPORTED;
19947 		spkt->satapkt_reason = SATA_PKT_CMD_UNSUPPORTED;
19948 		break;
19949 
19950 	case SATA_PKT_PORT_ERROR:
19951 		/* This is "rejected" command */
19952 		*rval = SATA_TRAN_PORT_ERROR;
19953 		spkt->satapkt_reason = SATA_PKT_PORT_ERROR;
19954 		/* Additional error setup could be done here - port state */
19955 		break;
19956 
19957 	case SATA_PKT_DEV_ERROR:
19958 		spkt->satapkt_reason = SATA_PKT_DEV_ERROR;
19959 		/*
19960 		 * Additional error setup could be done here
19961 		 */
19962 		break;
19963 
19964 	case SATA_PKT_ABORTED:
19965 		spkt->satapkt_reason = SATA_PKT_ABORTED;
19966 		break;
19967 
19968 	case SATA_PKT_TIMEOUT:
19969 		spkt->satapkt_reason = SATA_PKT_TIMEOUT;
19970 		/* Additional error setup could be done here */
19971 		break;
19972 
19973 	case SATA_PKT_RESET:
19974 		spkt->satapkt_reason = SATA_PKT_RESET;
19975 		/*
19976 		 * Additional error setup could be done here - device reset
19977 		 */
19978 		break;
19979 
19980 	default:
19981 		break;
19982 	}
19983 }
19984 
19985 #endif
19986 
19987 /*
19988  * SATA Trace Ring Buffer
19989  * ----------------------
19990  *
19991  * Overview
19992  *
19993  * The SATA trace ring buffer is a ring buffer created and managed by
19994  * the SATA framework module that can be used by any module or driver
19995  * within the SATA framework to store debug messages.
19996  *
19997  * Ring Buffer Interfaces:
19998  *
19999  *	sata_vtrace_debug()	<-- Adds debug message to ring buffer
20000  *	sata_trace_debug()	<-- Wraps varargs into sata_vtrace_debug()
20001  *
20002  *	Note that the sata_trace_debug() interface was created to give
20003  *	consumers the flexibilty of sending debug messages to ring buffer
20004  *	as variable arguments.  Consumers can send type va_list debug
20005  *	messages directly to sata_vtrace_debug(). The sata_trace_debug()
20006  *	and sata_vtrace_debug() relationship is similar to that of
20007  *	cmn_err(9F) and vcmn_err(9F).
20008  *
20009  * Below is a diagram of the SATA trace ring buffer interfaces and
20010  * sample consumers:
20011  *
20012  * +---------------------------------+
20013  * |    o  o  SATA Framework Module  |
20014  * | o  SATA  o     +------------------+      +------------------+
20015  * |o   Trace  o <--|sata_vtrace_debug/|<-----|SATA HBA Driver #1|
20016  * |o   R-Buf  o    |sata_trace_debug  |<--+  +------------------+
20017  * | o        o     +------------------+   |  +------------------+
20018  * |    o  o                ^        |     +--|SATA HBA Driver #2|
20019  * |                        |        |        +------------------+
20020  * |           +------------------+  |
20021  * |           |SATA Debug Message|  |
20022  * |           +------------------+  |
20023  * +---------------------------------+
20024  *
20025  * Supporting Routines:
20026  *
20027  *	sata_trace_rbuf_alloc()	<-- Initializes ring buffer
20028  *	sata_trace_rbuf_free()	<-- Destroys ring buffer
20029  *	sata_trace_dmsg_alloc() <-- Creates or reuses buffer in ring buffer
20030  *	sata_trace_dmsg_free()	<-- Destroys content of ring buffer
20031  *
20032  * The default SATA trace ring buffer size is defined by DMSG_RING_SIZE.
20033  * The ring buffer size can be adjusted by setting dmsg_ring_size in
20034  * /etc/system to desired size in unit of bytes.
20035  *
20036  * The individual debug message size in the ring buffer is restricted
20037  * to DMSG_BUF_SIZE.
20038  */
20039 void
20040 sata_vtrace_debug(dev_info_t *dip, const char *fmt, va_list ap)
20041 {
20042 	sata_trace_dmsg_t *dmsg;
20043 
20044 	if (sata_debug_rbuf == NULL) {
20045 		return;
20046 	}
20047 
20048 	/*
20049 	 * If max size of ring buffer is smaller than size
20050 	 * required for one debug message then just return
20051 	 * since we have no room for the debug message.
20052 	 */
20053 	if (sata_debug_rbuf->maxsize < (sizeof (sata_trace_dmsg_t))) {
20054 		return;
20055 	}
20056 
20057 	mutex_enter(&sata_debug_rbuf->lock);
20058 
20059 	/* alloc or reuse on ring buffer */
20060 	dmsg = sata_trace_dmsg_alloc();
20061 
20062 	if (dmsg == NULL) {
20063 		/* resource allocation failed */
20064 		mutex_exit(&sata_debug_rbuf->lock);
20065 		return;
20066 	}
20067 
20068 	dmsg->dip = dip;
20069 	gethrestime(&dmsg->timestamp);
20070 
20071 	(void) vsnprintf(dmsg->buf, sizeof (dmsg->buf), fmt, ap);
20072 
20073 	mutex_exit(&sata_debug_rbuf->lock);
20074 }
20075 
20076 void
20077 sata_trace_debug(dev_info_t *dip, const char *fmt, ...)
20078 {
20079 	va_list ap;
20080 
20081 	va_start(ap, fmt);
20082 	sata_vtrace_debug(dip, fmt, ap);
20083 	va_end(ap);
20084 }
20085 
20086 /*
20087  * This routine is used to manage debug messages
20088  * on ring buffer.
20089  */
20090 static sata_trace_dmsg_t *
20091 sata_trace_dmsg_alloc(void)
20092 {
20093 	sata_trace_dmsg_t *dmsg_alloc, *dmsg = sata_debug_rbuf->dmsgp;
20094 
20095 	if (sata_debug_rbuf->looped == TRUE) {
20096 		sata_debug_rbuf->dmsgp = dmsg->next;
20097 		return (sata_debug_rbuf->dmsgp);
20098 	}
20099 
20100 	/*
20101 	 * If we're looping for the first time,
20102 	 * connect the ring.
20103 	 */
20104 	if (((sata_debug_rbuf->size + (sizeof (sata_trace_dmsg_t))) >
20105 	    sata_debug_rbuf->maxsize) && (sata_debug_rbuf->dmsgh != NULL)) {
20106 		dmsg->next = sata_debug_rbuf->dmsgh;
20107 		sata_debug_rbuf->dmsgp = sata_debug_rbuf->dmsgh;
20108 		sata_debug_rbuf->looped = TRUE;
20109 		return (sata_debug_rbuf->dmsgp);
20110 	}
20111 
20112 	/* If we've gotten this far then memory allocation is needed */
20113 	dmsg_alloc = kmem_zalloc(sizeof (sata_trace_dmsg_t), KM_NOSLEEP);
20114 	if (dmsg_alloc == NULL) {
20115 		sata_debug_rbuf->allocfailed++;
20116 		return (dmsg_alloc);
20117 	} else {
20118 		sata_debug_rbuf->size += sizeof (sata_trace_dmsg_t);
20119 	}
20120 
20121 	if (sata_debug_rbuf->dmsgp != NULL) {
20122 		dmsg->next = dmsg_alloc;
20123 		sata_debug_rbuf->dmsgp = dmsg->next;
20124 		return (sata_debug_rbuf->dmsgp);
20125 	} else {
20126 		/*
20127 		 * We should only be here if we're initializing
20128 		 * the ring buffer.
20129 		 */
20130 		if (sata_debug_rbuf->dmsgh == NULL) {
20131 			sata_debug_rbuf->dmsgh = dmsg_alloc;
20132 		} else {
20133 			/* Something is wrong */
20134 			kmem_free(dmsg_alloc, sizeof (sata_trace_dmsg_t));
20135 			return (NULL);
20136 		}
20137 
20138 		sata_debug_rbuf->dmsgp = dmsg_alloc;
20139 		return (sata_debug_rbuf->dmsgp);
20140 	}
20141 }
20142 
20143 
20144 /*
20145  * Free all messages on debug ring buffer.
20146  */
20147 static void
20148 sata_trace_dmsg_free(void)
20149 {
20150 	sata_trace_dmsg_t *dmsg_next, *dmsg = sata_debug_rbuf->dmsgh;
20151 
20152 	while (dmsg != NULL) {
20153 		dmsg_next = dmsg->next;
20154 		kmem_free(dmsg, sizeof (sata_trace_dmsg_t));
20155 
20156 		/*
20157 		 * If we've looped around the ring than we're done.
20158 		 */
20159 		if (dmsg_next == sata_debug_rbuf->dmsgh) {
20160 			break;
20161 		} else {
20162 			dmsg = dmsg_next;
20163 		}
20164 	}
20165 }
20166 
20167 
20168 /*
20169  * This function can block
20170  */
20171 static void
20172 sata_trace_rbuf_alloc(void)
20173 {
20174 	sata_debug_rbuf = kmem_zalloc(sizeof (sata_trace_rbuf_t), KM_SLEEP);
20175 
20176 	mutex_init(&sata_debug_rbuf->lock, NULL, MUTEX_DRIVER, NULL);
20177 
20178 	if (dmsg_ring_size > 0) {
20179 		sata_debug_rbuf->maxsize = (size_t)dmsg_ring_size;
20180 	}
20181 }
20182 
20183 
20184 static void
20185 sata_trace_rbuf_free(void)
20186 {
20187 	sata_trace_dmsg_free();
20188 	mutex_destroy(&sata_debug_rbuf->lock);
20189 	kmem_free(sata_debug_rbuf, sizeof (sata_trace_rbuf_t));
20190 }
20191 
20192 /*
20193  * If SATA_DEBUG is not defined then this routine is called instead
20194  * of sata_log() via the SATA_LOG_D macro.
20195  */
20196 static void
20197 sata_trace_log(sata_hba_inst_t *sata_hba_inst, uint_t level,
20198     const char *fmt, ...)
20199 {
20200 #ifndef __lock_lint
20201 	_NOTE(ARGUNUSED(level))
20202 #endif
20203 
20204 	dev_info_t *dip = NULL;
20205 	va_list ap;
20206 
20207 	if (sata_hba_inst != NULL) {
20208 		dip = SATA_DIP(sata_hba_inst);
20209 	}
20210 
20211 	va_start(ap, fmt);
20212 	sata_vtrace_debug(dip, fmt, ap);
20213 	va_end(ap);
20214 }
20215